code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment =============================================================================== comment Trabalho 04 comment ------------------------------------------------------------------------------- comment Autor: Rodrigo Guimarães comment Universidade Tecnológica Federal do Paraná comment ================================...
# =============================================================================== # Trabalho 04 # ------------------------------------------------------------------------------- # Autor: Rodrigo Guimarães # Universidade Tecnológica Federal do Paraná # ====================================================================...
Python
zaydzuhri_stack_edu_python
from PyTest import * comment //////////////////////////// PROBLEM STATEMENT /////////////////////////////// comment Given a list of integers and start & end indexes into the list, print // comment the number of times where, between the start and end indices (inclusive), // comment an integer in the list is followed by ...
from PyTest import * ##//////////////////////////// PROBLEM STATEMENT /////////////////////////////// ## Given a list of integers and start & end indexes into the list, print // ## the number of times where, between the start and end indices (inclusive), // ## an integer in the list is followed by the same intege...
Python
zaydzuhri_stack_edu_python
function rename_object_data self old_name new_name begin for ct in all begin set model = call model_class set params = dict string custom_field_data__ { old_name } __isnull false set instances = filter keyword params for instance in instances begin set custom_field_data at new_name = pop custom_field_data old_name end ...
def rename_object_data(self, old_name, new_name): for ct in self.content_types.all(): model = ct.model_class() params = {f'custom_field_data__{old_name}__isnull': False} instances = model.objects.filter(**params) for instance in instances: instance...
Python
nomic_cornstack_python_v1
function get_token token gh_config hub_config begin if token begin return token end else if exists gh_config begin set config = call load_config gh_config set host = config at string github.com set token = host at string oauth_token return token end else if exists hub_config begin set config = call load_config hub_conf...
def get_token(token, gh_config, hub_config): if token: return token elif gh_config.exists(): config = load_config(gh_config) host = config["github.com"] token = host["oauth_token"] return token elif hub_config.exists(): config = load_config(hub_config) ...
Python
nomic_cornstack_python_v1
function _context_build self pending=false begin string Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set of pre-defined values which have a c...
def _context_build(self, pending=False): """ Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set of pre...
Python
jtatman_500k
import random for i in range 5 begin print string First Series: random integer 1 10 end for i in range 3 begin print string Second Series: call randrange 1 2 end
import random for i in range(5): print("First Series: ",random.randint(1,10)) for i in range(3): print("Second Series: ",random.randrange(1,2))
Python
zaydzuhri_stack_edu_python
function non_maximum_suppression prediction iou_threshold=0.45 score_threshold=0.25 begin comment num_classes = len(names) set max_wh = 4096 set max_det = 300 set max_nms = 30000 set output = list zeros tuple 0 6 device=device * shape at 0 for tuple xi x in enumerate prediction begin set x = x at x at tuple Ellipsis 4 ...
def non_maximum_suppression(prediction, iou_threshold=0.45, score_threshold=0.25): # num_classes = len(names) max_wh = 4096 max_det = 300 max_nms = 30000 output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] for xi, x in enumerate(prediction): x = x[x[..., 4] >...
Python
nomic_cornstack_python_v1
function _pq2df data_file begin set df = call read_parquet data_file return df end function
def _pq2df(data_file): df = pd.read_parquet(data_file) return df
Python
nomic_cornstack_python_v1
comment Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt comment Write a program that reads the words in words.txt and stores them as keys in a dictionary. comment It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary. co...
# Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt # Write a program that reads the words in words.txt and stores them as keys in a dictionary. # It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary. # text = open("wor...
Python
zaydzuhri_stack_edu_python
import itertools function accumulating_product lst begin return list accumulate lst lambda a b -> a * b end function
import itertools def accumulating_product(lst): return list(itertools.accumulate(lst, lambda a,b : a*b))
Python
zaydzuhri_stack_edu_python
function test_get_type_object name begin set result = call get_type_object name assert is instance result type set expected_name = __module__ + string . + __qualname__ if starts with expected_name string builtins. begin set expected_name = expected_name at slice length string builtins. : : end assert expected_name ==...
def test_get_type_object(name): result = walking.get_type_object(name) assert isinstance(result, type) expected_name = result.__module__ + "." + result.__qualname__ if expected_name.startswith("builtins."): expected_name = expected_name[len("builtins.") :] assert expected_name == name
Python
nomic_cornstack_python_v1
function add_item_unlocking_item self item begin set item_id = call insert_item_query item execute cursor string insert into item_unlocking_items values (:item_id, :unlocks_item) dict string item_id item_id ; string unlocks_item call get_unlocks_item return call ItemUnlockingItem name=call get_name description=call get...
def add_item_unlocking_item(self, item): item_id = self.insert_item_query(item) self.cursor.execute( \ """ insert into item_unlocking_items values (:item_id, :unlocks_item) """, {'item_id': item_id, 'unlocks_item': item.get_unlocks_item()}) return ItemUnlockingItem( n...
Python
nomic_cornstack_python_v1
comment tic-tac-toe comment stage 1: comment create the main loop comment print the board comment create your loop comment get the user input comment put the user input in the board comment stage2: comment check for player win comment stage3: comment create the second player comment check for second player win comment ...
#tic-tac-toe #stage 1: #create the main loop #print the board #create your loop #get the user input #put the user input in the board #stage2: #check for player win #stage3: #create the second player #check for second player win #check for a full board #stage4: #combine stages 2 & 3 into 1 function #def is winner(b...
Python
zaydzuhri_stack_edu_python
function test_move_right__ok_3 begin set old_puzzle = list 0 2 3 4 5 6 7 8 9 set obj_puzzle = list 2 0 3 4 5 6 7 8 9 set new_puzzle = call move_right 3 old_puzzle assert new_puzzle == obj_puzzle set old_puzzle = list 1 0 3 4 5 6 7 8 9 set obj_puzzle = list 1 3 0 4 5 6 7 8 9 set new_puzzle = call move_right 3 old_puzzle...
def test_move_right__ok_3(): old_puzzle = [ 0, 2, 3, 4, 5, 6, 7, 8, 9 ] obj_puzzle = [ 2, 0, 3, 4, 5, 6, 7, 8, 9 ] new_puzzle = moves.move_right(3, old_puzzle) assert new_puzzle == obj_puzzle old_puzzle = [ 1, 0, 3, 4, 5, 6, 7, 8, 9 ] obj_puzzle = [ 1, 3, 0, 4, 5, 6, 7, 8, 9 ] new_puz...
Python
nomic_cornstack_python_v1
import logging import sys from unittest import TestCase import matplotlib.pyplot as plt import numpy as np from src.SABRModel.SABRModel import SABRModelLognormalApprox from src.Utils.Extrapolator.PolynomialExtrapolator import PolynomialExtrapolator from src.Utils.Types.OptionType import OptionType from src.Utils.Valuat...
import logging import sys from unittest import TestCase import matplotlib.pyplot as plt import numpy as np from src.SABRModel.SABRModel import SABRModelLognormalApprox from src.Utils.Extrapolator.PolynomialExtrapolator import PolynomialExtrapolator from src.Utils.Types.OptionType import OptionType from src.Utils.Valu...
Python
zaydzuhri_stack_edu_python
from typing import List class Array begin function __init__ self nums begin set nums = nums end function function _merge self left mid right begin string Merge self.nums[left:mid+1] with nums[mid+1:right] set i = left set j = mid + 1 set pre = nums at slice : : for k in range left right + 1 begin comment left part h...
from typing import List class Array: def __init__(self, nums:List): self.nums = nums def _merge(self,left,mid,right): """ Merge self.nums[left:mid+1] with nums[mid+1:right] """ i = left j = mid+1 pre = self.nums[:] for k in range(left,right+1):...
Python
zaydzuhri_stack_edu_python
function report self begin comment Add Illumina-specific CSS rules call addCSSRule string table.fastqc_summary td.PASS { font-weight: bold; color: green; } call addCSSRule string table.fastqc_summary td.WARN { font-weight: bold; color: orange; } call addCSSRule string table.fastqc_summary td.FAIL { font-weight: bold; c...
def report(self): # Add Illumina-specific CSS rules self.html.addCSSRule("table.fastqc_summary td.PASS { font-weight: bold;\n" " color: green; }") self.html.addCSSRule("table.fastqc_summary td.WARN { font-weight: bold;\n" ...
Python
nomic_cornstack_python_v1
function append_start_power self power epanet_timestamp begin append powers_reads tuple power epanet_timestamp end function
def append_start_power(self, power: float, epanet_timestamp: float): self.powers_reads.append((power, epanet_timestamp))
Python
nomic_cornstack_python_v1
function test_returns_intent_data self begin set expected = intent_request at string intent set http_request = call _generate_intent_request set request = call EchoRequest http_request assert intent == expected end function
def test_returns_intent_data(self): expected = self.intent_request['intent'] http_request = self._generate_intent_request() request = EchoRequest(http_request) assert request.intent == expected
Python
nomic_cornstack_python_v1
function __init__ self proportion=1.0 n_neighbors=5 T=0.5 n_jobs=1 begin call __init__ call check_greater_or_equal proportion string proportion 0 call check_greater_or_equal n_neighbors string n_neighbors 1 call check_greater_or_equal T string T 0 call check_n_jobs n_jobs string n_jobs set proportion = proportion set n...
def __init__(self, proportion= 1.0, n_neighbors= 5, T= 0.5, n_jobs= 1): super().__init__() self.check_greater_or_equal(proportion, "proportion", 0) self.check_greater_or_equal(n_neighbors, "n_neighbors", 1) self.check_greater_or_equal(T, "T", 0) self.check_n_jobs(n_jobs, 'n_jobs'...
Python
nomic_cornstack_python_v1
function write_timing self times begin write lib string timing(){ write lib string timing_type : setup_rising; write lib string related_pin : "clk"; write lib string rise_constraint(CONSTRAINT_HIGH_POS) { write lib format string values("{0}"); times at string setup_time_one write lib string } write lib string fall_cons...
def write_timing(self, times): self.lib.write(" timing(){ \n") self.lib.write(" timing_type : setup_rising; \n") self.lib.write(" related_pin : \"clk\"; \n") self.lib.write(" rise_constraint(CONSTRAINT_HIGH_POS) {\n") self.lib.write(" ...
Python
nomic_cornstack_python_v1
comment reliably restored by inspect function emit_stop_by_name self detailed_signal begin pass end function
def emit_stop_by_name(self, detailed_signal): # reliably restored by inspect pass
Python
nomic_cornstack_python_v1
function solve_gevp_gen a t_0 algorithm sort_by_vectors=15 **kwargs begin set B = call matrix a at t_0 try begin set f = call algorithm B=B keyword kwargs end except TypeError begin comment If the function doesn't do currying, implement that here set f = lambda A -> call algorithm B=B A=A end except LinAlgError begin r...
def solve_gevp_gen(a, t_0, algorithm, sort_by_vectors=15, **kwargs): B = np.matrix(a[t_0]) try: f = algorithm(B=B, **kwargs) except TypeError: # If the function doesn't do currying, implement that here f = lambda A: algorithm(B=B, A=A) except LinAlgError: return eige...
Python
nomic_cornstack_python_v1
while true begin set a = a + 1 if a < 10 begin continue end comment 「10」と表示される print a break end comment 「loop ended」と表示される print string loop ended
while True: a = a + 1 if a < 10: continue print( a ) # 「10」と表示される break print( 'loop ended' ) # 「loop ended」と表示される
Python
zaydzuhri_stack_edu_python
function normalise_intensity image thres_roi=10.0 begin set val_l = call percentile image thres_roi set roi = image >= val_l set tuple mu sigma = tuple mean np image at roi standard deviation np image at roi set eps = 1e-06 set image2 = image - mu / sigma + eps return image2 end function
def normalise_intensity(image, thres_roi=10.0): val_l = np.percentile(image, thres_roi) roi = (image >= val_l) mu, sigma = np.mean(image[roi]), np.std(image[roi]) eps = 1e-6 image2 = (image - mu) / (sigma + eps) return image2
Python
nomic_cornstack_python_v1
function can_match self tutor weeks_per_course begin if user_type != string STUDENT begin raise call ValueError string self must have user_type of 'STUDENT' end if user_type != string TUTOR begin raise call ValueError string tutor must have user_type of 'TUTOR' end if weeks_per_course <= 0 begin raise call ValueError s...
def can_match(self, tutor, weeks_per_course): if self.user_type != 'STUDENT': raise ValueError('self must have user_type of \'STUDENT\'') if tutor.user_type != 'TUTOR': raise ValueError('tutor must have user_type of \'TUTOR\'') if weeks_per_course <= 0: raise ...
Python
nomic_cornstack_python_v1
comment for x in range(0, 1000): comment print "%d" % (x) import json set data = dict set data at string sensor = list comment data['sensor'].append({ comment 'y': 'x' comment }) comment data['sensor'].append({ comment 'y': 'x' comment }) comment data['sensor'].append({ comment 'y': 'x' comment }) from math import * ...
#for x in range(0, 1000): # print "%d" % (x) import json data = {} data['sensor'] = [] # # data['sensor'].append({ # 'y': 'x' # }) # data['sensor'].append({ # 'y': 'x' # }) # data['sensor'].append({ # 'y': 'x' # }) from math import* Fs=8000 f=500 sample=1000 a=[0]*sample for n in range(sample...
Python
zaydzuhri_stack_edu_python
function format_timestamp_array arr begin set tuple valid_buf num_buf = call buffers if unit != string ns begin comment pragma: no cover raise call NotImplementedError string TODO handle non-ns end comment l = int64 set nums = call cast string l set num_iter = call _num_iter valid_buf nums set offset = 0 comment uint32...
def format_timestamp_array(arr: pa.Array) -> pa.Array: valid_buf, num_buf = arr.buffers() if arr.type.unit != "ns": raise NotImplementedError("TODO handle non-ns") # pragma: no cover nums = memoryview(num_buf).cast("l") # l = int64 num_iter = _num_iter(valid_buf, nums) offset = 0 out...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from tree.base import DecisionTree from metrics import accuracy , precision , recall from tqdm import tqdm import os seed 42 comment Split ratio set split = 0.7 comment Loading and Preprocessing the data set iris = read csv join path string data str...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from tree.base import DecisionTree from metrics import accuracy, precision, recall from tqdm import tqdm import os np.random.seed(42) split = 0.7 # Split ratio # Loading and Preprocessing the data iris = pd.read_csv(os.path.join("data", "...
Python
zaydzuhri_stack_edu_python
from pptx.util import Inches , Pt from wand.compat import text from wand.image import Image from pptx import Presentation from os import chdir , listdir import pytest comment Counts number of images to be itirated over set img_count = length list directory string ./input_img comment pptx init set prs = call Presentatio...
from pptx.util import Inches, Pt from wand.compat import text from wand.image import Image from pptx import Presentation from os import chdir, listdir import pytest; # Counts number of images to be itirated over img_count = len(listdir('./input_img')); # pptx init prs = Presentation(); slide_register = prs.slide_layo...
Python
zaydzuhri_stack_edu_python
function stop_and_restart begin info string Restarting eduzen_bot... call stop call execl executable executable *sys.argv end function
def stop_and_restart(): logging.info("Restarting eduzen_bot...\n") bot.updater.stop() os.execl(sys.executable, sys.executable, *sys.argv)
Python
nomic_cornstack_python_v1
function draw_samples self num_samples begin comment draw uniform from -1 to 1 set samples = uniform - 1 1 num_samples set samples = call arccos samples % pi return samples end function
def draw_samples(self, num_samples): # draw uniform from -1 to 1 samples = np.random.uniform(-1, 1, num_samples) samples = np.arccos(samples) % np.pi return samples
Python
nomic_cornstack_python_v1
function prolog_models cls trial=none begin from persistence.models import Trial return list tuple Trial lambda -> list trial tuple Tag lambda -> tags tuple Argument lambda -> arguments tuple Module lambda -> modules tuple EnvironmentAttr lambda -> environment_attrs tuple CodeComponent lambda -> code_components t...
def prolog_models(cls, trial=None): from ..persistence.models import Trial return [ (Trial, lambda: [trial]), (Tag, lambda: trial.tags), (Argument, lambda: trial.arguments), (Module, lambda: trial.modules), (EnvironmentAttr, lambda: trial.envir...
Python
nomic_cornstack_python_v1
function raster ax event_times_list colors begin comment assuming 60s set event_times_list = event_times_list - event_times_list at 0 set et1 = event_times_list at where event_times_list < 15 set et2 = event_times_list at slice min where event_times_list > 15 : max where event_times_list < 30 : set et3 = event_times_l...
def raster(ax, event_times_list, colors): # assuming 60s event_times_list= event_times_list-event_times_list[0] et1 = event_times_list[np.where(event_times_list<15)] et2 = event_times_list[np.min(np.where(event_times_list>15)): np.max(np.where(event_times_list<30))] et3 = ...
Python
nomic_cornstack_python_v1
function _grid m dtype=float32 begin set M = m ^ 2 set x = linear space 0 1 m dtype=dtype set y = linear space 0 1 m dtype=dtype set tuple xx yy = call meshgrid x y set z = call empty tuple M 2 dtype set z at tuple slice : : 0 = reshape xx M set z at tuple slice : : 1 = reshape yy M return z end function
def _grid(m, dtype=np.float32): M = m**2 x = np.linspace(0, 1, m, dtype=dtype) y = np.linspace(0, 1, m, dtype=dtype) xx, yy = np.meshgrid(x, y) z = np.empty((M, 2), dtype) z[:, 0] = xx.reshape(M) z[:, 1] = yy.reshape(M) return z
Python
nomic_cornstack_python_v1
from time import sleep , ctime import thread
from time import sleep,ctime import thread
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from utils import set_init , norm , ratio class Net extends Module begin function __init__ self s_dim a_dim h_dim begin call __init__ set s_dim = s_dim set a_dim = a_dim comment Actor set a1 = linear s_dim h_dim set a21 = linear h_dim...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .utils import set_init, norm, ratio class Net(nn.Module): def __init__(self, s_dim, a_dim, h_dim): super().__init__() self.s_dim = s_dim self.a_dim = a_dim # Actor self.a1 = nn.Lin...
Python
zaydzuhri_stack_edu_python
for i in directory a begin if i at 0 != string _ begin print i end end
for i in dir(a): if i[0] != '_': print(i)
Python
zaydzuhri_stack_edu_python
string 30. Escreva um programa que transforme uma matriz 4x4 numa matriz triangular inferior, ou seja, atribuindo zero a todos os elementos acima da diagonal principal. Imprima a matriz original e a matriz transformada. from matrizes import * set matriz = call criaMatrizAleatoria 4 4 0 9 set matrizTriangularInferior = ...
""" 30. Escreva um programa que transforme uma matriz 4x4 numa matriz triangular inferior, ou seja, atribuindo zero a todos os elementos acima da diagonal principal. Imprima a matriz original e a matriz transformada. """ from matrizes import * matriz = criaMatrizAleatoria(4, 4, 0, 9) matrizTriangularInferior = criaMa...
Python
zaydzuhri_stack_edu_python
function __iadd__ self steps begin set children = children + steps return self end function
def __iadd__(self, steps): self.current_block.children += steps return self
Python
nomic_cornstack_python_v1
import os set ip_host = input string Digite o IP ou Host a ser verificado: call system string ping -n 6 { ip_host }
import os ip_host = input('Digite o IP ou Host a ser verificado: ') os.system(f'ping -n 6 {ip_host}')
Python
zaydzuhri_stack_edu_python
function luhn number begin set s_even = 0 set s_odd = 0 set l = length number set n = number at slice : : - 1 comment evens (парні) for i in range 1 l 2 begin if integer n at i < 5 begin set s_even = s_even + integer n at i * 2 end else begin set s_even = s_even + integer n at i * 2 - 9 end end comment odds (непарні)...
def luhn(number): s_even=0 s_odd=0 l = len(number) n = number[::-1] # evens (парні) for i in range(1,l,2): if int(n[i]) < 5: s_even = s_even + int(n[i])*2 else: s_even = s_even + int(n[i])*2-9 # odds (непарні) for i in range(0,l,2...
Python
zaydzuhri_stack_edu_python
comment sqrt_r.py - finding square roots comment you can write this as "1e-12" if you like. set ERROR = 1e-12 function sqrt x g=1 begin string Recursive version. if absolute g * g - x < ERROR begin return g end else begin return square root x g + x / g / 2 end end function
# sqrt_r.py - finding square roots # you can write this as "1e-12" if you like. ERROR = 0.000000000001 def sqrt(x, g = 1): """Recursive version.""" if abs(g*g - x) < ERROR: return g else: return sqrt(x, (g + x / g) / 2)
Python
zaydzuhri_stack_edu_python
class Solution begin function plusOne self digits begin set length = length digits if length == 1 and digits at 0 == 0 begin return list 1 end set last_d = digits at - 1 if last_d == 9 begin set digits at - 1 = 0 set i = - 2 while - i <= length and digits at i == 9 begin set digits at i = 0 set i = i - 1 end if - i > l...
class Solution: def plusOne(self, digits: List[int]) -> List[int]: length = len(digits) if length == 1 and digits[0] == 0: return [1] last_d = digits[-1] if last_d == 9: digits[-1] = 0 i = -2 while -i<=length and digits[i]==9: ...
Python
zaydzuhri_stack_edu_python
comment A. Team comment time limit per test2 seconds comment memory limit per test256 megabytes comment inputstandard input comment outputstandard output comment One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several probl...
# A. Team # time limit per test2 seconds # memory limit per test256 megabytes # inputstandard input # outputstandard output # One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Lon...
Python
zaydzuhri_stack_edu_python
import os import random function binary_search x a begin set l = 0 set r = length a - 1 while l <= r begin set mid = l + r / 2 if a at mid == x or x in a at mid or a at mid in x begin return mid end else if a at mid > x begin set r = mid - 1 end else if a at mid < x begin set l = mid + 1 end end return - 1 end function...
import os import random def binary_search(x, a): l = 0 r = len(a) - 1 while l <= r: mid = (l + r) / 2 if (a[mid] == x) or (x in a[mid]) or (a[mid] in x): return mid elif a[mid] > x: r = mid - 1 elif a[mid] < x: l = mid + 1 return -1 d...
Python
zaydzuhri_stack_edu_python
function euler27 num=1000 begin comment brute force very fast since is_prime is somewhat optimized set consec_prime = 0 set coeff_prod = 0 comment easiest base cases are that when n = 0, b must be prime comment a must be odd for n = 1, e.g. 1^2 + a + b = prime number comment b is odd as prime numbers > 2 are odd set nu...
def euler27(num: int = 1000) -> int: # brute force very fast since is_prime is somewhat optimized consec_prime = 0 coeff_prod = 0 # easiest base cases are that when n = 0, b must be prime # a must be odd for n = 1, e.g. 1^2 + a + b = prime number # b is odd as prime numbers > 2 are odd num =...
Python
nomic_cornstack_python_v1
function try_unpickle file_to_unpickle use_metapath_bkwcomp=false begin if call is_pickle file_to_unpickle begin set extra_path = if expression use_metapath_bkwcomp then PICKLE_PATH else string with open extra_path + file_to_unpickle string rb as f begin set file_to_unpickle = load pickle f end end return file_to_unpi...
def try_unpickle(file_to_unpickle, use_metapath_bkwcomp=False): if is_pickle(file_to_unpickle): extra_path = meta_config.PICKLE_PATH if use_metapath_bkwcomp else '' with open(extra_path + file_to_unpickle, 'rb') as f: file_to_unpickle = pickle.load(f) return file_to_unpickle
Python
nomic_cornstack_python_v1
string 需求:用户输入目标学员姓名,如果学员存在则修改该学员信息 步骤: 用户输入目标学员姓名 遍历学员数据列表,如果用户输入的学员姓名存在则修改学员的姓名、性别、手机号数据,否则则提示该学员不存在 comment 2.4 修改学员信息 function modify_student self begin comment 1 用户输入目标学员姓名 set modify_name = input string 请输入需要修改的学员姓名: comment 2 遍历数据列表,如果学员姓名存在则修改学员的姓名、性别、手机号数据,否则则提示该学员不存在 for i in student_list begin if modify_name...
""" 需求:用户输入目标学员姓名,如果学员存在则修改该学员信息 步骤: 用户输入目标学员姓名 遍历学员数据列表,如果用户输入的学员姓名存在则修改学员的姓名、性别、手机号数据,否则则提示该学员不存在 """ # 2.4 修改学员信息 def modify_student(self): # 1 用户输入目标学员姓名 modify_name = input('请输入需要修改的学员姓名:') # 2 遍历数据列表,如果学员姓名存在则修改学员的姓名、性别、手机号数据,否则则提示该学员不存在 for i in self.student_list: if modify_name =...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function reverse self x begin set neg = false set a = list string x at slice : : - 1 if string - in a begin set neg = true remove a string - end set f = integer join string a if f > MIN begin return 0 end return integer join string a * if expression neg then - 1 else 1 end functi...
class Solution(object): def reverse(self, x): neg = False a = list(str(x))[::(-1)] if ('-' in a): neg = True a.remove('-') f = int(''.join(a)) if (f > MIN): return 0 return (int(''.join(a)) * ((-1) if neg else 1))
Python
zaydzuhri_stack_edu_python
import abc import sys import numpy as np import uuid from core.base.GameState import GameState from core.base.Policy import Policy class TestCountGame extends GameState begin string N-Player game that requires the players to walk a random path that was decided when the game started. The game encodes how many moves you ...
import abc import sys import numpy as np import uuid from core.base.GameState import GameState from core.base.Policy import Policy class TestCountGame(GameState, metaclass=abc.ABCMeta): """ N-Player game that requires the players to walk a random path that was decided when the game started. The game encod...
Python
zaydzuhri_stack_edu_python
function parallel_solve POPULATION_X SOLUTIONS LOCK N_WORKERS MODEL df_kfolded error_type max_features round_prediction begin set parallel_execution = true set s = 0 set POPULATION_SIZE = length POPULATION_X while s < POPULATION_SIZE - 1 begin comment EN esta parte antes de meterlo a procesamiento deberia buscar la sol...
def parallel_solve(POPULATION_X, SOLUTIONS, LOCK, N_WORKERS, MODEL, df_kfolded, error_type, max_features, round_prediction): parallel_execution = True s = 0 POPULATION_SIZE = len(POPULATION_X) while s < POPULATION_SIZE-1: #EN esta parte antes de meterlo a procesamiento deberia buscar la solucio...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import time set start = time set train_df = read csv string ./train_preprocessed.csv dtype=dict string fullVisitorId string str fill missing train_df at string totals.transactionRevenue 0 inplace=true set end = time print string loading complete print end - start comment train_df ...
import pandas as pd import numpy as np import time start = time.time() train_df = pd.read_csv('./train_preprocessed.csv',dtype={'fullVisitorId': 'str'},) train_df["totals.transactionRevenue"].fillna(0, inplace=True) end = time.time() print('loading complete') print(end-start) #train_df = train_df.groupby("fullVisitor...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 import pandas as pd import os import cluster from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV import pickle from sklearn.decomposition import PCA class RootSIFT begin comment Derived from 'http://www.pyimagese...
import numpy as np import cv2 import pandas as pd import os import cluster from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV import pickle from sklearn.decomposition import PCA class RootSIFT: # Derived from 'http://www.pyimagesearch....
Python
zaydzuhri_stack_edu_python
function cost_type self cost_type begin string Sets the cost_type of this TableRateShipping. :param cost_type: The cost_type of this TableRateShipping. :type: str set allowed_values = list string orderSubtotal string weight if cost_type is not none and cost_type not in allowed_values begin raise call ValueError format ...
def cost_type(self, cost_type): """Sets the cost_type of this TableRateShipping. :param cost_type: The cost_type of this TableRateShipping. :type: str """ allowed_values = ["orderSubtotal", "weight"] if cost_type is not None and cost_type not in allowed_values: ...
Python
jtatman_500k
function main begin set base = argv at 1 for tuple root dirs files in walk base begin for name in files begin set fpath = join path root name if call is_bin fpath begin strip fpath end end end end function
def main(): base = sys.argv[1] for root, dirs, files in os.walk(base): for name in files: fpath = os.path.join(root, name) if is_bin(fpath): strip(fpath)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import random import re import sys function main begin if length argv < 2 or length argv > 4 begin tuple print ? stderr string Usage: %s <filename> [wordcount] [n] % argv at 0 exit 1 end set filename = argv at 1 if length argv >= 3 begin set wordcount = integer argv at 2 end else begin set ...
#!/usr/bin/env python import random import re import sys def main(): if len(sys.argv) < 2 or len(sys.argv) > 4: print >>sys.stderr, 'Usage: %s <filename> [wordcount] [n]' % sys.argv[0] sys.exit(1) filename = sys.argv[1] if len(sys.argv) >= 3: wordcount = int(sys.argv[2]) else: ...
Python
zaydzuhri_stack_edu_python
function remove_spaces string begin return join string split string end function comment Driver code set string = string this is a sample sentence print call remove_spaces string
def remove_spaces(string): return "".join(string.split()) # Driver code string = "this is a sample sentence" print(remove_spaces(string))
Python
jtatman_500k
import numpy as np import random import time class State begin set SHEEP = 0 set WOLF = 1 set WOLFB_R = - 8 set WOLFR_R = - 4 set SHEEP_R = - 5 function __init__ self dim sheep=none wolfB=none wolfR=none begin set turn = WOLF set grid = zeros tuple dim dim dtype=int set dim = dim set dim = dim - 1 set sheep = sheep or ...
import numpy as np import random import time class State: SHEEP = 0 WOLF = 1 WOLFB_R = -8 WOLFR_R = -4 SHEEP_R = -5 def __init__(self, dim, sheep=None, wolfB=None, wolfR=None): self.turn = State.WOLF self.grid = np.zeros((dim, dim), dtype=int) self.dim = dim ...
Python
zaydzuhri_stack_edu_python
import csv set file_path1 = string C:\Users\Lori\Desktop\info_transfer.csv set file_path2 = string C:\Users\Lori\Desktop\stations.csv set file_path = string C:\Users\Lori\Desktop\no.csv set f = open file_path string w encoding=string gbk set origin1 = open file_path1 string r encoding=string gbk set origin2 = open file...
import csv file_path1 = 'C:\\Users\\Lori\\Desktop\\info_transfer.csv' file_path2 = 'C:\\Users\\Lori\\Desktop\\stations.csv' file_path = 'C:\\Users\\Lori\\Desktop\\no.csv' f = open(file_path, 'w', encoding='gbk') origin1 = open(file_path1, 'r', encoding='gbk') origin2 = open(file_path2, 'r', encoding='gbk') csv_writ...
Python
zaydzuhri_stack_edu_python
function add_report_item self severity engine_name data begin raise call NotImplementedError string protocol not implemented: add_report_item end function
def add_report_item(self, severity, engine_name, data): raise NotImplementedError("protocol not implemented: add_report_item")
Python
nomic_cornstack_python_v1
import cv2 import numpy as np function translate img x y begin set M = array list list 1 0 x list 0 1 y dtype=float32 set dst = call warpAffine img M dsize=tuple shape at 1 shape at 0 return dst end function set img = call imread string ../resources/lena.jpg image show string original img set imgTranslate = call transl...
import cv2 import numpy as np def translate(img, x, y): M = np.array([[1,0,x],[0,1,y]], dtype=np.float32) dst = cv2.warpAffine(img, M, dsize=(img.shape[1], img.shape[0])) return dst img = cv2.imread('../resources/lena.jpg') cv2.imshow('original', img) imgTranslate = translate(img, 50,50) cv2.imshow('out'...
Python
zaydzuhri_stack_edu_python
function master_periodic self begin call assert_is_master true end function
def master_periodic(self): self.assert_is_master(True)
Python
nomic_cornstack_python_v1
function onReload self moduleName=string FiberDistance begin import imp , sys , os , slicer set widgetName = moduleName + string Widget comment reload the source code comment - set source file path comment - load the module to the global space set filePath = eval string slicer.modules.%s.path % lower moduleName set p =...
def onReload(self,moduleName="FiberDistance"): import imp, sys, os, slicer widgetName = moduleName + "Widget" # reload the source code # - set source file path # - load the module to the global space filePath = eval('slicer.modules.%s.path' % moduleName.lower()) p = os.path.dirname(filePat...
Python
nomic_cornstack_python_v1
function additional_result_export self additional_result_export begin set _additional_result_export = additional_result_export end function
def additional_result_export(self, additional_result_export): self._additional_result_export = additional_result_export
Python
nomic_cornstack_python_v1
function _get_field_info self field filter_rel_field page=none page_size=none begin set ret = dictionary set ret at string name = name comment print(ret["name"]) comment print(type(field)) comment print(field) comment 根据数据库信息添加 if datamodel begin comment 只有数据库存储的字段,没有外键字段 set list_columns = list_columns if name in list...
def _get_field_info(self, field, filter_rel_field, page=None, page_size=None): ret = dict() ret["name"] = field.name # print(ret["name"]) # print(type(field)) # print(field) # 根据数据库信息添加 if self.datamodel: list_columns = self.datamodel.list_co...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.header import Header from email import encoders function _is_ascii s begin strin...
# -*- coding: utf-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.header import Header from email import encoders def _is_ascii(s): """ Checks...
Python
zaydzuhri_stack_edu_python
function _AddArgumentHexadecimalInteger self string=string **unused_kwargs begin try begin set int_value = integer string 16 end except tuple TypeError ValueError begin raise call ParseError format string {0:s} is not a valid base16 integer. string end return call _AddArgument int_value end function
def _AddArgumentHexadecimalInteger(self, string='', **unused_kwargs): try: int_value = int(string, 16) except (TypeError, ValueError): raise errors.ParseError( '{0:s} is not a valid base16 integer.'.format(string)) return self._AddArgument(int_value)
Python
nomic_cornstack_python_v1
function _set_correct wizard parameter target begin set casepath = call _get_casepath wizard comment We don't worry about updating the XML tag. That is done by a calling comment procedure. The job here is to copy model output to the global output's comment folder specified by the user for the current module, and then r...
def _set_correct(wizard, parameter, target): casepath = _get_casepath(wizard) #We don't worry about updating the XML tag. That is done by a calling #procedure. The job here is to copy model output to the global output's #folder specified by the user for the current module, and then return the name #...
Python
nomic_cornstack_python_v1
function query_endpoint_pricehistorical self from_asset to_asset timestamp handling_special_case=false begin debug string Querying cryptocompare for daily historical price from_asset=from_asset to_asset=to_asset timestamp=timestamp set special_asset = identifier in CRYPTOCOMPARE_SPECIAL_CASES or identifier in CRYPTOCOM...
def query_endpoint_pricehistorical( self, from_asset: AssetWithOracles, to_asset: AssetWithOracles, timestamp: Timestamp, handling_special_case: bool = False, ) -> Price: log.debug( 'Querying cryptocompare for daily historical price', ...
Python
nomic_cornstack_python_v1
import sys class Solution begin function reverse self x begin set s = string x if x < 0 begin set s_reverse = string - + s at slice - 1 : 0 : - 1 end else begin set s_reverse = s at slice : : - 1 end set reverse_value = integer s_reverse if reverse_value >= 2 ^ 31 - 1 or reverse_value <= - 2 ^ 31 begin return 0 end r...
import sys class Solution: def reverse(self, x: int) -> int: s = str(x) if x < 0: s_reverse = '-' + s[-1:0:-1] else: s_reverse = s[::-1] reverse_value = int(s_reverse) if (reverse_value >= (2 ** 31) - 1) or (reverse_value <= - (2 ** 31)): ...
Python
zaydzuhri_stack_edu_python
comment Soma dos numeros nas casas, centenas, dezenas, unidade, etc function main begin set entrada = integer input string Digite um número inteiro: set ent_str = string entrada set tam = length ent_str function somando_unidades numero tamanho begin set potencia = tamanho set soma = 0 set a_dividir = numero while poten...
#Soma dos numeros nas casas, centenas, dezenas, unidade, etc def main(): entrada = int(input("Digite um número inteiro: ")) ent_str = str(entrada) tam = len(ent_str) def somando_unidades(numero, tamanho): potencia = tamanho soma = 0 a_dividir = numero while potencia > -1: a_somar = a_dividir // (10**pot...
Python
zaydzuhri_stack_edu_python
function automation_account_id self begin return get pulumi self string automation_account_id end function
def automation_account_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "automation_account_id")
Python
nomic_cornstack_python_v1
async function get_attached_sticker_sets self file_id request_id=none request_timeout=none skip_validation=false begin set _constructor = if expression skip_validation then construct else GetAttachedStickerSets return await call request call _constructor file_id=file_id request_id=request_id request_timeout=request_tim...
async def get_attached_sticker_sets( self, file_id: int, *, request_id: str = None, request_timeout: int = None, skip_validation: bool = False ) -> StickerSets: _constructor = GetAttachedStickerSets.construct if skip_validation else Get...
Python
nomic_cornstack_python_v1
function _get_tags_by_rarity self soup begin set rarity_nodes = find all soup string h1 comment Removes expansion title pop rarity_nodes 0 comment Stores all the tags containing cards (which are tables) by its rarity. set cards_by_rarity = list for tuple i current_node in enumerate rarity_nodes 0 begin if i == length ...
def _get_tags_by_rarity(self, soup: BeautifulSoup) -> List[TagListByRarity]: rarity_nodes = soup.find_all('h1') rarity_nodes.pop(0) # Removes expansion title # Stores all the tags containing cards (which are tables) by its rarity. cards_by_rarity = [] for i, current_node in enu...
Python
nomic_cornstack_python_v1
class StationNode begin string 간단한 지하철 역 노드 클래스 function __init__ self station_name begin set station_name = station_name end function end class function create_station_nodes input_file begin string input_file에서 데이터를 읽어 와서 지하철 그래프 노드들을 리턴하는 함수 comment 지하철 역 노드들을 담을 딕셔너리 set stations = dict comment 파라미터로 받은 input_file ...
class StationNode: """간단한 지하철 역 노드 클래스""" def __init__(self, station_name): self.station_name = station_name def create_station_nodes(input_file): """input_file에서 데이터를 읽어 와서 지하철 그래프 노드들을 리턴하는 함수""" stations = {} # 지하철 역 노드들을 담을 딕셔너리 # 파라미터로 받은 input_file 파일을 연다 with open(input_file)...
Python
zaydzuhri_stack_edu_python
import yaml import json from src.service.dolls_service import DollsScrapingRepository from datetime import datetime class DollsDump begin function __init__ self repository dumper begin set repository = repository set dumper = dumper end function function dump_file self begin write dumper string data/dolls_out result en...
import yaml import json from src.service.dolls_service import DollsScrapingRepository from datetime import datetime class DollsDump(): def __init__(self, repository, dumper): self.repository = repository self.dumper = dumper def dump_file(self): self.dumper.write('data/dolls_out', self.repository.result) cl...
Python
zaydzuhri_stack_edu_python
function _why self current_data begin if length answered_true > 0 begin print string Uživatel odpověděl pravdivě na následující otázky: for i in answered_true begin print string - name end end if length implied_true > 0 begin print string Z nich vyplývá, že: for i in implied_true begin print string - name end end print...
def _why(self, current_data): if len(self.answered_true) > 0: print("Uživatel odpověděl pravdivě na následující otázky: ") for i in self.answered_true: print("-", i.name) if len(self.implied_true) > 0: print("Z nich vyplývá, že: ") for i in...
Python
nomic_cornstack_python_v1
function _parse_words text begin comment // \w Alphanumeric characters (including non-latin characters, umlaut comment characters and digits) plus "_". [^\W_] is the equivalent of \w comment excluding "_". Compatible with non-latin characters, does not split comment words at apostrophes. Uses capturing groups to combin...
def _parse_words(text: str) -> List[str]: # // \w Alphanumeric characters (including non-latin characters, umlaut # characters and digits) plus "_". [^\W_] is the equivalent of \w # excluding "_". Compatible with non-latin characters, does not split # words at apostrophes. Uses capturing...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment File Name: 04communite comment Description : comment Author : zongyanzhang comment date: 2018/12/22 from multiprocessing import Process , Pipe import time comment 发送 function pro1 args begin for i in range 10 begin comment 向管道发送数据 call send i sleep 1 end close args end function fun...
# -*- coding: utf-8 -*- # File Name: 04communite # Description : # Author : zongyanzhang # date: 2018/12/22 from multiprocessing import Process, Pipe import time # 发送 def pro1(args): for i in range(10): # 向管道发送数据 args.send(i) time.sleep(1) args...
Python
zaydzuhri_stack_edu_python
function login self username password begin call execute_cdp_cmd string Network.setUserAgentOverride dict string userAgent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36 call execute_script string Object.defineProperty(navigator, 'webdriver', {g...
def login(self, username, password): self.driver.execute_cdp_cmd( "Network.setUserAgentOverride", { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36" }, ) self.driv...
Python
nomic_cornstack_python_v1
function evaluate self prediction_type target_field_name gcs_source_uris=none bigquery_source_uri=none bigquery_destination_output_uri=none class_labels=none prediction_label_column=none prediction_score_column=none staging_bucket=none service_account=none generate_feature_attributions=false evaluation_pipeline_display...
def evaluate( self, prediction_type: str, target_field_name: str, gcs_source_uris: Optional[List[str]] = None, bigquery_source_uri: Optional[str] = None, bigquery_destination_output_uri: Optional[str] = None, class_labels: Optional[List[str]] = None, predi...
Python
nomic_cornstack_python_v1
function realify fn imag_tol=1e-12 begin decorator wraps fn function realified_fn *args **kwargs begin return call realify_scalar call fn *args keyword kwargs imag_tol=imag_tol end function return realified_fn end function
def realify(fn, imag_tol=1e-12): @functools.wraps(fn) def realified_fn(*args, **kwargs): return realify_scalar(fn(*args, **kwargs), imag_tol=imag_tol) return realified_fn
Python
nomic_cornstack_python_v1
import abc class EnvironmentBase extends object begin set __metaclass__ = ABCMeta decorator abstractmethod function __init__ self begin string Initializes the environment return end function decorator abstractmethod function reset self begin string Resets the environment and returns the initial state return end functio...
import abc class EnvironmentBase(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self): """ Initializes the environment """ return @abc.abstractmethod def reset(self): """ Resets the environment and returns the initial state """ return @...
Python
zaydzuhri_stack_edu_python
import tabpy_client from sklearn.linear_model import Perceptron comment create a perceptron set ppn = call Perceptron n_iter=10 eta0=0.1 random_state=0 comment declare the training set set X = list list 0 0 list 0 1 list 1 0 list 1 1 set y = list 0 0 0 1 comment train the perceptron with the training set fit ppn X y fu...
import tabpy_client from sklearn.linear_model import Perceptron # create a perceptron ppn = Perceptron(n_iter=10, eta0=0.1, random_state=0) # declare the training set X = [[0,0],[0,1],[1,0],[1,1]] y = [0,0,0,1] # train the perceptron with the training set ppn.fit(X, y) def predict(x, y): import numpy as np ...
Python
zaydzuhri_stack_edu_python
import re import os if __name__ == string __main__ begin set fileList = open string list.txt string r for file_ in fileList begin set fileToRead = open file_ at slice : - 1 : string r set content = read lines fileToRead close fileToRead for line in content begin set doc_date = match string .*"doc_date":"([0-9]+)".* l...
import re import os if __name__ == "__main__": fileList = open("list.txt", "r"); for file_ in fileList: fileToRead = open(file_[:-1], "r"); content = fileToRead.readlines(); fileToRead.close(); for line in content: doc_date = re.match(r'.*"doc_date":"([0-9]+)".*', line, re.M|re.I); pr...
Python
zaydzuhri_stack_edu_python
function get_row self row begin string Format a single row (if necessary) if is instance fields dict begin return dictionary list comprehension tuple key if expression match value then format call text_type value keyword row else row at value for tuple key value in items fields end else begin return list comprehension ...
def get_row(self, row): '''Format a single row (if necessary)''' if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value]) for key, value in self.fields.items() ]) el...
Python
jtatman_500k
function softmax x begin return exp x / sum exp x axis=0 end function
def softmax(x): return np.exp(x) / np.sum(np.exp(x), axis=0)
Python
nomic_cornstack_python_v1
function sumatoria num begin if num == 0 begin return 0 end else begin return num + call sumatoria num - 1 end end function function suma num begin if is instance num int and num >= 0 begin return sumatoria == sumatoria end else begin print string error en la entrada end end function comment segunda forma de sumatoria ...
def sumatoria (num): if num == 0: return 0 else : return num+sumatoria(num-1) def suma (num): if isinstance (num,int)and num>=0: return (sumatoria==sumatoria) else: print("error en la entrada") #segunda forma de sumatoria def sumatoria_simple(n): retur...
Python
zaydzuhri_stack_edu_python
function addition self other begin comment Add to reference comment Add to main data concat list data _d end function
def addition(self, other: AddableData) -> pd.IndexSlice: # Add to reference # Add to main data pd.concat([self.data, self.other._d])
Python
nomic_cornstack_python_v1
function distance self puzzle begin function locate item matrix begin string A helper to locate an item in a state. Note: Assumption: The item is in the matrix. Rerturn: positions (int, int): A tuple of two int. set index = 0 while item not in matrix at index begin set index = index + 1 end return tuple index index mat...
def distance(self, puzzle): def locate(item, matrix): """A helper to locate an item in a state. Note: Assumption: The item is in the matrix. Rerturn: positions (int, int): A tuple of two int. """ index = 0 ...
Python
nomic_cornstack_python_v1
function item self request db begin return pop call select_items string id lambda x -> x == param end function
def item(self, request, db): return db.select_items('id', lambda x: x == request.param).pop()
Python
nomic_cornstack_python_v1
from typing import * class Solution begin function findDiagonalOrder self matrix begin set tuple m n = tuple length matrix length matrix at 0 set rtn = list for k in range 0 m + n - 1 begin if k % 2 == 0 begin set tuple i j = tuple min k m - 1 k - min k m - 1 while 0 <= i <= m - 1 and 0 <= j <= n - 1 begin append rtn ...
from typing import * class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: m, n = len(matrix), len(matrix[0]) rtn = [] for k in range(0, m + n - 1): if k % 2 == 0: i, j = min(k, m-1), k - min(k, m-1) while 0 <= i <= m...
Python
zaydzuhri_stack_edu_python
import requests import os from datetime import date set package_name = string abcd set package_url = string https://example.com/abcd-latest-version.zip set base_dir = string packages set current_date = string format time today string %Y-%m-%d set package_dir = join path base_dir current_date comment Create the base dir...
import requests import os from datetime import date package_name = "abcd" package_url = "https://example.com/abcd-latest-version.zip" base_dir = "packages" current_date = date.today().strftime("%Y-%m-%d") package_dir = os.path.join(base_dir, current_date) # Create the base directory if it doesn't exist if not os.p...
Python
jtatman_500k
function read_message letters begin set data = list set hash_table = dict for letter in letters begin extend data list split letter string , end set res = list for d in data begin if length d > 1 begin set hash_table at integer d at 0 = d at 1 append res integer d at 0 end else begin set hash_table at integer d at 0...
def read_message(letters): data = [] hash_table = {} for letter in letters: data.extend([letter.split(' , ')]) res = [] for d in data: if len(d) > 1: hash_table[int(d[0])] = d[1] res.append(int(d[0])) else: hash_table[int(d[0][:len(d[0])-2]...
Python
zaydzuhri_stack_edu_python
function test_smart_truncate_short self begin set s = string Quinoa cred brooklyn, sartorial letterpress. set trunc = call smart_truncate s assert true ends with trunc string letterpress. end function
def test_smart_truncate_short(self): s = 'Quinoa cred brooklyn, sartorial letterpress.' trunc = smart_truncate(s) self.assertTrue(trunc.endswith('letterpress.'))
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import seaborn from scipy.signal import savgol_filter , medfilt from scipy.integrate import solve_ivp from scipy.optimize import minimize from sklearn.metrics import mean_squared_error as MSE import keras from keras import backend as K from keras.models import Sequenti...
import numpy as np import matplotlib.pyplot as plt import seaborn from scipy.signal import savgol_filter, medfilt from scipy.integrate import solve_ivp from scipy.optimize import minimize from sklearn.metrics import mean_squared_error as MSE import keras from keras import backend as K from keras.models import Sequenti...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from collections import deque from p1_is_complete import is_complete from p2_is_consistent import is_consistent from p3_basic_backtracking import * comment from p5_ordering import select_unassigned_variable, order_domain_values function inference csp variable begin string Performs an infer...
# -*- coding: utf-8 -*- from collections import deque from p1_is_complete import is_complete from p2_is_consistent import is_consistent from p3_basic_backtracking import * #from p5_ordering import select_unassigned_variable, order_domain_values def inference(csp, variable): """Performs an inference procedure for...
Python
zaydzuhri_stack_edu_python
from webcam_funcs import * import time function gen_images_for_single_coin cap totaltime=300 live=false rate=5 begin string Takes labeled frames for single coin value from a capturer Receives a capturer to save frames from. A total time is passed as the time we'll be taking the frames, in a rate defined by a parameter....
from webcam_funcs import * import time def gen_images_for_single_coin(cap, totaltime=300, live=False, rate=5): """Takes labeled frames for single coin value from a capturer Receives a capturer to save frames from. A total time is passed as the time we'll be taking the frames, in a rate defined by a parameter. ...
Python
zaydzuhri_stack_edu_python
function mew char begin return ordinal lower char - ordinal string a end function
def mew(char): return ord(char.lower()) - ord('a')
Python
nomic_cornstack_python_v1