code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function parse_agi_result line begin string Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command 520-Invalid command syntax. Proper usage follows: int() argument must be a string, a byte...
def parse_agi_result(line): """Parse AGI results using Regular expression. AGI Result examples:: 100 result=0 Trying... 200 result=0 200 result=-1 200 result=132456 200 result= (timeout) 510 Invalid or unknown command 520-Invalid command syntax. Pr...
Python
jtatman_500k
function upload_file data bucket name begin set s3_client = call client string s3 set response = call upload_fileobj data bucket name return response end function
def upload_file(data, bucket, name): s3_client = boto3.client('s3') response = s3_client.upload_fileobj(data, bucket, name) return response
Python
nomic_cornstack_python_v1
function test_exc_on_call_flat_map self begin call _run_app fn=lambda se -> call flat_map call SuppressFlatMapCall tf n=4 e=list 1 1 3 3 set content = call _result 6 assert equal string __exit__ content at 3 assert equal string ValueError content at 4 assert equal string __exit__ content at 5 end function
def test_exc_on_call_flat_map(self): self._run_app(fn= lambda se : se.flat_map(SuppressFlatMapCall(self.tf)), n=4, e=[1,1,3,3]) content = self._result(6) self.assertEqual('__exit__\n', content[3]) self.assertEqual('ValueError\n', content[4]) self.assertEqual('__exit__\n', content...
Python
nomic_cornstack_python_v1
function set_num_rows self *args **kwargs begin return call time_raster_sink_f_set_num_rows self *args keyword kwargs end function
def set_num_rows(self, *args, **kwargs): return _qtgui_swig.time_raster_sink_f_set_num_rows(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
function split_dict_into_options_fontattrs_and_case d begin set c_d = dictionary comprehension case_s : if expression k == case_s then v else k for tuple k v in items d if k in case_dict_keys set f_d = dictionary comprehension if expression k in tuple funderline_s foverstrike_s then k at slice 1 : : else k : v for tu...
def split_dict_into_options_fontattrs_and_case(d): c_d = { case_s: (v if k == case_s else k) for k, v in d.items() if k in case_dict_keys } f_d = { (k[1:] if k in (funderline_s, foverstrike_s) else k): v for k, v in d.items() if k in ttfont_dict_keys } ...
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin import argparse , sys set parser = call ArgumentParser description=string Print FAT disk metadata call add_argument string -o string --offset help=string Starting block number type=int default=0 call add_argument string -b string --blocksize help=string Specify block size type=int d...
if __name__=="__main__": import argparse,sys parser = argparse.ArgumentParser(description="Print FAT disk metadata") parser.add_argument("-o","--offset",help="Starting block number",type=int,default=0) parser.add_argument("-b","--blocksize",help="Specify block size",type=int,default=512) parser.add_...
Python
zaydzuhri_stack_edu_python
function multinomial_logistic_loss_der m A Y begin set p = zeros shape set p at Y == 1 = - 1 - A at Y == 1 set p at Y == 0 = A at Y == 0 return p end function
def multinomial_logistic_loss_der(m, A, Y): p = np.zeros(A.shape) p[Y == 1] = -(1 - A[Y == 1]) p[Y == 0] = A[Y == 0] return p
Python
nomic_cornstack_python_v1
function reset self text=none acss=none begin comment We might get into a vicious loop of resetting speech, so comment we will abort if we see this happening. if time - __lastResetTime < 20 begin call println LEVEL_SEVERE string Something looks wrong with speech. Aborting. call printStack LEVEL_ALL call die 50 end else...
def reset(self, text=None, acss=None): # We might get into a vicious loop of resetting speech, so # we will abort if we see this happening. # if (time.time() - self.__lastResetTime) < 20: debug.println(debug.LEVEL_SEVERE, "Something looks wrong with...
Python
nomic_cornstack_python_v1
import Tugas23m set nilai = integer input string Masukkan jumlah bilangan : set data = call JumBil nilai print string Jumlah bilangan genap : + string length data at 0 + string yatu + string data at 0 print string Jumlah bilangan Ganjil : + string length data at 1 + string yatu + string data at 1
import Tugas23m nilai = int(input("Masukkan jumlah bilangan : ")) data = Tugas23m.JumBil(nilai) print ("Jumlah bilangan genap : "+str(len(data[0]))+" yatu " + str(data[0])) print ("Jumlah bilangan Ganjil : "+str(len(data[1]))+" yatu " + str(data[1]))
Python
zaydzuhri_stack_edu_python
function test_cannot_go_past_banana self begin if training < 2.5 begin set before = call getH end end function
def test_cannot_go_past_banana(self): if self.tb.training < 2.5: before = self.tb.base.camera.getH()
Python
nomic_cornstack_python_v1
comment 练习: comment 经理有: 曹操, 刘备, 孙权 comment 技术员有: 曹操, 孙权, 张飞, 关羽 comment 用集合求: comment 1. 即是经理也是技术员的有谁? comment 2. 是技术人员,但不是经理的人有谁? comment 3. 是经理,但不是技术人员的有谁? comment 4. 张飞是经理吗? comment 5. 身兼一职的人有谁? comment 6. 经理和技术人员共有几个人? set manager = set literal string 曹操 string 刘备 string 孙权 set techs = set literal string 曹操 string...
# 练习: # 经理有: 曹操, 刘备, 孙权 # 技术员有: 曹操, 孙权, 张飞, 关羽 # 用集合求: # 1. 即是经理也是技术员的有谁? # 2. 是技术人员,但不是经理的人有谁? # 3. 是经理,但不是技术人员的有谁? # 4. 张飞是经理吗? # 5. 身兼一职的人有谁? # 6. 经理和技术人员共有几个人? manager = {"曹操", "刘备", "孙权"} techs = {"曹操", "孙权", "张飞", "关羽"} print("即是经理也是技术员的有:", manager & techs) print("是技术人员,但不是经理的人有:...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import os import gspread from fctClassement import * from fctRankDomaine import * function fctpositionRanker id_workbook begin comment pour etre identifié sur internet comment suivre guidePython~Googlesheet set gc = call service_account filename=string credentials.json comment /!\ a modifie...
#!/usr/bin/env python import os import gspread from fctClassement import * from fctRankDomaine import * def fctpositionRanker(id_workbook): #pour etre identifié sur internet #suivre guidePython~Googlesheet gc = gspread.service_account(filename='credentials.json') #/!\ a modifier si nouveau w...
Python
zaydzuhri_stack_edu_python
while i < 5 begin set ai = 4 + 3 * i set s = s + ai set i = i + 1 end
while i<5: ai=4+3*i s=s+ai i=i+1
Python
zaydzuhri_stack_edu_python
async function _read_once self begin set msg = await call receive if type in set literal CLOSE CLOSING CLOSED begin await close websocket set websocket = none return end if type is not TEXT begin warning string Got unexpected message type: %s type return end set response = loads data debug string > %s response if strin...
async def _read_once(self): msg = await self.websocket.receive() if msg.type in {aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSED}: await self.websocket.close() self.websocket = None return if msg.type is not aiohttp.WSMsgType.TEXT...
Python
nomic_cornstack_python_v1
function regex_parse_gspreadsheet instr updated begin comment look ma, watch me parse XML a zillion times faster! comment <entry> comment <id>http://spreadsheets.google.com/feeds/cells/pMY64RHUNSVfKYZKPoVXPBg/1/public/basic/R14C15</id> comment <updated>2009-04-28T03:34:21.900Z</updated> comment <category scheme='http:/...
def regex_parse_gspreadsheet(instr, updated): # look ma, watch me parse XML a zillion times faster! #<entry> # <id>http://spreadsheets.google.com/feeds/cells/pMY64RHUNSVfKYZKPoVXPBg/1/public/basic/R14C15</id> # <updated>2009-04-28T03:34:21.900Z</updated> # <category scheme='http://schemas.google.com/spread...
Python
nomic_cornstack_python_v1
import nltk from nltk.book import text9 string 2a) find complete sentence that contains the word at index text9.index('sunset') function find_complete_sentence index begin set i = index string +i to get correct index in original text9, since the slice methods creates new list, i - x to take a new list that is traversed...
import nltk from nltk.book import text9 '''2a) find complete sentence that contains the word at index text9.index('sunset')''' def find_complete_sentence(index): i = index '''+i to get correct index in original text9, since the slice methods creates new list, i - x to take a new list that is traversed backwar...
Python
zaydzuhri_stack_edu_python
import sys import re import getopt from collections import defaultdict set _N = 13 function __main__ begin comment check aruguments if length argv == 1 begin call details exit end if length argv < 2 begin call usage end try begin set tuple opts args = call getopt argv at slice 2 : : string N: end except GetoptError b...
import sys import re import getopt from collections import defaultdict _N = 13 def __main__(): #check aruguments if len(sys.argv) == 1: details() sys.exit() if len(sys.argv) < 2: usage() try: opts, args = getopt.getopt(sys.argv[2:],"N:") except getopt.Get...
Python
zaydzuhri_stack_edu_python
function get_many self keys begin string Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. set d = dict for k...
def get_many(self, keys): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the respo...
Python
jtatman_500k
function solve_rk4 self f n h t0=0.0 begin for _ in range n begin call step_rk4 f t0 h set t0 = t0 + h end end function
def solve_rk4(self, f: Callable[[Union[float, int], np.ndarray], np.ndarray], n: int, h: Union[float, int], t0=0.0): for _ in range(n): self.step_rk4(f, t0, h) t0 += h
Python
nomic_cornstack_python_v1
comment Only add your code inside the function (including newly improted packages) comment You can design a new function and call the new function in the given functions. comment Not following the project guidelines will result in a 10% reduction in grades import cv2 import numpy as np import matplotlib.pyplot as plt f...
#Only add your code inside the function (including newly improted packages) # You can design a new function and call the new function in the given functions. # Not following the project guidelines will result in a 10% reduction in grades import cv2 import numpy as np import matplotlib.pyplot as plt from PIL import Im...
Python
zaydzuhri_stack_edu_python
function _get_config experiment **kwargs begin set root = parents at 2 with open root / string configs/main.yaml string r as f begin set config = load yaml f Loader at string model end with open root / string configs/charset/94_full.yaml string r as f begin update config load yaml f Loader at string model end with open...
def _get_config(experiment: str, **kwargs): root = PurePath(__file__).parents[2] with open(root / 'configs/main.yaml', 'r') as f: config = yaml.load(f, yaml.Loader)['model'] with open(root / f'configs/charset/94_full.yaml', 'r') as f: config.update(yaml.load(f, yaml.Loader)['model']) wit...
Python
nomic_cornstack_python_v1
function fit_nelson_siegel_yield tau y theta_0=none begin set n_ = length tau function minimization_target theta begin comment Step 1: Compute Nelson-Siegel yield curve set y_theta = call nelson_siegel_yield tau theta set output = 0.0 comment Step 2: Compute minimization function for n in range n_ begin if n == 0 begin...
def fit_nelson_siegel_yield(tau, y, theta_0=None): n_ = len(tau) def minimization_target(theta): # Step 1: Compute Nelson-Siegel yield curve y_theta = nelson_siegel_yield(tau, theta) output = 0.0 # Step 2: Compute minimization function for n in range(n_): ...
Python
nomic_cornstack_python_v1
import time function selection_sort array update_func delay begin for i in range length array begin comment find the minimum element to be put in head of array set min_idx = i for j in range i + 1 length array begin if array at min_idx > array at j begin set min_idx = j end call update_func array list comprehension if ...
import time def selection_sort(array, update_func, delay): for i in range(len(array)): #find the minimum element to be put in head of array min_idx = i for j in range(i+1, len(array)): if array[min_idx] > array[j]: min_idx = j update_func(array, ['ye...
Python
zaydzuhri_stack_edu_python
import os from flask import Flask , jsonify , flash , render_template , request , redirect , url_for from werkzeug.utils import secure_filename import algorithms set UPLOAD_FOLDER = string uploads set ALLOWED_EXTENSIONS = set list string txt string doc string docx string pdf set app = call Flask __name__ set secret_key...
import os from flask import Flask,jsonify,flash, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import algorithms UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['txt', 'doc', 'docx', 'pdf']) app = Flask(__name__) app.secret_key = "super secret key" def allowed_file(filenam...
Python
zaydzuhri_stack_edu_python
function test_fma_nan_param_okarray_ninfnum_infarray_okarray_b_112 self begin comment The expected results. set expected = list comprehension x * y + z for tuple x y z in zip okarrayx repeat ninfnumy infarrayz comment Exceptions are turned off so we can use the results to test for correct values. call fma okarrayx ninf...
def test_fma_nan_param_okarray_ninfnum_infarray_okarray_b_112(self): # The expected results. expected = [(x * y + z) for x,y,z in zip(self.okarrayx, itertools.repeat(self.ninfnumy), self.infarrayz)] # Exceptions are turned off so we can use the results to test for correct values. arrayfunc.fma(self.okarrayx, s...
Python
nomic_cornstack_python_v1
function getTable self begin set table = string table = set oppHands = string opponent cards = for card in table begin set table = table + string card + string , end return table end function
def getTable(self): table = 'table = ' oppHands = 'opponent cards = ' for card in self.table: table += (str(card) + ', ') return table
Python
nomic_cornstack_python_v1
comment Implement Skipgram model for word embeddings using Keras and NLTK import nltk call download string punkt call download string stopwords set text = string Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nost...
# Implement Skipgram model for word embeddings using Keras and NLTK import nltk nltk.download('punkt') nltk.download('stopwords') text = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ul...
Python
zaydzuhri_stack_edu_python
comment !python set INTRATE = 10 set amount = 100 set years = 5 set start = 0 print string Year Start Paid In Interest Final for year in range 1 years + 1 begin set interest = start + amount * INTRATE / 100 set final = start + amount + interest print year start amount interest final set start = final end
#!python INTRATE = 10 amount = 100 years = 5 start = 0 print("Year Start Paid In Interest Final") for year in range(1,years+1): interest = (start + amount) * INTRATE / 100 final = start + amount + interest print(year, start, amount, interest, final) start = final
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function removeDuplicates self nums begin if not nums or length nums == 1 begin return nums end set tmp = nums at 0 set tuple i j = tuple 0 1 while j <= length nums - 1 begin if nums at j > tmp begin if i + 1 < j begin set i = i + 1 set tmp = nums at j set tuple nums at i nums at j =...
class Solution(object): def removeDuplicates(self, nums): if not nums or len(nums) == 1: return nums tmp = nums[0] i, j = 0, 1 while j <= len(nums) - 1: if nums[j] > tmp: if i + 1 < j: i += 1 tmp = nums...
Python
zaydzuhri_stack_edu_python
function event_m50_37_x239 z112=537020063 z113=60375001 z114=762 begin string State 0,1: [Reproduction] NPC mimicry control_character_SubState assert call event_m50_37_x236 string State 3: [Condition] NPC mimicry control_Character_SubState assert call event_m50_37_x237 z112=z112 string State 2: [Map] SFX tracking setti...
def event_m50_37_x239(z112=537020063, z113=60375001, z114=762): """State 0,1: [Reproduction] NPC mimicry control_character_SubState""" assert event_m50_37_x236() """State 3: [Condition] NPC mimicry control_Character_SubState""" assert event_m50_37_x237(z112=z112) """State 2: [Map] SFX tracking setti...
Python
nomic_cornstack_python_v1
set x = list string apple string banana set y = list string apple string banana set z = x print x is not z print x is not y print x != y
x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is not z) print(x is not y) print(x != y)
Python
zaydzuhri_stack_edu_python
function is_prime n begin if n == 10959391665051308235299057234413833107 or n == 217015588102711300613106818822936738743 begin return true end if length string n > 10 begin return false end set i = 2 set k = integer n ^ 0.5 while i <= k begin if n % i == 0 begin return false end set i = i + 1 end return true end functi...
def is_prime(n): if(n==10959391665051308235299057234413833107 or n==217015588102711300613106818822936738743): return True if len(str(n))>10: return False i = 2 k = int(n ** 0.5) while(i<= k): if(n% i == 0): return False i += 1 return...
Python
zaydzuhri_stack_edu_python
function get_skeleton_game_path rig_object properties begin comment if a skeleton path is provided if unreal_skeleton_asset_path begin return unreal_skeleton_asset_path end else begin if children begin comment get all meshes from the mesh collection set mesh_collection = call get_from_collection mesh_collection_name st...
def get_skeleton_game_path(rig_object, properties): # if a skeleton path is provided if properties.unreal_skeleton_asset_path: return properties.unreal_skeleton_asset_path else: if rig_object.children: # get all meshes from the mesh collection mesh_collection = get_f...
Python
nomic_cornstack_python_v1
comment Implement an algorithm to determine if a string has all unique characters. comment What if you can't use additional data structure function isUnique string begin for tuple index char in enumerate string begin for j in call xrange index + 1 length string begin if char == string at j begin return true end end end...
# Implement an algorithm to determine if a string has all unique characters. # What if you can't use additional data structure def isUnique(string): for index, char in enumerate(string): for j in xrange(index + 1, len(string)): if char == string[j]: return True return False...
Python
zaydzuhri_stack_edu_python
function split n begin set x = list 1 1 2 4 if n < 5 begin return x at n - 1 end else begin if n % 3 == 0 begin return 3 ^ n / 3 end if n % 3 == 1 begin return 3 ^ n // 3 - 1 * 4 end if n % 3 == 2 begin return 3 ^ n // 3 * 2 end end end function
def split(n): x = [1,1,2,4] if n < 5: return x[n - 1] else: if n % 3 == 0: return 3 ** (n/3) if n % 3 == 1: return 3 ** (n // 3 - 1) * 4 if n % 3 == 2: return 3 ** (n // 3) * 2
Python
zaydzuhri_stack_edu_python
function reload self begin call create_all __engine set sess = call sessionmaker bind=__engine expire_on_commit=false set __session = call scoped_session sess end function
def reload(self): Base.metadata.create_all(self.__engine) sess = sessionmaker(bind=self.__engine, expire_on_commit=False) self.__session = scoped_session(sess)
Python
nomic_cornstack_python_v1
function visit_Lambda self node begin string [Lambda Definition] : <Python> lambda x,y :x*y <Ruby> lambda{|x,y| x*y} <Python> lambda *x: print(x) <Ruby> lambda {|*x| print(x)} <Python> def foo(x, y): x(y) foo(lambda x: print(a), a) <Ruby> def foo(x, y) x.(y) end foo(lambda{|x| print(a)}, a) return string lambda{|%s| %s...
def visit_Lambda(self, node): """ [Lambda Definition] : <Python> lambda x,y :x*y <Ruby> lambda{|x,y| x*y} <Python> lambda *x: print(x) <Ruby> lambda {|*x| print(x)} <Python> def foo(x, y): x(y) foo(lambda x: print(a), a) ...
Python
nomic_cornstack_python_v1
function _ event begin call cursor_left end function
def _(event): system_line.cursor_left()
Python
nomic_cornstack_python_v1
function set self val begin assert not __isReadOnly msg string This parameter(%s) was locked and now it can not be changed % name assert replacedWith is none msg string This param was replaced with new one and this should not exists set val = call toHVal val set defVal = val set _val = call staticEval set _dtype = _dty...
def set(self, val): assert not self.__isReadOnly, \ ("This parameter(%s) was locked" " and now it can not be changed" % self.name) assert self.replacedWith is None, \ ("This param was replaced with new one and this " "should not exists") val = t...
Python
nomic_cornstack_python_v1
import unittest import logging from datetime import datetime from database import db_engine , DbTable , Request , DbSession class DatabaseTest extends TestCase begin function __init__ self *args **kwargs begin call __init__ *args keyword kwargs comment logging.basicConfig(level=logging.DEBUG) call init_tests end functi...
import unittest import logging from datetime import datetime from database import db_engine, DbTable, Request, DbSession class DatabaseTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(DatabaseTest, self).__init__(*args, **kwargs) # logging.basicConfig(level=logging.DEBUG) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import vocab as vc import data_helpers as dh import custom_loss as cl from collections import Counter from gensim.models import Word2Vec import tensorflow as tf import numpy as np from tensorflow.contrib import learn set data_path = string ../data/books_text_full/test/ comment Make vocabul...
# -*- coding: utf-8 -*- import vocab as vc import data_helpers as dh import custom_loss as cl from collections import Counter from gensim.models import Word2Vec import tensorflow as tf import numpy as np from tensorflow.contrib import learn data_path = '../data/books_text_full/test/' # Make vocabulary # ==========...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , render_template_string import mondata set app = call Flask __name__ decorator call route string / function index begin set monsters = call check_images_exist call get_monsters return call render_template string index.html monsters=monsters end function decorator call route st...
from flask import Flask, render_template, render_template_string import mondata app = Flask(__name__) @app.route('/') def index(): monsters = mondata.check_images_exist(mondata.get_monsters()) return render_template('index.html', monsters=monsters) @app.route('/<name>') def eco_page(name): monsters = mon...
Python
zaydzuhri_stack_edu_python
comment !user/bin/python comment -*- coding: UTF-8 -*- class Dog begin function __init__ self name begin set name = name end function function cry self barking begin print barking end function end class class Puppy extends Dog begin comment 重写构造方法,添加了一个姓名 function __init__ self name age begin comment 这里不用加self call __i...
# !user/bin/python # -*- coding: UTF-8 -*- class Dog: def __init__(self, name): self.name = name def cry(self, barking): print(barking) class Puppy(Dog): def __init__(self, name, age): # 重写构造方法,添加了一个姓名 super().__init__(name) # 这里不用加self self.age = age def c...
Python
zaydzuhri_stack_edu_python
from flask import Flask from flask_restful import Resource , Api , reqparse import pandas as pd set app = call Flask __name__ set api = call Api app comment userss = { comment '1': { comment 'id': '1', comment 'username': 'Pe3oH', comment 'email': 'Pe3oH227@mail.ru', comment 'department': 'ART-Tanks', comment 'age': '2...
from flask import Flask from flask_restful import Resource, Api, reqparse import pandas as pd app = Flask(__name__) api = Api(app) # userss = { # '1': { # 'id': '1', # 'username': 'Pe3oH', # 'email': 'Pe3oH227@mail.ru', # 'department': 'ART-Tanks', # 'age': '26' # }, # ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string a basic script for importing student's POI identifier, and checking the results that they get from it requires that the algorithm, dataset, and features list be written to my_classifier.pkl, my_dataset.pkl, and my_feature_list.pkl, respectively that pro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ a basic script for importing student's POI identifier, and checking the results that they get from it requires that the algorithm, dataset, and features list be written to my_classifier.pkl, my_dataset.pkl, and my_feature_list.pkl, respectively ...
Python
zaydzuhri_stack_edu_python
comment strings set nome = string Wallyson Roberto print string Nome.: nome set tamanho = length nome print tamanho print nome at 5
#strings nome="Wallyson Roberto" print("Nome.: ",nome) tamanho=len(nome) print(tamanho) print(nome[5])
Python
zaydzuhri_stack_edu_python
async function update self **kwargs begin comment copy a new set of settings and pass it straight to `http.update_user_settings` set settings = copy self update dict settings keyword kwargs comment remove this so discord dont get confused pop settings string _bot set new_settings = await call update_user_settings keywo...
async def update(self, **kwargs): # copy a new set of settings and pass it straight to `http.update_user_settings` settings = self.copy() dict.update(settings, **kwargs) # remove this so discord dont get confused settings.pop("_bot") new_settings = await self._bot.http.u...
Python
nomic_cornstack_python_v1
function extract_value self data begin string Extract the id key and validate the request structure. set errors = list if string id not in data begin append errors string Must have an `id` field end if string type not in data begin append errors string Must have a `type` field end else if data at string type != type_ ...
def extract_value(self, data): """Extract the id key and validate the request structure.""" errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self...
Python
jtatman_500k
function total_power_square x y serial size begin set result = 0 for i in range x x + size begin for j in range y y + size begin set result = result + call cell_power i j serial end end return result end function
def total_power_square(x, y, serial, size): result = 0 for i in range(x, x + size): for j in range(y, y + size): result += cell_power(i, j, serial) return result
Python
nomic_cornstack_python_v1
function test_ui_vm_one self begin set ds = call Dataset set SOPInstanceUID = string 1.2.3.4 assert string (0008,0018) UI [1.2.3.4] # 1 SOPInstanceUID == call pretty_element ds at string SOPInstanceUID end function
def test_ui_vm_one(self): ds = Dataset() ds.SOPInstanceUID = "1.2.3.4" assert ( "(0008,0018) UI [1.2.3.4] # 1" " SOPInstanceUID" ) == pretty_element(ds["SOPInstanceUID"])
Python
nomic_cornstack_python_v1
from pyMorse.converter.converter import Converter class CompositeConverter extends Converter begin string This represents the conversion of characters using multiple converters. Args: converters(:obj:`list` of :obj:`Converter`): List of converts to be applied (in order for encoding). function __init__ self converters b...
from pyMorse.converter.converter import Converter class CompositeConverter(Converter): """This represents the conversion of characters using multiple converters. Args: converters(:obj:`list` of :obj:`Converter`): List of converts to be applied (in order for encoding). """ def __init__(self, co...
Python
zaydzuhri_stack_edu_python
function parse_blast_result result begin set found_queries = set if not result begin return found_queries end for row in split strip result string begin add found_queries split row string at 0 end return found_queries end function
def parse_blast_result(result: str) -> set[str]: found_queries = set() if not result: return found_queries for row in result.strip().split("\n"): found_queries.add(row.split("\t")[0]) return found_queries
Python
nomic_cornstack_python_v1
import nltk import remove_chars_from_text comment text1 = open(r'C:\Users\lisin\OneDrive\Рабочий стол\Third semester Sami Shimoon\InformationSearch\project_content\DocumentsToRead\Деловой стиль\Заявления.txt', encoding="utf-8").read() function average_word_length text begin set txt_clean = call remove_chars_from_text t...
import nltk import remove_chars_from_text #text1 = open(r'C:\Users\lisin\OneDrive\Рабочий стол\Third semester Sami Shimoon\InformationSearch\project_content\DocumentsToRead\Деловой стиль\Заявления.txt', encoding="utf-8").read() def average_word_length(text): txt_clean = remove_chars_from_text.remove_chars_from_tex...
Python
zaydzuhri_stack_edu_python
function test_instruction_init self begin set gate = call CnotGate set op = data set target = call to_matrix set global_phase_equivalent = call matrix_equal op target ignore_phase=true assert true global_phase_equivalent set gate = call CHGate set op = data set had = call to_matrix set target = call kron had call diag ...
def test_instruction_init(self): gate = CnotGate() op = Operator(gate).data target = gate.to_matrix() global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) gate = CHGate() op = Operator(gate).data h...
Python
nomic_cornstack_python_v1
function factorial begin set i = 1 set value = 1 while true begin yield value set value = value * i set i = i + 1 end end function
def factorial(): i = 1 value = 1 while True: yield value value *= i i += 1
Python
zaydzuhri_stack_edu_python
import string set identiList = dict set keywords = dict comment 标识符 set keywords at string var = 700 comment 整数 set keywords at string const = 400 comment Error set keywords at string Error = 500 function save text begin try begin decimal text call save_const text end except ValueError begin call save_var text end en...
import string identiList = {} keywords = {} # 标识符 keywords['var'] = 700 # 整数 keywords['const'] = 400 # Error keywords['Error'] = 500 def save(text): try: float(text) save_const(text) except ValueError: save_var(text) def save_const(text): if text not in identiList.keys(): ...
Python
zaydzuhri_stack_edu_python
function get_manifest_label label_uuid tag_manifest begin try begin return get where annotated == tag_manifest end except DoesNotExist begin return none end end function
def get_manifest_label(label_uuid, tag_manifest): try: return ( Label.select(Label, LabelSourceType) .join(LabelSourceType) .where(Label.uuid == label_uuid) .switch(Label) .join(TagManifestLabel) .where(TagManifestLabel.annotated == tag...
Python
nomic_cornstack_python_v1
async function delete self reason=string watch=false unwatch=false oldimage=false begin if not call can string delete begin raise call InsufficientPermission self end if not writeapi begin raise call NoWriteApi self end set data = dict if watch begin set data at string watch = string 1 end if unwatch begin set data a...
async def delete(self, reason="", watch=False, unwatch=False, oldimage=False): if not self.can("delete"): raise aiomwclient.errors.InsufficientPermission(self) if not self.site.writeapi: raise aiomwclient.errors.NoWriteApi(self) data = {} if watch: d...
Python
nomic_cornstack_python_v1
from django.db import models class Profile extends Model begin set telegram_id = call PositiveIntegerField unique=true verbose_name=string ID пользователя set name = call CharField verbose_name=string Имя пользователя max_length=200 function __str__ self begin return string # { telegram_id } _ { name } end function cla...
from django.db import models class Profile(models.Model): telegram_id = models.PositiveIntegerField(unique=True, verbose_name="ID пользователя") name = models.CharField(verbose_name='Имя пользователя', max_length=200) def __str__(self): return f'#{self.telegram_id}_{self.name}' class Meta: ...
Python
zaydzuhri_stack_edu_python
comment Bagged Decision Trees for Classification import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import cross_validation from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn imp...
# Bagged Decision Trees for Classification import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import cross_validation from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn import m...
Python
zaydzuhri_stack_edu_python
import unittest from unittest.mock import patch from client import Client class TestClient extends TestCase begin function setUp self begin set client_1 = call Client string Masayoshi string Son set client_2 = call Client string Lisa string Sue end function function test_trades_for_month self begin with patch string cl...
import unittest from unittest.mock import patch from client import Client class TestClient(unittest.TestCase): def setUp(self): self.client_1 = Client('Masayoshi', 'Son') self.client_2 = Client('Lisa', 'Sue') def test_trades_for_month(self): with patch('client.requests.get') as mocke...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Shit in, shit out. This tool generates two implementations of comment the finite automaton used in ticket-machine.c and a graphviz comment source to create a huge-ass graph for it, as required. import sys function w x begin write stdout x end function set functions = dict set actio...
#!/usr/bin/env python # Shit in, shit out. This tool generates two implementations of # the finite automaton used in ticket-machine.c and a graphviz # source to create a huge-ass graph for it, as required. import sys def w (x): sys.stdout.write (x) functions = {} action_table = [] states_table = [] for q in range (...
Python
zaydzuhri_stack_edu_python
function read_pcap_isn file_name begin set tuple max_tcp_pkt_seq max_tcp_pkt_ack = tuple 0 0 set tuple min_tcp_pkt_seq min_tcp_pkt_ack = tuple 0 0 set start = time for tuple counter tuple pkt_data pkt_metadata in enumerate call RawPcapReader file_name begin set ether_pkt = call Ether pkt_data set ip_pkt = ether_pkt at ...
def read_pcap_isn(file_name): max_tcp_pkt_seq, max_tcp_pkt_ack = 0, 0 min_tcp_pkt_seq, min_tcp_pkt_ack = 0, 0 start = time.time() for counter, (pkt_data, pkt_metadata) in enumerate(RawPcapReader(file_name)): ether_pkt = Ether(pkt_data) ip_pkt = ether_pkt[IP] tcp_pkt = ip_pkt[TCP...
Python
nomic_cornstack_python_v1
import re from utils import get_spark_context , SPARK_DATA_PATH function normalise text begin return split compile string \W+ UNICODE lower text end function set sc = call get_spark_context string RatingsHistogram set inpt = call textFile string { SPARK_DATA_PATH } /Book set words = call flatMap normalise comment Conve...
import re from utils import get_spark_context, SPARK_DATA_PATH def normalise(text): return re.compile(r'\W+', re.UNICODE).split(text.lower()) sc = get_spark_context('RatingsHistogram') inpt = sc.textFile(f"{SPARK_DATA_PATH}/Book") words = inpt.flatMap(normalise) # Convert each word to a key value pair with th...
Python
zaydzuhri_stack_edu_python
function find_second_largest arr begin set n = length arr if n < 2 begin print string Array should have at least two elements. return end set largest = arr at 0 set second_largest = arr at 0 for i in range 1 n begin if arr at i > largest begin set second_largest = largest set largest = arr at i end else if arr at i > s...
def find_second_largest(arr): n = len(arr) if n < 2: print("Array should have at least two elements.") return largest = arr[0] second_largest = arr[0] for i in range(1, n): if arr[i] > largest: second_largest = largest largest = arr[i] ...
Python
jtatman_500k
import cv2 import matplotlib.pyplot as plt import time import numpy as np set path = string images/grayscale1.jpg set img = call imread path IMREAD_GRAYSCALE comment plt.imshow(img) comment plt.show() set THRESHOLD_VALUE = 50 set maxValue = 255 comment def thresholdUsingLoop(image, threshold, v_max): # 0.02 comment dst...
import cv2 import matplotlib.pyplot as plt import time import numpy as np path = 'images/grayscale1.jpg' img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) # plt.imshow(img) # plt.show() THRESHOLD_VALUE = 50 maxValue = 255 # def thresholdUsingLoop(image, threshold, v_max): # 0.02 # dst = np.zeros_like(image) # p...
Python
zaydzuhri_stack_edu_python
import random function randomize arr n begin comment Start from the last element and comment swap one by one. We don't need to comment run for the first element comment that's why i > 0 for i in range n - 1 0 - 1 begin comment Pick a random index set j = random integer 0 i + 1 comment Swap arr[i] with the element comme...
import random def randomize(arr, n): # Start from the last element and # swap one by one. We don't need to # run for the first element # that's why i > 0 for i in range(n-1,0,-1): # Pick a random index j = random.randint(0,i+1) # Swap arr[i] with the element ...
Python
flytech_python_25k
function cap_text text begin string Input a string returns the capitalized version of that string :param text: str : a string to capitalize :return: the input text where each word's first letter is capitalized return title text end function
def cap_text(text): """ Input a string returns the capitalized version of that string :param text: str : a string to capitalize :return: the input text where each word's first letter is capitalized """ return text.title()
Python
zaydzuhri_stack_edu_python
set score = input string Enter score: print score
score=input("Enter score: ") print(score)
Python
zaydzuhri_stack_edu_python
if number > fave begin print string Sorry, you lose. :( end
if number > fave: print("Sorry, you lose. :(")
Python
zaydzuhri_stack_edu_python
function online self begin return true end function
def online(self): return True
Python
nomic_cornstack_python_v1
import math function check_unit x begin string Check plural (square meter or square meters) if x > 1 begin return string square meters end else begin return string square meter end end function function cal_circle r begin string Calculate and return area result) return pi * r * r end function function cal_triangle x y ...
import math def check_unit(x): """Check plural (square meter or square meters)""" if x > 1: return "square meters" else: return "square meter" def cal_circle(r): """Calculate and return area result)""" return math.pi * r * r def cal_triangle(x,y): """Calculate and return area...
Python
zaydzuhri_stack_edu_python
function glide_predict_links edgelist X params=dict thres_p=0.9 begin set edgedict = call create_edge_dict edgelist set ndict = call create_neighborhood_dict edgelist set params_ = dict comment Embedding set pairwise_dist = call squareform pdist X set N = shape at 0 set alpha = params at string alpha set local_metric...
def glide_predict_links(edgelist, X, params={}, thres_p=0.9): edgedict = create_edge_dict(edgelist) ndict = create_neighborhood_dict(edgelist) params_ = {} # Embedding pairwise_dist = spatial.squareform(spatial.pdist(X)) N = X.shape[0] alpha = params["alpha"] local_metric = params["loc"...
Python
nomic_cornstack_python_v1
function handle_extension extensions f begin set extensions = split lower extensions function g key data begin set extension = split lower key string . for target in extensions begin set target = split target string . if length target > length extension begin continue end if extension at slice - length target : : == ...
def handle_extension(extensions, f): extensions = extensions.lower().split() def g(key, data): extension = key.lower().split(".") for target in extensions: target = target.split(".") if len(target) > len(extension): continue if extension[-l...
Python
nomic_cornstack_python_v1
function set_floating_point_precision self precision begin call setFloatingPointPrecision call get_enum_value precision end function
def set_floating_point_precision( self, precision: FloatingPointPrecisionStr | QtCore.QDataStream.FloatingPointPrecision, ): self.setFloatingPointPrecision(FLOATING_POINT_PRECISION.get_enum_value(precision))
Python
nomic_cornstack_python_v1
function solution progresses speeds begin set answer = list set time = 1 set cnt = 0 while progresses begin set work = progresses at 0 + speeds at 0 * time if work >= 100 begin pop progresses 0 pop speeds 0 set cnt = cnt + 1 while progresses begin set task = progresses at 0 + speeds at 0 * time if task >= 100 begin po...
def solution(progresses, speeds): answer = [] time = 1 cnt = 0 while progresses: work = progresses[0] + (speeds[0] * time) if work >= 100: progresses.pop(0) speeds.pop(0) cnt += 1 while progresses: task = progresses[0] + (s...
Python
zaydzuhri_stack_edu_python
import os import hashlib from PIL import Image as Im from django.db import models from django.utils import timezone function get_image_path instance filename begin string Saves every image to the owner subfolder return join path string images string id filename end function class Student extends Model begin string Stud...
import os import hashlib from PIL import Image as Im from django.db import models from django.utils import timezone def get_image_path(instance, filename): """ Saves every image to the owner subfolder """ return os.path.join('images', str(instance.owner.id), filename) class Student(models.Model): ...
Python
zaydzuhri_stack_edu_python
comment https://codecombat.com/play/level/northwest comment Your pet should find and bring a potion to the hero. comment This function checks if the word is in the text. function wordInText text word begin comment Iterate letter indexes in the text. for i in range length text - length word begin comment For each index ...
# https://codecombat.com/play/level/northwest # Your pet should find and bring a potion to the hero. # This function checks if the word is in the text. def wordInText(text, word): # Iterate letter indexes in the text. for i in range(len(text) - len(word)): # For each index loop through the word. ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python3 comment given a BCF file of dbSNP variant calls in NCBI format, produce a BCF file with only variants above a minimum minor-allele frequency comment NCBI format shows results from multiple studies and a variant is kept if any of them reported a minor-allele frequency above the threshold c...
#! /usr/bin/env python3 # given a BCF file of dbSNP variant calls in NCBI format, produce a BCF file with only variants above a minimum minor-allele frequency # NCBI format shows results from multiple studies and a variant is kept if any of them reported a minor-allele frequency above the threshold # where more than o...
Python
zaydzuhri_stack_edu_python
function models self begin return call get_field string model end function
def models(self): return self.get_field('model')
Python
nomic_cornstack_python_v1
import gym import random from kaggle_environments import evaluate , make class ConnectX extends Env begin function __init__ self switch_prob=0.5 use_random_training=true random_agent=false test_mode=false begin set env = call make string connectx debug=true if use_random_training begin if uniform 0 1 < 0.6 begin set pa...
import gym import random from kaggle_environments import evaluate, make class ConnectX(gym.Env): def __init__(self, switch_prob=0.5, use_random_training=True, random_agent=False, test_mode=False): self.env = make('connectx', debug=True) if use_random_training: if random.uniform(0, 1) < ...
Python
zaydzuhri_stack_edu_python
function get_power_level x y serial begin set rack_id = x + 10 set power = rack_id * y + serial * rack_id if power > 99 begin return power // 100 % 10 - 5 end else begin return - 5 end end function
def get_power_level(x, y, serial): rack_id = x + 10 power = (((rack_id*y) + serial) * rack_id) if power > 99: return (power // 100) % 10 - 5 else: return -5
Python
nomic_cornstack_python_v1
function showBorn self context begin show context end function
def showBorn(self, context): self.getCircle().show(context)
Python
nomic_cornstack_python_v1
function GetSeed self begin return call itkNoiseBaseImageFilterIUC3IUC3_GetSeed self end function
def GetSeed(self) -> "unsigned int": return _itkNoiseBaseImageFilterPython.itkNoiseBaseImageFilterIUC3IUC3_GetSeed(self)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Feb 24 16:55:02 2021 @author: Luis Carlos Prada Funcion para calcular el costo y el gradiente para la regresion logistica, se usa como funcion la funcion sigmoide import numpy as np from sigmoide import sigmoide function cg_logistic theta x y begin string valores inic...
# -*- coding: utf-8 -*- """ Created on Wed Feb 24 16:55:02 2021 @author: Luis Carlos Prada Funcion para calcular el costo y el gradiente para la regresion logistica, se usa como funcion la funcion sigmoide """ import numpy as np from sigmoide import sigmoide def cg_logistic(theta,x,y): 'val...
Python
zaydzuhri_stack_edu_python
string Dynamic Programming - Use Cases: - Find total number of options (90%) - Find maximum value (80%) - Find feasibility of an option (80%) - Not Suited Use Cases: - List all options (99%) - The data is not sorted (except kanpsack, 60-70%) - The worst case run time is polynomial already (80%) - Four Elements for Dyna...
""" Dynamic Programming - Use Cases: - Find total number of options (90%) - Find maximum value (80%) - Find feasibility of an option (80%) - Not Suited Use Cases: - List all options (99%) - The data is not sorted (except kanpsack, 60-70%) - The worst case run time is polynomial already (80%) ...
Python
zaydzuhri_stack_edu_python
import http.client import json import rapid_cred set key = login at string key set host = login at string host comment can set up to return data that can be used by other function function search name begin set conn = call HTTPSConnection string imdb8.p.rapidapi.com set headers = dict string x-rapidapi-key key ; string...
import http.client import json import rapid_cred key = rapid_cred.login['key'] host = rapid_cred.login['host'] # can set up to return data that can be used by other function def search(name): conn = http.client.HTTPSConnection("imdb8.p.rapidapi.com") headers = { 'x-rapidapi-key': key, ...
Python
zaydzuhri_stack_edu_python
function time_to_bday bday current begin set nextbday = call datetime year month day if nextbday < current begin set nextbday = call datetime year + 1 month day 0 set nextbday = call datetime year + 1 month day 0 end set twait = nextbday - current end function
def time_to_bday(bday,current): nextbday = datetime(current.year,bday.month,bday.day) if nextbday < current: nextbday = nextbday = datetime(current.year+1,bday.month,bday.day,0) twait = nextbday - current
Python
nomic_cornstack_python_v1
function handler_NULL self qi begin call dbo string Nothing to do for %s % qi end function
def handler_NULL(self, qi): self.dbo('Nothing to do for %s' % qi)
Python
nomic_cornstack_python_v1
function map self f begin return call bind lambda x -> call ret f dist x end function
def map(self, f): return self.bind( lambda x: self.ret(f(x)) )
Python
nomic_cornstack_python_v1
comment One error, missing "aa" "a" scenario class Solution begin function longestCommonPrefix self strs begin comment check empty list if length strs == 0 begin return string end comment start with the first value set answer = strs at 0 comment compare it to all other values for s in range length strs - 1 begin comme...
#One error, missing "aa" "a" scenario class Solution: def longestCommonPrefix(self,strs: List[str]) -> str: if(len(strs) == 0):#check empty list return "" answer = strs[0]#start with the first value for s in range(len(strs)-1):#compare it to all other values ...
Python
zaydzuhri_stack_edu_python
function _handleOkayButtonClicked self begin call saveValues call emit end function
def _handleOkayButtonClicked(self): self.saveValues() self.okayButtonClicked.emit()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from __future__ import division import math set m = input string quantidade de termos: set cont = 3 set a = 4 set i = 1 while i <= m begin set pi = cont + a / i * j * k - a / k * i * j end
# -*- coding: utf-8 -*- from __future__ import division import math m=input('quantidade de termos:') cont=3 a=4 i=1 while i<=m: pi=cont+(a/(i*j*k))-(a/(k*i*j))
Python
zaydzuhri_stack_edu_python
for i in range n begin if a at i not in d begin set d at a at i = list i i end else begin set d at a at i at 1 = i end end set curent_grp = 0 set result = 0 for i in range n begin if d at a at i at 1 > curent_grp begin set curent_grp = d at a at i at 1 end if curent_grp == i begin set result = result + 1 end end set re...
for i in range(n): if a[i] not in d: d[a[i]] = [i, i] else: d[a[i]][1] = i curent_grp = 0 result = 0 for i in range(n): if d[a[i]][1] > curent_grp: curent_grp = d[a[i]][1] if curent_grp == i: result += 1 result-=1 result=pow(2, result,mod) print(result)
Python
zaydzuhri_stack_edu_python
from utils import * set inp = call ints call inp_readlines print length set inp length inp class Node begin function __init__ self val begin set next = none set prev = none set val = val end function function unlink self begin set pr = prev set nx = next assert next == self and prev == self set next = nx set prev = pr ...
from utils import * inp = ints(inp_readlines()) print(len(set(inp)), len(inp)) class Node: def __init__(self, val): self.next = None self.prev = None self.val = val def unlink(self): pr = self.prev nx = self.next assert pr.next == self and nx.prev == self ...
Python
zaydzuhri_stack_edu_python
function fstat_OLS OLSMod begin comment (scalar) number of ind. vars (includes constant) set k = nVars comment (scalar) number of observations set n = nObs comment (scalar) residual sum of squares set utu = res2 comment (array) vector of predicted values (n x 1) set predy = y_pred comment (scalar) mean of dependent obs...
def fstat_OLS(OLSMod): k = OLSMod.nVars # (scalar) number of ind. vars (includes constant) n = OLSMod.nObs # (scalar) number of observations utu = OLSMod.res2 # (scalar) residual sum of squares predy = OLSMod.y_pred # (array) vector of predicted values (n x 1) me...
Python
nomic_cornstack_python_v1
import random class event_list begin function __init__ self filename=string working_pmu.txt begin with open filename string r as file begin set event_list = list comprehension strip str s for s in list file end end function function sample self num begin return random sample event_list num end function function sample_...
import random class event_list: def __init__(self, filename="working_pmu.txt"): with open(filename, 'r') as file: self.event_list = [str.strip(s) for s in list(file)] def sample(self, num): return random.sample(self.event_list, num) def sample_range(self, min_e, max_e): ...
Python
zaydzuhri_stack_edu_python
string # Dictionary example sal = {"jane":15, "John":20} print(sal) # append to dictionary sal["andy"] = 25 print(sal) # looping dictionary on keys for item in sal.keys(): print(item) # looping dictionary on value for item in sal.values(): print(item) # looping dictionary and printing both key & value print("looping di...
''' # Dictionary example sal = {"jane":15, "John":20} print(sal) # append to dictionary sal["andy"] = 25 print(sal) # looping dictionary on keys for item in sal.keys(): print(item) # looping dictionary on value for item in sal.values(): print(item) # looping dictionary and printing both key & value print("l...
Python
zaydzuhri_stack_edu_python
from time import time as tick function time fn *args **kwds begin set start = call tick comment stars to unpack args and keywords set result = call fn *args keyword kwds set stop = call tick return tuple stop - start result end function function fib n begin string Recursive Fibonacci if n < 2 begin return 1 end else be...
from time import time as tick def time(fn, *args, **kwds): start = tick() result = fn(*args, **kwds) # stars to unpack args and keywords stop = tick() return stop - start, result def fib(n): """ Recursive Fibonacci""" if n < 2: return 1 else: return fib(n-1) + fib(n-2) ...
Python
zaydzuhri_stack_edu_python
function length self begin return call length end function
def length(self): return self.list.length()
Python
nomic_cornstack_python_v1