code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function hash_file filename blocksize=65536 begin set hasher = sha256 with open filename string rb as fd begin set buf = read fd blocksize while length buf > 0 begin update hasher buf set buf = read fd blocksize end end return call digest end function
def hash_file(filename, blocksize=65536): hasher = hashlib.sha256() with open( filename, "rb" ) as fd: buf = fd.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fd.read(blocksize) return hasher.digest()
Python
nomic_cornstack_python_v1
string The first line contains the integer,N, the total number of plants. The second line contains the N space separated heights of the plants. function average array begin comment your code goes here set unique_array = set array return sum unique_array / length unique_array end function if __name__ == string __main__ ...
'''The first line contains the integer,N, the total number of plants. The second line contains the N space separated heights of the plants.''' def average(array): # your code goes here unique_array=set(array) return sum(unique_array)/len(unique_array) if __name__ == '__main__': n = int(input())...
Python
zaydzuhri_stack_edu_python
comment 使用装饰器对无参数的函数进行装饰 from time import ctime , sleep function time_fun func begin function wrapped_func begin print string %s called at %s % tuple __name__ call ctime call func end function return wrapped_func end function decorator time_fun function foo begin print string I am a foo----------- end function call foo...
# 使用装饰器对无参数的函数进行装饰 from time import ctime,sleep def time_fun(func): def wrapped_func(): print("%s called at %s"%(func.__name__,ctime())) func() return wrapped_func @time_fun def foo(): print("I am a foo-----------") foo() def func(functionName): print("------func---1-------") ...
Python
zaydzuhri_stack_edu_python
function suggestMutation self connection table_name sample_dict add_rowz=true begin comment Check if the table exists and if so, eliminate duplicate rows set new_rows = dictionary sample_dict set new_table = false set current_schema = call getSchema connection table_name if current_schema is none begin set new_table = ...
def suggestMutation(self, connection, table_name, sample_dict, add_rowz=True): # Check if the table exists and if so, eliminate duplicate rows new_rows = dict(sample_dict) new_table = False current_schema = self.getSchema(connection, table_name) if current_schema is None: new_table = True...
Python
nomic_cornstack_python_v1
function test_tooFewModeParameters self begin call _sendModeChange string +o call _checkModeChange list set errors = call flushLoggedErrors IRCBadModes assert equal length errors 1 call assertSubstring string Not enough parameters call getErrorMessage end function
def test_tooFewModeParameters(self): self._sendModeChange("+o") self._checkModeChange([]) errors = self.flushLoggedErrors(irc.IRCBadModes) self.assertEqual(len(errors), 1) self.assertSubstring("Not enough parameters", errors[0].getErrorMessage())
Python
nomic_cornstack_python_v1
comment python opens text file with a space between every character set fread = read open string input.csv string rb set mytext = decode fread string utf-16
# python opens text file with a space between every character fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16')
Python
zaydzuhri_stack_edu_python
function __init__ self sptr dopplerscale distancefactor rolloffscale begin set _sysptr = sptr set _distancefactor = distancefactor set _dopplerscale = dopplerscale set _rolloffscale = rolloffscale end function
def __init__(self, sptr, dopplerscale, distancefactor, rolloffscale): self._sysptr = sptr self._distancefactor = distancefactor self._dopplerscale = dopplerscale self._rolloffscale = rolloffscale
Python
nomic_cornstack_python_v1
from Tkinter import Entry import Tkinter class EnterIPWindow extends object begin function __init__ self begin set serverAddress = 0 call setWindow call setEntryInput call setButtonOK call mainloop end function function setWindow self begin set root = call Tk set windowWidth = 300 set windowHeight = 50 set screenWidth ...
from Tkinter import Entry import Tkinter class EnterIPWindow(object): def __init__(self): self.serverAddress = 0 self.setWindow() self.setEntryInput() self.setButtonOK() self.root.mainloop() def setWindow(self): self.root = Tkinter.Tk() win...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D set fig_1 = figure set ax = call add_subplot 111 projection=string 3d set samNum1 = 1000 set spConst1 = 5.0 set t = linear space 0 89 * pi samNum1 set tuple T Z = call meshgrid t list 0 1 set X = spConst1 * cos T + T * sin T set ...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig_1 = plt.figure() ax = fig_1.add_subplot(111, projection='3d') samNum1 = 1000 spConst1 = 5.0 t = np.linspace(0,89*np.pi, samNum1) T, Z = np.meshgrid(t, [0,1]) X = spConst1 * (np.cos(T) + T* np.sin(T)) Y = spConst1 * (np.sin...
Python
zaydzuhri_stack_edu_python
function circle self x_center y_center radius color begin call _circle_helper x_center y_center radius color false end function
def circle(self, x_center: int, y_center: int, radius: int, color: int) -> None: self._circle_helper(x_center, y_center, radius, color, False)
Python
nomic_cornstack_python_v1
function test_rtt_80211mc_supporting_aps self begin set dut = android_devices at 0 call run_test_rtt_80211mc_supporting_aps dut end function
def test_rtt_80211mc_supporting_aps(self): dut = self.android_devices[0] self.run_test_rtt_80211mc_supporting_aps(dut)
Python
nomic_cornstack_python_v1
comment Take a list of ones and zeros. Determine the number of consecutive ones starting comment on the first index that has a one. set my_list = list 0 1 1 1 0 1 1 1 0 1 0 0 1 1 0 function make_continent index my_list begin set continent = list while my_list at index != 0 begin comment Add index to continent append c...
# Take a list of ones and zeros. Determine the number of consecutive ones starting # on the first index that has a one. # my_list = [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0] def make_continent(index, my_list): continent = [] while my_list[index] != 0: # Add index to continent continent.ap...
Python
zaydzuhri_stack_edu_python
import os import tempfile class File begin string Интерфейс для работы с файлами function __init__ self file_path begin if not is instance file_path str begin raise TypeError end else if not is file path file_path begin with open file_path string w begin pass end end set __file_path = file_path end function function re...
import os import tempfile class File: """Интерфейс для работы с файлами""" def __init__(self, file_path: str): if not isinstance(file_path, str): raise TypeError elif not os.path.isfile(file_path): with open(file_path, 'w'): pass self.__file_path...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Dec 8 11:27:00 2020 @author: Joel import tkinter import tkinter.ttk import searchQuerys import insertDelete import Allergens import re function remove_brackesParaQuotesComma string begin set string = sub string [()] string string set string = sub string [\[\]] string...
# -*- coding: utf-8 -*- """ Created on Tue Dec 8 11:27:00 2020 @author: Joel """ import tkinter import tkinter.ttk import searchQuerys import insertDelete import Allergens import re def remove_brackesParaQuotesComma(string): string = re.sub('[()]', '',string) string = re.sub('[\[\]]', '',s...
Python
zaydzuhri_stack_edu_python
function test_create_comment self begin set user = call create_user username=string davinchy password=string johnson.py set post = call create text=string this is a comment user=user set url = reverse string comment-list set data = dict string post id ; string user id set response = post url data format=string json set...
def test_create_comment(self): user = User.objects.create_user(username="davinchy", password="johnson.py") post = Post.objects.create(text="this is a comment", user=user) url = reverse('comment-list') data = {'post': post.id, "user": user.id} response = self.client.post(url, dat...
Python
nomic_cornstack_python_v1
import random set num = random integer 1 50 for i in range 6 begin print string Попытка № { i + 1 } set Num = input if integer Num == num begin print string Игра закончена, вы выйграли. break end else if integer Num >= num begin print string Ниже end else if integer Num <= num begin print string Выше end if i + 1 == 6 ...
import random num = random.randint(1, 50) for i in range(6): print(f'Попытка №{i + 1}') Num = input() if int(Num) == num: print('Игра закончена, вы выйграли.') break elif int(Num) >= num: print('Ниже') elif int(Num) <= num: print('Выше') if (i + 1) == 6: print('Игра закончена, вы проиграли.') print(f'З...
Python
zaydzuhri_stack_edu_python
if criminalsQuantity < 5 begin print string Я смогу сам end else if criminalsQuantity >= 5 ? criminalsQuantity <= 10 begin print string Помоги мне, Бэтмен end else if criminalsQuantity > 10 begin print string Удачи тебе! end
if criminalsQuantity < 5: print("Я смогу сам") elif (criminalsQuantity >= 5) & (criminalsQuantity <= 10): print("Помоги мне, Бэтмен") elif criminalsQuantity > 10: print("Удачи тебе!")
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 set W = 500.0 set Y_CUTOFF1 = 420 set Y_CUTOFF2 = 300 set Y_CUTOFF3 = 150 set X_CUTOFF1 = 115 set X_CUTOFF2 = 250 set X_CUTOFF3 = 375 function findNumDots img begin set lower = array list 0 0 0 set upper = array list 15 15 15 set shapeMask = call inRange img lower upper image show string M...
import numpy as np import cv2 W = 500.0 Y_CUTOFF1 = 420 Y_CUTOFF2 = 300 Y_CUTOFF3 = 150 X_CUTOFF1 = 115 X_CUTOFF2 = 250 X_CUTOFF3 = 375 def findNumDots(img): lower = np.array([0, 0, 0]) upper = np.array([15, 15, 15]) shapeMask = cv2.inRange(img, lower, upper) cv2.imshow("Mask", shapeMask) cv2.waitKey(0) # find...
Python
zaydzuhri_stack_edu_python
function advance self begin set pos = pos + 1 if pos > length text - 1 begin comment Indicates end of input set current_char = none end else begin set current_char = text at pos end end function
def advance(self): self.pos += 1 if self.pos > len(self.text) - 1: self.current_char = None # Indicates end of input else: self.current_char = self.text[self.pos]
Python
nomic_cornstack_python_v1
function test_atomic_unsigned_long_max_exclusive_3_nistxml_sv_iv_atomic_unsigned_long_max_exclusive_4_2 mode save_output output_format begin call assert_bindings schema=string nistData/atomic/unsignedLong/Schema+Instance/NISTSchema-SV-IV-atomic-unsignedLong-maxExclusive-4.xsd instance=string nistData/atomic/unsignedLon...
def test_atomic_unsigned_long_max_exclusive_3_nistxml_sv_iv_atomic_unsigned_long_max_exclusive_4_2(mode, save_output, output_format): assert_bindings( schema="nistData/atomic/unsignedLong/Schema+Instance/NISTSchema-SV-IV-atomic-unsignedLong-maxExclusive-4.xsd", instance="nistData/atomic/unsignedLong...
Python
nomic_cornstack_python_v1
comment Howard: 6.5 min function fibonacci a b iterations max_iterations begin comment print ("\ta:", a, " | b: ", b) if iterations + 1 > max_iterations begin return a end return call fibonacci b a + b iterations + 1 max_iterations end function set lines = list open string Prob04.in.txt set n = integer lines at 0 comme...
# Howard: 6.5 min def fibonacci(a, b, iterations, max_iterations): # print ("\ta:", a, " | b: ", b) if( iterations + 1 > max_iterations): return a; return fibonacci(b, a + b, iterations + 1, max_iterations) lines = list(open('Prob04.in.txt')) n = int(lines[0]) # print (n) for i in range(1, n + 1): i...
Python
zaydzuhri_stack_edu_python
from typing import NamedTuple from bert_api.segmented_instance.seg_instance import SegmentedInstance from bert_api.segmented_instance.segmented_text import text_to_word_level_segmented_text class RelatedEvalInstance extends NamedTuple begin set problem_id : str set seg_instance : SegmentedInstance set score : float dec...
from typing import NamedTuple from bert_api.segmented_instance.seg_instance import SegmentedInstance from bert_api.segmented_instance.segmented_text import text_to_word_level_segmented_text class RelatedEvalInstance(NamedTuple): problem_id: str seg_instance: SegmentedInstance score: float @classmeth...
Python
zaydzuhri_stack_edu_python
function raw_write self location_a location_b value begin if is instance value Info begin raise call TypeError string Use append or append_uniq to store vulnerabilities end set location_a = call _get_real_name location_a clear self location_a location_b append self location_a location_b value ignore_type=true end funct...
def raw_write(self, location_a, location_b, value): if isinstance(value, Info): raise TypeError('Use append or append_uniq to store vulnerabilities') location_a = self._get_real_name(location_a) self.clear(location_a, location_b) self.append(location_a, location_b, value, i...
Python
nomic_cornstack_python_v1
function initialize_new_state self begin pass end function
def initialize_new_state(self): pass
Python
nomic_cornstack_python_v1
function getUrlFiles url tag begin set u = url open url set xml = read u close u set dom = call parseString xml comment Get file list: set fileList = list set previousFilename = string for fe in call getElementsByTagName tag begin set fitsFile = string data comment exclude consecutive duplicates: if fitsFile != previ...
def getUrlFiles(url,tag): u = urllib.urlopen(url) xml = u.read() u.close() dom = parseString(xml) # Get file list: fileList = [] previousFilename ="" for fe in dom.getElementsByTagName(tag): fitsFile = str(fe.getElementsByTagName('filename')[0].childNodes[0].data) # excl...
Python
nomic_cornstack_python_v1
comment Implement Baum-Welch Learning comment http://rosalind.info/problems/BA10K/ comment Given: A sequence of emitted symbols x = x1 . comment . . xn in an alphabet A, generated by a k-state comment HMM with unknown transition and emission probabilities, comment initial Transition and Emission matrices and comment a ...
################################################## # Implement Baum-Welch Learning # # http://rosalind.info/problems/BA10K/ # # Given: A sequence of emitted symbols x = x1 . # . . xn in an alphabet A, generated by a k-state # HMM with unknown transition and emission probabilities, # initial Transition and Emission ...
Python
zaydzuhri_stack_edu_python
function vector_settings self vector_settings begin set _vector_settings = vector_settings end function
def vector_settings(self, vector_settings): self._vector_settings = vector_settings
Python
nomic_cornstack_python_v1
function add x y begin string Add two number return x + y end function function subtract x y begin string Substract two number return x - y end function function multiply x y begin string Multiply two number return x * y end function function divide x y begin string Divide two numbers return x / y end function function...
def add(x , y): """Add two number""" return x + y def subtract(x,y): """Substract two number""" return x - y def multiply(x,y): """Multiply two number""" return x * y def divide(x, y): """Divide two numbers""" return x / y def modulus(x, y): """Return the remainder (modulus) of t...
Python
zaydzuhri_stack_edu_python
function _create_nncf_config preset target_device subset_size model_type ignored_scope advanced_parameters begin if model_type is none begin set compression_config = call _get_default_quantization_config preset subset_size end else if model_type == TRANSFORMER begin set compression_config = call _get_transformer_quanti...
def _create_nncf_config( preset: QuantizationPreset, target_device: TargetDevice, subset_size: int, model_type: Optional[ModelType], ignored_scope: Optional[IgnoredScope], advanced_parameters: Optional[AdvancedQuantizationParameters], ) -> NNCFConfig: if model_type is None: compressi...
Python
nomic_cornstack_python_v1
function testCreateCDMatrix self begin set md = call PropertySet set string NAXIS 2 set string CTYPE1 string RA---TAN set string CTYPE2 string DEC--TAN set string CRPIX1 0 set string CRPIX2 0 set string CRVAL1 0 set string CRVAL2 0 set string RADECSYS string FK5 set string EQUINOX 2000.0 set wcs = call makeWcs md asser...
def testCreateCDMatrix(self): md = dafBase.PropertySet() md.set("NAXIS", 2) md.set("CTYPE1", "RA---TAN") md.set("CTYPE2", "DEC--TAN") md.set("CRPIX1", 0) md.set("CRPIX2", 0) md.set("CRVAL1", 0) md.set("CRVAL2", 0) md.set("RADECSYS", "FK5") ...
Python
nomic_cornstack_python_v1
comment list comprehensions comment list comprehensions make the code cleaner as well works faster than normal looping. comment ----- ----- ----- comment integer list from 0 to 10. set l = list comprehension i for i in range 10 comment this is equivalent to: set l1 = list for i in range 10 begin append l1 i end commen...
# list comprehensions # list comprehensions make the code cleaner as well works faster than normal looping. # ----- ----- ----- l=[i for i in range(10)] # integer list from 0 to 10. # this is equivalent to: l1=[] for i in range(10): l1.append(i) # ----- ----- ----- m=[i**2 for i in range(10)] ...
Python
zaydzuhri_stack_edu_python
function is_special_kernel_valid self begin try begin if get environ string SPY_AUTOLOAD_PYLAB_O == string True begin import matplotlib end else if get environ string SPY_SYMPY_O == string True begin import sympy end else if get environ string SPY_RUN_CYTHON == string True begin import cython end end except Exception b...
def is_special_kernel_valid(self): try: if os.environ.get('SPY_AUTOLOAD_PYLAB_O') == 'True': import matplotlib elif os.environ.get('SPY_SYMPY_O') == 'True': import sympy elif os.environ.get('SPY_RUN_CYTHON') == 'True': import cy...
Python
nomic_cornstack_python_v1
import treenode_ import field_ import copy from sys import stdin , stdout from game_ import Game from main import Main class Bot begin function __init__ self begin set _game = call Game set _main = call Main _game end function function evaluate_pos self pos bot field piece begin set list_aggr = list set a = - 0.510066...
import treenode_ import field_ import copy from sys import stdin, stdout from game_ import Game from main import Main class Bot: def __init__(self): self._game = Game() self._main = Main(self._game) def evaluate_pos(self,pos,bot, field, piece): list_aggr=[] a = -0.510066 ...
Python
zaydzuhri_stack_edu_python
import random function shuffle arr begin set i = 0 while i < length arr begin set index = random integer 0 i set swap = arr at index set arr at index = arr at i set arr at i = swap set i = i + 1 end return arr end function function recShuffle arr i begin if i == 0 begin return arr end set rand = random integer 0 i set ...
import random def shuffle(arr): i = 0 while i < len(arr): index = random.randint(0, i) swap = arr[index] arr[index] = arr[i] arr[i] = swap i+=1 return arr def recShuffle(arr, i): if i == 0: return arr rand = random.randint(0, i) swap = arr[rand] arr[rand] = arr[i] arr[i] = swap return recShuffle(...
Python
zaydzuhri_stack_edu_python
function reset self interval=none begin if interval is not none and is instance interval datetime begin set interval = call mktime call timetuple - time end else if interval is not none begin set interval = interval end set expiry = time + interval end function
def reset(self, interval=None): if interval is not None and isinstance(interval, datetime): self.interval = mktime(interval.timetuple()) - time() elif interval is not None: self.interval = interval self.expiry = time() + self.interval
Python
nomic_cornstack_python_v1
import re import socket import ssl from base64 import b64encode from smtp.smtp_exception import SMTPError set B_SIZE = 4096 set CODE_PATTERN = compile string (\d{3}) function create_connection_security addr port user begin set sock = call socket AF_INET SOCK_STREAM set sock = call wrap_socket sock call settimeout 1 cal...
import re import socket import ssl from base64 import b64encode from smtp.smtp_exception import SMTPError B_SIZE = 4096 CODE_PATTERN = re.compile('(\d{3})') def create_connection_security(addr, port, user): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = ssl.wrap_socket(sock) sock.settim...
Python
zaydzuhri_stack_edu_python
function send cmd server_host server_port debug begin set log = call get_logger __name__ debug set app = call WsCmdApp server_host server_port cmd debug=debug try begin call main end finally begin debug string done end end function
def send(cmd, server_host, server_port, debug): log = get_logger(__name__, debug) app = WsCmdApp(server_host, server_port, cmd, debug=debug) try: app.main() finally: log.debug('done')
Python
nomic_cornstack_python_v1
function cls_method_fn cls method_name begin return get attribute cls method_name end function
def cls_method_fn(cls, method_name): return getattr(cls, method_name)
Python
nomic_cornstack_python_v1
function upload self fileobj tileset name=none patch=false callback=none bypass=false begin string Upload data and create a Mapbox tileset Effectively replicates the Studio upload feature. Returns a Response object, the json() of which returns a dict with upload metadata. Parameters ---------- fileobj: file object or s...
def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False): """Upload data and create a Mapbox tileset Effectively replicates the Studio upload feature. Returns a Response object, the json() of which returns a dict with upload metadata. Parameters ...
Python
jtatman_500k
function _create_mbean self type_name model_nodes base_location log_created=false begin set _method_name = string _create_mbean call entering type_name string base_location log_created class_name=__class_name method_name=_method_name if model_nodes is none or length model_nodes == 0 or not call _is_type_valid base_loca...
def _create_mbean(self, type_name, model_nodes, base_location, log_created=False): _method_name = '_create_mbean' self.logger.entering(type_name, str(base_location), log_created, class_name=self.__class_name, method_name=_method_name) if model_nodes is None or len(m...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon May 3 01:22:48 2021 @author: Fetibek Aliev set r_1 = decimal input string Введите r_1 - set r_2 = decimal input string Введите r_2 - function compute_resist r_1 r_2 begin set r = r_1 * r_2 / r_1 + r_2 return r end function print call compute_resist r_1 r_2
# -*- coding: utf-8 -*- """ Created on Mon May 3 01:22:48 2021 @author: Fetibek Aliev """ r_1 =float(input("Введите r_1 - ")) r_2 =float(input("Введите r_2 - ")) def compute_resist(r_1, r_2): r = r_1 * r_2 / (r_1 + r_2) return r print(compute_resist(r_1, r_2))
Python
zaydzuhri_stack_edu_python
comment **** Основы объектно-ориентированного программирования (ООП) **** comment Объекты обладает свойствами и методами (умение объекта) comment Каждый объект принадлежит к определенному типу (классу) comment Класс - это "чертеж" объекта comment "Реализация " класса - объект (экземпляр, инстанс) comment Создание класс...
# **** Основы объектно-ориентированного программирования (ООП) **** # Объекты обладает свойствами и методами (умение объекта) # Каждый объект принадлежит к определенному типу (классу) # Класс - это "чертеж" объекта # "Реализация " класса - объект (экземпляр, инстанс) # Создание класса. Название класса принято писать ...
Python
zaydzuhri_stack_edu_python
function collision_cost L d m obstacle threshold dt begin set Jc = zeros 3 comment If dt == 1, T = [0] comment * time_scaling set T = array range 0 1 dt for i in range 3 begin comment Second cost value set summation_cost = 0 for j in range m begin for t in T begin set P_vector = zeros m * 10 set V_vector = zeros m * 10...
def collision_cost(L, d, m, obstacle, threshold, dt): Jc = np.zeros(3) # If dt == 1, T = [0] T = np.arange(0, 1, dt) # * time_scaling for i in range(3): # Second cost value summation_cost = 0 for j in range(m): for t in T: P_vector = np.zeros(m * 1...
Python
nomic_cornstack_python_v1
function _compute_objective Cb isigma_b begin return call trace dot isigma_b Cb - 2 * sum log call diag call cholesky isigma_b end function
def _compute_objective(Cb, isigma_b): return np.trace(np.dot(isigma_b, Cb)) - 2 * np.sum (np.log(np.diag(linalg.cholesky(isigma_b))))
Python
nomic_cornstack_python_v1
function sort_terms dictionary begin return list comprehension term for term in sorted dictionary end function
def sort_terms(dictionary): return [term for term in sorted(dictionary)]
Python
nomic_cornstack_python_v1
comment Import the Workspace and Datastore from azureml.core import Workspace , Datastore , Dataset string Let's acces to workspace The work space was created before in the sricpt "create_workspace.py" set ws = call from_config path=string ./config string Let's access to datastore (in Azure cloud) -------- recall : ---...
# Import the Workspace and Datastore from azureml.core import Workspace, Datastore, Dataset """ Let's acces to workspace The work space was created before in the sricpt "create_workspace.py" """ ws = Workspace.from_config(path="./config") """ Let's access to datastore (in Azure cloud) -------- recall : ----------...
Python
zaydzuhri_stack_edu_python
function getAliasList self begin pass end function
def getAliasList(self): pass
Python
nomic_cornstack_python_v1
function quote_handles_blank self begin call login string cs50 string ohHai28! call status 400 end function
def quote_handles_blank(self): self.login("cs50", "ohHai28!") self.quote("").status(400)
Python
nomic_cornstack_python_v1
function test_put_not_allowed self begin call assertViewBehavior dict string put unique method=string put status_code=405 end function
def test_put_not_allowed(self): self.assertViewBehavior( {"put": self.unique()}, method="put", status_code=405)
Python
nomic_cornstack_python_v1
async function _opt_set self ctx param arg begin set param = lower param set opt_list = OPTIONS_LIST if param in keys opt_list begin if is instance arg opt_list at param begin execute db format string UPDATE options SET {} = %s WHERE guild_id = %s; param tuple arg string id await call send string { param } set to { arg...
async def _opt_set(self, ctx, param: str, arg: typing.Union[int, str]): param = param.lower() opt_list = ctx.bot.OPTIONS_LIST if param in opt_list.keys(): if(isinstance(arg, opt_list[param])): self.bot.db.execute(""" UPDATE options SET {} = %s ...
Python
nomic_cornstack_python_v1
from PIL import Image , ImageColor import os from ast import literal_eval function main begin set path = string ./sus_files/ for file in list directory path begin if ends with file string .txt or file == string 6 begin call createImage path file end end end function function createImage path file begin print string Cre...
from PIL import Image, ImageColor import os from ast import literal_eval def main(): path = './sus_files/' for file in os.listdir(path): if file.endswith('.txt') or file == '6': createImage(path, file) def createImage(path, file): print('Creating Image: ', file) file_content = read_file(path + file) image...
Python
zaydzuhri_stack_edu_python
function update_next_round_data args bin matched_subs_dataset1 matched_subs_dataset2 name1=string MACC name2=string ADNI begin set curr_round_data_path = join path checkpoint_path matching_pair string matching_ + string nb_bins + string BINs string BIN_ + string bin string round_ + string round set next_round_data_path...
def update_next_round_data(args, bin, matched_subs_dataset1, matched_subs_dataset2, name1='MACC', name2='ADNI'): curr_round_data_path = os.path.join( args.checkpoint_path, a...
Python
nomic_cornstack_python_v1
from datetime import datetime as date import csv from copy import * from Sheets import * class Date begin function __init__ self begin set Annee = 0 set Mois = 0 set Jour = 0 set Heure = 0 set Minute = 0 end function function Maintenant self begin set D = now return Annee == year and Mois == month and Jour == day and a...
from datetime import datetime as date import csv from copy import * from Sheets import * class Date: def __init__(self): self.Annee = 0 self.Mois = 0 self.Jour = 0 self.Heure = 0 self.Minute = 0 def Maintenant(self): D = date.now() return (self.Annee == ...
Python
zaydzuhri_stack_edu_python
for i in range 0 n 1 begin set idade = integer input string digite idade: if idade > maior begin set maior = idade end if idade < menor begin set menor = idade end end print maior print menor
for i in range(0,n,1): idade=int(input('digite idade: ')) if idade>maior: maior=idade if idade<menor: menor=idade print(maior) print(menor)
Python
zaydzuhri_stack_edu_python
comment What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? function find_smallest_multiple cap begin set smallest_multiple = cap set state = true while state begin for x in range 1 cap + 1 begin if smallest_multiple % x == 0 and x != cap begin continue end else if smallest...
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def find_smallest_multiple(cap): smallest_multiple = cap state = True while state: for x in range(1, cap+1): if smallest_multiple % x == 0 and x != cap: continue ...
Python
zaydzuhri_stack_edu_python
async function get_token self *scopes **kwargs begin comment pylint:disable=unused-argument return call AccessToken token expiry end function
async def get_token( self, *scopes: str, **kwargs: Any # pylint:disable=unused-argument ) -> AccessToken: return AccessToken(self.token, self.expiry)
Python
nomic_cornstack_python_v1
from numpy import zeros , dot , diag , sqrt , ones , exp , complexfloating , linspace , conjugate , zeros_like from scipy.linalg import norm , eig , expm , inv import time function construct_matrix N kind=string minij begin function delta i j begin return if expression i == j then 1 else 0 end function set H = zeros tu...
from numpy import zeros, dot, diag, sqrt, ones, exp, complexfloating, linspace, conjugate, zeros_like from scipy.linalg import norm, eig, expm, inv import time def construct_matrix(N, kind='minij'): def delta(i, j): return 1 if i == j else 0 H = zeros((N, N), dtype=complexfloating)
Python
zaydzuhri_stack_edu_python
import kivy call require string 1.11.1 from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty import sqlite3 as sql from kivy.uix.screenmanager import ScreenManager , Screen class Start extends Screen begin set user = call ObjectProperty set password = call ObjectPr...
import kivy kivy.require('1.11.1') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty import sqlite3 as sql from kivy.uix.screenmanager import ScreenManager,Screen class Start(Screen): user = ObjectProperty() password = ObjectProperty() def get_s...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Implementation of the LANG data model import codecs import copy import os import glob from unicode_tools import simplify_spaces , to_latin from eg_one import EG_One from eg_trans import EG_Trans from eg_grammar import EG_Grammar from forms import Forms set ENCODING = string utf-8 se...
# -*- coding: utf-8 -*- """Implementation of the LANG data model""" import codecs import copy import os import glob from unicode_tools import simplify_spaces, to_latin from eg_one import EG_One from eg_trans import EG_Trans from eg_grammar import EG_Grammar from forms import Forms ENCODING = 'utf-8' DATA_FILES = '*...
Python
zaydzuhri_stack_edu_python
function read_file file begin set line = read file set pair = list comprehension integer s for s in split line if is digit s return tuple pair at 0 pair at 1 end function function get_digit_count X begin set dc = 0 while X > 0 begin set dc = dc + 1 set X = X // 10 end return dc end function function f X N begin set val...
def read_file(file): line = file.read() pair = [int(s) for s in line.split() if s.isdigit()] return pair[0], pair[1] def get_digit_count(X): dc = 0 while X > 0: dc += 1 X = X // 10 return dc def f(X, N): val = 0 digit_count = get_digit_count(X) # digits count in th...
Python
zaydzuhri_stack_edu_python
function namespace_needs_visibility self diagnostics=none context=none begin raise call NotImplementedError string operation namespace_needs_visibility(...) not yet implemented end function
def namespace_needs_visibility(self, diagnostics=None, context=None): raise NotImplementedError( 'operation namespace_needs_visibility(...) not yet implemented')
Python
nomic_cornstack_python_v1
string Provides utilities to clean up the chapter records read in via CSV from Moodle courses from datetime import datetime , timedelta function hour_checker student begin set student = student set dd_1 = 0 set dd_2 = 0 set dd_3 = 0 set dd_4 = 0 set dd_5 = 0 for tuple k v in items student begin if k == string Complete ...
""" Provides utilities to clean up the chapter records read in via CSV from Moodle courses """ from datetime import datetime, timedelta def hour_checker(student): student = student dd_1 = 0 dd_2 = 0 dd_3 = 0 dd_4 = 0 dd_5 = 0 for k, v in student.items(): if k == "Complete chapte...
Python
zaydzuhri_stack_edu_python
function random_private_image begin set high = call private_count set random_id = call integers low=1 high=high size=1 at 0 return call private_image_by_id integer random_id end function
def random_private_image() -> dict: high = DB.private_count() random_id = rng.integers(low=1, high=high, size=1)[0] return DB.private_image_by_id(int(random_id))
Python
nomic_cornstack_python_v1
function _coordinates self begin raise NotImplementedError end function
def _coordinates(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string https://www.hackerrank.com/challenges/append-and-delete comment !/bin/python import sys set s = strip call raw_input set t = strip call raw_input set k = integer strip call raw_input set lens = length s set lent = length t set samesies = true set matches = 0 for ix in range min lent...
# -*- coding: utf-8 -*- """ https://www.hackerrank.com/challenges/append-and-delete """ #!/bin/python import sys s = raw_input().strip() t = raw_input().strip() k = int(raw_input().strip()) lens = len(s) lent = len(t) samesies = True matches = 0 for ix in range(min(lent, lens)): if s[ix] == t[ix]: matche...
Python
zaydzuhri_stack_edu_python
function successive_poisson tau1 tau2 size=1 begin comment Draw samples out of first exponential distribution: t1 set t1 = call exponential tau1 size comment Draw samples out of second exponential distribution: t2 set t2 = call exponential tau2 size return t1 + t2 end function
def successive_poisson(tau1, tau2, size=1): # Draw samples out of first exponential distribution: t1 t1 = np.random.exponential(tau1, size) # Draw samples out of second exponential distribution: t2 t2 = np.random.exponential(tau2, size) return t1 + t2
Python
nomic_cornstack_python_v1
function max_current self begin return _max_current end function
def max_current(self): return self._max_current
Python
nomic_cornstack_python_v1
function update self begin set sum = call calculateSum call sendEmail end function
def update(self): self.sum = self.calculateSum() self.sendEmail()
Python
nomic_cornstack_python_v1
for tuple s ns in zip S S at slice 1 : : begin if s + ns == string AC begin print string Yes exit end end print string No
for s, ns in zip(S, S[1:]): if s + ns == "AC": print("Yes") exit() print("No")
Python
jtatman_500k
function get_networkx_func func_name seed=0 **kwargs begin set nx_func = get attribute call import_module string networkx func_name set generated_graph = call nx_func seed=seed keyword kwargs return generated_graph end function
def get_networkx_func (func_name, seed=0, **kwargs): nx_func = getattr(importlib.import_module("networkx"), func_name) generated_graph = nx_func(seed=seed, **kwargs) return generated_graph
Python
nomic_cornstack_python_v1
set N = integer input string студентов: set K = integer input string яблук: set appleForStudent = K // N set appleInBag = K % N print string Сколько яблок на студента appleForStudent print string Сколько яблок в ящике appleInBag
N = int(input("студентов:")) K = int(input("яблук:")) appleForStudent = K // N appleInBag = K % N print("Сколько яблок на студента",appleForStudent) print("Сколько яблок в ящике",appleInBag)
Python
zaydzuhri_stack_edu_python
import pickle import codecs set data_path = string D:/data/defect-detection/ function pickle_to_text dataset=string test begin set data = load pickle open data_path + string tokenized_ + dataset + string .pickle string rb print dataset + string loaded, + string length data set wp = open data_path + dataset + string .tx...
import pickle import codecs data_path = 'D:/data/defect-detection/' def pickle_to_text(dataset='test'): data = pickle.load(open(data_path + 'tokenized_' + dataset + '.pickle', 'rb')) print(dataset + ' loaded, ' + str(len(data))) wp = codecs.open(data_path + dataset + '.txt', 'w', 'utf-8') cnt = 0 ...
Python
zaydzuhri_stack_edu_python
import numpy as np class CrossEntropy extends object begin function __init__ self stabilizer=1e-06 begin string :param stabilizer: A small value used to prevent division by zero in bprop. Will make the derivatives slightly inaccurate. :return: set _stabilizer = stabilizer end function function fprop self Y Y_true meta ...
import numpy as np class CrossEntropy(object): def __init__(self, stabilizer=1e-6): """ :param stabilizer: A small value used to prevent division by zero in bprop. Will make the derivatives slightly inaccurate. :return: """ self._stabilizer = stabilizer def fprop(self...
Python
zaydzuhri_stack_edu_python
import os , sys from ROOT import TFile , TH1D
import os, sys from ROOT import TFile, TH1D
Python
zaydzuhri_stack_edu_python
comment Libarary User ######## class Address begin function __init__ self city country begin set __city = city set __country = country end function function lib self begin print string the library is in { __city } { __country } end function end class class Person begin set dic = dict set member_id = 0 function __init_...
###### Libarary User ######## class Address: def __init__(self,city, country): self.__city = city self.__country = country def lib(self): print(f'the library is in {self.__city} {self.__country} ') class Person: dic = {} member_id = 0 def __init__(self, name, email): self.name = name s...
Python
zaydzuhri_stack_edu_python
function timeit func log limit begin string Print execution time of the function. For quick'n'dirty profiling. function newfunc *args **kwargs begin string Execute function and print execution time. set t = time set res = call func *args keyword kwargs set duration = time - t if duration > limit begin print __name__ st...
def timeit (func, log, limit): """Print execution time of the function. For quick'n'dirty profiling.""" def newfunc (*args, **kwargs): """Execute function and print execution time.""" t = time.time() res = func(*args, **kwargs) duration = time.time() - t if duration > li...
Python
jtatman_500k
function _chat_invite self chat user_id begin set error = call invite_room chat user_id if error != string begin call receive_msg error error end end function
def _chat_invite(self, chat: str, user_id: str) -> None: error = self.client.invite_room(chat, user_id) if error != "": self.account.receive_msg(Message.error(error))
Python
nomic_cornstack_python_v1
function cli_condense outfile m8_alignment begin call condense_alignment outfile m8_alignment logger=lambda x -> call echo x err=true end function
def cli_condense(outfile, m8_alignment): condense_alignment( outfile, m8_alignment, logger=lambda x: click.echo(x, err=True), )
Python
nomic_cornstack_python_v1
function _get_address_by_hash self block_hash begin string Get mapped address by its hash. :param block_hash: :return: set address_key = address_prefix + block_hash return get db address_key end function
def _get_address_by_hash(self, block_hash): """Get mapped address by its hash. :param block_hash: :return: """ address_key = address_prefix + block_hash return self.db.get(address_key)
Python
jtatman_500k
function get_parameters_nodes input_nodes begin set parameters = list for node in input_nodes begin if is_trainable begin append parameters node end end return parameters end function
def get_parameters_nodes(input_nodes): parameters = list() for node in input_nodes: if node.is_trainable: parameters.append(node) return parameters
Python
nomic_cornstack_python_v1
function _make_presentable self datum begin if is instance datum dict begin set iid = string get datum string id set model_instance = model keyword datum set instance = to json model_instance encode=false end else begin set iid = string id set instance = to json datum encode=false end set data = call make_safe_json mod...
def _make_presentable(self, datum): if isinstance(datum, dict): iid = str(datum.get('id')) model_instance = self.model(**datum) instance = to_json(model_instance, encode=False) else: iid = str(datum.id) instance = to_json(datum, encode=False) ...
Python
nomic_cornstack_python_v1
string ============================ 하이퍼파라미터 서치 함수 ============================ SVM 파라미터 서치 함수 - C, gamma, epsilon 서치 import math import itertools import optunity import optunity.metrics import sklearn.svm import pymssql import matplotlib.pyplot as plt import numpy as np from sklearn import svm from sklearn import prepr...
""" ============================ 하이퍼파라미터 서치 함수 ============================ SVM 파라미터 서치 함수 - C, gamma, epsilon 서치 """ import math import itertools import optunity import optunity.metrics import sklearn.svm import pymssql import matplotlib.pyplot as plt import numpy as np from sklearn import svm from sklearn import pre...
Python
zaydzuhri_stack_edu_python
function update_draw self begin update selected_level call draw end function
def update_draw(self): self.selected_level.update() self.selected_level.draw()
Python
nomic_cornstack_python_v1
function pc_work_time self begin return call Parity_interleaver_ATSC_sptr_pc_work_time self end function
def pc_work_time(self): return _mack_sdr_rossi_swig.Parity_interleaver_ATSC_sptr_pc_work_time(self)
Python
nomic_cornstack_python_v1
function bokeh self begin if _chartEngine is none begin set _chartEngine = call DsChart end set engine = string bokeh end function
def bokeh(self) -> None: if self._chartEngine is None: self._chartEngine = DsChart() self._chartEngine.engine = "bokeh"
Python
nomic_cornstack_python_v1
function _transform self X begin set X_tf = call expand_and_copy_tensor X=X batch_shape=batch_shape set k = call Kumaraswamy concentration1=concentration1 concentration0=concentration0 comment normalize to [eps, 1-eps] set X_tf at tuple Ellipsis indices = call cdf clamp torch X_tf at tuple Ellipsis indices * _X_range +...
def _transform(self, X: Tensor) -> Tensor: X_tf = expand_and_copy_tensor(X=X, batch_shape=self.batch_shape) k = Kumaraswamy( concentration1=self.concentration1, concentration0=self.concentration0 ) # normalize to [eps, 1-eps] X_tf[..., self.indices] = k.cdf( ...
Python
nomic_cornstack_python_v1
set n = integer input set binary = list while 1 begin set a = n // 2 set b = n % 2 set n = a insert binary 0 b if a == 0 begin break end end print join string map str binary
n = int(input()) binary = [] while(1): a = n // 2 b = n % 2 n = a binary.insert(0, b) if(a == 0): break print(''.join(map(str, binary)))
Python
zaydzuhri_stack_edu_python
import random function create_phone_number begin set first_digit = random integer 2 9 set second_digit = random integer 0 1 set third_digit = random choice list 2 3 4 5 6 9 set remaining_digits = random choices range 10 k=6 set phone_number = list first_digit second_digit third_digit + remaining_digits comment Sorts th...
import random def create_phone_number(): first_digit = random.randint(2, 9) second_digit = random.randint(0, 1) third_digit = random.choice([2, 3, 4, 5, 6, 9]) remaining_digits = random.choices(range(10), k=6) phone_number = [first_digit, second_digit, third_digit] + remaining_digits phone_numb...
Python
greatdarklord_python_dataset
from src.Statement import Statement from src.Report import Report import pandas as pd import os set file = join path get current directory string test string files string Test.pdf set s = call Statement file set r = call Report list s function test_statements begin assert is instance statements list for statement in st...
from src.Statement import Statement from src.Report import Report import pandas as pd import os file = os.path.join(os.getcwd(), 'test', 'files', 'Test.pdf') s = Statement(file) r = Report([s]) def test_statements(): assert isinstance(r.statements, list) for statement in r.statements: assert isinstance(statem...
Python
zaydzuhri_stack_edu_python
function run self fetch_list feed_dict=none sess=none begin string Runs the graph with the provided feeds and fetches. This function wraps sess.Run(), but takes care of state saving and restoring by feeding in states and storing the new state values. Args: fetch_list: A list of requested output tensors. feed_dict: A di...
def run(self, fetch_list, feed_dict=None, sess=None): """Runs the graph with the provided feeds and fetches. This function wraps sess.Run(), but takes care of state saving and restoring by feeding in states and storing the new state values. Args: fetch_list: A list of requested output tensors. ...
Python
jtatman_500k
function _state_set_vaex_5 self state use_active_range=false keep_columns=none set_filter=true trusted=true warn=true begin set description = state at string description if use_active_range begin set tuple _index_start _index_end = state at string active_range end set _length_unfiltered = _index_end - _index_start if k...
def _state_set_vaex_5(self, state, use_active_range=False, keep_columns=None, set_filter=True, trusted=True, warn=True): self.description = state['description'] if use_active_range: self._index_start, self._index_end = state['active_range'] self._length_unfiltered = self._index_end -...
Python
nomic_cornstack_python_v1
function substitute self args lvars within_list begin if call is_String args and not is instance args CmdStringHolder begin comment In case it's a UserString. set args = string args set args = find all args for a in args begin if a at 0 in string begin if string in a begin call next_line end else if within_list begin...
def substitute(self, args, lvars, within_list): if is_String(args) and not isinstance(args, CmdStringHolder): args = str(args) # In case it's a UserString. args = _separate_args.findall(args) for a in args: if a[0] in ' \t\n\r\f\v': ...
Python
nomic_cornstack_python_v1
import os import pickle import numpy as np import tensorflow as tf from keras import backend as K import random function mean_squared_error y_true y_pred begin print string mse buatan shape shape return mean K call square y_pred - y_true axis=- 1 end function function negative_log_likelihood_w point distribution begin ...
import os import pickle import numpy as np import tensorflow as tf from keras import backend as K import random def mean_squared_error(y_true, y_pred): print('mse buatan', y_true.shape, y_pred.shape) return K.mean(K.square(y_pred - y_true), axis=-1) def negative_log_likelihood_w(point, distribution): pri...
Python
zaydzuhri_stack_edu_python
with open filename as file_object begin set lines = read lines file_object end set pi_string = string comment 用于存储文件的值 for line in lines begin set pi_string = pi_string + right strip line end comment 使用循环将各行都加入pi_string,并删除末尾的换行符 print pi_string print length pi_string set filename = string pi_digits.txt with open file...
with open(filename)as file_object: lines=file_object.readlines() pi_string='' #用于存储文件的值 for line in lines: pi_string+=line.rstrip() #使用循环将各行都加入pi_string,并删除末尾的换行符 print(pi_string) print(len(pi_string)) filename='pi_digits.txt' with open(filename)as file_object: lines=file_object.readlines() pi_string='' for l...
Python
zaydzuhri_stack_edu_python
function get_spec_matched begin return dict string fields dict string state str ; string entity str ; string explanation str ; string sorting dict string field string entity ; string ordering string asc end function
def get_spec_matched(): return { 'fields': { 'state': str, 'entity': str, 'explanation': str, }, 'sorting': { 'field': 'entity', 'ordering': 'asc', } }
Python
nomic_cornstack_python_v1
function supports_http_1_1 self begin return version == string HTTP/1.1 end function
def supports_http_1_1(self): return self.version == "HTTP/1.1"
Python
nomic_cornstack_python_v1
comment real signature unknown; restored from __doc__ function svn_client_url_from_path char_url char_path_or_url apr_pool_t_pool begin pass end function
def svn_client_url_from_path(char_url, char_path_or_url, apr_pool_t_pool): # real signature unknown; restored from __doc__ pass
Python
nomic_cornstack_python_v1
import numpy as np import lsst.sims.skybrightness as sb import unittest import lsst.sims.photUtils.Bandpass as Bandpass from lsst.utils import getPackageDir import os class TestSkyModel extends TestCase begin function testmergedComp self begin string Test that the 3 components that have been merged return the same resu...
import numpy as np import lsst.sims.skybrightness as sb import unittest import lsst.sims.photUtils.Bandpass as Bandpass from lsst.utils import getPackageDir import os class TestSkyModel(unittest.TestCase): def testmergedComp(self): """ Test that the 3 components that have been merged return the ...
Python
zaydzuhri_stack_edu_python
function delete_module modname begin string Delete module and sub-modules from `sys.module` try begin set _ = modules at modname end except KeyError begin raise call ValueError format string Module not found in sys.modules: '{}' modname end for module in list keys modules begin if module and starts with module modname ...
def delete_module(modname): """ Delete module and sub-modules from `sys.module` """ try: _ = sys.modules[modname] except KeyError: raise ValueError("Module not found in sys.modules: '{}'".format(modname)) for module in list(sys.modules.keys()): if module and module.start...
Python
jtatman_500k
import unicodedata import itertools comment https://docs.python.org/3/library/itertools.html#itertools-recipes function pairwise iterable begin string s -> (s0,s1), (s1,s2), (s2, s3), ... set tuple a b = tee iterable next b none return zip a b end function comment http://ls.pwd.io/2014/08/singly-and-doubly-linked-lists...
import unicodedata import itertools # https://docs.python.org/3/library/itertools.html#itertools-recipes def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return zip(a, b) #http://ls.pwd.io/2014/08/singly-and-doubly-linked-lists-in-python/ clas...
Python
zaydzuhri_stack_edu_python