code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function reset self begin set loss = list set funcargs = list set nSteps = 0 set converged = false end function
def reset(self): self.loss = [] self.funcargs = [] self.nSteps = 0 self.converged = False
Python
nomic_cornstack_python_v1
function __init__ self func sequence fail=none size=40 begin set func = func set fail = fail set all = sequence set total = length all set temp = dict set queue = dict set size = size set stop = false if callable func and is instance sequence tuple tuple list begin call start_new_thread _host tuple end end function
def __init__(self, func, sequence, fail=None, size=40): self.func = func self.fail = fail self.all = sequence self.total = len(self.all) self.temp = {} self.queue = {} self.size = size self.stop = False if callable(self.func) and isinstanc...
Python
nomic_cornstack_python_v1
function main begin set desc = string Converts between geodetic, modified apex, quasi-dipole and MLT set parser = call ArgumentParser description=desc prog=string apexpy call add_argument string source metavar=string SOURCE choices=list string geo string apex string qd string mlt help=string Convert from {geo, apex, qd...
def main(): desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT' parser = argparse.ArgumentParser(description=desc, prog='apexpy') parser.add_argument('source', metavar='SOURCE', choices=['geo', 'apex', 'qd', 'mlt'], help='Convert from {ge...
Python
nomic_cornstack_python_v1
function predict input_csv begin try begin set df = call read_excel format string {} string ./data/b2b.xlsx for column in df begin set unique_vals = unique df at column set nr_values = length unique_vals if nr_values < 12 begin print format string The number of values for feature {} :{} -- {} column nr_values unique_va...
def predict(input_csv): try: df=pd.read_excel('{}'.format('./data/b2b.xlsx')) for column in df: unique_vals = np.unique(df[column]) nr_values = len(unique_vals) if nr_values < 12: print('The number of values for feature {} :{} -- {}'.format(column,...
Python
nomic_cornstack_python_v1
from __future__ import annotations from typing import TYPE_CHECKING import logger if TYPE_CHECKING begin from mysql.connector import MySQLConnection end set logger = call get_logger string riyasewana.storage class RiyasewanaStorage begin set FROM_SERVER = 1 set FROM_LOCAL = 0 set GET_LOCAL_ADS_QUERY : str = string SELE...
from __future__ import annotations from typing import TYPE_CHECKING import logger if TYPE_CHECKING: from mysql.connector import MySQLConnection logger = logger.get_logger("riyasewana.storage") class RiyasewanaStorage: FROM_SERVER = 1 FROM_LOCAL = 0 GET_LOCAL_ADS_QUERY: str = f"SELECT ad_id FROM r...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np set url = string https://raw.githubusercontent.com/Umair115/PIAIC-BATCH-35-Q2/main/Assignment/inventory.csv set inventory = read csv url print head inventory 10 set staten_island = read csv url nrows=10 print staten_island set product_request = staten_island at string product_desc...
import pandas as pd import numpy as np url = "https://raw.githubusercontent.com/Umair115/PIAIC-BATCH-35-Q2/main/Assignment/inventory.csv" inventory = pd.read_csv(url) print(inventory.head(10)) staten_island = pd.read_csv(url, nrows = 10) print(staten_island) product_request = staten_island['product_descripti...
Python
zaydzuhri_stack_edu_python
function Select self Append=defaultNamedNotOptArg Data=defaultNamedNotOptArg begin return call InvokeTypes 25 LCID 1 tuple 11 0 tuple tuple 11 1 tuple 9 1 Append Data end function
def Select(self, Append=defaultNamedNotOptArg, Data=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(25, LCID, 1, (11, 0), ((11, 1), (9, 1)),Append , Data)
Python
nomic_cornstack_python_v1
function acUpdate deltaT begin global timer_60_hz timer_10_hz global timer_trace global trace_update_batch comment Update timers set timer_60_hz = timer_60_hz + deltaT set timer_10_hz = timer_10_hz + deltaT set timer_trace = timer_trace + deltaT comment Run on 10hz if timer_10_hz > PERIOD_10_HZ begin set timer_10_hz = ...
def acUpdate(deltaT): global timer_60_hz, timer_10_hz global timer_trace global trace_update_batch # Update timers timer_60_hz += deltaT timer_10_hz += deltaT timer_trace += deltaT # Run on 10hz if timer_10_hz > PERIOD_10_HZ: timer_10_hz -= PERIOD_10_HZ # Update ac...
Python
nomic_cornstack_python_v1
function InsertInstruction asm_store index mnemonic=string label=string address=0 opcode=string comment=string begin set row = call RowData 0 label address opcode mnemonic comment in_use=true call InsertRowAt index row end function
def InsertInstruction(asm_store, index, mnemonic='', label='', address=0, opcode='', comment=''): row = assembly_store.RowData(0, label, address, opcode, mnemonic, comment, in_use=True) asm_store.InsertRowAt(index, row)
Python
nomic_cornstack_python_v1
function _scroll_plot1 image name init_z begin set fig = figure figsize=tuple 12 12 set ax1 = call add_subplot 111 set scroller = call Scroller list ax1 list image list name init_z call mpl_connect string scroll_event onscroll tight layout return scroller end function
def _scroll_plot1(image, name, init_z): fig = plt.figure(figsize=(12, 12)) ax1 = fig.add_subplot(111) scroller = Scroller([ax1], [image, ], [name, ], init_z) fig.canvas.mpl_connect('scroll_event', scroller.onscroll) fig.tight_layout() return scroller
Python
nomic_cornstack_python_v1
import pickle from music21 import instrument , note , stream , chord from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.layers import Activation from flask import Flask , jsonify , render_template , request , Response , send_file ...
import pickle from music21 import instrument, note, stream, chord from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.layers import Activation from flask import Flask, jsonify, render_template, request,Response,send_file im...
Python
zaydzuhri_stack_edu_python
comment _*_ coding:utf-8 _*_ comment author: comment 归并排序 function merge_sort alist begin string 归并排序 set n = length alist if n <= 1 begin return alist end comment 折半 set mid = n // 2 comment left 采用归并排序后形成的有序的新的列表 set left_li = call merge_sort alist at slice : mid : comment right 采用归并排序后形成的有序的新的列表 set right_li = call...
# _*_ coding:utf-8 _*_ # # author: # # 归并排序 def merge_sort(alist): """归并排序""" n = len(alist) if n <= 1: return alist mid = n//2 # 折半 # left 采用归并排序后形成的有序的新的列表 left_li = merge_sort(alist[:mid]) # right 采用归并排序后形成的有序的新的列表 right_li = merge_sort(alist[mid:]) # 将两个子序列合并成一个新的整体...
Python
zaydzuhri_stack_edu_python
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * comment QMainWindow类基于QWidget类,因此本类直接继承QMainWindow即可 class MyWidget extends QMainWindow QDialog begin function __init__ self begin call __init__ call initUI end function function initUI self begin call center comment 窗口大小 call resize 800 600 comment 窗口图...
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * class MyWidget(QMainWindow, QDialog): # QMainWindow类基于QWidget类,因此本类直接继承QMainWindow即可 def __init__(self): super().__init__() self.initUI() def initUI(self): self.center() self.resize(800, 600) # 窗口大小 s...
Python
zaydzuhri_stack_edu_python
function convert_node element begin comment add node's GPS coordinates set node = dict string y element at string lat ; string x element at string lon comment add tags if expression string tags in element then update node element at string tags else none return node end function
def convert_node(element): # add node's GPS coordinates node = {'y': element['lat'], 'x': element['lon']} # add tags node.update(element['tags']) if "tags" in element else None return node
Python
nomic_cornstack_python_v1
function get_postre self begin return postre end function
def get_postre(self): return self.postre
Python
nomic_cornstack_python_v1
import MySQLdb comment import sys comment boroughinput = sys.argv[1] set db = call connect host=string localhost user=string hw1067 passwd=string 81828384yomama db=string coursedb set cur = call cursor set query = string SELECT address FROM incident AS i INNER JOIN boroughs AS b ON i.zip_code = b.zip_code WHERE b.name ...
import MySQLdb #import sys #boroughinput = sys.argv[1] db = MySQLdb.connect(host = "localhost", user = "hw1067", passwd = "81828384yomama", db = "coursedb") cur = db.cursor() query = "SELECT address FROM incident AS i INNER JOIN boroughs AS b ON i.zip_code = b.zip_code WHERE b.name = "+ "'" + boroughinput + "'" +...
Python
zaydzuhri_stack_edu_python
function test_pixel_error_threshold scene begin pass end function
def test_pixel_error_threshold(scene): pass
Python
nomic_cornstack_python_v1
function findRedundantConnection self edges begin comment Solution 1 - 56 ms comment Solution 2 - 36 ms comment union find set tuple parents ranks = tuple dict dict function findParent n parents begin while parents at n != n begin set parents at n = parents at parents at n set n = parents at n end return n end functi...
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: # Solution 1 - 56 ms # Solution 2 - 36 ms # union find parents, ranks = {}, {} def findParent(n, parents): while parents[n] != n: parents[n] = parents[parents[n]] ...
Python
nomic_cornstack_python_v1
function _TestQueryEpisodes tester user_cookie request_dict begin set validator = validator set cookie_dict = call DecodeUserCookie user_cookie set user_id = get cookie_dict string user_id none set device_id = get cookie_dict string device_id none set cookie_viewpoint_id = get cookie_dict string viewpoint_id none comme...
def _TestQueryEpisodes(tester, user_cookie, request_dict): validator = tester.validator cookie_dict = tester.DecodeUserCookie(user_cookie) user_id = cookie_dict.get('user_id', None) device_id = cookie_dict.get('device_id', None) cookie_viewpoint_id = cookie_dict.get('viewpoint_id', None) # Send quer...
Python
nomic_cornstack_python_v1
function initialize_true_labels self dataframe begin set true_labels = list none * length dataframe set df = dataframe if dtypes != string int64 and dtypes != string float64 begin set feature_values = dict for tuple index value in enumerate unique begin set feature_values at value = index end for row in call iterrows ...
def initialize_true_labels(self, dataframe) : self.true_labels = [None] * len(dataframe) df = dataframe if df[df.columns[-1]].dtypes != "int64" and df[df.columns[-1]].dtypes != "float64" : feature_values = {} for index, value in enumerate(df[df.columns[-1]].unique()) : ...
Python
nomic_cornstack_python_v1
import appscript from time import sleep import requests while true begin set url = none try begin set time = call player_position if type time is float begin set url = string http://192.168.179.7/setting?num=%02d:%02d:%02d&dot=00100100 % tuple time / 3600 time % 3600 / 60 time % 60 / 1 end else begin set url = string h...
import appscript from time import sleep import requests while True: url = None try: time = appscript.app('iTunes').player_position() if(type(time) is float): url = 'http://192.168.179.7/setting?num=%02d:%02d:%02d&dot=00100100' % (time/3600, (time%3600)/60, (time%60)/1) else:...
Python
zaydzuhri_stack_edu_python
import torch from torch.nn import functional as F from torchvision import datasets , transforms class UnNormalize extends object begin function __init__ self mean std begin set mean = mean set std = std end function function __call__ self tensor begin string Args: tensor (Tensor): Tensor image of size (C, H, W) to be n...
import torch from torch.nn import functional as F from torchvision import datasets, transforms class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, tensor): """ Args: tensor (Tensor): Tensor image of size (C, H...
Python
zaydzuhri_stack_edu_python
function event_m50_37_2300 begin string State 0,2: [Preset] Lighthouse under the snowstorm_SubState assert call event_m50_37_x133 z201=537000001 string State 1: Finish call EndMachine end function
def event_m50_37_2300(): """State 0,2: [Preset] Lighthouse under the snowstorm_SubState""" assert event_m50_37_x133(z201=537000001) """State 1: Finish""" EndMachine()
Python
nomic_cornstack_python_v1
function dayname self begin return string format time self string %A end function
def dayname(self): return self.strftime("%A")
Python
nomic_cornstack_python_v1
comment 当一个函数A的参数,接收的是另一个函数时,则函数A就是高阶函数 function fn1 num1 num2 begin return num1 + num2 end function function fn2 num1 num2 begin return num1 - num2 end function function test num1 num2 fn begin print call fn num1 num2 end function call test 5 6 fn1 call test 5 6 fn2
# 当一个函数A的参数,接收的是另一个函数时,则函数A就是高阶函数 def fn1(num1, num2): return num1 + num2 def fn2(num1, num2): return num1 - num2 def test(num1, num2, fn): print(fn(num1, num2)) test(5, 6, fn1) test(5, 6, fn2)
Python
zaydzuhri_stack_edu_python
function _asciify_list data begin string Ascii-fies list values set ret = list for item in data begin if is instance item unicode begin set item = call _remove_accents item set item = encode item string utf-8 end else if is instance item list begin set item = call _asciify_list item end else if is instance item dict b...
def _asciify_list(data): """ Ascii-fies list values """ ret = [] for item in data: if isinstance(item, unicode): item = _remove_accents(item) item = item.encode('utf-8') elif isinstance(item, list): item = _asciify_list(item) elif isinstance(item, ...
Python
jtatman_500k
import matplotlib.pyplot as plt import numpy as np set f = open string losses_record.txt string r set w = open string new_losses.txt string w set fl = read lines f set frame = list set rewards = list set index = 0 for line in fl begin if index % 10000 == 0 begin set one_line = split line string , comment frame.append...
import matplotlib.pyplot as plt import numpy as np f = open("losses_record.txt", "r") w = open("new_losses.txt", "w") fl = f.readlines() frame = [] rewards = [] index = 0 for line in fl: if index % 10000 == 0: one_line = line.split(",") # frame.append(float(one_line[0]) / 100000) # rewards...
Python
zaydzuhri_stack_edu_python
import requests import statistics comment Replace 'YOUR_API_KEY' with your actual API key set api_key = string YOUR_API_KEY set city = string Boston comment Make the API request set response = get requests string https://api.weatherapi.com/v1/history.json?key= { api_key } &q= { city } &dt=2022-01-01&end_dt=2022-01-07 s...
import requests import statistics # Replace 'YOUR_API_KEY' with your actual API key api_key = 'YOUR_API_KEY' city = 'Boston' # Make the API request response = requests.get(f'https://api.weatherapi.com/v1/history.json?key={api_key}&q={city}&dt=2022-01-01&end_dt=2022-01-07') data = response.json() # Extract the temper...
Python
jtatman_500k
function solve_arithmetic_sequence begin comment Define the given terms set t1 = - 1 / 3 comment Let t2 = y + 2 comment Let t3 = 4y comment Set up the equation (t2 - t1) = (t3 - t2) comment This translates to: (y + 2) - (-1/3) = 4y - (y + 2) comment Simplifying the equation: comment (y + 2) + (1/3) = 4y - (y + 2) comme...
def solve_arithmetic_sequence(): # Define the given terms t1 = -1 / 3 # Let t2 = y + 2 # Let t3 = 4y # Set up the equation (t2 - t1) = (t3 - t2) # This translates to: (y + 2) - (-1/3) = 4y - (y + 2) # Simplifying the equation: # (y + 2) + (1/3) = 4y - (y + 2) # Left side: ...
Python
dbands_pythonMath
import sys set d = string \][POIUYTREWQ';LKJHGFDSA/.,MNBVCXZ=-0987654321` set lines = read lines stdin for line in lines begin set line = strip line set new_s = string for c in line begin if c == string begin set new_s = new_s + string end else begin set new_s = new_s + d at index d c + 1 end end print new_s end
import sys d = "\][POIUYTREWQ';LKJHGFDSA/.,MNBVCXZ=-0987654321`" lines = sys.stdin.readlines() for line in lines: line = line.strip() new_s = "" for c in line: if c == " ": new_s += " " else: new_s += d[d.index(c)+1] print(new_s)
Python
zaydzuhri_stack_edu_python
import fitz import fitz.utils from fitz.utils import getColorList comment READ IN PDF set doc = open string input.pdf comment Define colors set CYAN = tuple 0 255 255 set GOLD = tuple 1 1 0 set GREEN = tuple 0 1 0 set MAGENTA = tuple 255 0 255 set BLUE = tuple 0 0 1 set ORANGE = tuple 255 165 0 set LIGHTCORAL = tuple 2...
import fitz import fitz.utils from fitz.utils import getColorList ### READ IN PDF doc = fitz.open("input.pdf") # Define colors CYAN = (0, 255, 255) GOLD = (1, 1, 0) GREEN = (0, 1, 0) MAGENTA = (255, 0, 255) BLUE = (0, 0, 1) ORANGE = (255, 165, 0) LIGHTCORAL = (240, 128, 128) RED = (1, 0, 0) GRAY0 = (0, 0, 0) CHECKLIST...
Python
zaydzuhri_stack_edu_python
comment Unique Email Addresses comment https://leetcode.com/problems/unique-email-addresses/ class Solution extends object begin function __init__ self begin set ht = dict end function function insertDomains self emails begin comment key is domain name and value is local name for email in emails begin if not split ema...
#Unique Email Addresses #https://leetcode.com/problems/unique-email-addresses/ class Solution(object): def __init__(self): self.ht = {} def insertDomains(self, emails): #key is domain name and value is local name for email in emails: if not(email.split("@")[1] in self.ht): ...
Python
zaydzuhri_stack_edu_python
import dill as pickle import collections from model1 import train1 import os from util import tokenize set file1 = string ../parallel_corpus_IR2/english.txt set file2 = string ../parallel_corpus_IR2/french.txt set parallel_corpus = list set size = 0 class customDict extends defaultdict begin function __missing__ self ...
import dill as pickle import collections from model1 import train1 import os from util import tokenize file1='../parallel_corpus_IR2/english.txt' file2='../parallel_corpus_IR2/french.txt' parallel_corpus=[] size=0 class customDict(collections.defaultdict): def __missing__(self, key): if self.default_factory i...
Python
zaydzuhri_stack_edu_python
import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense , Dropout from keras.optimizers import RMSprop import matplotlib.pyplot as plt set batch_size = 256 set num_classes = 10 set epochs = 20 comment the data, split between train and test sets set tuple tuple x_...
import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import matplotlib.pyplot as plt batch_size = 256 num_classes = 10 epochs = 20 # the data, split between train and test sets (x_train, y_train), (x_test, y_tes...
Python
zaydzuhri_stack_edu_python
function generateDeck begin set suits = list string ♤ string ♡ string ♢ string ♧ set values = list string A string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 string 10 string J string Q string K set deck = list for suit in suits begin for value in values begin append deck value + suit end end ret...
def generateDeck(): suits = ["♤", "♡", "♢", "♧"] values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] deck = [] for suit in suits: for value in values: deck.append(value + suit) return deck def getDeck(): return generateDeck() def getValue(card): value = card[0:-1] if(...
Python
zaydzuhri_stack_edu_python
function hit_or_stand deck hand begin comment to control an upcoming while loop global PLAYING if starts with lower input string Would you want to hit? yes/no string y begin call hit deck hand end else begin set PLAYING = false end end function
def hit_or_stand(deck, hand): global PLAYING # to control an upcoming while loop if input("Would you want to hit? yes/no").lower().startswith('y'): hit(deck, hand) else: PLAYING = False
Python
nomic_cornstack_python_v1
string PLL Analysis methods Cole Nielsen 2019 import numpy as np import matplotlib.pyplot as plt import scipy.signal import scipy.linalg import scipy.integrate from libpll._signal import make_signal , freq_to_index from libpll.optimize import gss from copy import copy comment Autoregressive phase noise fit function aut...
""" PLL Analysis methods Cole Nielsen 2019 """ import numpy as np import matplotlib.pyplot as plt import scipy.signal import scipy.linalg import scipy.integrate from libpll._signal import make_signal, freq_to_index from libpll.optimize import gss from copy import copy #############################################...
Python
zaydzuhri_stack_edu_python
function updateContents self begin set selSpots = call selectedSpots if isChildView begin if length selSpots > 1 or hideChildView begin call hide return end if not selSpots begin comment use top node childList from tree structure set selSpots = list call structSpot end end else if not selSpots begin call hide return en...
def updateContents(self): selSpots = self.treeView.selectionModel().selectedSpots() if self.isChildView: if len(selSpots) > 1 or self.hideChildView: self.hide() return if not selSpots: # use top node childList from tree structure ...
Python
nomic_cornstack_python_v1
function get self post_id begin set key = call from_path string Post integer post_id set post = get db key if post begin set comments = call by_post_id post_id if user begin set like_self = call by_post_id_uid post_id name set like_others_num = call by_post_id_ex_uid_num post_id name set like_others = call by_post_id p...
def get(self, post_id): key = db.Key.from_path("Post", int(post_id)) post = db.get(key) if post: comments = Comment.by_post_id(post_id) if self.user: like_self = Like.by_post_id_uid(post_id, self.user.name) ...
Python
nomic_cornstack_python_v1
function strip_string input begin return replace lower input string string end function
def strip_string(input): return input.lower().replace(" ", "")
Python
nomic_cornstack_python_v1
function set_html_error_placeholder_form_template self template begin set html_error_placeholder_form_template = template end function
def set_html_error_placeholder_form_template(self, template: str) -> None: self.html_error_placeholder_form_template = template
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Aug 28 11:14:10 2019 @author: Brock function mile_to_feet miles begin set feet = miles * 5280 return feet end function function seconds begin set hours = input string Enter numer of hours: set minutes = input string Enter number of minutess: set seconds = input string...
# -*- coding: utf-8 -*- """ Created on Wed Aug 28 11:14:10 2019 @author: Brock """ def mile_to_feet(miles): feet = miles * 5280 return feet def seconds(): hours = input("Enter numer of hours: ") minutes = input("Enter number of minutess: ") seconds = input("Enter number of seconds: ") time = ...
Python
zaydzuhri_stack_edu_python
from sign_up import is_member_exists class CreateGroup begin comment def __init__(self, creator, group_member): comment self.creator = creator comment self.group_member = group_member function is_group_exists self group_details begin return false end function function is_all_users_exists self group_details begin return...
from sign_up import is_member_exists class CreateGroup: # def __init__(self, creator, group_member): # self.creator = creator # self.group_member = group_member def is_group_exists(self, group_details): return False def is_all_users_exists(self, group_details): ...
Python
zaydzuhri_stack_edu_python
function handle_event self event begin call _handle_dir_x event K_LEFT 1 call _handle_dir_x event K_RIGHT - 1 call _handle_dir_y event K_UP 1 call _handle_dir_y event K_DOWN - 1 end function
def handle_event(self, event): self._handle_dir_x(event, K_LEFT, 1) self._handle_dir_x(event, K_RIGHT, -1) self._handle_dir_y(event, K_UP, 1) self._handle_dir_y(event, K_DOWN, -1)
Python
nomic_cornstack_python_v1
class Convert begin function __init__ self num begin set num = num end function function binary self begin set coci = num set Bin = list while coci != 0 begin set rest = coci % 2 set coci = coci // 2 append Bin rest end set result = list for i in range length Bin - 1 - 1 - 1 begin append result Bin at i end return re...
class Convert: def __init__(self, num): self.num = num def binary(self): coci = self.num Bin = [] while coci != 0: rest = coci % 2 coci = coci // 2 Bin.append(rest) result = [] for i in range(len(Bin)-1,-1,-1): result.append(Bin[i]) return result def hexa(self): pass ...
Python
zaydzuhri_stack_edu_python
comment sum of pairs of elements in a list set inp_list = input string Enter the numbers seperated by commas: set num_list = split inp_list string , set ret_lis = list for num in num_list begin append ret_lis integer num end set ret_list = list for i in range length ret_lis begin if length ret_lis == i + 1 begin brea...
#sum of pairs of elements in a list inp_list = input("Enter the numbers seperated by commas: " ) num_list = inp_list.split(",") ret_lis = [] for num in num_list: ret_lis.append(int(num)) ret_list = [] for i in range(len(ret_lis)): if len(ret_lis) == i+1: break else: ret_sum = ret_lis[i] + r...
Python
zaydzuhri_stack_edu_python
class Widget begin set all_widgets = dict set spokes = 0 set teeth = 0 function __init__ self realname spokes teeth begin set spokes = spokes set teeth = teeth set realname = realname set all_widgets at realname = self set name = all_widgets at realname end function end class comment def __str__(self): comment return ...
class Widget: all_widgets = { } spokes=0 teeth=0 def __init__(self, realname, spokes, teeth): self.spokes=spokes self.teeth=teeth self.realname = realname Widget.all_widgets[realname]= self name = Widget.all_widgets[realname] # def __str__(self): # retu...
Python
zaydzuhri_stack_edu_python
import math function findPath label begin if label == 0 begin return list end if label == 1 begin return list 1 end set res = list label while label > 1 begin set level = integer call log2 label set level_start = 2 ^ level set remain = label - level_start // 2 set label = level_start - 1 - remain append res label end ...
import math def findPath(label): if label == 0: return [] if label == 1: return [1] res = [label] while label > 1: level = int(math.log2(label)) level_start = 2 ** level remain = (label - level_start) // 2 label = level_start - 1 - remain res.append(label) ret...
Python
zaydzuhri_stack_edu_python
function find self vport_name=none emulation_host=none **filters begin return find call super IxnSpbSimEdgeIsidListEmulation self list string topology string deviceGroup string ipv4Loopback string ldpTargetedRouter string ldppwvpls string ipv6Loopback string ldpTargetedRouterV6 string ldpotherpws string ethernet string...
def find(self, vport_name=None, emulation_host=None, **filters): return super(IxnSpbSimEdgeIsidListEmulation, self).find(["topology","deviceGroup","ipv4Loopback","ldpTargetedRouter","ldppwvpls","ipv6Loopback","ldpTargetedRouterV6","ldpotherpws","ethernet","ipv6","greoipv6","ipv4","greoipv4","isisSpbSimRouter",...
Python
nomic_cornstack_python_v1
comment from tkinter import * comment # from PIL import ImageTk,Image comment from tkinter import messagebox comment root = Tk() comment root.title('Learn To Code at Codemy.com') comment root.iconbitmap('IT.ico') comment # showinfo, showwarning, showerror, askquestion, askokcancel, askyesno comment def popup(): comment...
# from tkinter import * # # from PIL import ImageTk,Image # from tkinter import messagebox # # root = Tk() # root.title('Learn To Code at Codemy.com') # root.iconbitmap('IT.ico') # # # showinfo, showwarning, showerror, askquestion, askokcancel, askyesno # # # def popup(): # response = messagebox.showinfo("This is m...
Python
zaydzuhri_stack_edu_python
function run self begin string Begin listening for keyboard input events. set state = true set KeyAll = handler call HookKeyboard while state begin sleep 0.01 call PumpWaitingMessages end end function
def run(self): """Begin listening for keyboard input events.""" self.state = True self.hm.KeyAll = self.handler self.hm.HookKeyboard() while self.state: time.sleep(0.01) pythoncom.PumpWaitingMessages()
Python
jtatman_500k
import gym import argparse import matplotlib.pyplot as plt import numpy as np import torch from rl import PPO import json import pickle from hdt import HeuristicAgentLunarLander set filename = string ./il/il.json with open filename string r as read_file begin comment hyperparameters for rl training set il_confs = load ...
import gym import argparse import matplotlib.pyplot as plt import numpy as np import torch from rl import PPO import json import pickle from hdt import HeuristicAgentLunarLander filename = "./il/il.json" with open(filename, "r") as read_file: il_confs = json.load(read_file) # hyperparameters for rl training ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matrix function test_matrixMultiplication begin set a = array list 1 2 set b = array list 1 2 assert call matrixMultiplication a b == list 5 end function
import numpy as np import matrix def test_matrixMultiplication(): a = np.array([1,2]) b = np.array([1,2]) assert matrix.matrixMultiplication(a,b) == [5]
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution begin function convertBST self root begin if not root begin return none end comment inorder = [] comment ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def convertBST(self, root: TreeNode) -> TreeNode: if not root: return None # ino...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding:utf-8 string @author: jimmy zhang from rediscluster import RedisCluster from multiprocessing import Pool import sys function redis_cluster i begin set redis_nodes = list dict string host string redis-master ; string port 6379 try begin comment redisconn = StrictRedisCluster(s...
#!/usr/bin/env python #coding:utf-8 ''' @author: jimmy zhang ''' from rediscluster import RedisCluster from multiprocessing import Pool import sys def redis_cluster(i): redis_nodes = [{'host':'redis-master','port':6379}] try: #redisconn = StrictRedisCluster(startup_nodes=redis_nodes) redisco...
Python
zaydzuhri_stack_edu_python
function is_palindrome s begin comment Remove non-alphanumeric characters and convert to lowercase set s = lower join string generator expression e for e in s if is alphanumeric e comment Reverse the string and check if it is equal to the original string return s == s at slice : : - 1 end function comment True print...
def is_palindrome(s): # Remove non-alphanumeric characters and convert to lowercase s = ''.join(e for e in s if e.isalnum()).lower() # Reverse the string and check if it is equal to the original string return s == s[::-1] print(is_palindrome("A man, a plan, a canal, Panama")) # True print(is_pal...
Python
jtatman_500k
function lucas_series n begin if n == 0 begin return list end else if n == 1 begin return list 2 end else if n == 2 begin return list 2 1 end else begin set series = list 2 1 while length series < n begin append series series at - 1 + series at - 2 end return series end end function
def lucas_series(n): if n == 0: return [] elif n == 1: return [2] elif n == 2: return [2, 1] else: series = [2, 1] while len(series) < n: series.append(series[-1] + series[-2]) return series
Python
jtatman_500k
import ply.yacc as yacc from anytree import Node from lexer import tokens import sys from anytree.exporter import UniqueDotExporter set raiz = none function p_programa p begin string programa : lista_declaracoes global raiz set raiz = call Node string programa set p at 0 = raiz set parent = raiz end function function p...
import ply.yacc as yacc from anytree import Node from lexer import tokens import sys from anytree.exporter import UniqueDotExporter raiz = None def p_programa(p): """ programa : lista_declaracoes """ global raiz raiz = Node("programa") p[0] = raiz p[1].parent = raiz def p_lista_declaracoes(p): ...
Python
zaydzuhri_stack_edu_python
function load_csv_metadata file_path begin set path = join path file_path + string .csv with open path string rb as data begin set output = read csv data end return output end function
def load_csv_metadata(file_path): path = os.path.join(file_path + '.csv') with open(path, 'rb') as data: output = pd.read_csv(data) return output
Python
nomic_cornstack_python_v1
function find_max_element matrix begin comment Step 1: Check if the matrix is 4x4 if length matrix != 4 or any generator expression length row != 4 for row in matrix begin raise call ValueError string Input matrix should be 4x4 end comment Initialize the maximum element to negative infinity set max_element = decimal st...
def find_max_element(matrix): # Step 1: Check if the matrix is 4x4 if len(matrix) != 4 or any(len(row) != 4 for row in matrix): raise ValueError("Input matrix should be 4x4") max_element = float('-inf') # Initialize the maximum element to negative infinity max_indices = [] # List to store the...
Python
jtatman_500k
function __init__ self port frequency begin call __init__ data=join b'' list call pack string >B port call pack string >B frequency max_response_time=0.05 post_processing_time=0.0 min_response_length=0 max_response_length=0 end function
def __init__(self, port, frequency): super(SensorBridgeCmdSetI2cFrequency, self).__init__( data=b"".join([pack(">B", port), pack(">B", frequency)]), max_response_time=0.05, post_processing_time=0.0, min_response_length=0, max...
Python
nomic_cornstack_python_v1
function _async_receive_data self device latitude longitude battery accuracy attributes begin if device != _name begin return end set _latitude = latitude set _longitude = longitude set _battery = battery set _accuracy = accuracy update _attributes attributes call async_write_ha_state end function
def _async_receive_data( self, device, latitude, longitude, battery, accuracy, attributes ): if device != self._name: return self._latitude = latitude self._longitude = longitude self._battery = battery self._accuracy = accuracy self._attributes.u...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup from datetime import date import consulta import insertar import filtro import time set product = list string precios-supermercado string precio-restaurantes string precio-ropa-calzado string precio-transporte-servicios string precio-vivienda-salarios string precio-ocio-dep...
import requests from bs4 import BeautifulSoup from datetime import date import consulta import insertar import filtro import time product = ['precios-supermercado', 'precio-restaurantes', 'precio-ropa-calzado', 'precio-transporte-servicios', 'precio-vivienda-salarios', 'precio-ocio-deportes'] lista_sub_categoria = ['pr...
Python
zaydzuhri_stack_edu_python
function _update_adp_calculation_parallel self Temp begin import multiprocessing import time set start2 = time class Worker extends Process begin string Worker class used for calculating ADPs. function __init__ self data_pointer Tempe message_queue job_queue ID begin call __init__ set data_pointer = data_pointer set Te...
def _update_adp_calculation_parallel(self, Temp): import multiprocessing import time start2 = time.time() class Worker(multiprocessing.Process): """ Worker class used for calculating ADPs. """ def __init__(self, data_pointer, Tempe, mess...
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other IngredientObjectPortions begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, IngredientObjectPortions): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
comment 940. 不同的子序列 II [动态规划] import collections class Solution begin function distinctSubseqII self S begin set length = length S set indexes = default dictionary list for tuple index world in enumerate S begin append indexes at world index end set dp = list 0 * length + 1 set mod_value = 10 ^ 9 + 7 for index in range...
# 940. 不同的子序列 II [动态规划] import collections class Solution: def distinctSubseqII(self, S: str) -> int: length = len(S) indexes = collections.defaultdict(list) for index, world in enumerate(S): indexes[world].append(index) dp = [0] * (length + 1) mod_value = 10 *...
Python
zaydzuhri_stack_edu_python
function join_cameras_as_batch cameras_list begin set c0 = cameras_list at 0 set fields = _FIELDS set shared_fields = _SHARED_FIELDS if not all generator expression is instance c CamerasBase for c in cameras_list begin raise call ValueError string cameras in cameras_list must inherit from CamerasBase end if not all gen...
def join_cameras_as_batch(cameras_list: Sequence[CamerasBase]) ->CamerasBase: c0 = cameras_list[0] fields = c0._FIELDS shared_fields = c0._SHARED_FIELDS if not all(isinstance(c, CamerasBase) for c in cameras_list): raise ValueError('cameras in cameras_list must inherit from CamerasBase') if ...
Python
nomic_cornstack_python_v1
function main begin comment ####### Initialization ####### comment "time_tracker" - timestamp to track running time set total_execution_start = now print string Started main(): + string total_execution_start comment set up environment variables set environment_variables = call set_up_environment_variables set data_tabl...
def main(): # ####### Initialization ####### # "time_tracker" - timestamp to track running time total_execution_start = datetime.now() print("Started main(): " + str(total_execution_start)) # set up environment variables environment_variables = set_up_environment_variables() data_tables_av...
Python
nomic_cornstack_python_v1
function loadProject self project=none begin if project is not none begin call loadProject project end call setWindowTitle string Foundation | %s | %s % tuple project __user__ call setVisible true call buildTree end function
def loadProject(self, project=None): if project is not None: self.foundation.project.loadProject(project) self.setWindowTitle("Foundation | %s | %s" % (self.foundation.project.project, self.foundation.__user__)) self.qf_left.setVisible(True) self.wg_projectTree.buildTree()
Python
nomic_cornstack_python_v1
from django.db import models from ifc.models import IfcModel from robot.models import RobotModel comment This class represents a mission for a robot with a starting point and finishing point class DeplacementMissionModel extends Model begin set ifc = call ForeignKey IfcModel on_delete=CASCADE set name = call CharField ...
from django.db import models from ifc.models import IfcModel from robot.models import RobotModel # This class represents a mission for a robot with a starting point and finishing point class DeplacementMissionModel(models.Model): ifc = models.ForeignKey(IfcModel, on_delete=models.CASCADE) name = models.CharF...
Python
zaydzuhri_stack_edu_python
function count_a_letters substr n begin if length substr >= n begin return call count_a_letters_in_substr substr at slice : n : end return floor n / length substr * call count_a_letters_in_substr substr + call count_a_letters_in_substr substr at slice : n % length substr : end function
def count_a_letters(substr, n): if len(substr) >= n: return count_a_letters_in_substr(substr[:n]) return math.floor(n / len(substr)) * count_a_letters_in_substr(substr) + count_a_letters_in_substr(substr[:n % len(substr)])
Python
nomic_cornstack_python_v1
function startPreprocessing self modelNode textureImageNode targetColor begin print string ----Start Processing---- set startTime = time print string Start time: + string format time time string %Y-%m-%d %H:%M:%S call localtime startTime + string set mainModelNode = modelNode set newPolyData = call vtkPolyData deep cop...
def startPreprocessing(self, modelNode, textureImageNode, targetColor): print("----Start Processing----") startTime = time.time() print("Start time: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(startTime)) + "\n") self.mainModelNode = modelNode newPolyData = vtk.vtkPol...
Python
nomic_cornstack_python_v1
import json import copy import web import datetime from time import strftime set urls = tuple string /rest/users/(.*) string user string /rest/points/(.*) string points comment Return point balance for a specific user comment Add or remove points comment Initialize with a single user, with empty points log comment Entr...
import json import copy import web import datetime from time import strftime urls = ( # Return point balance for a specific user '/rest/users/(.*)', 'user', # Add or remove points '/rest/points/(.*)', 'points' ) # Initialize with a single user, with empty points log # Entries in the array will be in f...
Python
zaydzuhri_stack_edu_python
from sample import create_samples from models import ApartmentSell , ApartmentRent , HouseSell , HouseRent , StoreSell , StoreRent class Handler begin set ADVERTISEMENTS = list ApartmentSell ApartmentRent HouseSell HouseRent StoreSell StoreRent set SWITCHES = dict string r string get_reports ; string t string get_ticke...
from sample import create_samples from models import (ApartmentSell, ApartmentRent, HouseSell, HouseRent, StoreSell, StoreRent) class Handler: ADVERTISEMENTS = [ApartmentSell, ApartmentRent, HouseSell, HouseRent, StoreSell, StoreRent] SWITCHES = { 'r': 'get_re...
Python
zaydzuhri_stack_edu_python
from aisc import url function test_expand begin set short_url = string http://bit.ly set expanded_url = string https://bitly.com/ assert call expand short_url == expanded_url end function function test_replace begin set original = string http://example.com?foo=bar set replaced = string http://example.com?foo=spam asser...
from aisc import url def test_expand(): short_url = "http://bit.ly" expanded_url = "https://bitly.com/" assert url.expand(short_url) == expanded_url def test_replace(): original = "http://example.com?foo=bar" replaced = "http://example.com?foo=spam" assert url.replace(original, {'foo': 'spam...
Python
zaydzuhri_stack_edu_python
comment ********************* GUI CALCULATOR *************************** import tkinter from tkinter import * from tkinter.font import Font from tkinter import messagebox comment Global declaration set val = string set A = 0 set operator = string comment button functions function btn_1_isclicked begin comment Scope o...
#********************* GUI CALCULATOR *************************** import tkinter from tkinter import * from tkinter.font import Font from tkinter import messagebox #Global declaration val = "" A = 0 operator = "" #button functions def btn_1_isclicked() : global val ...
Python
zaydzuhri_stack_edu_python
function __init__ self logits p=0.1 clinical=false freeze_embeddings=false pretrain_path=none begin call __init__ if pretrain_path is not none begin set bert = call from_pretrained pretrain_path end else if clinical begin set bert = call from_pretrained string emilyalsentzer/Bio_ClinicalBERT end else begin set bert = c...
def __init__(self, logits, p=0.1, clinical=False, freeze_embeddings=False, pretrain_path=None): super(bert_encoder, self).__init__() if pretrain_path is not None: self.bert = BertModel.from_pretrained(pretrain_path) elif clinical: self.bert = AutoModel.from_pretrained("e...
Python
nomic_cornstack_python_v1
from pyspark import SparkContext as sc from pyspark import SparkConf set conf = call setMaster string local[*] set sc = call getOrCreate conf set text_file = call textFile string hdfs://localhost:9000/user/chikuo/evaluate.txt print first text_file set worldCount = call reduceByKey lambda a b -> a + b print call collect
from pyspark import SparkContext as sc from pyspark import SparkConf conf = SparkConf().setAppName("miniProject").setMaster("local[*]") sc = sc.getOrCreate(conf) text_file = sc.textFile("hdfs://localhost:9000/user/chikuo/evaluate.txt") print(text_file.first()) worldCount = text_file.flatMap(lambda line: line.split("...
Python
zaydzuhri_stack_edu_python
function resilience_constraint self resilience_constraint begin set _resilience_constraint = resilience_constraint end function
def resilience_constraint(self, resilience_constraint: List[ResilienceConstraint]): self._resilience_constraint = resilience_constraint
Python
nomic_cornstack_python_v1
function byte value begin if is instance value str and length value == 1 begin return ordinal value end else if is instance value int begin if value > 127 begin return call byte value - 256 end if value < - 128 begin return call byte 256 + value end return value end end function
def byte(value): if isinstance(value, str) and len(value) == 1: return ord(value) elif isinstance(value, int): if value > 127: return byte(value - 256) if value < -128: return byte(256 + value) return value
Python
nomic_cornstack_python_v1
function factorial n begin string returns n! return if expression n < 2 then 1 else n * call factorial n - 1 end function print directory factorial class C begin pass end class set obj = call C function func begin pass end function print set directory func - set directory obj
def factorial(n): '''returns n!''' return 1 if n < 2 else n * factorial(n-1) print(dir(factorial)) class C: pass obj = C() def func(): pass print(set(dir(func)) - set(dir(obj)))
Python
zaydzuhri_stack_edu_python
function boolean_renderer value field begin comment TODO caching of template set tpl = join path ADMIN2_THEME_DIRECTORY string renderers/boolean.html return call render_to_string tpl dict string value value end function
def boolean_renderer(value, field): # TODO caching of template tpl = os.path.join(settings.ADMIN2_THEME_DIRECTORY, 'renderers/boolean.html') return render_to_string(tpl, {'value': value})
Python
nomic_cornstack_python_v1
import os import spotipy from spotipy import client from api.src.track_data import Track class Spotify begin function __init__ self code begin set client_id = call getenv string SPOTIFY_CLIENT_ID set client_secret = call getenv string SPOTIFY_CLIENT_SECRET set redirect_url = call getenv string SPOTIFY_REDIRECT_URL set ...
import os import spotipy from spotipy import client from api.src.track_data import Track class Spotify(): def __init__(self, code: str): self.client_id = os.getenv('SPOTIFY_CLIENT_ID') self.client_secret = os.getenv('SPOTIFY_CLIENT_SECRET') self.redirect_url = os.getenv('SPOTIFY_REDIRECT_UR...
Python
zaydzuhri_stack_edu_python
function recognize models test_set begin filter warnings string ignore category=DeprecationWarning set probabilities = list set guesses = list set all_Xlengths = ordered dictionary sorted items call get_all_Xlengths key=lambda t -> t at 0 for tuple X length in values all_Xlengths begin set word_probabilities = dict ...
def recognize(models: dict, test_set: SinglesData): warnings.filterwarnings("ignore", category=DeprecationWarning) probabilities = [] guesses = [] all_Xlengths = OrderedDict(sorted(test_set.get_all_Xlengths().items(), key=lambda t: t[0])) for X, length in all_Xlengths.values(): word_probab...
Python
nomic_cornstack_python_v1
import mandrill from django.shortcuts import render from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate , login , logout function new_user request begin set username = POST at string username s...
import mandrill from django.shortcuts import render from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def new_user(request): username = request.POST['username'] password1 =...
Python
zaydzuhri_stack_edu_python
for charac in sen begin if charac in alphabet begin if charac in charac_count begin set charac_count at charac = charac_count at charac + 1 end else begin set charac_count at charac = 1 end end end for i in charac_count begin print i charac_count at i end
for charac in sen: if charac in alphabet: if charac in charac_count: charac_count[charac] += 1 else: charac_count[charac] = 1 for i in charac_count: print(i,charac_count[i])
Python
zaydzuhri_stack_edu_python
import csv from pprint import pprint import pandas as pd import matplotlib.pyplot as plt from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA set news = list with open string fin_news.csv as f begin set reader = dict reader f set data = list comprehension r for r in reader comment remove header pop data ...
import csv from pprint import pprint import pandas as pd import matplotlib.pyplot as plt from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA news = [] with open("fin_news.csv") as f: reader = csv.DictReader(f) data = [r for r in reader] data.pop(0) # remove header x = 0 while x < le...
Python
zaydzuhri_stack_edu_python
function eval_tangent_matrices self state tangent_matrix by_blocks=false begin call set_variables_from_state state evaluate self mode=string weak dw_mode=string matrix asm_obj=tangent_matrix if by_blocks begin set out = dict set get_indx = get_indx for eq in self begin set tuple key rname cname = list comprehension st...
def eval_tangent_matrices(self, state, tangent_matrix, by_blocks=False): self.set_variables_from_state(state) self.evaluate(mode='weak', dw_mode='matrix', asm_obj=tangent_matrix) if by_blocks: out = {} get_indx = self.variables.get_indx for eq in self: ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Oct 3 12:47:35 2019 @author: Kevin function gravTorques mu R c I begin set cx = c at 0 set cy = c at 1 set cz = c at 2 set Ix = I at 0 set Iy = I at 1 set Iz = I at 3 set Mx = 3 * mu / R ? 3 * Iz - Iy * cy * cz set My = 3 * mu / R ? 3 * Ix - Iz * cz * cx set Mz = 3 * ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 3 12:47:35 2019 @author: Kevin """ def gravTorques(mu,R,c,I): cx = c[0] cy = c[1] cz = c[2] Ix = I[0] Iy = I[1] Iz = I[3] Mx = 3*mu/R^3 * (Iz - Iy) * cy * cz My = 3*mu/R^3 * (Ix - Iz) * cz * cx Mz = 3*mu/R^3 * (Iy - Ix) * cx * cy M...
Python
zaydzuhri_stack_edu_python
function _objectListGenerator self request objectList begin string Returns a generator over the objects in the specified list using _topLevelObjectGenerator to generate page tokens. return call _topLevelObjectGenerator request length objectList lambda index -> objectList at index end function
def _objectListGenerator(self, request, objectList): """ Returns a generator over the objects in the specified list using _topLevelObjectGenerator to generate page tokens. """ return self._topLevelObjectGenerator( request, len(objectList), lambda index: objectList[ind...
Python
jtatman_500k
function _split_asteroid self asteroid asteroid_hit_speed new_asteroids_pos torpedo_speed begin set new_x_speed = call _asteroid_new_axis_speed X_AXIS asteroid_hit_speed torpedo_speed set new_y_speed = call _asteroid_new_axis_speed Y_AXIS asteroid_hit_speed torpedo_speed if call get_size == BIGGEST_SIZE_ASTEROID begin ...
def _split_asteroid(self, asteroid, asteroid_hit_speed, new_asteroids_pos, torpedo_speed): new_x_speed = self._asteroid_new_axis_speed(X_AXIS, asteroid_hit_speed, torpedo_speed) ...
Python
nomic_cornstack_python_v1
function add_in self delay fn_process *args **kwargs begin string Adds a process to the simulation, which is made to start after the given delay in simulated time. See method add() for more details. set process = process self fn_process _gr if _logger is not none begin call _log INFO string add __now=now fn=fn_process ...
def add_in(self, delay: float, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process': """ Adds a process to the simulation, which is made to start after the given delay in simulated time. See method add() for more details. """ process = Process(self, fn_process, self._gr...
Python
jtatman_500k
function evaluate formula model begin assert call is_model model assert call issubset call variables model comment Task 2.1 set root = root if call is_variable root begin return model at root end else if call is_constant root begin return root == string T end else if call is_unary root begin return not evaluate first m...
def evaluate(formula: Formula, model: Model) -> bool: assert is_model(model) assert formula.variables().issubset(variables(model)) # Task 2.1 root = formula.root if is_variable(root): return model[root] elif is_constant(root): return root == 'T' elif is_unary(root): ...
Python
nomic_cornstack_python_v1
function get_words self begin return _words end function
def get_words(self): return self._words
Python
nomic_cornstack_python_v1
set A = integer input set B = integer input set N = integer input set cost = N * 100 * A + B print cost // 100 cost % 100
A = int(input()) B = int(input()) N = int(input()) cost = N * (100 * A + B) print(cost // 100, cost % 100)
Python
zaydzuhri_stack_edu_python
import pygame class level begin function __init__ self bg b_hitboxes s_hitboxes state begin set LIGHTBG = call convert set DARKBG = call convert comment True = light comment False = dark set STATE = state set platGroup = call Group add platGroup s_hitboxes set bigGroup = call Group add bigGroup b_hitboxes set currentBa...
import pygame class level: def __init__(self, bg, b_hitboxes ,s_hitboxes ,state): self.LIGHTBG = pygame.image.load(bg[0]).convert() self.DARKBG = pygame.image.load(bg[1]).convert() #True = light #False = dark self.STATE = state self.platGroup = pygame.sprite.Group(...
Python
zaydzuhri_stack_edu_python
function alias_bank self bank_id alias_id begin pass end function
def alias_bank(self, bank_id, alias_id): pass
Python
nomic_cornstack_python_v1
if mark >= 70 begin print string You scored an A end else if mark >= 60 begin print string You scored a B end else if mark >= 50 begin print string You scored a C end else begin print string You failed the test. end
if (mark >= 70): print("You scored an A") elif (mark >= 60): print("You scored a B") elif (mark >= 50): print("You scored a C") else: print("You failed the test.")
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np set img = call imread string lena.jpg set tuple height width = shape at slice : 2 : set tuple start_row start_col = tuple integer height * 0.25 integer width * 0.25 set tuple end_row end_col = tuple integer height * 0.75 integer width * 0.75 set cropped = img at tuple slice start_row : e...
import cv2 import numpy as np img=cv2.imread("lena.jpg") height,width=img.shape[:2] start_row,start_col=int(height*.25),int(width*.25) end_row,end_col=int(height*.75),int(width*.75) cropped=img[start_row:end_row,start_col:end_col] cv2.imshow("Original",img) cv2.waitKey(0) cv2.imshow("Cropped image",c...
Python
zaydzuhri_stack_edu_python
function get_menu_choice begin print string Contacts and Their Email Addresses print string 1. Look up a contact print string 2. Add a new contact print string 3. Edit a contact print string 4. Delete a contact print string 5. Quit set choice = integer input string Enter your choice: while choice < LOOK_UP or choice > ...
def get_menu_choice(): print('Contacts and Their Email Addresses') print('1. Look up a contact') print('2. Add a new contact') print('3. Edit a contact') print('4. Delete a contact') print('5. Quit\n') choice = int(input('Enter your choice: ')) while choice < LOOK_UP or choic...
Python
zaydzuhri_stack_edu_python