code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import io from urllib.request import urlopen import base64 from tkinter import * from tkinter import ttk import tkinter from PIL import Image , ImageTk from logo_crawler import download_image , get_url , convert_to_csv set root = call Tk title root string Email Verifier comment initial window size set window_width = 60...
import io from urllib.request import urlopen import base64 from tkinter import * from tkinter import ttk import tkinter from PIL import Image, ImageTk from logo_crawler import download_image, get_url, convert_to_csv root = Tk() root.title('Email Verifier') #initial window size window_width = 600 window_height = 500...
Python
zaydzuhri_stack_edu_python
function global_context request begin set context = dict string WITH_WS4REDIS has attribute settings string WEBSOCKET_URL return context end function
def global_context(request): context = { 'WITH_WS4REDIS': hasattr(settings, 'WEBSOCKET_URL'), } return context
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Oct 8 11:51:25 2018 Code to investigate individual flux curves of stars to see why median flux curve looks so wrong @author: ppxee comment Import required libraries ### comment for plotting import matplotlib.pyplot as plt comment for hand...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 8 11:51:25 2018 Code to investigate individual flux curves of stars to see why median flux curve looks so wrong @author: ppxee """ ### Import required libraries ### import matplotlib.pyplot as plt #for plotting from astropy.io import fits #for h...
Python
zaydzuhri_stack_edu_python
function print_hdf5_file_structure file_name begin comment open read-only set file = call File file_name string r comment ["/Configure:0000/Run:0000"] set item = file call print_hdf5_item_structure item close file end function
def print_hdf5_file_structure(file_name) : file = h5py.File(file_name, 'r') # open read-only item = file #["/Configure:0000/Run:0000"] print_hdf5_item_structure(item) file.close()
Python
nomic_cornstack_python_v1
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
comment %% import os import platform import torch.nn as nn import torch import pickle import time if call system == string Windows begin set ROOT_DIR = string D:\GitHub\Fashion_Search end else begin set ROOT_DIR = string /content/Fashion_Search end change directory ROOT_DIR import pandas as pd set train_label_df = read...
#%% import os import platform import torch.nn as nn import torch import pickle import time if platform.system() == 'Windows': ROOT_DIR = r'D:\GitHub\Fashion_Search' else: ROOT_DIR = '/content/Fashion_Search' os.chdir(ROOT_DIR) import pandas as pd train_label_df = pd.read_csv('data/cloth_train.csv') MasterDict = {...
Python
zaydzuhri_stack_edu_python
function toCoords piece begin return tuple call getRank - 1 call getFile - 1 end function
def toCoords(piece): return(piece.getRank()-1,piece.getFile()-1)
Python
nomic_cornstack_python_v1
comment finds indexes of values that sum to val comment O(n) sol function sum_to_value val arr begin set hash_t = dict set pairs = list for i in arr begin if i not in hash_t begin set hash_t at val - i = i end else if tuple i val - i not in pairs begin append pairs tuple i val - i end end return pairs end function pr...
#finds indexes of values that sum to val #O(n) sol def sum_to_value(val,arr): hash_t = {} pairs = [] for i in arr: if i not in hash_t: hash_t[val - i] = i else: if (i,val-i) not in pairs: pairs.append((i,val-i)) return(pairs) print(sum_to_value(5,...
Python
zaydzuhri_stack_edu_python
comment 类中 定义私有属性 comment self.__name=xxx comment 私有化的处理 comment 如果模块中的变量不希望被其他模块 以 from...import * 方式导入,此时 comment 可以在变量名前加 _ 以表示私有的意思。 set _age = 18
# 类中 定义私有属性 # self.__name=xxx # 私有化的处理 # 如果模块中的变量不希望被其他模块 以 from...import * 方式导入,此时 # 可以在变量名前加 _ 以表示私有的意思。 _age = 18
Python
zaydzuhri_stack_edu_python
from math import sqrt comment sum set total_1 = 0 comment x^2 set total_2 = 0 set count = 0 set value = 0 while value != - 1 begin set value = decimal input string Enter floating-point data : if value != - 1 begin set total_1 = total_1 + value set total_2 = total_2 + value * value set count = count + 1 end end comment ...
from math import sqrt total_1 = 0 # sum total_2 = 0 # x^2 count = 0 value = 0 while value != -1 : value = float(input("Enter floating-point data : ")) if(value != -1) : total_1 += value total_2 += value * value count += 1 ave = (total_1/count) # average value s = sqrt((total_2-(...
Python
zaydzuhri_stack_edu_python
for i in range n begin set a = integer input append List a end set M = max List set m = min List set List = sorted List set th = integer M - m / k - 1 function len_search L U begin set Mid = integer L + U // 2 return Mid end function set distance = 0 set count = 1 set now = 0 set compare = 1 set distance = call len_sea...
for i in range(n) : a = int(input()) List.append(a) M = max(List) m = min(List) List = sorted(List) th = int((M-m)/(k-1)) def len_search(L, U) : Mid = int((L+U)//2) return Mid distance = 0 count = 1 now = 0 compare = 1 distance = len_search(0, th) distance_max = 0 print(distance) while True : while...
Python
zaydzuhri_stack_edu_python
function get_smbus begin set i2c__bus = 1 comment detect the device that is being used set device = call uname at 1 comment running on orange pi one if device == string orangepione begin set i2c__bus = 0 end else comment running on orange pi plus if device == string orangepiplus begin set i2c__bus = 0 end else comment ...
def get_smbus(): i2c__bus = 1 # detect the device that is being used device = platform.uname()[1] if device == "orangepione": # running on orange pi one i2c__bus = 0 elif device == "orangepiplus": # running on orange pi plus i2c__bus = 0 elif ...
Python
nomic_cornstack_python_v1
set file = open string html.txt string w set line1 = string I love God and Python . write file line1 set line2 = string I am a programmer. write file line2 close file print string File written successfully...
file = open('html.txt', 'w') line1 = 'I love God and Python\n.' file.write(line1) line2 = 'I am a programmer.' file.write(line2) file.close() print('File written successfully...')
Python
zaydzuhri_stack_edu_python
import sys , math function absolute_complex x y begin return square root x ^ 2 + y ^ 2 end function function calculate_square_complex x y begin set x_new = x ^ 2 - y ^ 2 set y_new = 2 * x * y return tuple x_new y_new end function set case = 0 set line = read line stdin while line begin set line = split line at slice :...
import sys, math def absolute_complex(x, y): return math.sqrt(x**2 + y**2) def calculate_square_complex(x, y): x_new = x**2 - y**2 y_new = 2 * x * y return x_new, y_new case = 0 line = sys.stdin.readline() while line: line = line[:len(line) - 1].split(' ') case += 1 c_x = float(line[0])...
Python
zaydzuhri_stack_edu_python
function parse_ansi self string strip_ansi=false xterm256=false mxp=false begin if has attribute string string _raw_string begin if strip_ansi begin return call clean end else begin return call raw end end if not string begin return string end comment check cached parsings global _PARSE_CACHE set cachekey = string %s-...
def parse_ansi(self, string, strip_ansi=False, xterm256=False, mxp=False): if hasattr(string, "_raw_string"): if strip_ansi: return string.clean() else: return string.raw() if not string: return "" # check cached parsings ...
Python
nomic_cornstack_python_v1
comment This script fixes continuity errors. For records that reverted to a previous state comment at a later date after some intermediate changes, the SQL join does not recognize them as a separate change. Instead comment they are considered a continuation of the original data and merged into one row with validity per...
# This script fixes continuity errors. For records that reverted to a previous state # at a later date after some intermediate changes, the SQL join does not recognize them as a separate change. Instead # they are considered a continuation of the original data and merged into one row with validity period that ove...
Python
zaydzuhri_stack_edu_python
comment 2020-11-11 (3일차) comment 앙상블(Ensemble): 모델 합치기 comment X1, X2 -> Y1 comment 1. 데이터 import numpy as np set x1 = array list range 1 101 range 711 811 range 100 set x2 = array tuple range 4 104 range 761 861 range 100 set y1 = array list range 101 201 range 311 411 range 100 set x1 = T set x2 = T set y1 = T commen...
#2020-11-11 (3일차) #앙상블(Ensemble): 모델 합치기 #X1, X2 -> Y1 #1. 데이터 import numpy as np x1 = np.array([range(1, 101), range(711, 811), range(100)]) x2 = np.array((range(4, 104), range(761, 861), range(100))) y1 = np.array([range(101, 201), range(311, 411), range(100)]) x1 = x1.T x2 = x2.T y1 = y1.T #data 분리 (인자 3개까지 가...
Python
zaydzuhri_stack_edu_python
comment La secuencia de fibonacci tiene la siguiente forma: F1 = 1F2 = 1F3 = 2F4 = 3F5 = comment 5F6 = 8F7 = 13F8 = 21F9 = 34F10 = 55F11 = 89F12 = 144 Observamos que en la comment posici´on 12 (11 si comenzamos a contar desde el cero) es el d´onde empieza el primer comment n´umero de la serie que tiene 3 d´ıgitos. Enco...
# La secuencia de fibonacci tiene la siguiente forma: F1 = 1F2 = 1F3 = 2F4 = 3F5 = # 5F6 = 8F7 = 13F8 = 21F9 = 34F10 = 55F11 = 89F12 = 144 Observamos que en la # posici´on 12 (11 si comenzamos a contar desde el cero) es el d´onde empieza el primer # n´umero de la serie que tiene 3 d´ıgitos. Encontrar la posici´on d´on...
Python
zaydzuhri_stack_edu_python
string This is an example script. import sys function greet name begin string Return greeting. return format string Hello {}! name end function if __name__ == string __main__ begin set name = argv at 1 print call greet name end
"""This is an example script.""" import sys def greet(name): """Return greeting.""" return "Hello {}!".format(name) if __name__ == "__main__": name = sys.argv[1] print(greet(name))
Python
zaydzuhri_stack_edu_python
async function set self key value ttl=none refresh=none prev_exist=none begin async_with call ClientSession as session begin set _ = await put call _get_url key headers=auth_headers end end function
async def set(self, key, value, ttl=None, refresh=None, prev_exist=None): async with client.ClientSession() as session: _ = await session.put( self._get_url(key), headers=self.client.auth_headers )
Python
nomic_cornstack_python_v1
function reseed self entropy begin if length entropy * 8 * 2 < 3 * security_strength begin raise call RuntimeError string entropy must be at least %f bits. % 1.5 * security_strength end if length entropy * 8 > 1000 begin raise call RuntimeError string entropy cannot exceed 1000 bits. end call __update entropy set resee...
def reseed(self, entropy: bytes): if (len(entropy) * 8 * 2) < (3 * self.security_strength): raise RuntimeError("entropy must be at least %f bits." % (1.5 * self.security_strength)) if len(entropy) * 8 > 1000: raise RuntimeError("entropy cannot exceed 1000 bits.") self._...
Python
nomic_cornstack_python_v1
function get_plugin_installer self name begin raise NotImplementedError end function
def get_plugin_installer(self, name: str) -> "PluginInstaller": raise NotImplementedError
Python
nomic_cornstack_python_v1
from random import randint function findMedian arr l r begin set n = r - l for i in range n begin set j = i while j > 0 and arr at l + j - 1 > arr at l + j begin set tuple arr at l + j - 1 arr at l + j = tuple arr at l + j arr at l + j - 1 set j = j - 1 end end return arr at l + n // 2 end function function medianMedia...
from random import randint def findMedian(arr, l, r): n = r - l for i in range(n): j = i while j > 0 and arr[l + j - 1] > arr[l + j]: arr[l + j - 1], arr[l + j] = arr[l + j], arr[l + j - 1] j -= 1 return arr[l + n // 2] def medianMedians(arr, l, r): n = r - l ...
Python
zaydzuhri_stack_edu_python
function add_b_zeros bvecs bvals b0_spacing=10 leading_b0s=1 begin comment Start with list of b-zeros set bvals_zeros = list set non_b_zeros_remaining = length bvals set leading_b0s_remaining = leading_b0s set count = b0_spacing set bval_index = 0 while non_b_zeros_remaining > 0 begin while leading_b0s_remaining > 0 b...
def add_b_zeros(bvecs, bvals, b0_spacing=10, leading_b0s=1): # Start with list of b-zeros bvals_zeros = [] non_b_zeros_remaining = len(bvals) leading_b0s_remaining = leading_b0s count = b0_spacing bval_index = 0 while(non_b_zeros_remaining > 0): while(leading_b0s_remaining > 0): bvals_zeros.append(0) le...
Python
nomic_cornstack_python_v1
import cv2 import glob import os from tqdm import tqdm import sys import json set path_base = join path string /media/md0/xt1800i/Bite/datasets/ function json_parser species begin set string = read open join path path_base string raw_data species + string .json string r set json_data = loads string set filename = list ...
import cv2 import glob import os from tqdm import tqdm import sys import json path_base = os.path.join('/media/md0/xt1800i/Bite/datasets/') def json_parser(species): string = open(os.path.join(path_base, 'raw_data', species + '.json'), 'r').read() json_data = json.loads(string) filename = [] fileinfo...
Python
zaydzuhri_stack_edu_python
import sys call setrecursionlimit 1 ? 25 set read = readline set ra = range set enu = enumerate function read_ints begin return list map int split read end function function read_a_int begin return integer read end function function read_tuple H begin string H is number of rows set ret = list for _ in range H begin ap...
import sys sys.setrecursionlimit(1 << 25) read = sys.stdin.readline ra = range enu = enumerate def read_ints(): return list(map(int, read().split())) def read_a_int(): return int(read()) def read_tuple(H): ''' H is number of rows ''' ret = [] for _ in range(H): ret.append(tuple...
Python
zaydzuhri_stack_edu_python
function check_ts self log=true begin if any list comprehension e0 is none for spc in r_species + p_species + list ts_species begin error format string Could not get E0's of all species participating in reaction {0}. Cannot check TS E0. label return true end set r_e0 = sum list comprehension e0 for spc in r_species set...
def check_ts(self, log=True): if any([spc.e0 is None for spc in self.r_species + self.p_species + [self.ts_species]]): logging.error("Could not get E0's of all species participating in reaction {0}. Cannot check TS E0.".format( self.label)) return True r_e0 = sum(...
Python
nomic_cornstack_python_v1
function __init__ self data=none ptr=none format=string PEM begin if ptr is not none begin if data is not none begin raise call TypeError string Cannot use data and ptr simultaneously end set cert = ptr end else if data is none begin raise call TypeError string data argument is required end else begin set bio = call Me...
def __init__(self, data=None, ptr=None, format="PEM"): if ptr is not None: if data is not None: raise TypeError("Cannot use data and ptr simultaneously") self.cert = ptr elif data is None: raise TypeError("data argument is required") else: ...
Python
nomic_cornstack_python_v1
function brightness self value begin set cmd = value set msg = call pack string hB cmd integer 255 * value call _send msg end function
def brightness(self, value): cmd = QCKPrismCMDs.BRIGHTNESS.value msg = struct.pack('hB', cmd, int(255*value)) self._send(msg)
Python
nomic_cornstack_python_v1
import tkinter.messagebox import os from tkinter import * from tkinter import filedialog from pygame import mixer set root = call Tk comment initializing the mixer call init call geometry string 400x400 title root string Muse call iconbitmap string headphone.ico comment menubar set menubar = call Menu root call config ...
import tkinter.messagebox import os from tkinter import * from tkinter import filedialog from pygame import mixer root=Tk() mixer.init() #initializing the mixer root.geometry("400x400") root.title("Muse") root.iconbitmap(r"headphone.ico") # menubar menubar=Menu(root) root.config(menu=menubar) def aboutUs(): ...
Python
zaydzuhri_stack_edu_python
function template_server begin function predicate ctx begin return guild and id == template_guild_id end function return call check predicate end function
def template_server(): def predicate(ctx): return ctx.guild and ctx.guild.id == template_guild_id return commands.check(predicate)
Python
nomic_cornstack_python_v1
string DICCIONARIO Un tipo de datos que almacena un conjunto de datos. En formato clave > valor Es parecido a un array asociativo o un objeto JSON Índice alfanumérico set persona = dict string nombre string Pili ; string apellido string González ; string edad string ? print persona print type persona print persona at s...
""" DICCIONARIO Un tipo de datos que almacena un conjunto de datos. En formato clave > valor Es parecido a un array asociativo o un objeto JSON Índice alfanumérico """ persona ={ "nombre": "Pili", "apellido": "González", "edad": "?" } print(persona) print(type(persona)) print(persona["apellido"]) # Lista con diccin...
Python
zaydzuhri_stack_edu_python
function PostData self postdata begin if length postdata > 0 begin for key in postdata begin if postdata at key == string %TARGET% begin set postdata at key = _target end end set _postdata = postdata end else begin set _postdata = none end end function
def PostData(self, postdata): if len(postdata) > 0: for key in postdata: if postdata[key] == "%TARGET%": postdata[key] = self._target self._postdata = postdata else: self._postdata = None
Python
nomic_cornstack_python_v1
function test_exports__all_of_submodule_exports self begin set exported_by_submodules = set for mod in call get_submodules begin update exported_by_submodules __all__ end set exported_by_root = set __all__ set missing_exports = exported_by_submodules - exported_by_root call assertEmpty missing_exports msg=string some p...
def test_exports__all_of_submodule_exports(self): exported_by_submodules = set() for mod in self.get_submodules(): exported_by_submodules.update(mod.__all__) exported_by_root = set(calleee.__all__) missing_exports = exported_by_submodules - exported_by_root self.asse...
Python
nomic_cornstack_python_v1
string File name: data_extract.py Author: Daniel G Perico Sánchez Date created: 31/03/2019 Date last modified: 02/04/2019 Python Version: 3.7.2 import pandas as pd import requests as rq from bs4 import BeautifulSoup as beso import re import sys , os set country = string argv at 2 set city = string argv at 1 set year = ...
''' File name: data_extract.py Author: Daniel G Perico Sánchez Date created: 31/03/2019 Date last modified: 02/04/2019 Python Version: 3.7.2 ''' import pandas as pd import requests as rq from bs4 import BeautifulSoup as beso import re import sys, os country = str(sys.argv[2]) city = str(sys.argv[1...
Python
zaydzuhri_stack_edu_python
import pytz function check_restaurant_availability restaurant_status day begin if day not in restaurant_status begin return string Invalid day end set current_time = now set restaurant_timezone = call timezone string Your Restaurant Time Zone set current_time = call astimezone restaurant_timezone set current_time = str...
import pytz def check_restaurant_availability(restaurant_status, day): if day not in restaurant_status: return "Invalid day" current_time = datetime.datetime.now() restaurant_timezone = pytz.timezone('Your Restaurant Time Zone') current_time = pytz.utc.localize(current_time).astimezone(restaur...
Python
greatdarklord_python_dataset
import random class Bidder begin function __init__ self name budget bid_probability bid_increase_perc highest_bid begin set name = name set budget = budget set bid_probability = bid_probability set highest_bid = 0 set bid_increase_perc = bid_increase_perc end function function bid self auctioneer begin set bid = highes...
import random class Bidder: def __init__(self, name, budget, bid_probability, bid_increase_perc, highest_bid): self.name = name self.budget = budget self.bid_probability = bid_probability self.highest_bid = 0 self.bid_increase_perc = bid_increase_perc ...
Python
zaydzuhri_stack_edu_python
function test_registerWithTakenNick self begin set username = string testuser set hostname = string testhost set servername = string testserver set realname = string testname set password = string testpass call register username hostname servername call irc_ERR_NICKNAMEINUSE string prefix list string param set lastLine...
def test_registerWithTakenNick(self): username = "testuser" hostname = "testhost" servername = "testserver" self.protocol.realname = "testname" self.protocol.password = "testpass" self.protocol.register(username, hostname, servername) self.protocol.irc_ERR_NICKNAM...
Python
nomic_cornstack_python_v1
import sys set x = string si while x == string si begin set tecla = read stdin 1 print string Has presionado { tecla } if tecla == string s begin set x = string no end end
import sys x='si' while x=='si': tecla = sys.stdin.read(1) print (f'Has presionado {tecla}') if tecla=='s': x='no'
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 05.py string 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ. この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. [n-gram] : bigramとは、任意の文字列が2文字だけ続いた文字列のこと n-gram は「文章中に現れる N 個連続した連なり」?? import re string (seq[i:] for i in range(n)) は例えば "Hello" という文字列から ("Hello", "ello", "llo") と開始を1文字ずつず...
# -*- coding: utf-8 -*- # 05.py """ 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ. この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. [n-gram] : bigramとは、任意の文字列が2文字だけ続いた文字列のこと n-gram は「文章中に現れる N 個連続した連なり」?? """ import re """ (seq[i:] for i in range(n)) は例えば "Hello" という文字列から ("Hello", "ello", "llo") と開始を1文字ずつずらした N 個組みの...
Python
zaydzuhri_stack_edu_python
function yolo_boxes_to_corners box_xy box_wh begin set box_mins = box_xy - box_wh / 2.0 set box_maxes = box_xy + box_wh / 2.0 return concatenate list box_mins at tuple Ellipsis slice 1 : 2 : box_mins at tuple Ellipsis slice 0 : 1 : box_maxes at tuple Ellipsis slice 1 : 2 : box_maxes at tuple Ellipsis slice 0 : 1 : e...
def yolo_boxes_to_corners(box_xy, box_wh): box_mins = box_xy - (box_wh / 2.) box_maxes = box_xy + (box_wh / 2.) return K.concatenate([ box_mins[..., 1:2], # y_min box_mins[..., 0:1], # x_min box_maxes[..., 1:2], # y_max box_maxes[..., 0:1] # x_max ])
Python
nomic_cornstack_python_v1
import os from itertools import combinations from typing import List import numpy as np import pandas as pd import pytest from sklearn.preprocessing import LabelEncoder from hydro_stat.statistical_report.statistical_feature_report import HeatMapData set TEST_SCRIPT_PATH = directory name path real path path __file__ cla...
import os from itertools import combinations from typing import List import numpy as np import pandas as pd import pytest from sklearn.preprocessing import LabelEncoder from hydro_stat.statistical_report.statistical_feature_report import HeatMapData TEST_SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) cl...
Python
zaydzuhri_stack_edu_python
function _to_categorical self y begin set num_classes = length set y set x = call eye num_classes dtype=string uint8 at y return x end function
def _to_categorical(self, y): num_classes = len(set(y)) x = np.eye(num_classes, dtype='uint8')[y] return x
Python
nomic_cornstack_python_v1
function parse_mapping_from_string s parse_cell_extensions=false begin set handler = call AlignmentHandler parse etree call BytesIO encode s string utf-8 call XMLParser target=handler if parse_cell_extensions == false begin call remove_cell_extensions alignment end return tuple alignment onto1 onto2 extension end funct...
def parse_mapping_from_string(s, parse_cell_extensions=False): handler = AlignmentHandler() etree.parse(BytesIO(s.encode("utf-8")), etree.XMLParser(target=handler)) if parse_cell_extensions == False: remove_cell_extensions(handler.alignment) return handler.alignment, handler.onto1, handler.onto2...
Python
nomic_cornstack_python_v1
function save_as self file_path begin return call SavableGraph self file_path end function
def save_as(self, file_path): return SavableGraph(self, file_path)
Python
nomic_cornstack_python_v1
function test_edit_position_post_fail self begin set response = post reverse string hours:edit_position args=tuple id dict string name string follow=true assert equal status_code 200 assert false call is_valid assert equal errors dict string name list string To pole jest wymagane. call assertTemplateUsed response stri...
def test_edit_position_post_fail(self): response = self.client.post( reverse('hours:edit_position', args=(self.barista.id,)), {u'name': u''}, follow=True ) self.assertEqual(response.status_code, 200) self.assertFalse(response.context['form'].is_valid...
Python
nomic_cornstack_python_v1
comment implementation of card game - Memory import simplegui import random comment Populate card deck - only needs to be done once set cards = range 8 + range 8 comment helper function to initialize globals, shuffle deck and turn face-down function new_game begin global state cards faceup turns match set state = 0 set...
# implementation of card game - Memory import simplegui import random cards = range(8) + range(8) # Populate card deck - only needs to be done once # helper function to initialize globals, shuffle deck and turn face-down def new_game(): global state, cards, faceup, turns, match state = 0 turns = 0 la...
Python
zaydzuhri_stack_edu_python
function test_005_get_work_package begin comment Send GET request set actual = call get_work_package TEST_005 at string WORK_PACKAGE_ID comment Parse response to json format set actual_data = json actual comment Validate status code assert status_code == 200 msg string Failed to send status code: { status_code } commen...
def test_005_get_work_package(): # Send GET request actual = WorkPackagesApi(API.BASE_URL, API.API_KEY).get_work_package(API.TEST_005["WORK_PACKAGE_ID"]) # Parse response to json format actual_data = actual.json() # Validate status code assert actual.status_code == 200, f'Failed to send status ...
Python
nomic_cornstack_python_v1
function set_Radius self value begin call _set_input string Radius value end function
def set_Radius(self, value): super(TextSearchInputSet, self)._set_input('Radius', value)
Python
nomic_cornstack_python_v1
comment Libraries import matplotlib.pyplot as plt import sklearn from sklearn.datasets import make_classification from sklearn.datasets import make_blobs from sklearn.datasets import make_gaussian_quantiles from sklearn.cross_validation import train_test_split from sklearn import svm from sklearn.neighbors import KNeig...
#Libraries import matplotlib.pyplot as plt import sklearn from sklearn.datasets import make_classification from sklearn.datasets import make_blobs from sklearn.datasets import make_gaussian_quantiles from sklearn.cross_validation import train_test_split from sklearn import svm from sklearn.neighbors import KNeighborsCl...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Date 2015/10/31 comment By Charlotte.HonG comment unix_mid_test_05 import random comment 演算法 comment def insertion_sort(lst, start, end): comment if len(lst) == 1: comment return comment for i in xrange(start + 1, end + 1): comment temp = lst[i] comment j =...
#!/usr/bin/python # -*- coding: utf-8 -*- # Date 2015/10/31 # By Charlotte.HonG # unix_mid_test_05 import random # 演算法 # def insertion_sort(lst, start, end): # if len(lst) == 1: # return # for i in xrange(start + 1, end + 1): # temp = lst[i] # j = i - 1 # while j >= start and...
Python
zaydzuhri_stack_edu_python
comment Import cv2 module import cv2 from dataPath import DATA_PATH comment Path to the image we are going to read comment This can be an absolute or relative path comment Here we are using a relative path set imageName = DATA_PATH + string images/boy.jpg comment Load the image set image = call imread imageName IMREAD_...
# Import cv2 module import cv2 from dataPath import DATA_PATH # Path to the image we are going to read # This can be an absolute or relative path # Here we are using a relative path imageName = DATA_PATH+"images/boy.jpg" # Load the image image = cv2.imread(imageName, cv2.IMREAD_COLOR) # Draw an ellipse # Note: Ellip...
Python
zaydzuhri_stack_edu_python
comment Problem Statement string Q.21 Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. comment Defining a function to return list corresponding to length of each elements in a given list function len_each_list_elements lst begin set len_list = list fo...
# Problem Statement '''Q.21 Write a program that maps a list of words into a list of integers representing the lengths of the correponding words.''' #Defining a function to return list corresponding to length of each elements in a given list def len_each_list_elements(lst): len_list = list() for i in lst: ...
Python
zaydzuhri_stack_edu_python
function gg_lpdf x a d p begin set tmp = log p - d * log a - log call gamma d / p + d - 1 * log x - x / a ^ p return tmp end function
def gg_lpdf(x, a, d, p): tmp = np.log(p) - d*np.log(a) - np.log(scipy.special.gamma(d/p)) + (d-1) * np.log(x) - (x/a)**p return tmp
Python
nomic_cornstack_python_v1
function elements_position self selector begin set tuple attr pattern val = call parser_selector selector attr=string identifier set strip = lambda v -> strip v if pattern begin set val = call val end function identifier query begin return call id query or call name query end function function name query begin return c...
def elements_position(self, selector): attr, pattern, val = self.parser_selector(selector, attr='identifier') strip = lambda v: v.strip() if pattern: val = locals()[pattern](val) def identifier(query): return id(query) or name(query) def name(query): ...
Python
nomic_cornstack_python_v1
string Extends inspyred with the functionality to continue an evoluationary algorithm that was stopped due to some reason. import collections import copy class ContinueEvaluator begin set EVALUATE_INITIAL_POPULATION = 0 set EVALUATE_FIRST_OFFSPRING = 1 set NORMAL_EVALUATION = 2 function __init__ self normal_evaluator p...
""" Extends inspyred with the functionality to continue an evoluationary algorithm that was stopped due to some reason. """ import collections import copy class ContinueEvaluator: EVALUATE_INITIAL_POPULATION = 0 EVALUATE_FIRST_OFFSPRING = 1 NORMAL_EVALUATION = 2 def __init__ (self, normal_evaluator, p...
Python
zaydzuhri_stack_edu_python
function getDBConnectionAndCursor begin comment connect to the database comment you might need to change this to suit your filesystem set pathname = string /Users/xiangormirko/Desktop/miniFB.db set conn = call connect pathname comment obtain a cursor object set cursor = call cursor comment return connection and cursor ...
def getDBConnectionAndCursor(): # connect to the database pathname = "/Users/xiangormirko/Desktop/miniFB.db" # you might need to change this to suit your filesystem conn = db.connect(pathname) # obtain a cursor object cursor = conn.cursor() # return connection and cursor to calling context ...
Python
nomic_cornstack_python_v1
function any_public_tests self begin return any list comprehension not hidden for t in tests end function
def any_public_tests(self): return any([not t.hidden for t in self.tests])
Python
nomic_cornstack_python_v1
from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import Client import time from forms import PostForm from models import Post set User = call get_user_model comment Create your tests here. class TestStringMethods extends TestCase begin function test_length self beg...
from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import Client import time from .forms import PostForm from .models import Post User = get_user_model() # Create your tests here. class TestStringMethods(TestCase): def test_length(self): self.ass...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix comment...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix # Read...
Python
flytech_python_25k
function substitute self args lvars begin if call is_String args and not is instance args CmdStringHolder begin comment In case it's a UserString. set args = string args try begin function sub_match match begin return call conv call expand call group 1 lvars end function set result = sub sub_match args end except TypeE...
def substitute(self, args, lvars): if is_String(args) and not isinstance(args, CmdStringHolder): args = str(args) # In case it's a UserString. try: def sub_match(match): return self.conv(self.expand(match.group(1), lvars)) result...
Python
nomic_cornstack_python_v1
import subprocess import itertools import random import cv2 import librosa from video_group import VideoGroup class MusicVideo begin function __init__ self video_dir audio_track begin string set video_groups = call make_clip_groups video_dir set audio_track = audio_track set all_video_clips = list call from_iterable m...
import subprocess import itertools import random import cv2 import librosa from video_group import VideoGroup class MusicVideo: def __init__(self, video_dir, audio_track): """ """ self.video_groups = VideoGroup.make_clip_groups(video_dir) self.audio_track = audio_track ...
Python
zaydzuhri_stack_edu_python
import random function vvod_massiva begin set b = list set c = list set d = list set f = list set a = list b c d f for i in range 4 begin set x = random integer 0 100 append b x end for i in range 4 begin set x = random integer 0 100 append c x end for i in range 4 begin set x = random integer 0 100 append d x end ...
import random def vvod_massiva(): b = [] c = [] d = [] f = [] a = [b, c, d, f] for i in range (4): x = random.randint(0,100) b.append(x) for i in range (4): x = random.randint(0,100) c.append(x) for i in range (4): x = random.randint(0,100) d.append(x) for i in range (4): x = random.randint(0,10...
Python
zaydzuhri_stack_edu_python
function getKindIdxForLabelFromCoords inpCoords kindLabel begin set foundLabels = list set currIdx = 1 set outIdx = none for x in inpCoords begin set currLabel = x at - 1 if currLabel == kindLabel begin set outIdx = currIdx break end else if x at - 1 not in foundLabels begin append foundLabels x at - 1 set currIdx = cu...
def getKindIdxForLabelFromCoords(inpCoords, kindLabel): foundLabels = list() currIdx = 1 outIdx = None for x in inpCoords: currLabel = x[-1] if currLabel==kindLabel: outIdx = currIdx break elif x[-1] not in foundLabels: foundLabels.append(x[-1]) currIdx += 1 if outIdx is None: raise KeyError("...
Python
nomic_cornstack_python_v1
function dumpMemory begin call xmlDumpMemory end function
def dumpMemory(): libxml2mod.xmlDumpMemory()
Python
nomic_cornstack_python_v1
function __init__ self obj begin if not scipy_available begin raise call RuntimeError string scipy is not available end if not is instance obj SuperLU begin raise call TypeError string obj must be scipy.sparse.linalg.SuperLU end set shape = shape set nnz = nnz set perm_r = array perm_r set perm_c = array perm_c set L =...
def __init__(self, obj): if not scipy_available: raise RuntimeError('scipy is not available') if not isinstance(obj, scipy.sparse.linalg.SuperLU): raise TypeError('obj must be scipy.sparse.linalg.SuperLU') self.shape = obj.shape self.nnz = obj.nnz self.pe...
Python
nomic_cornstack_python_v1
comment g属性 comment 1.g对象是专门用来保存用户的数据的 comment 2.g对象再一次请求中所有的代码都是可以使用的 from flask import Flask , request , render_template from flask import g from utils import login_log set app = call Flask __name__ decorator call route string / function hello_world begin return string Hello World! end function decorator call route s...
# g属性 # 1.g对象是专门用来保存用户的数据的 # 2.g对象再一次请求中所有的代码都是可以使用的 from flask import Flask,request,render_template from flask import g from utils import login_log app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/login/',methods=['GET','POST']) def login(): if request.method=='...
Python
zaydzuhri_stack_edu_python
import math as m import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as plt3d import sympy.combinatorics.permutations as sp function points_circle r n sigma=0 begin string Return a list of n equidistant points on a circle of radius r in cartesian coordinates. Also add Gaussian noise with vari...
import math as m import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as plt3d import sympy.combinatorics.permutations as sp def points_circle(r, n, sigma=0): """Return a list of n equidistant points on a circle of radius r in cartesian coordinates. Also add Gaussian noise with varia...
Python
zaydzuhri_stack_edu_python
comment module안에 여러 객체(Class)를 담을 수도 있으므로 모듈이 객체보다 큰 개념이다. import lib set obj = call A print call a comment import로 가져오는건 모듈(파이선 파일명)이며 그 안에 정의 되있는 Class들이 객체이다. comment Class는 자바의 Class와 같은 개념이며, Module을 import해주고 사용할때 (루비나 자바에선(방식은 조금 다르지만) new로 인스턴스 변수 생성해주고) comment Python에선 new안쓰고 그냥 인스턴스 변수로 생성해서 Class를 선언한 후에 사용...
import lib #module안에 여러 객체(Class)를 담을 수도 있으므로 모듈이 객체보다 큰 개념이다. obj = lib.A() print(obj.a()) # import로 가져오는건 모듈(파이선 파일명)이며 그 안에 정의 되있는 Class들이 객체이다. # Class는 자바의 Class와 같은 개념이며, Module을 import해주고 사용할때 (루비나 자바에선(방식은 조금 다르지만) new로 인스턴스 변수 생성해주고) # Python에선 new안쓰고 그냥 인스턴스 변수로 생성해서 Class를 선언한 후에 사용 가능하다 # 일반적인 Module은 항상 준...
Python
zaydzuhri_stack_edu_python
function angles_points a b c begin set u = call subtract_vectors b a set v = call subtract_vectors c a return call angles_vectors u v end function
def angles_points(a, b, c): u = subtract_vectors(b, a) v = subtract_vectors(c, a) return angles_vectors(u, v)
Python
nomic_cornstack_python_v1
comment Distribution comment Distributed for different activities import matplotlib.pyplot as plt set days = list 1 2 3 4 5 set sleeping = list 7 8 6 11 7 set eating = list 2 3 1 3 2 set working = list 10 11 9 8 9 set travel = list 5 2 4 3 1 plot list list color=string c label=string Sleeping linewidth=5 plot list l...
#Distribution #Distributed for different activities import matplotlib.pyplot as plt days=[1,2,3,4,5] sleeping=[7,8,6,11,7] eating=[2,3,1,3,2] working=[10,11,9,8,9] travel=[5,2,4,3,1] plt.plot([],[],color='c',label='Sleeping',linewidth=5) plt.plot([],[],color='m',label='Eating',linewidth=5) plt.plot([],...
Python
zaydzuhri_stack_edu_python
function get_representatives self begin return all end function
def get_representatives(self): return self.representatives.all()
Python
nomic_cornstack_python_v1
class Bob begin function silence self message begin return not message end function function question self message begin return message at - 1 == string ? end function function shout self message begin return is upper message end function function hey self message begin if call silence message begin return string Fine....
class Bob(): def silence(self, message): return not message def question(self, message): return message[-1] == '?' def shout(self, message): return message.isupper() def hey(self, message): if self.silence(message): return 'Fine. Be that way.' ...
Python
zaydzuhri_stack_edu_python
function timestamp_string_value timestamp begin return format string {:d}.{:09d} seconds nanos end function
def timestamp_string_value(timestamp): return '{:d}.{:09d}'.format(timestamp.seconds, timestamp.nanos)
Python
nomic_cornstack_python_v1
import json import os import os.path import cv2 import mysql.connector import numpy as np import copy from connect import connection comment fetch the id's of queued tasks from the database try begin set cursor = call cursor set sql = string SELECT taskId FROM Task WHERE taskState = 0 execute cursor sql set task_data =...
import json import os import os.path import cv2 import mysql.connector import numpy as np import copy from connect import connection # fetch the id's of queued tasks from the database try: cursor = connection.cursor() sql = "SELECT taskId FROM Task WHERE taskState = 0" cursor.execute(sql) task_data = c...
Python
zaydzuhri_stack_edu_python
import random from tkinter import * function load_images card_images begin set suits = list string heart string club string diamond string spade set face_cards = list string jack string queen string king if TkVersion >= 8.6 begin set extension = string png end else begin print string Please upload appropiate image file...
import random from tkinter import * def load_images(card_images): suits = ["heart", "club", "diamond", "spade"] face_cards = ["jack", "queen", "king"] if TkVersion >= 8.6: extension = "png" else: print("Please upload appropiate image file") for suit in suits: for card in ...
Python
zaydzuhri_stack_edu_python
function merge self persons begin comment each person will be merged into this one set keep = pop persons 0 comment loop over all the rest for i in persons begin merge keep i call refresh_from_db end comment also delete the now duplicated PersonIdentifier objects set keep_filer_ids = filter scheme=string calaccess_file...
def merge(self, persons): # each person will be merged into this one keep = persons.pop(0) # loop over all the rest for i in persons: merge(keep, i) keep.refresh_from_db() # also delete the now duplicated PersonIdentifier objects keep_filer_ids =...
Python
nomic_cornstack_python_v1
function type self begin return get pulumi self string type end function
def type(self) -> str: return pulumi.get(self, "type")
Python
nomic_cornstack_python_v1
for _ in range T begin set tuple a b c = map int split input if a < b - c begin print string advertise end else if a == b - c begin print string does not matter end else begin print string do not advertise end end
for _ in range(T): a,b,c=map(int,input().split()) if(a<b-c): print('advertise') elif(a==b-c): print('does not matter') else: print('do not advertise')
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment This is how to define a list and and use the append method to add 1,2,3 to the bottom of the file. set mylist = list append mylist 1 append mylist 2 append mylist 3 comment print(mylist[0]) # prints 1 comment print(mylist[1]) # prints 2 comment print(mylist[2]) # prints 3 comment T...
#!/usr/bin/env python # This is how to define a list and and use the append method to add 1,2,3 to the bottom of the file. mylist = [] mylist.append(1) mylist.append(2) mylist.append(3) #print(mylist[0]) # prints 1 #print(mylist[1]) # prints 2 #print(mylist[2]) # prints 3 # This is using a for loop in x using mylist ...
Python
zaydzuhri_stack_edu_python
string Used to extract forest, crop, and urban masks from landcover. import argparse import glob import os import logging import multiprocessing import numpy from ecoshard import taskgraph from ecoshard import geoprocessing from osgeo import gdal set CROPLAND_LULC_CODES = tuple range 10 41 set URBAN_LULC_CODES = tuple ...
"""Used to extract forest, crop, and urban masks from landcover.""" import argparse import glob import os import logging import multiprocessing import numpy from ecoshard import taskgraph from ecoshard import geoprocessing from osgeo import gdal CROPLAND_LULC_CODES = tuple(range(10, 41)) URBAN_LULC_CODES = (190,) FOR...
Python
zaydzuhri_stack_edu_python
function parameter_generator cache initial_state_gen seed_gen=none max_iterations=10000 begin set cache_gen = call constant_generator cache set max_iterations_gen = call constant_generator max_iterations if not seed_gen begin set seed_gen = call random_seed_generator end return call izip cache_gen initial_state_gen see...
def parameter_generator(cache, initial_state_gen, seed_gen=None, max_iterations=10000): cache_gen = constant_generator(cache) max_iterations_gen = constant_generator(max_iterations) if not seed_gen: seed_gen = random_seed_generator() return itertools.izip(cache_gen, init...
Python
nomic_cornstack_python_v1
function read_dataset_tf path_to_dataset_folder index_filename begin set f = open path_to_dataset_folder + string / + index_filename string r set lines = read lines f set index_list = list set sample_filename_list = list set feature_list = list for i in lines begin if split i string at 0 == string -1 begin append in...
def read_dataset_tf(path_to_dataset_folder,index_filename): ############################################################### f = open(path_to_dataset_folder+'/'+index_filename,'r') lines = f.readlines() index_list = [] sample_filename_list = [] feature_list = [] for i in lines: if (i....
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- import struct call pack string >I 10240099 function checkbmp bmp_file begin with open bmp_file string rb as f begin set header = read f 30 return call checkbmp_header header end end function function checkbmp_header header_in_byte begin if length header_in_byte ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import struct struct.pack('>I', 10240099) def checkbmp(bmp_file): with open(bmp_file, 'rb') as f: header = f.read(30) return checkbmp_header(header) def checkbmp_header(header_in_byte): if len(header_in_byte) != struct.calcsize('>ccIIIIIIHH'): rais...
Python
zaydzuhri_stack_edu_python
function csv_to_latex_tabular input_csv_path output_tex_path contains_header=true use_booktabks=true begin with open input_csv_path string r as csv_file ; open output_tex_path string w as tex_file begin write tex_file string \begin{tabular}{ for tuple i row in enumerate reader csv_file begin if i == 0 begin write tex_f...
def csv_to_latex_tabular(input_csv_path, output_tex_path, contains_header=True, use_booktabks=True): with open(input_csv_path, "r") as csv_file, open(output_tex_path, "w") as tex_file: tex_file.write("\\begin{tabular}{") for i, row in enumerate(csv.reader(csv_file)): if i == 0: ...
Python
nomic_cornstack_python_v1
comment Define the size of the array set rows = 4 set cols = 4 comment Create an empty 2-D array set array = list comprehension list comprehension 0 for _ in range cols for _ in range rows comment Fill the array with alternating 1's and 0's for i in range rows begin for j in range cols begin if i + j % 2 == 0 begin set...
# Define the size of the array rows = 4 cols = 4 # Create an empty 2-D array array = [[0 for _ in range(cols)] for _ in range(rows)] # Fill the array with alternating 1's and 0's for i in range(rows): for j in range(cols): if (i + j) % 2 == 0: array[i][j] = 1 # Print the array for row in arra...
Python
greatdarklord_python_dataset
function eval_popularity popularity eval_train test method=string recall begin set eval_train_lil = call tolil set all_train_items = rows set test_lil = call tolil set all_test_items = rows set hit = 0 set num_user = 0 if method == string recall begin for tuple user rows in enumerate all_train_items begin comment not N...
def eval_popularity(popularity,eval_train,test,method='recall'): eval_train_lil = eval_train.tolil() all_train_items = eval_train_lil.rows test_lil = test.tolil() all_test_items = test_lil.rows hit = 0 num_user = 0 if method == 'recall': for user,rows in enumerate(all_train_item...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import argparse import os set parser = call ArgumentParser description=string Run image denoising with learnt dictionary call add_argument string dictionary type=unicode help=string the directory containing the dataset call add_argument string zcaMatrix type=unicode help=string the name of ...
#!/usr/bin/env python import argparse import os parser = argparse.ArgumentParser(description='Run image denoising with learnt dictionary') parser.add_argument('dictionary', type=unicode, help="the directory containing the dataset") parser.add_argument('zcaMatrix', type=unicode, help="the name of the dataset") parser....
Python
zaydzuhri_stack_edu_python
import sys function fib n begin if n < 2 begin return n end set x = 1 set y = 1 set mod = 1000000007 for i in range 2 n begin set t = x + y set x = y set y = t % mod end return y end function if __name__ == string __main__ begin for line in stdin begin set n = integer strip line print call fib n end end
import sys def fib(n): if(n < 2): return n x = 1 y = 1 mod = 1000000007 for i in range(2, n): t = x + y x = y y = t % mod return y if __name__ == "__main__": for line in sys.stdin: n = int(line.strip()) print(fib(n))
Python
zaydzuhri_stack_edu_python
import json import sys import datetime from newspaper import Article import newsplease function main begin print string > sys.args: argv file=stderr set args_path = argv at 1 with open args_path as args_fp begin set args_raw = read args_fp set args = loads args_raw print string > args_raw: args_raw at slice : 300 : f...
import json import sys import datetime from newspaper import Article import newsplease def main(): print('> sys.args: ', sys.argv, file=sys.stderr) args_path = sys.argv[1] with open(args_path) as args_fp: args_raw = args_fp.read() args = json.loads(args_raw) print('> args_raw: ', ...
Python
zaydzuhri_stack_edu_python
function test_close_all_exception self mock_update begin with call LogCapture as log_capture begin call close_all call check tuple string aggregator.streams.models string ERROR string An error occurred while closing Streams: foobar end end function
def test_close_all_exception(self, mock_update): with LogCapture() as log_capture: Stream.objects.close_all() log_capture.check( ('aggregator.streams.models', 'ERROR', 'An error occurred while closing Streams: foobar'), )
Python
nomic_cornstack_python_v1
while k + wiz / num * 100 < per begin set k = k + 1 end print k
while (k+wiz)/num*100 < per: k += 1 print(k)
Python
jtatman_500k
function main begin set path_list = list directory get current directory comment noqa: E501 print string asdjflkasjfksdajfkdsjfkdasjfkdasjfkdasjfkasdjfkasdjfaksdjfksadfasdfjadsk print string { path_list } print string { add 1 2 } end function
def main(): path_list = os.listdir(os.getcwd()) print("asdjflkasjfksdajfkdsjfkdasjfkdasjfkdasjfkasdjfkasdjfaksdjfksadfasdfjadsk") # noqa: E501 print(f'{path_list}') print(f'{add(1,2)}')
Python
nomic_cornstack_python_v1
import unittest from binary_tree import BinaryTree comment python3 -m unittest tests.py class BinaryTreeTesting extends TestCase begin function test_create_binary_tree self begin set binary_tree = call BinaryTree return binary_tree print string here end function function test_add_node_to_tree self begin set binary_tree...
import unittest from binary_tree import BinaryTree # python3 -m unittest tests.py class BinaryTreeTesting(unittest.TestCase): def test_create_binary_tree(self): binary_tree = BinaryTree() return binary_tree print('here') def test_add_node_to_tree(self): binary_tree = self.test_...
Python
zaydzuhri_stack_edu_python
function tool_shed_from_repository_clone_url repository_clone_url begin return right strip split call clean_repository_clone_url repository_clone_url string /repos/ at 0 string / end function
def tool_shed_from_repository_clone_url( repository_clone_url ): return clean_repository_clone_url( repository_clone_url ).split( '/repos/' )[ 0 ].rstrip( '/' )
Python
nomic_cornstack_python_v1
function __init__ self path=string IdentityFunction begin set path = path set heal = lambda X -> X set heal_tf = lambda X -> X end function
def __init__(self, path="IdentityFunction"): self.path = path self.heal = lambda X: X self.heal_tf = lambda X: X
Python
nomic_cornstack_python_v1
import socket set socket_client = call socket call connect tuple string 127.0.0.1 10000 while true begin set data = input string >>> if data != string exit begin call send encode data encoding=string utf-8 set recv_data = decode call recv 1024 encoding=string utf-8 print recv_data end else begin close socket_client bre...
import socket socket_client = socket.socket() socket_client.connect(('127.0.0.1', 10000)) while True: data = input('>>>') if data != 'exit': socket_client.send(data.encode(encoding='utf-8')) recv_data = socket_client.recv(1024).decode(encoding='utf-8') print(recv_data) else: ...
Python
zaydzuhri_stack_edu_python
function Get self request global_params=none begin set config = call GetMethodConfig string Get return call _RunMethod config request global_params=global_params end function
def Get(self, request, global_params=None): config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params)
Python
nomic_cornstack_python_v1
function set_adc_gain self sensitivity begin if not 0 <= sensitivity < 4 begin raise call ValueError string sensitivity is out of bounds [0,3] end set val = call _era_read 391 ? 63 ? sensitivity ? 6 call _era_write 391 val end function
def set_adc_gain(self, sensitivity: int): if not 0 <= sensitivity < 4: raise ValueError("sensitivity is out of bounds [0,3]") val = self._era_read(0x0187) & 0x3F | (sensitivity << 6) self._era_write(0x0187, val)
Python
nomic_cornstack_python_v1
import json import os from datetime import timedelta , date comment module to convert an address into latitude and longitude values from geopy.geocoders import Nominatim import requests function select_keys d ks begin return dictionary comprehension k : d at k for k in ks if k in d end function class Weather extends ob...
import json import os from datetime import timedelta, date # module to convert an address into latitude and longitude values from geopy.geocoders import Nominatim import requests def select_keys(d, ks): return {k: d[k] for k in ks if k in d} class Weather(object): """API for getting the weather at a spacetime...
Python
zaydzuhri_stack_edu_python