code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
with open string Day24.txt as f begin set content = split read f string end print content set dict = list for l in content begin set tuple x y z = tuple 0 0 0 while l begin if starts with l string e begin set x = x + 1 set y = y - 1 set l = l at slice 1 : : end else if starts with l string se begin set y = y - 1 set...
with open('Day24.txt') as f: content = f.read().split('\n') print(content) dict = [] for l in content: x, y, z = 0, 0, 0 while l: if l.startswith('e'): x += 1 y -= 1 l = l[1:] elif l.startswith('se'): y -= 1 z += 1 l =...
Python
zaydzuhri_stack_edu_python
function connection self begin set ctx = top if ctx is not none begin if not has attribute ctx string simple_connection begin set simple_connection = call connect_to_region config at string AWS_REGION aws_access_key_id=config at string AWS_ACCESS_KEY_ID aws_secret_access_key=config at string AWS_SECRET_ACCESS_KEY end r...
def connection(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'simple_connection'): ctx.simple_connection = connect_to_region( self.app.config['AWS_REGION'], aws_access_key_id = self.app.config['AWS_ACCESS_KEY_ID'], ...
Python
nomic_cornstack_python_v1
function setup_test_data db begin set sub = call make string submissions.SubmissionAttributes submission_id=1 reporting_fiscal_year=2019 reporting_fiscal_period=3 set agencies = list call make string references.ToptierAgency toptier_code=string 123 abbreviation=string ABC name=string Test Agency call make string refere...
def setup_test_data(db): sub = mommy.make( "submissions.SubmissionAttributes", submission_id=1, reporting_fiscal_year=2019, reporting_fiscal_period=3 ) agencies = [ mommy.make("references.ToptierAgency", toptier_code="123", abbreviation="ABC", name="Test Agency"), mommy.make("referen...
Python
nomic_cornstack_python_v1
function calc_min_max npn_heights hrrr_heights begin try begin set npn_max_height = max set npn_min_height = min set hrrr_max_height = max set hrrr_min_height = min set global_max_height_1 = min npn_max_height hrrr_max_height set global_max_height = if expression global_max_height_1 > 0 then global_max_height_1 else 10...
def calc_min_max(npn_heights, hrrr_heights): try: npn_max_height = npn_heights.max() npn_min_height = npn_heights.min() hrrr_max_height = hrrr_heights.max() hrrr_min_height = hrrr_heights.min() global_max_height_1 = min(npn_max_height, hrrr_max_height) global_max_heig...
Python
nomic_cornstack_python_v1
function info *objects file=stderr flush=true style=none **kwargs begin with call ScopedColoredStream file style flush_on_exit=flush as stream begin print *objects file=stream flush=false keyword kwargs end end function
def info(*objects, file=sys.stderr, flush=True, style=None, **kwargs): with ScopedColoredStream(file, style, flush_on_exit=flush) as stream: print(*objects, file=stream, flush=False, **kwargs)
Python
nomic_cornstack_python_v1
class UnionFind begin comment https://note.nkmk.me/python-union-find/ comment note.nkmk.me 2019-08-18 function __init__ self n begin set n = n set parents = list - 1 * n end function function find self x begin if parents at x < 0 begin return x end else begin set parents at x = find self parents at x return parents at ...
class UnionFind(): #https://note.nkmk.me/python-union-find/ #note.nkmk.me 2019-08-18 def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]...
Python
zaydzuhri_stack_edu_python
function test_x_shape self begin comment invalid inputs for x in list call placeholder float32 list none 5 call placeholder float32 list none 5 4 8 call placeholder float32 list 1 5 4 8 call placeholder float32 tuple begin with assert raises ValueError begin call vector_quantization x 2 end end comment valid input call...
def test_x_shape(self) -> None: # invalid inputs for x in [ tf.placeholder(tf.float32, [None, 5]), tf.placeholder(tf.float32, [None, 5, 4, 8]), tf.placeholder(tf.float32, [1, 5, 4, 8]), tf.placeholder(tf.float32, ()) ]: with self.assert...
Python
nomic_cornstack_python_v1
function download_file url local_filename begin set response = get requests url stream=true with open local_filename string wb as file_handle begin for chunk in call iter_content chunk_size=1024 begin comment filter out keep-alive new chunks if chunk begin write file_handle chunk end end end return local_filename end f...
def download_file(url, local_filename): response = requests.get(url, stream=True) with open(local_filename, 'wb') as file_handle: for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks file_handle.write(chunk) return local_filen...
Python
nomic_cornstack_python_v1
string Module for all geometry classes and methods that are used in multiple modules import numpy as np class DoubleCircle begin function __init__ self position pos_orientation neg_orientation begin set position = position set pos_orientation = pos_orientation set neg_orientation = neg_orientation set sign = none end f...
""" Module for all geometry classes and methods that are used in multiple modules """ import numpy as np class DoubleCircle: def __init__(self, position, pos_orientation, neg_orientation): self.position = position self.pos_orientation = pos_orientation self.neg_orientation = neg_orientatio...
Python
zaydzuhri_stack_edu_python
function process_page url scrolls begin set scroll_script = string window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight;return lenOfPage; set options = call ChromeOptions call add_argument string headless set browser = call Chrome chrome_options=options get browser url set lenOfPage ...
def process_page(url: str, scrolls: int): scroll_script = "window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight;return lenOfPage;" options = webdriver.ChromeOptions() options.add_argument('headless') browser = webdriver.Chrome(chrome_options=options) browser.get(u...
Python
nomic_cornstack_python_v1
comment !/us/bin/python import boto3 function unique sg_list begin string This function is used to fetch unique values from the list. set unique_list = list for x in sg_list begin if x not in unique_list begin append unique_list x end end print unique_list end function function security_group_check begin string This f...
#!/us/bin/python import boto3 def unique(sg_list): """ This function is used to fetch unique values from the list. """ unique_list = [] for x in sg_list: if x not in unique_list: unique_list.append(x) print(unique_list) def security_group_check (): """ ...
Python
zaydzuhri_stack_edu_python
function corner_cases bits=16 begin set cases = list list 0 1 0 2 ^ bits - 1 2 ^ bits - 2 list 1 1 1 0 0 list 2 ^ bits - 1 2 ^ bits - 2 2 ^ bits - 3 2 ^ bits - 4 2 ^ bits / 2 for case in cases begin for variation in permutations case begin yield variation end end end function
def corner_cases(bits=16): cases = [[0, 1, 0, 2**bits-1, 2**bits-2], [1, 1, 1, 0, 0], [2**bits-1, 2**bits-2, 2**bits-3, 2**bits-4, 2**bits/2]] for case in cases: for variation in itertools.permutations(case): y...
Python
nomic_cornstack_python_v1
import re import pandas as pd from requests_html import HTMLSession from fake_useragent import UserAgent import random import time function googlescraper query begin print string 關鍵字: query set query = replace query string string + set ua = call UserAgent set session = call HTMLSession set results = list for num in r...
import re import pandas as pd from requests_html import HTMLSession from fake_useragent import UserAgent import random import time def googlescraper(query): print('關鍵字:', query) query = query.replace(' ', '+') ua = UserAgent() session = HTMLSession() results = [] for num in r...
Python
zaydzuhri_stack_edu_python
function __itruediv__ self other begin call set_self call __truediv__ other return call __truediv__ other end function
def __itruediv__(self, other): self.set_self(self.__truediv__(other)) return self.__truediv__(other)
Python
nomic_cornstack_python_v1
function modify self new_state=in_place begin if new_state is not in_place begin set state = new_state end for element in call get_downstream_dependencies begin add _dirty at __name__ element end return self end function
def modify(self, new_state=in_place): if new_state is not link._instance.in_place: self.state = new_state for element in self.get_downstream_dependencies(): link._dirty[element.func.__name__].add(element) return self
Python
nomic_cornstack_python_v1
function separate data begin set ldata = copy data set aug_data = call matrix map augment_sample ldata set n = shape at 0 set wt_dimensions = shape at 1 comment Intial weigth vector set w = T set total_count = 0 comment Learning rate set eta = 1 comment Main loop for the batch perceptron while true begin set total_coun...
def separate(data): ldata = data.copy() aug_data = np.matrix(map(augment_sample, ldata)) n = aug_data.shape[0] wt_dimensions = aug_data.shape[1] # Intial weigth vector w = np.matrix(np.zeros(wt_dimensions)).T total_count = 0 # Learning rate eta = 1 # Main loop for the batch perc...
Python
nomic_cornstack_python_v1
function getint self key begin return integer call __getitem__ key end function
def getint(self, key): return int(self.__getitem__(key))
Python
nomic_cornstack_python_v1
comment store.py comment Lowes comment Created by Noah Christiano on 7/21/2014. comment noahchristiano@rochester.edu class Store begin set country = string set state = string set town = string set address = string set store_number = string function set_state self string begin set state = string set canada = list s...
# store.py # Lowes # Created by Noah Christiano on 7/21/2014. # noahchristiano@rochester.edu class Store(): country = '' state = '' town = '' address = '' store_number = '' def set_state(self, string): self.state = string canada = ['Alberta', 'Ontario', 'British Columbia', 'Saskatchewan'] if string in can...
Python
zaydzuhri_stack_edu_python
function contact request begin assert is instance request HttpRequest return call render request string app/contact.html dict string title string Contact ; string message string Ramapriya's contact page. ; string year year end function
def contact(request): assert isinstance(request, HttpRequest) return render( request, 'app/contact.html', { 'title':'Contact', 'message':'Ramapriya\'s contact page.', 'year':datetime.now().year, } )
Python
nomic_cornstack_python_v1
function update_completed self update begin acquire mutex_downloaded set downloaded_images = downloaded_images + update release mutex_downloaded end function
def update_completed(self, update : int) -> NoReturn: self.mutex_downloaded.acquire() self.downloaded_images += update self.mutex_downloaded.release()
Python
nomic_cornstack_python_v1
import math function quadratic a b c begin set A = b ^ 2 - 4 * a * c if A >= 0 begin set x = - b + square root b * b - 4 * a * c / 2 * a set y = - b - square root b * b - 4 * a * c / 2 * a return tuple x y end else begin return string Without solution end end function set a = integer input string a= set b = integer inp...
import math def quadratic(a,b,c): A = b**2 - 4*a*c if A>= 0: x = (-b + math.sqrt(b*b - 4*a*c))/(2*a) y = (-b - math.sqrt(b*b - 4*a*c))/(2*a) return(x,y) else: return('Without solution') a = int(input('a=')) b = int(input('b=')) c = int(input('c=')) print(quadratic(a,b,c))
Python
zaydzuhri_stack_edu_python
function run begin set programPointer = length PROGRAM - 1 set step = 0 while step == 0 or call getMinExpectedNumber > 0 begin call simulationStep set programPointer = min programPointer + 1 length PROGRAM - 1 set no = call getLastStepVehicleNumber string 0 if no > 0 begin set programPointer = if expression programPoin...
def run(): programPointer = len(PROGRAM)-1 step = 0 while step == 0 or traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() programPointer = min(programPointer+1, len(PROGRAM)-1) no = traci.inductionloop.getLastStepVehicleNumber("0") if no > 0: prog...
Python
nomic_cornstack_python_v1
function _pcloud_path_standardise p begin return string / + strip p string / end function
def _pcloud_path_standardise(p): return '/' + p.strip('/')
Python
nomic_cornstack_python_v1
function prepare self begin set fname = call getstyle string obj-filename if fname begin set obj = call get_obj fname end else begin set obj = none end end function
def prepare(self): fname = self.getstyle("obj-filename") if fname: self.obj = get_obj(fname) else: self.obj = None
Python
nomic_cornstack_python_v1
function costFun self x begin set tmp = reshape x inp_shape set c = call float64 call calcCost call asarray tmp dtype=float32 + alpha * dot T x return c end function
def costFun(self, x): tmp = x.reshape(self.inp_shape) c = np.float64(self.calcCost(np.asarray(tmp,dtype=np.float32))) + self.alpha * np.dot(x.T, x) return c
Python
nomic_cornstack_python_v1
from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError from xml.etree import ElementTree class XMLAssertions extends object begin function assertXPathNodeCount self xml_str num xpath begin set doc = call fromstring xml_str assert equal num length find all xpath end function function assertXPat...
from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError from xml.etree import ElementTree class XMLAssertions(object): def assertXPathNodeCount(self, xml_str, num, xpath): doc = ElementTree.fromstring(xml_str) self.assertEqual(num, len(doc.findall(xpath))) def assert...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , redirect , HttpResponse from django.contrib import messages from models import Course , Description , Comment comment Create your views here. function index request begin set context = dict string courses all return call render request string index.html context end function comment...
from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from .models import Course, Description, Comment # Create your views here. def index(request): context = { 'courses': Course.objects.all() } return render(request,'index.html', context) # return H...
Python
zaydzuhri_stack_edu_python
function policy_eps_suboptimal env optimal_policy epsilon=0 begin return epsilon * call policy_random env + 1 - epsilon * optimal_policy end function
def policy_eps_suboptimal(env, optimal_policy, epsilon=0): return epsilon * policy_random(env) + (1 - epsilon) * optimal_policy
Python
nomic_cornstack_python_v1
function with_secondary_colour self colour begin set __secondary_colour = colour return self end function
def with_secondary_colour(self, colour): self.__secondary_colour = colour return self
Python
nomic_cornstack_python_v1
function measure_uvot_flux galaxy reg foreground_reg=list coi_mask=none region_image=none **kwargs begin set uvotbands = list string w1 string w2 string m2 set tuple fluxes uncertainties = tuple list list for band in uvotbands begin set tuple hdr images masks = call load_uvot_images galaxy band keyword kwargs set tu...
def measure_uvot_flux(galaxy, reg, foreground_reg=[], coi_mask=None, region_image=None, **kwargs): uvotbands = ['w1', 'w2', 'm2'] fluxes, uncertainties = [], [] for band in uvotbands: hdr, images, masks = load_uvot_images(galaxy, band, **kwargs) cps, exp, resp = images...
Python
nomic_cornstack_python_v1
function printProgressBar iteration total prefix=string suffix=string decimals=1 length=100 fill=string | begin set percent = format string {0:. + string decimals + string f} 100 * iteration / decimal total set filledLength = integer length * iteration // total set bar = fill * filledLength + string - * length - fill...
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '|'): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print (...
Python
nomic_cornstack_python_v1
function chkpt dmc_obj prop_step begin comment calls __deepcopy__ set cheq = deep copy dmc_obj with open string { output_folder } /chkpts/ { sim_name } _ { string prop_step } .pickle string wb as handle begin comment explicit protocol 4 to account for 3.8's upgrade to 5. dump cheq handle protocol=4 end end function
def chkpt(dmc_obj, prop_step): cheq = copy.deepcopy(dmc_obj) # calls __deepcopy__ with open(f'{dmc_obj.output_folder}/chkpts/{dmc_obj.sim_name}_{str(prop_step)}.pickle', 'wb') as handle: pickle.dump(cheq, handle, protocol=4) # explicit protocol 4 to account for 3.8's upgrade to 5.
Python
nomic_cornstack_python_v1
function init_scenario begin set df_gen = read csv join path default_path string generation_projects_info.tab sep=string set column_order = columns comment FIXME: Quick fix to replace tg for turbo_gas set df_gen at string gen_tech = replace df_gen at string gen_tech string tg string turbo_gas set gen_default = read csv...
def init_scenario(): df_gen = pd.read_csv(os.path.join(default_path, 'generation_projects_info.tab'), sep='\t') column_order = df_gen.columns #FIXME: Quick fix to replace tg for turbo_gas df_gen['gen_tech'] = df_gen['gen_tech'].replace('tg', 'turbo_gas') gen_default = pd.read_csv(os.path....
Python
nomic_cornstack_python_v1
function max_cal_year self demand begin set year_position = index names string year set max_service_year = integer max comment return min(current_year, max_service_year) return max_service_year end function
def max_cal_year(self, demand): year_position = getattr(demand, 'raw_values').index.names.index('year') max_service_year = int(getattr(demand, 'raw_values').index.levels[year_position].max()) # return min(current_year, max_service_year) return max_service_year
Python
nomic_cornstack_python_v1
function _result self msg_id begin if __async begin return call _poll msg_id end else begin return call get_result msg_id true end end function
def _result(self, msg_id): if self.__async: return self._poll(msg_id) else: return self.get_result(msg_id, True)
Python
nomic_cornstack_python_v1
function limitPowerTo self limit begin comment Validate input parameter if limit >= 0 and limit <= 1 begin comment Parameter is valid set limit = limit end else begin comment Paramter is invalid return end end function
def limitPowerTo(self, limit): # Validate input parameter if limit >= 0 and limit <= 1: # Parameter is valid self.limit = limit else: # Paramter is invalid return
Python
nomic_cornstack_python_v1
function save_user user begin try begin call create uuid=user at string uuid user_name=user at string user_name return call response true end except Exception as e begin comment TODO: log exceptions print e return call response false message=string Exception thrown, check logs end end function
def save_user(user: dict) -> response: try: DB.UserModel.create(uuid=user["uuid"], user_name=user["user_name"]) return response(True) except Exception as e: # TODO: log exceptions print(e) return response(False, message="Exception thrown, check...
Python
nomic_cornstack_python_v1
import logging from utils.phases import * comment parent (abstract) class for a phase comment this still needs to be finished, I just wanted to move comment on to making an implementation to get a better idea of comment what's going on here comment THIS IS ONLY INTENDED TO SPECIFY WHAT SYSTEM ACCESS FUNCTIONS comment A...
import logging from utils.phases import * # parent (abstract) class for a phase # # this still needs to be finished, I just wanted to move # on to making an implementation to get a better idea of # what's going on here # THIS IS ONLY INTENDED TO SPECIFY WHAT SYSTEM ACCESS FUNCTIONS # ARE NEEDED, NOTHING ELSE class P...
Python
zaydzuhri_stack_edu_python
comment 打印一个 5*5 matrix(while loop) function matrix begin string this method is to print a 5*5 matrix set i = 0 while i < 5 begin set j = 0 while j < 5 begin print string * end=string set j = j + 1 end comment 一行打印结束,换行 print set i = i + 1 end end function
#打印一个 5*5 matrix(while loop) def matrix(): """ this method is to print a 5*5 matrix """ i = 0 while i<5: j=0 while j<5: print("* ",end="") j+=1 #一行打印结束,换行 print() i+=1
Python
zaydzuhri_stack_edu_python
function matchLongestRE stream tokens begin set kind = none set block = string for tuple k r in tokenTypes begin set m = match text if m begin set g = call group comment sys.stderr.write('%s: %s'%(k,g)) if length g > length block begin set kind = k set block = g end end end if kind begin if not call isSkipType kind be...
def matchLongestRE(stream,tokens): kind = None; block = '' for k,r in tokenTypes: m = r.match(stream.text) if m: g = m.group() #sys.stderr.write('%s: %s'%(k,g)) if len(g) > len(block): kind = k ...
Python
nomic_cornstack_python_v1
function set_params self *argv **kwargs begin pass end function
def set_params(self, *argv, **kwargs): pass
Python
nomic_cornstack_python_v1
for n in range 50 10 - 1 begin print n end
for n in range(50,10,-1) : print(n)
Python
zaydzuhri_stack_edu_python
comment noqa: E501 function add_book body begin set cnx = call connect keyword DB_CONFIG set cursor = call cursor buffered=true set author_id = call get_author cursor body comment insert book set add_book = string INSERT INTO books (isbn, name, price, availability, authorId) VALUES (%s, %s, %s, %s, %s) set data_book = ...
def add_book(body): # noqa: E501 cnx = mysql.connector.connect(**config.DB_CONFIG) cursor = cnx.cursor(buffered=True) author_id = get_author(cursor, body) # insert book add_book = ("INSERT INTO books " "(isbn, name, price, availability, authorId) " "VALUES (%s, %s, %s...
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin import csv import json import os import sys import json import datetime import time set dictValue = dict set dictEffectiveFrom = dict set dictEffectiveTo = dict set dictSystemFrom = dict set dictSystemTo = dict set dictRest = dict set dictRest at string data = dict function r...
if __name__=='__main__': import csv import json import os import sys import json import datetime import time dictValue = {} dictEffectiveFrom = {} dictEffectiveTo = {} dictSystemFrom = {} dictSystemTo = {} dictRest = {} dictRest["data"] = {} def readJson(fi...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import rospy from std_msgs.msg import Int16 import math comment seconds range set period = 4.0 set freq = 1 / period comment peak mm range set range = 800.0 set sim_rate = 60.0 function main begin call init_node string gantry_sim set pub = call Publisher string gantry_pos Int16 queue_size=1...
#!/usr/bin/env python import rospy from std_msgs.msg import Int16 import math period = 4.0 # seconds range freq = 1 / period range = 800.0 # peak mm range sim_rate = 60.0 def main(): rospy.init_node('gantry_sim') pub = rospy.Publisher('gantry_pos', Int16, queue_size=10) time = 0.0 r = rospy.Rate(...
Python
zaydzuhri_stack_edu_python
function similarity_score self comparing_doctor begin set score = 0 set score_points = dict string specialty 3 ; string area 2 ; string score 1 comment Largest factor because the doctors have the same profession if specialty == specialty begin set score = score + score_points at string specialty end if area == area beg...
def similarity_score(self, comparing_doctor): score = 0 score_points = { 'specialty': 3, # Largest factor because the doctors have the same profession 'area': 2, 'score': 1 }; if self.specialty == comparing_doctor.specialty: score += score_points['specialty'] if self.area == comparing_doctor.ar...
Python
nomic_cornstack_python_v1
import pandas as pd import ast import json comment def compare_dataframes_by_column( comment df1, comment df2, comment comparison_column comment ): comment return comment def get_data_frame_comparison( comment df1, comment df2, comment comparison_column comment ): comment result = { comment "no_of_duplicate_records_by_...
import pandas as pd import ast import json # def compare_dataframes_by_column( # df1, # df2, # comparison_column # ): # return # # def get_data_frame_comparison( # df1, # df2, # comparison_column # ): # result = { # "no_of_duplicate_records_by_code": None, # "index_of_new_record":...
Python
zaydzuhri_stack_edu_python
function match_ans answer user begin set n = length user set k = 0 for idx in range length answer begin if answer at idx == user at idx % n begin set k = k + 1 end end return k end function function solution answers begin comment define patterns set a = list 1 2 3 4 5 set b = list 2 1 2 3 2 4 2 5 set c = list 3 3 1 1 2...
def match_ans(answer:list, user:list): n = len(user) k = 0 for idx in range(len(answer)): if answer[idx] == user[idx%n]: k += 1 return k def solution(answers:list): # define patterns a = [1,2,3,4,5] b = [2,1,2,3,2,4,2,5] c = [3,3,1,1,2,2,4,4,5,5] _user = [] # 유저...
Python
zaydzuhri_stack_edu_python
function _fight_action self fight_action begin set move_effects = call get_effects set hp = hp + hp if hp < 0 begin set hp = 0 end else if hp > stats at HP begin set hp = stats at HP end for tuple staged_stat value in items staged_stats begin if value > 0 begin set staged_stats at staged_stat = min 6 staged_stats at st...
def _fight_action(self, fight_action: FightActionModel) -> None: move_effects = fight_action.get_effects() fight_action.defender.hp = fight_action.defender.hp + move_effects.hp if fight_action.defender.hp < 0: fight_action.defender.hp = 0 elif fight_action.defender.hp > fig...
Python
nomic_cornstack_python_v1
function click_handler self event begin if game_status == 0 and 0 <= x <= canvas_size and 0 <= y <= canvas_size begin comment Compute board_x and board_y set board_x = integer x - line_space / line_space + line_width + 0.5 set board_y = integer y - line_space / line_space + line_width + 0.5 call place_piece tuple board...
def click_handler(self, event): if self.game_status == 0 and 0 <= event.x <= canvas_size and 0 <= event.y <= canvas_size: # Compute board_x and board_y board_x = int((event.x - self.line_space) / (self.line_space + line_width) + 0.5) board_y = int((e...
Python
nomic_cornstack_python_v1
function snakeviz_magic line cell=none begin comment get location for saved profile set filename = name comment call signature for prun set line = string -q -D + filename + string + line comment generate the stats file using IPython's prun magic set ip = call get_ipython if cell begin call run_cell_magic string prun l...
def snakeviz_magic(line, cell=None): # get location for saved profile filename = tempfile.NamedTemporaryFile().name # call signature for prun line = '-q -D ' + filename + ' ' + line # generate the stats file using IPython's prun magic ip = get_ipython() if cell: ip.run_cell_magic(...
Python
nomic_cornstack_python_v1
string Class for handling rational numbers function gcd a b begin string Use Euclid's algorithm to compute the greatest common divisor of two natural numbers. if b == 0 begin return a end else begin return call gcd b a % b end end function class Rational extends object begin function __init__ self numer=none denom=none...
""" Class for handling rational numbers """ def gcd(a, b): """ Use Euclid's algorithm to compute the greatest common divisor of two natural numbers. """ if b == 0: return a else: return gcd(b, a % b) class Rational(object): def __init__(self, numer=None, denom=None): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment ########## 偏函数 ########### comment Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。要注意,这里的偏函数和数学意义上的偏函数不一样。 comment 在介绍函数参数的时候,我们讲到,通过设定参数的默认值,可以降低函数调用的难度。而偏函数也可以做到这一点 import functools comment int()函数可以把字符串转换为整数,当仅传入字符串时,int()函数默认按十进制转换 commen...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ########## 偏函数 ########### # Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。要注意,这里的偏函数和数学意义上的偏函数不一样。 # 在介绍函数参数的时候,我们讲到,通过设定参数的默认值,可以降低函数调用的难度。而偏函数也可以做到这一点 import functools # int()函数可以把字符串转换为整数,当仅传入字符串时,int()函数默认按十进制转换 # 但int()函数还提供额外的base参数,默认值为10。如果传入bas...
Python
zaydzuhri_stack_edu_python
function _async_load_all_buckets self server kv_gen op_type exp kv_store=1 flag=0 only_store_hash=true batch_size=1 pause_secs=1 timeout_secs=30 proxy_client=none begin set tasks = list for bucket in buckets begin set gen = deep copy kv_gen if type != string memcached begin comment tasks.append(self.cluster.async_load...
def _async_load_all_buckets(self, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=30, proxy_client=None): tasks = [] for bucket in self.buckets: gen = copy.deepcop...
Python
nomic_cornstack_python_v1
function handle_out_bound self convo packet begin append convo at string out_pkts packet comment Latency between tap and Server if packet at string tcp at string flags at string SYN and packet at string tcp at string flags at string ACK begin set convo at string syn_ack_ts = packet at string ts comment Server stack pkt...
def handle_out_bound(self, convo, packet): convo['out_pkts'].append(packet) # Latency between tap and Server if packet['tcp']['flags']['SYN'] and packet['tcp']['flags']['ACK']: convo['syn_ack_ts'] = packet['ts'] # Server stack pktponse time c...
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class TwitterBot begin function __init__ self username password begin set username = username set password = password set bot = call Firefox end function function login self begin set bot = bot get bot string https://twitter.com/...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class TwitterBot: def __init__(self, username, password): self.username = username self.password = password self.bot = webdriver.Firefox() def login(self): bot = self.bot bot.get...
Python
zaydzuhri_stack_edu_python
function plot_companies_by_sector df title out_path begin comment Number of companies by sector set sectored_df = group by df string Industry set sectored_df = call agg dict string Stock Ticker string nunique set sectored_df = reset index sectored_df comment Plot set style=string whitegrid title plt title set ax = call...
def plot_companies_by_sector(df, title, out_path): # Number of companies by sector sectored_df = df.groupby("Industry") sectored_df = sectored_df.agg({"Stock Ticker": "nunique"}) sectored_df = sectored_df.reset_index() # Plot sns.set(style="whitegrid") plt.title(title) ax = sns.barplot(...
Python
nomic_cornstack_python_v1
comment 파이썬 기초 코딩 comment print 구문 예제 comment 기본 출력 print string HELLO PYTHON print string HELLO PYTHON print string HELLO PYTHON print string HELLO PYTHON print comment Seperator 옵션 comment TEST print string T string E string S string T sep=string comment 2019-02-19 print string 2019 string 02 string 19 sep=string - c...
# 파이썬 기초 코딩 # print 구문 예제 # 기본 출력 print('HELLO PYTHON') print("HELLO PYTHON") print("""HELLO PYTHON""") print('''HELLO PYTHON''') print() # Seperator 옵션 print('T', 'E', 'S', 'T', sep='') # TEST print('2019', '02', '19', sep='-') # 2019-02-19 print('niceman', 'google.com', sep='@') # niceman@google.com # end 옵션 사...
Python
zaydzuhri_stack_edu_python
function test_condition_vars self begin comment If condition variables didn't work, a ``NameError`` would be raised. assert raises NotImplementedError where string c_string > bound dict string bound 0 function where_with_locals begin comment this wouldn't cause an error set bound = string foo comment silence pyflakes w...
def test_condition_vars(self): # If condition variables didn't work, a ``NameError`` would be raised. self.assertRaises(NotImplementedError, self.table.where, 'c_string > bound', {'bound': 0}) def where_with_locals(): bound = 'foo' # this wouldn't cause a...
Python
nomic_cornstack_python_v1
function save_shortcuts self begin string Save shortcuts from table model. call check_shortcuts for shortcut in shortcuts begin save end end function
def save_shortcuts(self): """Save shortcuts from table model.""" self.check_shortcuts() for shortcut in self.source_model.shortcuts: shortcut.save()
Python
jtatman_500k
function test_fma_invalid_param_intnum_floatnum_intarray_str_809 self begin comment This version is expected to pass. call fma floatarrayx floatnumy floatarrayz floatarrayout comment This is the actual test. with assert raises TypeError begin call fma intnumx floatnumy intarrayz strout end end function
def test_fma_invalid_param_intnum_floatnum_intarray_str_809(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz, self.floatarrayout) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.intnumx, self.floatnumy, self.intarray...
Python
nomic_cornstack_python_v1
function get_ssh_keylist_by_name manager name begin set all_ssh_keys = call get_all_sshkeys set ssh_keys = list for key in all_ssh_keys begin if name == name begin append ssh_keys key end end return ssh_keys end function
def get_ssh_keylist_by_name(manager, name): all_ssh_keys = manager.get_all_sshkeys() ssh_keys = [] for key in all_ssh_keys: if key.name == name: ssh_keys.append(key) return ssh_keys
Python
nomic_cornstack_python_v1
function pushZeroesToEnd arr begin set length = length arr set count = 0 for i in range 0 length begin if arr at i != 0 begin set arr at count = arr at i set count = count + 1 end end while count < length begin set arr at count = 0 set count = count + 1 end end function comment Read input as specified in the question. ...
def pushZeroesToEnd(arr): length = len(arr) count = 0 for i in range(0,length): if arr[i] != 0: arr[count] = arr[i] count = count + 1 while count < length: arr[count] = 0 count = count + 1 ## Read input as specified in the question. n = int(input()) ar...
Python
zaydzuhri_stack_edu_python
function task_detail username task_id begin set profile = call get_profile username if profile begin set task = get query task_id if task in tasks begin set output = dict string username username ; string task call to_dict set response = call Response mimetype=string application/json response=dumps output return call a...
def task_detail(username, task_id): profile = get_profile(username) if profile: task = Task.query.get(task_id) if task in profile.tasks: output = {'username': username, 'task': task.to_dict()} response = Response( mimetype="application/json", ...
Python
nomic_cornstack_python_v1
function GrabRevision c begin try begin return integer revision end except TypeError begin return 0 end end function
def GrabRevision(c): try: return int(c.revision) except TypeError: return 0
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torch.nn.functional as F set HIDDEN_SIZE = 200 set LSTM_LAYERS = 1 set LSTM_FEATUES = 10 function weights_init_ m begin if is instance m Linear begin call xavier_uniform_ weight gain=1 call constant_ bias 0 end end function class Critic extends Module begin function __init__ se...
import torch import torch.nn as nn import torch.nn.functional as F HIDDEN_SIZE = 200 LSTM_LAYERS = 1 LSTM_FEATUES = 10 def weights_init_(m): if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight, gain=1) torch.nn.init.constant_(m.bias, 0) class Critic(nn.Module): def __init__...
Python
zaydzuhri_stack_edu_python
function random_horizontal_filp self img p=0.5 begin if call decision p begin set img = call flip img 1 end return img end function
def random_horizontal_filp(self, img, p = 0.5): if self.decision(p): img = cv2.flip(img, 1) return img
Python
nomic_cornstack_python_v1
from threading import Thread from Queue import Queue from uber_rides.session import Session from uber_rides.client import UberRidesClient from geocoder import google from RouteCalculators import routeCalculator import json comment gloabal variable declared comment bestRoute=[] set startVar = 2 set signal = true set ele...
from threading import Thread from Queue import Queue from uber_rides.session import Session from uber_rides.client import UberRidesClient from geocoder import google from RouteCalculators import routeCalculator import json #gloabal variable declared #bestRoute=[] startVar=2 signal=True elements=0 dictiona...
Python
zaydzuhri_stack_edu_python
comment Treyton Krupp comment CS3910 import csv comment Long data of first table. Format: [[row1], [row2],...] set current_dolla = list comment For 2nd table. Both will be iterated over when read in to set old_dolla = list with open string PythonCSV.csv string rb as csvfile begin comment Read entire csv file into a 2...
#Treyton Krupp #CS3910 import csv current_dolla = [] #Long data of first table. Format: [[row1], [row2],...] old_dolla = [] #For 2nd table. Both will be iterated over when read in to with open('PythonCSV.csv', 'rb') as csvfile: overall = csv.reader(csvfile, delimiter=',') #Read entire csv file into a ...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np from matplotlib import pyplot as plt import argparse set parser = call ArgumentParser call add_argument string path help=string Path to image set args = call parse_args function magnitude_spectrum im begin set f = call fft2 im set fshift = call fftshift f return 20 * log absolute fshift en...
import cv2 import numpy as np from matplotlib import pyplot as plt import argparse parser = argparse.ArgumentParser() parser.add_argument('path', help='Path to image') args = parser.parse_args() def magnitude_spectrum(im): f = np.fft.fft2(im) fshift = np.fft.fftshift(f) return 20*np.log(np.abs(fshift)) ...
Python
zaydzuhri_stack_edu_python
comment install python : to get some additional functionality comment install run : to get run code comment Kerboard shortcut change comment user setting : setting for full interface comment Workspace setting : Setting for just the folder comment change setting : comment type "code runner" and change:- comment 1."clear...
#install python : to get some additional functionality #install run : to get run code #Kerboard shortcut change #user setting : setting for full interface #Workspace setting : Setting for just the folder #change setting : # type "code runner" and change:- # 1."clear output before each run", a new setting,json will ...
Python
zaydzuhri_stack_edu_python
function ssp self begin return voids * 3 + singletons * 2 + doubletons end function
def ssp(self) -> int: return self.voids * 3 + self.singletons * 2 + self.doubletons
Python
nomic_cornstack_python_v1
while true begin set name = read line rawnames write namelist name set temp = read line rawnames set temp = read line rawnames set temp = read line rawnames set temp = read line rawnames set temp = read line rawnames if name == string begin break end end close rawnames close namelist
while True: name = rawnames.readline() namelist.write(name) temp = rawnames.readline() temp = rawnames.readline() temp = rawnames.readline() temp = rawnames.readline() temp = rawnames.readline() if name == '': break rawnames.close() namelist.close()
Python
zaydzuhri_stack_edu_python
import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.floatlayout import FloatLayout comment from kivy.uix.boxlayout import BoxLayout comment from kivy.uix.rst import RstDocument from kivy.uix.actionbar import ActionBar call load_string string <Tab...
import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.floatlayout import FloatLayout # from kivy.uix.boxlayout import BoxLayout # from kivy.uix.rst import RstDocument from kivy.uix.actionbar import ActionBar Builder.load_string(''' <TabbedPanel>...
Python
zaydzuhri_stack_edu_python
comment util functions for the development of this project import re function read_file path begin comment print(path) set file_object = open string { path } string r set file_line = read line file_object return file_line end function function to_lower str_in begin set str_out = string str_in return lower str_out end f...
# util functions for the development of this project import re def read_file(path): # print(path) file_object = open(f'{path}', "r") file_line = file_object.readline() return file_line def to_lower(str_in): str_out = str(str_in) return str_out.lower() def rm_hashtags(str_in, hashes =...
Python
zaydzuhri_stack_edu_python
import random import cv2 import numpy as np import math function calculate_aspect filler begin set x = _WIDTH + filler set y = _HEIGHT + filler return tuple round _DENS * x / 100 round _DENS * y / 100 end function function painter img mat begin set r = tuple 0 0 _HEIGHT + _AR at 1 _WIDTH + _AR at 0 set subdiv = call Su...
import random import cv2 import numpy as np import math def calculate_aspect(filler): x = (_WIDTH + filler) y = (_HEIGHT + filler) return (round((_DENS * x) / 100), round((_DENS * y) / 100)) def painter(img, mat): r = (0, 0, _HEIGHT + _AR[1], _WIDTH + _AR[0]) subdiv = cv2.Subdiv2D(r) ...
Python
zaydzuhri_stack_edu_python
function get_descendant_elements self xpath begin set tmp_xpath = call _chain_xpath xpath set tmp_loc = tuple XPATH tmp_xpath return call until call visibility_of_all_elements_located tmp_loc end function
def get_descendant_elements(self, xpath) -> list: tmp_xpath = self._chain_xpath(xpath) tmp_loc = (By.XPATH, tmp_xpath) return self._wait.until(EC.visibility_of_all_elements_located(tmp_loc))
Python
nomic_cornstack_python_v1
function _generateID self begin return call generate_id end function
def _generateID(self): return generate_id()
Python
nomic_cornstack_python_v1
import sys set input = readline set N = integer input set A_array = list comprehension list map int split input for _ in range N comment print(A_array) set s_index = list 0 * N set ans_date = 1 set finish_player = 0 set match_count = 0 set M = N * N - 1 // 2 set first_flag = 1 while 1 begin set flag = 0 set match_array...
import sys input = sys.stdin.readline N = int(input()) A_array = [list(map(int, input().split())) for _ in range(N)] # print(A_array) s_index = [0] * N ans_date = 1 finish_player = 0 match_count = 0 M = N * (N-1) // 2 first_flag = 1 while(1): flag = 0 match_array = [0] * N if first_flag: match_ca...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: UTF-8 -*- comment autor: Carlos Rueda comment fecha: 2014-02-14 comment mail: carlos.rueda@deimos-space.com import time import datetime import os import sys import MySQLdb as mdb import math function distance origin destination begin set tuple lat1 lon1 = origin set tupl...
#!/usr/bin/env python #-*- coding: UTF-8 -*- # autor: Carlos Rueda # fecha: 2014-02-14 # mail: carlos.rueda@deimos-space.com import time import datetime import os import sys import MySQLdb as mdb import math def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371.137...
Python
zaydzuhri_stack_edu_python
function subscribe_all self obj begin for member_name in directory obj begin set member = get attribute obj member_name set message_types = get attribute member string asab_pubsub_subscribe_to_message_types none if message_types is not none begin for message_type in message_types begin call subscribe message_type membe...
def subscribe_all(self, obj): for member_name in dir(obj): member = getattr(obj, member_name) message_types = getattr(member, 'asab_pubsub_subscribe_to_message_types', None) if message_types is not None: for message_type in message_types: self.subscribe(message_type, member)
Python
nomic_cornstack_python_v1
function get_plugins self project_id begin set content_type = string application/json set project_plugins = plugins set plugins = list for plugin in keys project_plugins begin append plugins dict string id plugin end return dumps plugins end function
def get_plugins(self, project_id): response.content_type = 'application/json' project_plugins = self.server.projects[project_id].plugins plugins = [] for plugin in project_plugins.keys(): plugins.append({'id': plugin}) return json.dumps(plugins)
Python
nomic_cornstack_python_v1
import random import string comment Generate a random character function generate_random_character used_chars begin while true begin set char = random choice ascii_lowercase if char not in used_chars begin return char end end end function comment Generate a string array of length 10 with unique random characters in rev...
import random import string # Generate a random character def generate_random_character(used_chars): while True: char = random.choice(string.ascii_lowercase) if char not in used_chars: return char # Generate a string array of length 10 with unique random characters in reverse alphabeti...
Python
jtatman_500k
import random set random_number = random integer 1 10
import random random_number = random.randint(1, 10)
Python
flytech_python_25k
function _get_campaigns self params begin return call get_campaigns params=dict none params ; none call _state_filter fields=list state_pk end function
def _get_campaigns(self, params): return self._api.account.get_campaigns(params={**params, **self._state_filter()}, fields=[self.state_pk])
Python
nomic_cornstack_python_v1
function signature_ids json_object signature_name supported_algorithms=SUPPORTED_ALGORITHMS begin comment type: (JsonDict, str, Iterable[str]) -> List[str] set key_ids = keys get get json_object string signatures dict signature_name dict return list generator expression key_id for key_id in key_ids if split key_id stri...
def signature_ids( json_object, signature_name, supported_algorithms=SUPPORTED_ALGORITHMS ): # type: (JsonDict, str, Iterable[str]) -> List[str] key_ids = json_object.get("signatures", {}).get(signature_name, {}).keys() return list( key_id for key_id in key_ids if key_id.split(":")[0] in support...
Python
nomic_cornstack_python_v1
function filter_applies search_filter document begin if search_filter is none begin return true end else if is instance search_filter ObjectId begin set search_filter = dict string _id search_filter end for tuple key search in call iteritems search_filter begin set is_match = false for doc_val in call iter_key_candidat...
def filter_applies(search_filter, document): if search_filter is None: return True elif isinstance(search_filter, ObjectId): search_filter = {'_id': search_filter} for key, search in iteritems(search_filter): is_match = False for doc_val in iter_key_candidates(ke...
Python
nomic_cornstack_python_v1
from dashlogger import Logger import config_handler from werkzeug.security import generate_password_hash , check_password_hash import json set d = dict string val string bla ; string abc string def ; string list dict string nested1 string hallo ; string nested2 string hallooo ; string another_list dict string bla strin...
from dashlogger import Logger import config_handler from werkzeug.security import generate_password_hash, check_password_hash import json d = {"val": "bla", "abc": "def", "list": { "nested1": "hallo", "nested2": "hallooo", "another_list": { "bla": "blub", "nested_item": "ok" } }} x = j...
Python
zaydzuhri_stack_edu_python
function plot_sigmoid begin set X = linear space - 10 10 100 set sX = sigmoid X figure figsize=tuple 15 5 x label string $\theta^Tx^{(i)}$ y label string $h(x^{(i)}, \theta)$ plot X sX show end function
def plot_sigmoid(): X = np.linspace(-10, 10, 100) sX = sigmoid(X) plt.figure(figsize=(15,5)) plt.xlabel(r'$\theta^Tx^{(i)}$') plt.ylabel(r'$h(x^{(i)}, \theta)$') plt.plot(X, sX) plt.show()
Python
nomic_cornstack_python_v1
function buyOpenQtyLot self buyOpenQtyLot begin set _buyOpenQtyLot = buyOpenQtyLot end function
def buyOpenQtyLot(self, buyOpenQtyLot): self._buyOpenQtyLot = buyOpenQtyLot
Python
nomic_cornstack_python_v1
comment 随机数字, 重复输入数字去猜, 对的话('终于猜对了'), 错的话('你的答案太大或太小') import random set start = input string 请输入你想输入的开始值: set end = input string 请输入你想输入的结束值: set start = integer start set end = integer end set r = random integer start end comment count计数 set count = 0 while true begin comment count += 1 set count = count + 1 set num ...
#随机数字, 重复输入数字去猜, 对的话('终于猜对了'), 错的话('你的答案太大或太小') import random start = input('请输入你想输入的开始值: ') end = input('请输入你想输入的结束值: ') start = int(start) end = int(end) r = random.randint(start, end) count = 0 #count计数 while True: count = count + 1 #count += 1 num = input('请猜数字: ') num ...
Python
zaydzuhri_stack_edu_python
comment ! usr/bin/python comment --- DOB: v1 - 05 Feb 2015 import numpy as np comment USER INPUTS ############## comment number of dimensions of the system set ndim = 3 comment Default setting is 2 types of atoms set ntyp = 2 comment no of species 1 (i.e. S) set nsp1 = 1 comment no of species 2 (i.e. H) set nsp2 = 3 co...
#! usr/bin/python # --- DOB: v1 - 05 Feb 2015 import numpy as np ################ USER INPUTS ############## ndim = 3 # number of dimensions of the system ntyp = 2 # Default setting is 2 types of atoms nsp1 = 1 # no of species 1 (i.e. S) nsp2 = 3 # no of...
Python
zaydzuhri_stack_edu_python
from util import * decorator apply function apply given index=- 1 begin set tuple lhs rhs = call of Equal assert is_Matrix and is_Matrix assert length _args == length _args set first = call simplify set second = call simplify return tuple first second end function decorator prove function prove Eq begin set tuple a b c...
from util import * @apply def apply(given, index=-1): lhs, rhs = given.of(Equal) assert lhs.is_Matrix and rhs.is_Matrix assert len(lhs._args) == len(rhs._args) first = Equal(Matrix(lhs._args[:index]), Matrix(rhs._args[:index])).simplify() second = Equal(Matrix(lhs._args[index:]), Matrix(rhs._arg...
Python
zaydzuhri_stack_edu_python
from typing import Generator , List , Dict import time import requests from sqlalchemy.exc import OperationalError from storage.base import Base , engine , Session from storage.numbers import Diaposon , Operator , Location function get_data begin string Getting csv numbers data from rossvyaz.ru set links = tuple string...
from typing import Generator, List, Dict import time import requests from sqlalchemy.exc import OperationalError from storage.base import ( Base, engine, Session, ) from storage.numbers import ( Diaposon, Operator, Location, ) def get_data() -> Generator[List[str], None, None]: """ G...
Python
zaydzuhri_stack_edu_python
function real input Tout=none name=none begin set result = call apply_op string Real input=input Tout=Tout name=name return result end function
def real(input, Tout=None, name=None): result = _op_def_lib.apply_op("Real", input=input, Tout=Tout, name=name) return result
Python
nomic_cornstack_python_v1
for i in range n - 1 0 - 1 begin for j in range 1 n - i + 1 begin write f string end for k in range 0 2 * i - 1 begin write f string * end write f string for j in range 1 n - i + 1 begin write f string end write f string end print string Done
for i in range(n-1,0,-1): for j in range(1,(n-i)+1): f.write(" ") for k in range(0,2*i-1): f.write("*") f.write("\n") for j in range(1,(n-i)+1): f.write(" ") f.write("\n") print("Done")
Python
zaydzuhri_stack_edu_python
function lengthOfLongestSubstring s begin string :type s: str :rtype: int comment if not s: comment return 0 comment elif len(s)==1: comment return 1 comment i, l,m = 0, 1,0 comment j = i + 1 comment d = {s[i]: 0} comment # d[s[i]] = True comment while j < len(s): comment if s[j] not in d.keys(): comment d[s[j]] = j co...
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ # if not s: # return 0 # elif len(s)==1: # return 1 # i, l,m = 0, 1,0 # j = i + 1 # d = {s[i]: 0} # # d[s[i]] = True # while j < len(s): # if s[j] not in d.keys(): # d[s[j]] ...
Python
zaydzuhri_stack_edu_python
for t in range 1 test + 1 begin set final = list tuple 1 1 set arr = list map int split input set id = pop arr 0 if id == 1 begin set n = pop arr 0 set k = 0 while k >= 0 begin set tuple p q = final at k set tuple temp1 temp2 = tuple tuple p p + q tuple p + q q append final temp1 append final temp2 if length final > n ...
for t in range(1, test+1): final = [(1,1)] arr = list(map(int, input().split())) id = arr.pop(0) if id == 1: n = arr.pop(0) k = 0 while k >= 0: p,q = final[k] temp1, temp2 = (p, p+q), (p+q, q) final.append(temp1) final.append(temp2)...
Python
zaydzuhri_stack_edu_python
comment Python defines functions in order comment top to bottom comment Classes are created as a whole and don't adhere to this rule. function getPosInt prompt begin while true begin set quantity = input prompt if is digit quantity begin return integer quantity end else begin print string Please enter a positive number...
# Python defines functions in order # top to bottom # Classes are created as a whole and don't adhere to this rule. def getPosInt(prompt): while True: quantity = input(prompt) if quantity.isdigit(): return int(quantity) else: print("Please enter a positive number.") ...
Python
zaydzuhri_stack_edu_python
function find_min_max_avg arr begin comment set the min, max numbers to the first item in the array set min_num = arr at 0 set max_num = arr at 0 comment keep track of the sum of all the numbers set sum_num = 0 comment iterate through the array for item in arr begin comment find smallest number if item < min_num begin ...
def find_min_max_avg(arr): # set the min, max numbers to the first item in the array min_num = arr[0] max_num = arr[0] # keep track of the sum of all the numbers sum_num = 0 # iterate through the array for item in arr: # find smallest number if item < min_num: m...
Python
iamtarun_python_18k_alpaca