code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function linear_search arr target begin string Searches through a given input array to find the index of a provided target number. Returns -1 if the target number is not found. for i in range length arr begin if arr at i == target begin return i end end return - 1 end function
def linear_search(arr, target): """ Searches through a given input array to find the index of a provided target number. Returns -1 if the target number is not found. """ for i in range(len(arr)): if arr[i] == target: return i return -1
Python
jtatman_500k
function test_handle_other_connection_response self begin set response = call resp set status_code = 502 call assertEquals call _TimeSync__response_to_python response dict error string connection to TimeSync failed at baseurl http://ts.example.com/v1 - response status was 502 end function
def test_handle_other_connection_response(self): response = resp() response.status_code = 502 self.assertEquals(self.ts._TimeSync__response_to_python(response), {self.ts.error: "connection to TimeSync failed at baseurl " ...
Python
nomic_cornstack_python_v1
function test_user_schema begin set data = dict string id 1 ; string name string Name Test Unit ; string cpf string 12345678912 ; string birth_date string 1991-07-13 set user = load user_schema data assert is instance user dict == true assert user at string id == 1 assert user at string name == string Name Test Unit as...
def test_user_schema(): data = { 'id': 1, 'name': 'Name Test Unit', 'cpf': '12345678912', 'birth_date': '1991-07-13' } user = user_schema.load(data) assert isinstance(user, dict) == True assert user['id'] == 1 assert user['name'] == 'Name Test Unit' assert u...
Python
nomic_cornstack_python_v1
function reverseVowels s begin set ls = list s set tuple i j = tuple 0 length ls - 1 set vowel = list string a string A string e string i string o string u string E string I string O string U while i < j begin while i < j and ls at i not in vowel begin set i = i + 1 end while i < j and ls at j not in vowel begin set j ...
def reverseVowels(s): ls = list(s) i ,j = 0 ,len(ls)-1 vowel = ['a','A','e','i','o','u','E','I','O','U'] while i<j: while i<j and ls[i] not in vowel: i+=1 while i<j and ls[j] not in vowel: j-=1 if i<j: ls[i] , ls[j] = ls[j] , ls[i] ...
Python
zaydzuhri_stack_edu_python
function superReducedString s begin if not s begin return string Empty String end for i in range 0 length s begin if i < length s - 1 begin if s at i == s at i + 1 begin return call superReducedString s at slice : i : + s at slice i + 2 : : end end end return s end function print call superReducedString string aaabc...
def superReducedString(s): if not s: return "Empty String" for i in range(0,len(s)): if i < len(s)-1: if s[i] == s[i+1]: return superReducedString(s[:i]+s[i+2:]) return s print(superReducedString('aaabccddd'))
Python
zaydzuhri_stack_edu_python
function recursiveDigitSum n k begin print n k if length string n == 1 begin return n end set arr = list comprehension v for tuple _ v in enumerate string n set sum = 0 for i in range length arr begin set sum = sum + integer arr at i end return call recursiveDigitSum sum * k 1 end function function main begin set n = 9...
def recursiveDigitSum(n,k): print(n,k) if len(str(n))==1: return n arr = [v for (_,v) in enumerate(str(n))] sum = 0; for i in range(len(arr)): sum +=int(arr[i]) return recursiveDigitSum(sum*k,1) def main(): n=9875 k=4 print(recursiveDigitSum(n,k)) if __name__=="__main...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment ============================================================================= comment Copyright (c) Ostap developers. comment ============================================================================= comment @file test_fitting_efficiency.py comment ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Copyright (c) Ostap developers. # ============================================================================= # @file test_fitting_efficiency.py # Test module for ostap/fitting/efficiency.p...
Python
jtatman_500k
function test_name self begin set inst = call Place assert equal name string assert true has attribute inst string name end function
def test_name(self): inst = Place() self.assertEqual(inst.name, "") self.assertTrue(hasattr(inst, "name"))
Python
nomic_cornstack_python_v1
function advertise self routers=none name=none timeout=none router_file=none jitter=none begin if routers is not none and router_file is not none begin raise call ValueError string Only one of routers and router_file can be provided. end if routers is none and router_file is not none begin comment should just let the e...
def advertise(self, routers=None, name=None, timeout=None, router_file=None, jitter=None): if routers is not None and router_file is not None: raise ValueError( 'Only one of routers and router_file can be provided.') if routers is None and router_file is no...
Python
nomic_cornstack_python_v1
for i in data begin if target < i begin break end set target = target + i end print target comment 풀이 전략 string target을 처음에 1로 두고, 입력받은 숫자들과 비교해서 그숫자들을 더해가며 타겟을 업데이트한다. 1~ target-1까지 만들수 있는 상황일 때, target을 만들 수 있는지 판단한다.
for i in data: if target<i: break target+=i print(target) #풀이 전략 ''' target을 처음에 1로 두고, 입력받은 숫자들과 비교해서 그숫자들을 더해가며 타겟을 업데이트한다. 1~ target-1까지 만들수 있는 상황일 때, target을 만들 수 있는지 판단한다. '''
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- from numpy import * import feedparser comment RSS源分类器及高频词去除函数 function calcMostFreq vocabList fullText begin import operator set freqDict = dict comment 遍历词汇表中的每个词 for token in vocabList begin comment 统计每个词在文本中出现的次数 set freqDict at token = count fullText token end comment 根据每个词出现的次数从高到底对字典...
# -*- coding:utf-8 -*- from numpy import * import feedparser #RSS源分类器及高频词去除函数 def calcMostFreq(vocabList,fullText): import operator freqDict={} for token in vocabList: #遍历词汇表中的每个词 freqDict[token]=fullText.count(token) #统计每个词在文本中出现的次数 sortedFreq=sorted(freqDict.iteritems(),key=operator.itemgett...
Python
zaydzuhri_stack_edu_python
function is_on self begin return _state end function
def is_on(self): return self._state
Python
nomic_cornstack_python_v1
function create_python_data self begin set s = scale set tuple minimum maximum = call get_min_max set diff = maximum - minimum set output = dict comment Create the data for the scatters for tuple name data in items scatters_data begin set mapping = scatters at name at string mapping set colormaps = scatters at name at...
def create_python_data(self) -> dict: s = self.scale minimum, maximum = self.get_min_max() diff = maximum - minimum output = {} # Create the data for the scatters for name, data in self.scatters_data.items(): mapping = self.scatters[name]["mapping"]...
Python
nomic_cornstack_python_v1
comment New Subcount for Illustris Hydro, designed for M(<R) output. Currently configured to look primaries with 1sigma around Deason et al. 2012 with R = 50 kpc comment Deason et al. 2012 Range for M(<50kpc): 3.8-4.6e11 import sys import numpy as np comment Taking weighing parameters from command line
#New Subcount for Illustris Hydro, designed for M(<R) output. Currently configured to look primaries with 1sigma around Deason et al. 2012 with R = 50 kpc #Deason et al. 2012 Range for M(<50kpc): 3.8-4.6e11 import sys import numpy as np #Taking weighing parameters from command line
Python
zaydzuhri_stack_edu_python
function tune self begin comment init the environment... set tmp_log_file = log_filename + string .tmp if exists path tmp_log_file begin remove os tmp_log_file end comment set the tunning budget set budget = n_trials * length tasks for tuple i task in enumerate reversed tasks begin call reset task use_transfer_learning...
def tune(self): ### init the environment... tmp_log_file = self.log_filename + ".tmp" if os.path.exists(tmp_log_file): os.remove(tmp_log_file) ### set the tunning budget budget = self.n_trials * len(self.tasks) for i, task in enumerate(reversed(self.tasks)):...
Python
nomic_cornstack_python_v1
function xtss body begin print string [*] request: body set operation = body at string operation if starts with operation string set- begin set ousUID = body at string ousUID set value = body at string value end if operation == string set-state begin set retcode = call setState ousUID=ousUID state=value return retcode ...
def xtss( body ): print(" [*] request: ", body ) operation = body["operation"] if operation.startswith( "set-" ): ousUID = body["ousUID"] value = body["value"] if operation == "set-state": retcode = setState( ousUID=ousUID, state=value ) return retcode elif operati...
Python
nomic_cornstack_python_v1
from collections import defaultdict import sys function closestNumbers arr begin sort arr set diffs = default dictionary list set mindiff = maxsize for i in range length arr - 1 begin set diff = arr at i + 1 - arr at i append diffs at diff i set mindiff = min mindiff diff end set result = list for elem in diffs at min...
from collections import defaultdict import sys def closestNumbers(arr): arr.sort() diffs = defaultdict(list) mindiff = sys.maxsize for i in range(len(arr)-1): diff = arr[i+1] - arr[i] diffs[diff].append(i) mindiff = min(mindiff, diff) result = [] for elem in diffs...
Python
zaydzuhri_stack_edu_python
import cv2 comment color 설정 set black_c = tuple 0 0 0 set white_c = tuple 255 255 255 set blue_c = tuple 255 0 0 set red_c = tuple 0 0 255 set green_c = tuple 0 255 0 set img = call imread string images/person1.jpg IMREAD_COLOR call rectangle img tuple 80 100 160 200 green_c thickness=2 lineType=none shift=none call re...
import cv2 #color 설정 black_c = (0,0,0) white_c = (255,255,255) blue_c = (255,0,0) red_c = (0,0,255) green_c = (0,255,0) img = cv2.imread('images/person1.jpg', cv2.IMREAD_COLOR) cv2.rectangle(img, (80,100,160,200), green_c, thickness=2, lineType=None, shift=None) cv2.rectangle(img, (270,80,170,215), green...
Python
zaydzuhri_stack_edu_python
from addressbook import * import unittest class Test_AddressBook extends TestCase begin function setUp self begin set addressbook = call Address_Book string abc list call Contact string b 12 end function function test_init self begin assert equal owner string abc assert equal length contacts 1 end function function tes...
from addressbook import * import unittest class Test_AddressBook(unittest.TestCase): def setUp(self): self.addressbook = Address_Book('abc', [Contact('b', 12)]) def test_init(self): self.assertEqual(self.addressbook.owner, 'abc') self.assertEqual(len(self.addressbook.contacts),...
Python
zaydzuhri_stack_edu_python
from argparse import ArgumentParser set parser = call ArgumentParser call add_argument string string_in help=string words to capitalize call add_argument string -v string --verbosity help=string increase output verbosity action=string store_true set group = call add_mutually_exclusive_group call add_argument string -l ...
from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('string_in',help="words to capitalize") parser.add_argument("-v", "--verbosity", help="increase output verbosity", action="store_true") group = parser.add_mutually_exclusive_group() group.add_argument("-l", "--lower", help="will send you...
Python
zaydzuhri_stack_edu_python
comment key value - key 값은 숫자 / 문자 모두 가능 comment 사전에서는 키에대한 중복이 허용되지 않음 set cabinet = dict 3 string 유재석 ; 100 string 김태호 print cabinet at 3 print cabinet at 100 print get cabinet 3 comment none print get cabinet 5 comment 값이없으면 뒤에 값 줌 print get cabinet 5 string 사용가능 comment print(cabinet[5]) # error comment return bool...
# key value - key 값은 숫자 / 문자 모두 가능 # 사전에서는 키에대한 중복이 허용되지 않음 cabinet = {3:"유재석",100:"김태호"} print(cabinet[3]) print(cabinet[100]) print(cabinet.get(3)) print(cabinet.get(5)) #none print(cabinet.get(5), "사용가능") # 값이없으면 뒤에 값 줌 #print(cabinet[5]) # error print(3 in cabinet) # return boolean key in 변수 : key가 변수안에 있는가?...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[122]: import numpy as np import pandas as pd import matplotlib.pyplot as plt call run_line_magic string matplotlib string inline import seaborn as sns comment In[123]: set df = read csv string Information.csv engine=string python head df 5 comment In[124]: c...
#!/usr/bin/env python # coding: utf-8 # In[122]: import numpy as np import pandas as pd import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import seaborn as sns # In[123]: df=pd.read_csv("Information.csv",engine='python') df.head(5) # In[124]: df.columns # In[125]: ...
Python
zaydzuhri_stack_edu_python
function importAckk self filename begin if not exists path filename begin return end comment print("Found KKwik cluster file", filename, ':',) comment Everything is little endian comment A .ackk record is as folows: comment Header: comment uint32 + n x char - subject string comment uint32 + n x char - session date stri...
def importAckk(self, filename): if not os.path.exists(filename): return #print("Found KKwik cluster file", filename, ':',) # Everything is little endian # A .ackk record is as folows: # Header: # uint32 + n x char - subject string # uint32 + n x char ...
Python
nomic_cornstack_python_v1
function get_data_structure_representation self begin call check set xaxis_json = list set yaxis_json = list for tuple key value in items xaxis_data begin set x_temp = list set data_key = key set data_value = value for i in range 0 length data_value begin append x_temp data_value at i end set temp_xaxis_json = dict ...
def get_data_structure_representation(self): self.check() xaxis_json = [] yaxis_json = [] for key, value in self.xaxis_data.items(): x_temp = [] data_key = key data_value = value for i in range(0, len(data_value)): x_temp.a...
Python
nomic_cornstack_python_v1
import unittest import random import time from doodle import double_kill , triple_kill comment PLEASE DO NOT MODIFY ################################## class Ghost begin function __init__ self moves begin set moves = moves set lives_lost = 0 end function function __repr__ self begin if call alive begin return join strin...
import unittest import random import time from doodle import double_kill, triple_kill #################################################################################################### ################################ PLEASE DO NOT MODIFY ################################## ###############################...
Python
zaydzuhri_stack_edu_python
class DH begin function __init__ self p g begin set p = p set g = g end function function keygenStage1 self secret begin return g ^ secret % p end function function keygenStage2 self ctext secret begin return ctext ^ secret % p end function end class
class DH: def __init__(self, p, g): self.p = p self.g = g def keygenStage1(self, secret): return (self.g ** secret) % self.p def keygenStage2(self, ctext, secret): return (ctext ** secret) % self.p
Python
zaydzuhri_stack_edu_python
comment loop while set count = 0 while count < 10 begin print count comment equilave a count = count + 1 set count = count + 1 end print string Good Bye! set count = 0 while count < 10 begin if count % 2 == 0 begin print count string - Numero Par end else begin print count string - Numero Impar end set count = count + ...
# loop while count = 0 while count < 10: print(count) count += 1 # equilave a count = count + 1 print('Good Bye!') count = 0 while count < 10: if count % 2 == 0: print(count, ' - Numero Par') else: print(count, '- Numero Impar') count += 1 print('Good Bye again') # continue for l...
Python
zaydzuhri_stack_edu_python
function check_security_token request begin set inbound_token = headers at string Token set match = inbound_token == call get_security_token if match begin pass end else begin exit string Invalid security token! end end function
def check_security_token(request: typing.Any) -> None: inbound_token = request.headers['Token'] match = inbound_token == get_security_token() if match: pass else: sys.exit("Invalid security token!")
Python
nomic_cornstack_python_v1
comment print(bin(2)) comment print(bin(1)) comment print(bin(0)) comment print(bin(100)) print 18 print 10 comment print(bin(12)) print hexadecimal 18 print octal 10 set list = list 0 1 2 3 4 5
# print(bin(2)) # print(bin(1)) # print(bin(0)) # print(bin(100)) print(0x12) print(0o12) # print(bin(12)) print(hex(18)) print(oct(10)) list = [0, 1, 2, 3, 4, 5]
Python
zaydzuhri_stack_edu_python
function pc_input_buffers_full_avg self *args begin return call sink_f_sptr_pc_input_buffers_full_avg self *args end function
def pc_input_buffers_full_avg(self, *args): return _qtgui_swig.sink_f_sptr_pc_input_buffers_full_avg(self, *args)
Python
nomic_cornstack_python_v1
comment even or odd set userNum = integer input string Enter a number: if userNum % 2 == 0 begin print string Your number is even end else begin print string Your number is odd end set userNum1 = integer input string Enter a number: set userNum2 = integer input string Enter a second number: set userNum3 = integer input...
#even or odd userNum = int(input("Enter a number: ")) if (userNum % 2) == 0: print("Your number is even") else: print("Your number is odd") userNum1 = int(input("Enter a number: ")) userNum2 = int(input("Enter a second number: ")) userNum3 = int(input("Enter a third number: ")) rem1 = userNum1 % 2 rem2 = use...
Python
zaydzuhri_stack_edu_python
function multiply a b begin comment Check if either number is zero if a == 0 or b == 0 begin return 0 end comment Check if either number is negative set is_negative = a < 0 ? b < 0 comment Convert both numbers to positive set a = absolute a set b = absolute b comment Swap numbers if necessary to make a the larger numbe...
def multiply(a, b): # Check if either number is zero if a == 0 or b == 0: return 0 # Check if either number is negative is_negative = (a < 0) ^ (b < 0) # Convert both numbers to positive a = abs(a) b = abs(b) # Swap numbers if necessary to make a the larger number ...
Python
greatdarklord_python_dataset
function get_paginated_doc self doctype filters=none fields=none limit_page_length=100 limit_start=none order_by=none headers=none begin if headers begin update headers headers end else begin set headers = headers end set start = if expression limit_start then limit_start else 0 set limit_page_length = if expression li...
def get_paginated_doc( self, doctype, filters=None, fields=None, limit_page_length=100, limit_start=None, order_by=None, headers=None ): if headers: headers.update(self.headers) else: headers = self.headers start = limit_start if l...
Python
nomic_cornstack_python_v1
import sys set file1 = open argv at 1 string r set file2 = open argv at 2 string r set result1 = open string Result_crucialnodes.txt string w set result2 = open string Result_noncrucialnodes.txt string w set result3 = open string Result_moderatenodes.txt string w for line1 in file1 begin set word1 = split line1 seek fi...
import sys file1 = open(sys.argv[1],'r') file2 = open(sys.argv[2],'r') result1= open('Result_crucialnodes.txt','w') result2= open('Result_noncrucialnodes.txt','w') result3 =open('Result_moderatenodes.txt','w') for line1 in file1: word1 = line1.split() file2.seek(0) for line2 in file2: word2 = line2...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 import sys class AnonymizeMethod begin set PIXELATE = tuple 1 set BLUR = tuple 2 set BlackRectangle = 3 end class function _pixelate_image image blocks=8 begin set tuple h w = shape at slice : 2 : set x_steps = linear space 0 w blocks + 1 dtype=string int set y_steps = linear space 0 h b...
import numpy as np import cv2 import sys class AnonymizeMethod: PIXELATE = 1, BLUR = 2, BlackRectangle = 3 def _pixelate_image(image, blocks=8): (h, w) = image.shape[:2] x_steps = np.linspace(0, w, blocks + 1, dtype="int") y_steps = np.linspace(0, h, blocks + 1, dtype="int") for i in ra...
Python
zaydzuhri_stack_edu_python
function restore_chkp ckpt_file output_ckpt begin set termination = list string .meta string .index string .data-00000-of-00001 set files_ok = true for term in termination begin if not is file path ckpt_file + term begin set files_ok = false end end assert files_ok msg string Files are missing, can not restore with cal...
def restore_chkp(ckpt_file, output_ckpt): termination = ['.meta', '.index', '.data-00000-of-00001'] files_ok = True for term in termination: if not os.path.isfile(ckpt_file+term): files_ok = False assert files_ok, 'Files are missing, can not restore' with tf.Session() a...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None comment My solution using BFS approach. Slower because a lot of work is repeated class Solution begin function diameterOfBinaryTree self root begin fu...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ###### My solution using BFS approach. Slower because a lot of work is repeated class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: ...
Python
zaydzuhri_stack_edu_python
function export_uniq_ads ads out_folder rel_folder begin try begin make directories out_folder make directories join path out_folder rel_folder end except OSError begin debug string Creating output folder end set fwtr = open join path out_folder string uniq_ads.csv string w comment Relative location = Location of the a...
def export_uniq_ads(ads, out_folder, rel_folder): try : os.makedirs(out_folder) os.makedirs(os.path.join(out_folder, rel_folder)) except OSError: LOG.debug('Creating output folder') fwtr = open(os.path.join(out_folder, 'uniq_ads.csv'), 'w') # Relative location = Location of the ad within this curre...
Python
nomic_cornstack_python_v1
function get_data self begin set X = X_sorted set y = y return tuple X y end function
def get_data(self): X = self.X_sorted y = self.y return X, y
Python
nomic_cornstack_python_v1
function winhttp_WinHttpCreateProxyResolver jitter begin set tuple ret_ad args = call func_args_stdcall list string hSession string phResolver raise call RuntimeError string API not implemented call func_ret_stdcall ret_ad ret_value end function
def winhttp_WinHttpCreateProxyResolver(jitter): ret_ad, args = jitter.func_args_stdcall(["hSession", "phResolver"]) raise RuntimeError('API not implemented') jitter.func_ret_stdcall(ret_ad, ret_value)
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torch.nn.functional as f from torch.utils.data import DataLoader from torchvision import datasets , transforms comment 优先选择gpu set device = device if expression call is_available then string cuda:0 else string cpu comment LeNet 5用于对Mnist数据集分类 class CnnNet extends Module begin f...
import torch import torch.nn as nn import torch.nn.functional as f from torch.utils.data import DataLoader from torchvision import datasets, transforms # 优先选择gpu device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # LeNet 5用于对Mnist数据集分类 class CnnNet(nn.Module): def __init__(self): sup...
Python
zaydzuhri_stack_edu_python
comment Databricks notebook source comment MAGIC %fs ls /mnt/the-movies-dataset/ comment COMMAND ---------- set movies = call csv string /mnt/the-movies-dataset/movies_metadata.csv header=true inferSchema=true comment COMMAND ---------- call printSchema comment COMMAND ---------- from pyspark.sql.types import StructTyp...
# Databricks notebook source # MAGIC %fs ls /mnt/the-movies-dataset/ # COMMAND ---------- movies = spark.read.csv('/mnt/the-movies-dataset/movies_metadata.csv', header=True, inferSchema=True) # COMMAND ---------- movies.printSchema(); # COMMAND ---------- from pyspark.sql.types import StructType, StructField, Int...
Python
zaydzuhri_stack_edu_python
function stop_event_wait begin try begin set user_event = call SDL_Event set type = SDL_USEREVENT set code = 2 set data1 = none set data2 = none call SDL_PushEvent call byref user_event end except any begin pass end end function
def stop_event_wait(): try: user_event = sdl2.SDL_Event() user_event.type = sdl2.SDL_USEREVENT user_event.user.code = 2 user_event.user.data1 = None user_event.user.data2 = None sdl2.SDL_PushEvent(ctypes.byref(user_event)) except: pass
Python
nomic_cornstack_python_v1
function graph_as_str graph begin set STR = string for tuple SourceNode DestinationNodes in sorted list items graph begin set STR = STR + SourceNode + string -> + string DestinationNodes + string end print STR return STR end function
def graph_as_str(graph:dict)->str: STR = "" for SourceNode,DestinationNodes in sorted(list(graph.items())): STR += SourceNode + "->" + str(DestinationNodes) + "\n" print(STR) return STR
Python
nomic_cornstack_python_v1
comment Recursion is a function which call itself comment IT is used to directly use a mathematical formula as a function comment NOTE factorial(n)= n x factorial(n-1) comment n! = 1 * 2 * 3 * 4 .....*n comment NOTE n! = (n-1) * n function factorial_iter n begin set product = 1 for i in range n begin set product = prod...
# Recursion is a function which call itself # IT is used to directly use a mathematical formula as a function # NOTE factorial(n)= n x factorial(n-1) # n! = 1 * 2 * 3 * 4 .....*n # NOTE n! = (n-1) * n def factorial_iter(n): product = 1 for i in range(n): product = product * (i+1) return...
Python
zaydzuhri_stack_edu_python
class HexToDecimal extends object begin function __init__ self hex_string=string ff.ff.ff.ff begin set hex_string = hex_string try begin set hex_list = split hex_string string . end except any begin set hex_list = hex_string end end function function __str__ self begin return string call convertion end function functio...
class HexToDecimal(object): def __init__(self, hex_string="ff.ff.ff.ff"): self.hex_string = hex_string try: self.hex_list = hex_string.split(".") except: self.hex_list = hex_string def __str__(self): return str(self.convertion()) ...
Python
zaydzuhri_stack_edu_python
function locations_x self begin return _locations at 0 end function
def locations_x(self): return self._locations[0]
Python
nomic_cornstack_python_v1
import os comment BOLETA DE VENTA comment declarar variables set tuple cliente marca_de_celular01 marca_de_celular02 marca_de_celular03 precio_del_celular01 precio_del_celular02 precio_del_celular03 = tuple string string string string 0.0 0.0 0.0 comment INPUT set cliente = argv at 1 set marca_de_celular01 = argv a...
import os # BOLETA DE VENTA # declarar variables cliente,marca_de_celular01,marca_de_celular02,marca_de_celular03,precio_del_celular01,precio_del_celular02,precio_del_celular03="","","","",0.0,0.0,0.0 # INPUT cliente=os.sys.argv[1] marca_de_celular01=os.sys.argv[2] marca_de_celular02=os.sys.argv[3] marca_de_celular03...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf8 -*- from django import template set register = call Library decorator filter function index List i begin string https://stackoverflow.com/questions/4651172/reference-list-item-by-index-within-django-template/29664945#29664945 {{ List|index:x|index:y }} :param List: ...
#!/usr/bin/env python # -*- coding: utf8 -*- from django import template register = template.Library() @register.filter def index(List, i): """ https://stackoverflow.com/questions/4651172/reference-list-item-by-index-within-django-template/29664945#29664945 {{ List|index:x|index:y }} :param List: ...
Python
zaydzuhri_stack_edu_python
comment В упражнении мы потренируемся в создании объектно-ориентированной среды и создадим приложение, проводящее comment лингвистический анализ. Следуйте алгоритму и выполняйте действия последовательно, чтобы получить полноценный класс: comment 1. Создайте класс Word. (Вспомните, какое зарезервированное слово использу...
# В упражнении мы потренируемся в создании объектно-ориентированной среды и создадим приложение, проводящее # лингвистический анализ. Следуйте алгоритму и выполняйте действия последовательно, чтобы получить полноценный класс: # 1. Создайте класс Word. (Вспомните, какое зарезервированное слово используется для создания...
Python
zaydzuhri_stack_edu_python
function gbk x y begin set p1 = format string {} x set p2 = format string {} y if p1 == string G begin if p2 == string G begin return 0 end else if p2 == string B begin return 2 end else begin return 1 end end if p1 == string B begin if p2 == string G begin return 1 end else if p2 == string B begin return 0 end else be...
def gbk(x,y): p1 = '{}'.format(x) p2 = '{}'.format(y) if p1 == 'G': if p2 == 'G': return 0 elif p2 == 'B': return 2 else: return 1 if p1 == 'B': if p2 == 'G': return 1 elif p2 == 'B': return 0 else: return 2 if p1 == 'K': if p2 == 'G': retu...
Python
zaydzuhri_stack_edu_python
function test_queued_or_running_jobs begin for job_name in list string test-sleepy-job string test-unicode-sléépy-job begin yield tuple check_job_name_queued_or_running_sge job_name yield tuple check_job_name_queued_or_running_slurm job_name end end function
def test_queued_or_running_jobs(): for job_name in ["test-sleepy-job", u'test-unicode-sl\xe9\xe9py-job']: yield check_job_name_queued_or_running_sge, job_name yield check_job_name_queued_or_running_slurm, job_name
Python
nomic_cornstack_python_v1
set a = 3 if a == o begin print string a is zero end
a=3 if(a==o): print("a is zero")
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment Project Euler Problem 1 comment ----------------------- comment Multiples of 3 and 5: comment If we list all the natural numbers below 10 that are multiples of 3 or 5, we comment get 3, 5, 6, 9. The sum of these multiples is 23. Find the sum of all the comment multiples of 3 or 5 below ...
#!/usr/bin/python # Project Euler Problem 1 # ----------------------- # Multiples of 3 and 5: # If we list all the natural numbers below 10 that are multiples of 3 or 5, we # get 3, 5, 6, 9. The sum of these multiples is 23. Find the sum of all the # multiples of 3 or 5 below 1000. x = 1000 numbers = [] for n in ran...
Python
zaydzuhri_stack_edu_python
import math from collections import Counter as co function primeFactors n begin comment Print the number of two's that divide n set l = list while n % 2 == 0 begin append l 2 set n = n / 2 end comment n must be odd at this point comment so a skip of 2 ( i = i + 2) can be used for i in range 3 integer square root n + 1...
import math from collections import Counter as co def primeFactors(n): # Print the number of two's that divide n l = [] while n % 2 == 0: l.append(2) n = n / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3, int(math.sqrt(n)) + 1, 2): ...
Python
zaydzuhri_stack_edu_python
function add_loss self begin with call variable_scope string loss begin comment [batch_size, context_len] set weights = call to_float call not_equal ans_ids PAD_ID comment shift the weight right to include the end id set batch_size = call shape weights at 0 set shift_val = ones list batch_size 1 set new_ans_ids = conca...
def add_loss(self): with vs.variable_scope("loss"): weights = tf.to_float(tf.not_equal(self.ans_ids, PAD_ID)) # [batch_size, context_len] # shift the weight right to include the end id batch_size = tf.shape(weights)[0] shift_val = tf.ones([batch_size, 1]) ...
Python
nomic_cornstack_python_v1
import sys import os if __name__ == string __main__ begin try begin class node extends object begin function __init__ self begin set data = none set pointers = list end function end class class tree extends object begin set Z = 0 set clild = list function __init__ self begin set root = none end function function inse...
import sys import os if __name__ == '__main__': try: class node(object): def __init__(self): self.data = None self.pointers = [] class tree(object): Z = 0 clild=[] def __init__(self): self.root = None def insert_root(self,data): if (self.root == None): nnode = node() ...
Python
zaydzuhri_stack_edu_python
function ask_which_query begin try begin call go_to_start call interact string =============================== call interact string Enter the name of a TPC-H query, for example Q22 set name = call prompt if name begin return strip name end call interact string (Two more ENTERs mean QUIT) for _ in range 2 begin set name...
def ask_which_query(): try: interact.go_to_start() interact("\n===============================\n") interact("Enter the name of a TPC-H query, for example Q22\n") name = interact.prompt() if name: return name.strip() interact("(Two more ENTERs mean QUIT)\n"...
Python
nomic_cornstack_python_v1
string bvnormal.py import numpy as np from numpy.random import randn import matplotlib.pyplot as plt set N = 1000 comment change to 0.8 for other plot set r = 0.0 set Sigma = array list list 1 r list r 1 set B = call cholesky Sigma set x = B @ randn 2 N scatter plt list x at tuple 0 slice : : list x at tuple 1 slice...
""" bvnormal.py """ import numpy as np from numpy.random import randn import matplotlib.pyplot as plt N = 1000 r = 0.0 #change to 0.8 for other plot Sigma = np.array([[1, r], [r, 1]]) B = np.linalg.cholesky(Sigma) x = B @ randn(2,N) plt.scatter([x[0,:]],[x[1,:]], alpha =0.4, s = 4)
Python
zaydzuhri_stack_edu_python
function Chain *inputs begin set init_funs = tuple generator expression i at 0 for i in inputs set bijector_info = tuple string Chain tuple generator expression i at 1 for i in inputs decorator InitFunction function init_fun rng input_dim **kwargs begin set tuple all_params forward_funs inverse_funs = tuple list list ...
def Chain( *inputs: Sequence[Tuple[InitFunction, Bijector_Info]] ) -> Tuple[InitFunction, Bijector_Info]: init_funs = tuple(i[0] for i in inputs) bijector_info = ("Chain", tuple(i[1] for i in inputs)) @InitFunction def init_fun(rng, input_dim, **kwargs): all_params, forward_funs, inverse_...
Python
nomic_cornstack_python_v1
function ordinal n begin if not is instance n int or n < 0 begin raise call ValueError string Must be a positive or zero integer. end if n < 20 begin return string n + if expression n < 4 then ORDINAL_SUFFIXES at n else string th end else begin set unit = integer string n at - 1 return string n + if expression integer ...
def ordinal(n): if not isinstance(n, int) or n < 0: raise ValueError("Must be a positive or zero integer.") if n < 20: return str(n) + (ORDINAL_SUFFIXES[n] if n < 4 else 'th') else: unit = int(str(n)[-1]) return str(n) + ('th' if int(str(n)[-2]) == 1 else ORDINAL_SUFFIXES[uni...
Python
nomic_cornstack_python_v1
set frozen_set = call frozenset list 1 2 3 4 5 set outro_frozen_set = call frozenset list 1 3 5 print type frozen_set print frozen_set print frozen_set ? outro_frozen_set
frozen_set = frozenset([1, 2, 3, 4, 5]) outro_frozen_set = frozenset([1, 3, 5]) print(type(frozen_set)) print(frozen_set) print(frozen_set ^ outro_frozen_set)
Python
zaydzuhri_stack_edu_python
import os import sys import glob import zipfile import color_string as cs comment main文 if __name__ == string __main__ begin comment ↲コマンドライン引数を取得 set args = argv comment 引数の数が間違っていた場合 if length args != 3 begin print call str_color string コマンドライン引数の数が間違っています! string RED print string 使い方 print string python + args at 0 ...
import os import sys import glob import zipfile import color_string as cs # main文 if __name__ == "__main__": args = sys.argv # ↲コマンドライン引数を取得 # 引数の数が間違っていた場合 if len(args) != 3: print(cs.str_color("コマンドライン引数の数が間違っています!", "RED")) print("\n使い方\n") print("python " + args[0] + " フォルダのパス...
Python
zaydzuhri_stack_edu_python
import json from bson import json_util from pymongo import MongoClient from pymongo import errors from bson.json_util import dumps set connection = call MongoClient string localhost 27017 set db = connection at string market set collection = db at string stocks function aggregate filt proj begin try begin set myReadRes...
import json from bson import json_util from pymongo import MongoClient from pymongo import errors from bson.json_util import dumps connection = MongoClient('localhost', 27017) db = connection['market'] collection = db['stocks'] def aggregate(filt, proj): try: myReadResult = collection.aggregate([filt, proj]) ...
Python
zaydzuhri_stack_edu_python
function checkCooCooException group1 group2 version begin set exception = true set list closest_atom1 distance closest_atom2 = call get_smallest_distance call get_interaction_atoms group2 call get_interaction_atoms group1 comment dpka_max = parameters.sidechain_interaction.get_value(group1.type,group2.type) comment cut...
def checkCooCooException(group1, group2, version): exception = True [closest_atom1, distance, closest_atom2] = get_smallest_distance(group1.get_interaction_atoms(group2), group2.get_interaction_atoms(group1)) #dpka_max = parameters.sidech...
Python
nomic_cornstack_python_v1
import random from tkinter import * function print_song one two three four five six begin print string I am not throwing away my %s I am not %s away my %s Hey yo, I'm just like my country I'm %s, %s and %s And I'm not %s away my %s % tuple one two three four five six two three end function set window = call Tk title wi...
import random from tkinter import * def print_song(one, two, three, four, five, six): print('''I am not throwing away my %s I am not %s away my %s Hey yo, I'm just like my country I'm %s, %s and %s And I'm not %s away my %s ''' %(one, two, three, four, five, six, two, three)) window...
Python
zaydzuhri_stack_edu_python
for i in range 50000000 begin set index = index + 329 set index = index % length set length = length + 1 set index = index + 1 if index == 1 begin set current = i + 1 end end print current
for i in range(50000000): index += 329 index %= length length += 1 index += 1 if index == 1: current = i + 1 print(current)
Python
zaydzuhri_stack_edu_python
function my_function begin print string MY FUNCTION WAS CALLED! end function set description = string My Function function another_function begin print string ANOTHER FUNCTION WAS CALLED end function set description = string Another Function function some_other_function func begin print string Description= end=string p...
def my_function(): print("MY FUNCTION WAS CALLED!") my_function.description = "My Function" def another_function(): print("ANOTHER FUNCTION WAS CALLED") another_function.description = "Another Function" def some_other_function(func): print("Description=", end=" ") print(func.description) print("Name= ", end=" ...
Python
zaydzuhri_stack_edu_python
function split_grids N A begin set B = list comprehension list string . * N for i in call xrange N for x in A begin set B at x at 1 - 1 at x at 2 - 1 = x at 0 end set r1 = list comprehension list comprehension integer B at i at j in string +o for j in call xrange N for i in call xrange N set r2 = list comprehension lis...
def split_grids(N, A): B = [['.'] * N for i in xrange(N)] for x in A: B[x[1] - 1][x[2] - 1] = x[0] r1 = [[int(B[i][j] in '+o') for j in xrange(N)] for i in xrange(N)] r2 = [[int(B[i][j] in 'xo') for j in xrange(N)] for i in xrange(N)] return r1, r2 def iter_diag(N, p, rev=False): x, y =...
Python
zaydzuhri_stack_edu_python
function call_later self task_id delay aio_func *args **kwargs begin async function later_func begin await sleep delay await call aio_func *args keyword kwargs end function set task = call _sched_task task_id call later_func if task is not none begin debug string Schedule task(%s), %d sec later % tuple task_id delay en...
def call_later( self, task_id: TaskId, delay: float, aio_func: AsyncFunc, *args, **kwargs ) -> SchedRtn: async def later_func(): await asyncio.sleep(delay) await aio_func(*args, **kwargs) task = self._sched_task(task_id, later_func()) if task is not None: ...
Python
nomic_cornstack_python_v1
string Module Name: TSEImageUtils Description: Provides functionality relating to image processing and template matching. from __future__ import division import math import cv2 import numpy as np from tse_compiled.tse_c_imageutils import TSECImageUtils from tse.tse_geometry import TSEGeometry from tse_datautils import ...
""" Module Name: TSEImageUtils Description: Provides functionality relating to image processing and template matching. """ from __future__ import division import math import cv2 import numpy as np from tse_compiled.tse_c_imageutils import TSECImageUtils from tse.tse_geometry import TSEGeometry from tse_datautils ...
Python
zaydzuhri_stack_edu_python
function _pack_length buffer begin set length = length buffer set length_bytes = call pack string !Q length return length_bytes end function
def _pack_length(buffer: bytes) -> bytes: length = len(buffer) length_bytes = struct.pack('!Q', length) return length_bytes
Python
nomic_cornstack_python_v1
function perform_post_job context metadata job_id state begin set filename = call job_metadata_filename metadata set endpoint = call flow_sheduling_endpoint context state job_id set response = call send_json_file endpoint filename end function
def perform_post_job(context, metadata, job_id, state): filename = job_metadata_filename(metadata) endpoint = flow_sheduling_endpoint(context, state, job_id) context.response = context.send_json_file(endpoint, filename)
Python
nomic_cornstack_python_v1
function orbital_id grid grid_coordinates spin=none begin comment Initialize. if is instance grid_coordinates int begin set grid_coordinates = list grid_coordinates end comment Loop through dimensions of coordinate tuple. set tensor_factor = 0 for tuple dimension grid_coordinate in enumerate grid_coordinates begin comm...
def orbital_id(grid, grid_coordinates, spin=None): # Initialize. if isinstance(grid_coordinates, int): grid_coordinates = [grid_coordinates] # Loop through dimensions of coordinate tuple. tensor_factor = 0 for dimension, grid_coordinate in enumerate(grid_coordinates): # Make sure c...
Python
nomic_cornstack_python_v1
function filter_batches_by_length batches min_length=3 begin return list filter lambda b -> item min > min_length batches end function
def filter_batches_by_length(batches: List[BatchType], min_length: int = 3): return list(filter(lambda b: b[1].min().item() > min_length, batches))
Python
nomic_cornstack_python_v1
function test_main begin for template in templates begin call main list string -g template comment One at a time for xyz_file in example_xyz_files begin call main list template xyz_file end comment All at once call main list template + list example_xyz_files end comment Allow use of template in the parent directory wit...
def test_main(): for template in templates: main(["-g", template]) # One at a time for xyz_file in example_xyz_files: main([template, xyz_file]) # All at once main([template] + list(example_xyz_files)) # Allow use of template in the parent directory wit...
Python
nomic_cornstack_python_v1
function checkOutputPath self output_path begin string Create or clean up output path if not output_path begin comment output_path = self.output_path_DEFAULT set output_path = join path output_path_DEFAULT call slugify call unicode title end if exists path output_path begin remove tree output_path end make directories ...
def checkOutputPath(self, output_path): """ Create or clean up output path """ if not output_path: # output_path = self.output_path_DEFAULT output_path = os.path.join(self.output_path_DEFAULT, slugify(unicode(self.title))) ...
Python
jtatman_500k
function get_assignment_by_request self request begin return call get_assignment_by_request request end function
def get_assignment_by_request(self, request): return self.context.provider.get_assignment_by_request(request)
Python
nomic_cornstack_python_v1
function create_app self begin set app = call Flask __name__ set config at string TESTING = true set config at string SQLALCHEMY_TRACK_MODIFICATIONS = false set config at string SQLALCHEMY_DATABASE_URI = string sqlite:///:memory: call init_app app comment this does the binding call push return app end function
def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:" users.db.init_app(app) app.app_context().push() # this does the binding retu...
Python
nomic_cornstack_python_v1
function getViewNum weights begin set max = 0 set maxInd = 0 for i in range 0 length weights begin if weights at i > max begin set max = weights at i set maxInd = i end end return maxInd end function
def getViewNum(weights): max = 0 maxInd = 0 for i in range(0, len(weights)): if weights[i] > max: max = weights[i] maxInd = i return maxInd
Python
nomic_cornstack_python_v1
function rotate90 self matrix begin set tmatrix = transpose self matrix set rmatrix = call reverseColumns tmatrix return rmatrix end function
def rotate90(self, matrix): tmatrix = self.transpose(matrix) rmatrix = self.reverseColumns(tmatrix) return rmatrix
Python
nomic_cornstack_python_v1
import csv import pandas as pd from numpy import * from operantanalysis import * from operator import itemgetter from tkinter import filedialog , Tk function choose_file begin set project = call Tk set filename = call askopenfilename initialdir=string / title=string Choose an IDPS CSV file filetypes=list tuple string C...
import csv import pandas as pd from numpy import * from operantanalysis import * from operator import itemgetter from tkinter import filedialog, Tk def choose_file(): project = Tk() project.filename = filedialog.askopenfilename(initialdir="/", title="Choose an IDPS CSV file", ...
Python
zaydzuhri_stack_edu_python
comment Temp converter problem (1) function FtoC F begin return F / 1.8 - 32 end function function CtoF C begin return C * 1.8 + 32 end function set C = 30 set F = call CtoF C print string C string degrees C is string F string degrees F comment characters problem (1) set a = string 0123456789 set b = string abcdABCD@#!...
# Temp converter problem (1) def FtoC(F): return (F / 1.8) - 32 def CtoF(C): return (C * 1.8) + 32 C = 30 F = CtoF(C) print(str(C), "degrees C is", str(F), "degrees F") # characters problem (1) a = "0123456789" b = "abcdABCD@#!£" print(a) print(b) print(a, b) # fish tank volume problem (2) def volume(length, ...
Python
zaydzuhri_stack_edu_python
function gameLoop begin set Grid = list 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 set Grid = call initBoard Grid set gameRun = true while gameRun == true begin call printGrid Grid set userInput = call getInput set Grid = move userInput Grid set state = call checkWin Grid set Grid = call addRandtwo Grid if state == string win beg...
def gameLoop(): Grid = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Grid = initBoard(Grid) gameRun = True while gameRun == True: printGrid(Grid) userInput = getInput() Grid = move(userInput, Grid) state = checkWin(Grid) ...
Python
nomic_cornstack_python_v1
from pymongo import MongoClient from progress.bar import Bar from six.moves import cPickle import numpy as np from matplotlib import pyplot as plt function load_dict filename begin set fin = open filename string rb return load cPickle fin end function function crawl_acct_ids players begin comment Append account ids in ...
from pymongo import MongoClient from progress.bar import Bar from six.moves import cPickle import numpy as np from matplotlib import pyplot as plt def load_dict(filename): fin = open(filename, 'rb') return cPickle.load(fin) def crawl_acct_ids(players): # Append account ids in a list ids = [] bar ...
Python
zaydzuhri_stack_edu_python
string POC for a cipher system that translates 1 char into multiple words import string as s import math import random from collections import OrderedDict import base64 import time comment A list of valid characters for ascii encoding set ascii_chars = list ascii_letters + whitespace + punctuation + digits comment A li...
"""POC for a cipher system that translates 1 char into multiple words """ import string as s import math import random from collections import OrderedDict import base64 import time # A list of valid characters for ascii encoding ascii_chars = list(s.ascii_letters + s.whitespace + s.punctuation + s.digits) # A list of...
Python
zaydzuhri_stack_edu_python
comment POST방식으로 요청 보내기 comment 방법1:requests.post(요청url) comment 방법2:requests.request('POST',요청url) comment 로그인이 필요 없을때는 requests.post() comment 로그인이 필요한 경우 세션이 필요하기 때문에 comment 1.session=requests.Session() 로 세션 객체를 얻고 comment 2.세션 객체로 session.post() import requests comment 세션이 필요없는 POST 요청 comment 방법1 comment res= req...
#POST방식으로 요청 보내기 #방법1:requests.post(요청url) #방법2:requests.request('POST',요청url) #로그인이 필요 없을때는 requests.post() #로그인이 필요한 경우 세션이 필요하기 때문에 #1.session=requests.Session() 로 세션 객체를 얻고 #2.세션 객체로 session.post() import requests #세션이 필요없는 POST 요청 #방법1 #res= requests.post('http://localhost:10004/springapp/Annotation/Re...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python from __future__ import print_function try begin import httplib end except ImportError begin import http.client as httplib end import sys import os import optparse import time import json function change_priority url workflow priority cert key retry begin set data = dict string RequestPrior...
#! /usr/bin/env python from __future__ import print_function try: import httplib except ImportError: import http.client as httplib import sys import os import optparse import time import json def change_priority(url, workflow, priority, cert, key, retry): data = {'RequestPriority': priority} headers ...
Python
zaydzuhri_stack_edu_python
function paintHouses cost begin if not cost begin return 0 end else if length cost == 1 begin return min cost at 0 end for house in range 1 length cost begin comment red set cost at house at 0 = cost at house at 0 + min cost at house - 1 at 1 cost at house - 1 at 2 comment blue set cost at house at 1 = cost at house at...
def paintHouses(cost): if not cost: return 0 elif(len(cost) == 1): return min(cost[0]) for house in range(1, len(cost)): cost[house][0] += min(cost[house-1][1], cost[house-1][2])#red cost[house][1] += min(cost[house-1][0], cost[house-1][2])#blue cost[house...
Python
zaydzuhri_stack_edu_python
function sample self begin set experiences = random sample memory k=batch_size set states = to decimal device set actions = to decimal device set rewards = to decimal device set next_states = to decimal device set dones = to decimal device return tuple states actions rewards next_states dones end function
def sample(self): experiences = random.sample(self.memory, k=self.batch_size) states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device) actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device) ...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt class MCP begin function __init__ self entradas w g begin set qnt_amostras = length entradas - 1 set n_entradas = length entradas at 1 set entradas = entradas set w = w set func = g end function function setFunc self func begin set func = func end function function setEntradas self entra...
import matplotlib.pyplot as plt class MCP: def __init__(self, entradas, w, g): self.qnt_amostras = len(entradas)-1 self.n_entradas = len(entradas[1]) self.entradas = entradas self.w = w self.func = g def setFunc(self, func): self.func = func def set...
Python
zaydzuhri_stack_edu_python
function inorder self begin if call is_empty begin return none end else begin call inorder print _root call inorder end end function
def inorder(self): if self.is_empty(): return None else: self._left.inorder() print(self._root) self._right.inorder()
Python
nomic_cornstack_python_v1
import os from datetime import date from pathlib import Path from typing import Dict , List from urllib.request import urlretrieve import json import calendar set URL = string https://bites-data.s3.us-east-2.amazonaws.com/exchangerates.json set TMP = call Path call getenv string TMP string /tmp set RATES_FILE = TMP / s...
import os from datetime import date from pathlib import Path from typing import Dict, List from urllib.request import urlretrieve import json import calendar URL = "https://bites-data.s3.us-east-2.amazonaws.com/exchangerates.json" TMP = Path(os.getenv("TMP", "/tmp")) RATES_FILE = TMP / "exchangerates.json" if not RAT...
Python
zaydzuhri_stack_edu_python
function IsAutomaticValueRestoreDeactivated self begin set callResult = call _Call string IsAutomaticValueRestoreDeactivated if callResult is none begin return none end return callResult end function
def IsAutomaticValueRestoreDeactivated(self): callResult = self._Call("IsAutomaticValueRestoreDeactivated", ) if callResult is None: return None return callResult
Python
nomic_cornstack_python_v1
function get self begin set login = call get_jwt_identity set as_courier = false if get args string as_courier string false == string true begin if not call isUserCourier login begin return tuple call jsonify error_message=format string The user is not a courier (login: {}). login 400 end set as_courier = true end set ...
def get(self): login = get_jwt_identity() as_courier = False if request.args.get("as_courier", "false") == "true": if not dbi.isUserCourier(login): return jsonify(error_message="The user is not a courier " "(login: {}).".format(login)), ...
Python
nomic_cornstack_python_v1
comment 赋值运算符 set a = 1 set b = 2 set c = 3 set d = 4 set e = 5 set f = 6 set g = 7 comment 加法赋值运算符 comment a += 1 comment 减法、 乘法、除法赋值运算符 comment b = b - a set b = b - a print b set c = c * 3 print c set d = d // 1 print d comment 取模、幂赋值 set sheet = list string 张三 if string 张三 in sheet begin print string 他在上课 end else ...
# 赋值运算符 a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 # 加法赋值运算符 # a += 1 # 减法、 乘法、除法赋值运算符 b -= a # b = b - a print(b) c *= 3 print(c) d //= 1 print(d) # 取模、幂赋值 sheet = ['张三'] if '张三' in sheet: print('他在上课') else: print('他旷课了啊')
Python
zaydzuhri_stack_edu_python
import random import min_heap import timeit import copy comment Undirected graph using an adjacency list class WeightedGraph begin comment G = WeightedGraph(4) function __init__ self n begin comment {0:[], 1:[], 2:[], 3:[]} set adj = dict for i in range n begin set adj at i = list end end function function are_connec...
import random import min_heap import timeit import copy #Undirected graph using an adjacency list class WeightedGraph: def __init__(self, n): # G = WeightedGraph(4) self.adj = {} # {0:[], 1:[], 2:[], 3:[]} for i in range(n): self.a...
Python
zaydzuhri_stack_edu_python
function resource_path relative_path begin try begin comment PyInstaller creates a temp folder and stores path in _MEIPASS set base_path = _MEIPASS end except AttributeError begin set base_path = absolute path string . end return join base_path relative_path end function
def resource_path(relative_path): try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except AttributeError: base_path = abspath(".") return join(base_path, relative_path)
Python
nomic_cornstack_python_v1
function __repr__ self begin return string <Airport(id= { string id } , name= { name } )> end function
def __repr__(self): return f"<Airport(id={str(self.id)}, name={self.name})>"
Python
nomic_cornstack_python_v1
function get_fibonacci_last_digit_naive n begin set array = list none * n + 1 set array at 0 = 0 set array at 1 = 1 for i in range 2 n + 1 begin set array at i = integer array at i - 1 + integer array at i - 2 % 10 end return array at n % 10 end function function fibonacci_sum n begin set sum = 0 for i in range 0 n / 2...
def get_fibonacci_last_digit_naive(n): array=[None]*(n+1) array[0]=0 array[1]=1 for i in range(2,n+1): array[i]=(int(array[i-1])+int(array[i-2]))%10 return array[n]%10 def fibonacci_sum(n): sum=0 for i in range(0,n/2): sum= (get_fibonacci_last_digit_naive(n) +sum)%10 f...
Python
zaydzuhri_stack_edu_python