code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function is_self_dividing self i
begin
if not i
begin
return false
end
set p = i
while p > 0
begin
comment Extract remaining digits and target digit
set tuple p d = divide mod p 10
if d == 0 or i % d != 0
begin
comment Found target integer is not self-dividing
return false
end
end
comment Found target integer is self-d... | def is_self_dividing(self, i):
if not i:
return False
p = i
while p > 0:
# Extract remaining digits and target digit
p, d = divmod(p, 10)
if (d == 0 or
i % d != 0):
# Found target integer is not self... | Python | nomic_cornstack_python_v1 |
set a = input string 輸入一串小寫英文:
set b = replace a string a string .
set c = replace b string e string .
set d = replace c string i string .
set e = replace d string o string .
set f = replace e string u string .
print f | a = input("輸入一串小寫英文:")
b= a.replace("a",".")
c= b.replace("e",".")
d= c.replace("i",".")
e= d.replace("o",".")
f= e.replace("u",".")
print(f) | Python | zaydzuhri_stack_edu_python |
while true
begin
set userInput = input string Enter quiz score:
if userInput == string Done
begin
break
end
set score = integer userInput
if score >= 0 and score <= 100
begin
set numQuizzes = numQuizzes + 1
set total = total + score
comment print(numQuizzes)
if score < lowestVal
begin
set lowestVal = score
end
continue... | while True:
userInput = input("Enter quiz score: ")
if (userInput == "Done"):
break
score = int(userInput)
if (score >= 0 and score <= 100):
numQuizzes += 1
total += score
#print(numQuizzes)
if (score < lowestVal):
lowestVal = score
... | Python | zaydzuhri_stack_edu_python |
function __radd__ self other
begin
from import compose
if is instance other TransformerUnion
begin
return call __add__ self
end
return call TransformerUnion list other self
end function | def __radd__(self, other):
from . import compose
if isinstance(other, compose.TransformerUnion):
return other.__add__(self)
return compose.TransformerUnion([other, self]) | Python | nomic_cornstack_python_v1 |
comment exercise
set counts = dictionary
set names = list string Rishu string Prince string Nisi string Rishu string Satyam string Rishu
for name in names
begin
if name not in counts
begin
set counts at name = 1
end
else
begin
set counts at name = counts at name + 1
end
end
print counts | #exercise
counts = dict()
names = ['Rishu', 'Prince', 'Nisi', 'Rishu','Satyam', 'Rishu']
for name in names:
if name not in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
print(counts) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import dpkt
import struct
import socket
set DIR_IN = string DIR_IN
set DIR_OUT = string DIR_OUT
set fe_server = string 221.130.199.241
set hash_table = dictionary
class stat_struct
begin
function __init__ self
begin
set start_time = 0
set in_time = list
set out_time = 0
end function
... | #!/usr/bin/python
import sys
import dpkt
import struct
import socket
DIR_IN = 'DIR_IN'
DIR_OUT = 'DIR_OUT'
fe_server = '221.130.199.241'
hash_table = dict()
class stat_struct:
def __init__(self):
self.start_time = 0
self.in_time = list()
self.out_time = 0
def is_valid_vse_pkt(pkt):
... | Python | zaydzuhri_stack_edu_python |
function getHistoriesByLocation self comps params=none timeSteps=none
begin
if versionMinor < 4
begin
raise call ValueError string Location-based histories are only supported for db version 3.4 and greater. This database is version {self.versionMajor}, {self.versionMinor}.
end
set locations = list comprehension call ge... | def getHistoriesByLocation(
self,
comps: Sequence[ArmiObject],
params: Optional[List[str]] = None,
timeSteps: Optional[Sequence[Tuple[int, int]]] = None,
) -> Histories:
if self.versionMinor < 4:
raise ValueError(
f"Location-based histories are onl... | Python | nomic_cornstack_python_v1 |
from index import db
class Blog extends Model
begin
set __tablename__ = string blogs
set id = call Column Integer primary_key=true
set title = call Column call String 300
set company = call Column call String 25
set url = call Column call String 300
set thumbnail = call Column call String 300
function __init__ self tit... | from index import db
class Blog(db.Model):
__tablename__ = 'blogs'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(300))
company = db.Column(db.String(25))
url = db.Column(db.String(300))
thumbnail = db.Column(db.String(300))
def __init__(self, title, company, u... | Python | zaydzuhri_stack_edu_python |
function factorial n
begin
set result = 1
for i in range n
begin
set result = result * i + 1
end
return result
end function | def factorial(n):
result = 1
for i in range(n):
result = result * (i + 1)
return result | Python | jtatman_500k |
comment !/usr/bin/env python3
from OpenSSL import crypto
import argparse
import os , sys
comment Command line arguments
set parser = call ArgumentParser description=string Script for SSL Certificate CSR and key generating The most of parameteres, that usually used as fields in CSR, are already given with default values... | #!/usr/bin/env python3
from OpenSSL import crypto
import argparse
import os,sys
# Command line arguments
parser = argparse.ArgumentParser(description='''
Script for SSL Certificate CSR and key generating
The most of parameteres, that usually used as fields in CSR, are already given with default values. If you want to... | Python | zaydzuhri_stack_edu_python |
import abc
from random import *
class Range extends object
begin
function __init__ self low high
begin
set min = low
set max = high
end function
function is_in_range self val
begin
return not min > val < max
end function
decorator property
function delta self
begin
return max - min
end function
end class
class BaseRand... | import abc
from random import *
class Range(object):
def __init__(self, low, high):
self.min = low
self.max = high
def is_in_range(self, val):
return not self.min > val < self.max
@property
def delta(self):
return self.max - self.min
class BaseRandom(object):
def... | Python | zaydzuhri_stack_edu_python |
from time import sleep
function ajuda function
begin
print string [m[1;30;44m~ * 50
print string { string Acessando o manual do comando { function } }
print string ~ * 50
sleep 2
print string [m[7;30m
call help function
end function
while true
begin
print string [m[1;30;42m~ * 30
print string { string SISTEMA DE ... | from time import sleep
def ajuda(function):
print(f'\033[m\033[1;30;44m~' * 50)
print(f'{f"Acessando o manual do comando {function}":^50}')
print(f'~' * 50)
sleep(2)
print('\033[m\033[7;30m')
help(function)
while True:
print(f'\033[m\033[1;30;42m~' * 30)
print(f'{"SISTEMA DE AJUDA Py... | Python | zaydzuhri_stack_edu_python |
function getjobinfo jobid load
begin
string Job Id: 139273.m1.lobos.nih.gov Job_Name = tryitout Job_Owner = mglerner@m1.lobos.nih.gov resources_used.cput = 00:00:00 resources_used.mem = 3100kb resources_used.vmem = 138456kb resources_used.walltime = 00:21:42 job_state = R queue = xeon server = m1.lobos.nih.gov Checkpoi... | def getjobinfo(jobid,load):
'''
Job Id: 139273.m1.lobos.nih.gov
Job_Name = tryitout
Job_Owner = mglerner@m1.lobos.nih.gov
resources_used.cput = 00:00:00
resources_used.mem = 3100kb
resources_used.vmem = 138456kb
resources_used.walltime = 00:21:42
job_state = R
queue = xeon
server... | Python | nomic_cornstack_python_v1 |
function close self
begin
pass
end function | def close(self) -> None:
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
set f1 = 2
set fs = 60
set sa = 100
set n = array range sa
comment first sine signal
set c = sin 2 * pi * n * f1 / fs
figure 1
x label string time period
y label string Amplitude
subplot 311
call stem n c
show | ##!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
f1=2
fs=60
sa=100
n=np.arange(sa)
c=np.sin(2*np.pi*n*f1/fs) #first sine signal
plt.figure(1)
plt.xlabel('time period')
plt.ylabel('Amplitude')
plt.subplot(311)
plt.stem(n,c)
plt.show()
| Python | zaydzuhri_stack_edu_python |
function apply self tag_bundle_set
begin
set evaluation_switcher = dict string firstMatching apply_fm_evaluation ; string all apply_all_evaluation
return call get evaluation_switcher evaluationStrategy lambda x -> error string Unsupported evaluation strategy: evaluationStrategy tag_bundle_set
end function | def apply(self, tag_bundle_set):
evaluation_switcher = {
"firstMatching": self.apply_fm_evaluation,
"all": self.apply_all_evaluation
}
return evaluation_switcher.get(self.evaluationStrategy,
lambda x: error("Unsupported evaluation st... | Python | nomic_cornstack_python_v1 |
function _get_entities self
begin
pass
end function | def _get_entities(self):
pass | Python | nomic_cornstack_python_v1 |
function get self request *args **kwargs
begin
if not exists call get_queryset
begin
return call redirect call reverse_lazy string program:proposal_combined_submit kwargs=dict string camp_slug slug ; string event_type_slug slug
end
return get call super request *args keyword kwargs
end function | def get(self, request, *args, **kwargs):
if not self.get_queryset().exists():
return redirect(
reverse_lazy(
"program:proposal_combined_submit",
kwargs={
"camp_slug": self.camp.slug,
"event_type_s... | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
import time
comment setting a current mode
call setmode BCM
comment removing the warings
call setwarnings false
set pins = list 2 3 4 17
setup GPIO pins OUT
print string Enter Your Choice of Color
print string 1.Red 2.Green 3.Blue
set n = integer input
if n == 1
begin
call output 2 HIGH
sleep 5
... | import RPi.GPIO as GPIO
import time
# setting a current mode
GPIO.setmode(GPIO.BCM)
#removing the warings
GPIO.setwarnings(False)
pins = [2,3,4,17]
GPIO.setup(pins, GPIO.OUT)
print("Enter Your Choice of Color")
print("1.Red\n2.Green\n3.Blue")
n = int(input())
if n==1:
GPIO.output(2,GPIO.HIGH)
time.sleep... | Python | zaydzuhri_stack_edu_python |
set highest_grade_person = max students key=lambda x -> x at string grade
print format string The student with highest grade is {} highest_grade_person | highest_grade_person = max(students, key=lambda x:x['grade'])
print("The student with highest grade is {}".format(highest_grade_person)) | Python | jtatman_500k |
function test_tour_can_be_created self
begin
set test_user = dict string username string test_username ; string first_name string John ; string last_name string Doe ; string phone string 254711999888 ; string email string testuser@gmail.com ; string password string a1234567
call User keyword test_user
set client = call... | def test_tour_can_be_created(self):
self.test_user = {
'username': 'test_username',
'first_name': 'John',
'last_name': 'Doe',
'phone': '254711999888',
'email': 'testuser@gmail.com',
'password': 'a1234567',
}
User(**self.test... | Python | nomic_cornstack_python_v1 |
import re
function get_word_count sentence
begin
set phrase = split sentence
set x = 0
for word in phrase
begin
if search string [a-zA-Z] word
begin
set x = x + 1
end
end
return x
end function
function run
begin
assert call get_word_count string Bonjour == 1
assert call get_word_count string Bonjour toi == 2
assert cal... | import re
def get_word_count(sentence):
phrase = sentence.split()
x = 0
for word in phrase :
if re.search("[a-zA-Z]", word) :
x += 1
return x
def run():
assert get_word_count("Bonjour") == 1
assert get_word_count("Bonjour toi") == 2
assert get_wo... | Python | zaydzuhri_stack_edu_python |
function bani self A B C
begin
set regs at C = regs at A ? B
end function | def bani(self, A, B, C):
self.regs[C] = self.regs[A] & B | Python | nomic_cornstack_python_v1 |
comment Arken Ibrahim: amibrah2@illinois.edu
import re , sys
from collections import defaultdict
from math import log
string Takes as input a list of strings (unigrams) and returns a dict of dicts that contains the count for each occurrence of a bigram. Accesses to keys that do not exist will return the default callabl... | #Arken Ibrahim: amibrah2@illinois.edu
import re, sys
from collections import defaultdict
from math import log
'''
Takes as input a list of strings (unigrams) and returns a dict of dicts
that contains the count for each occurrence of a bigram.
Accesses to keys that do not exist will return the default callable.
(i... | Python | zaydzuhri_stack_edu_python |
function write_tree_from_cache entries odb sl si=0
begin
set tree_items : List at string TreeCacheTup = list
set ci = start
set end = stop
while ci < end
begin
set entry = entries at ci
if stage != 0
begin
raise call UnmergedEntriesError entry
end
comment END abort on unmerged
set ci = ci + 1
set rbound = find path st... | def write_tree_from_cache(
entries: List[IndexEntry], odb: "GitCmdObjectDB", sl: slice, si: int = 0
) -> Tuple[bytes, List["TreeCacheTup"]]:
tree_items: List["TreeCacheTup"] = []
ci = sl.start
end = sl.stop
while ci < end:
entry = entries[ci]
if entry.stage != 0:
raise U... | Python | nomic_cornstack_python_v1 |
function _test_rss_memory_lower test_microvm stable_delta=1
begin
comment Get the firecracker pid, and open an ssh connection.
set firecracker_pid = jailer_clone_pid
set ssh_connection = ssh
comment Using deflate_on_oom, get the RSS as low as possible
patch amount_mib=200
comment Get initial rss consumption.
set init_r... | def _test_rss_memory_lower(test_microvm, stable_delta=1):
# Get the firecracker pid, and open an ssh connection.
firecracker_pid = test_microvm.jailer_clone_pid
ssh_connection = test_microvm.ssh
# Using deflate_on_oom, get the RSS as low as possible
test_microvm.api.balloon.patch(amount_mib=200)
... | Python | nomic_cornstack_python_v1 |
import torch
import torchvision
import torchvision.transforms as transforms
comment import random
comment torch.manual_seed(random.randint(0, 1000))
comment torch.cuda.manual_seed_all(random.randint(0, 1000))
set transform = call Compose list call ToTensor call Normalize 0.5 0.5
set trainset = call MNIST root=string ./... | import torch
import torchvision
import torchvision.transforms as transforms
#import random
#torch.manual_seed(random.randint(0, 1000))
#torch.cuda.manual_seed_all(random.randint(0, 1000))
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5), (0.5))])
trainset = torchvision.data... | Python | zaydzuhri_stack_edu_python |
function transform self srid driver=none name=none resampling=string NearestNeighbour max_error=0.0
begin
comment Convert the resampling algorithm name into an algorithm id
set algorithm = GDAL_RESAMPLE_ALGORITHMS at resampling
comment Instantiate target spatial reference system
set target_srs = call SpatialReference s... | def transform(self, srid, driver=None, name=None, resampling='NearestNeighbour',
max_error=0.0):
# Convert the resampling algorithm name into an algorithm id
algorithm = GDAL_RESAMPLE_ALGORITHMS[resampling]
# Instantiate target spatial reference system
target_srs = Spa... | Python | nomic_cornstack_python_v1 |
function place_ball self game
begin
comment Note left_center square is 7,8
set center_opposite : Square = call Square call reverse_x_for_left game my_team 7 8
return call Action PLACE_BALL position=center_opposite
end function | def place_ball(self, game: g.Game):
# Note left_center square is 7,8
center_opposite: m.Square = m.Square(reverse_x_for_left(game, self.my_team, 7), 8)
return m.Action(t.ActionType.PLACE_BALL, position=center_opposite) | Python | nomic_cornstack_python_v1 |
function figure_eight self
begin
call set_speed 200 200
call encR 8
call fwd
call set_speed 100 200
sleep 2
call fwd
call set_speed 200 100
sleep 4
call fwd
call set_speed 100 200
sleep 2
call set_speed 200 200
end function | def figure_eight(self):
self.set_speed(200,200)
self.encR(8)
self.fwd()
self.set_speed(100,200)
time.sleep(2)
self.fwd()
self.set_speed(200,100)
time.sleep(4)
self.fwd()
self.set_speed(100,200)
time.sleep(2)
self.set_speed(2... | Python | nomic_cornstack_python_v1 |
import copy
comment função para reitar todos empecilhos para que o print da matriz seja igual ao tipo de matriz exigido na saida
function print_certo vetor
begin
for linha in range length vetor at 0
begin
for matriz in range length vetor
begin
set rwagjln = 937028475
set line = join string vetor at matriz at linha
set... | import copy
def print_certo(vetor):#função para reitar todos empecilhos para que o print da matriz seja igual ao tipo de matriz exigido na saida
for linha in range(len(vetor[0])):
for matriz in range(len(vetor)):
rwagjln = 937028475
line = "".join(vetor[matriz][linha])
dt... | Python | zaydzuhri_stack_edu_python |
function get_target_actors self
begin
set target_actors = list comprehension target_actor for ddpg_agent in maddpg_agent
return target_actors
end function | def get_target_actors(self):
target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]
return target_actors | Python | nomic_cornstack_python_v1 |
function build_gee_vector_asset basins out_path=string basins.zip
begin
set path_parts = split out_path string /
set out_dir = join string / path_parts at slice 0 : length path_parts - 1 :
make directories string temp/ + out_dir exist_ok=true
set temp_dir = call Path string temp/ + out_dir
call to_file filename=string ... | def build_gee_vector_asset(basins, out_path="basins.zip"):
path_parts = out_path.split("/")
out_dir = "/".join(path_parts[0 : len(path_parts) - 1])
os.makedirs("temp/" + out_dir, exist_ok=True)
temp_dir = Path("temp/" + out_dir)
basins.to_file(filename="temp/" + out_dir + "/basins.shp", driver="ES... | Python | nomic_cornstack_python_v1 |
function get_image2tensor_transforms train
begin
return call ToTensor
end function | def get_image2tensor_transforms(train: bool):
return ToTensor() | Python | nomic_cornstack_python_v1 |
string Created on May 4, 2017 @author: sathish
import re
set dateValue = string 10/4/9999
set result = search string ^([1-9]|[12][0-9]|3[01])/(\d|1[012])/\d(\d?){3}$ dateValue
print string result | '''
Created on May 4, 2017
@author: sathish
'''
import re
dateValue="10/4/9999";
result=re.search("^([1-9]|[12][0-9]|3[01])/(\d|1[012])/\d(\d?){3}$", dateValue);
print(str(result))
| Python | zaydzuhri_stack_edu_python |
function batch_photo
begin
set directory = call fsencode string /home/jon/nutrient_tester_rpi/Calibration/
with open string /home/jon/nutrient_tester_rpi/Calibration/result_hsv.csv string w newline=string as csvfile
begin
set writer = writer csvfile
write row writer list string filename string h string s string v
for f... | def batch_photo():
directory = os.fsencode('/home/jon/nutrient_tester_rpi/Calibration/')
with open('/home/jon/nutrient_tester_rpi/Calibration/result_hsv.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['filename', 'h', 's', 'v'])
for file in os.listdir(dir... | Python | nomic_cornstack_python_v1 |
import argparse
import cv2
if __name__ == string __main__
begin
set parser = call ArgumentParser description=string Create dataset
call add_argument string -v string --video help=string mp4 video type=str required=true
call add_argument string -o string --output help=string output folder type=str required=true
set args... | import argparse
import cv2
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create dataset')
parser.add_argument('-v', '--video', help='mp4 video', type=str, required = True)
parser.add_argument('-o', '--output', help='output folder', type=str, required = True)
args = parser.par... | Python | zaydzuhri_stack_edu_python |
function get_server port
begin
set server_address = tuple string port
return call ThreadedHTTPServer server_address TestHandler
end function | def get_server(port):
server_address = ("", port)
return ThreadedHTTPServer(server_address, TestHandler) | Python | nomic_cornstack_python_v1 |
function SELECT *args **kwargs
begin
set this = get kwargs string this
append _callstack _SELECT
set num_of_args = length args
if num_of_args == 0
begin
set separator = string *
end
else
if num_of_args == 1
begin
set arg = args at 0
if is instance arg str
begin
if expression call get_tablename arg != arg then add _tabl... | def SELECT(*args, **kwargs):
this = kwargs.get('this')
this._callstack.append(_SELECT)
num_of_args = len(args)
if num_of_args == 0:
separator = "*"
elif num_of_args == 1:
arg = args[0]
if isinstance(arg, str):
this._tablenames.add(
get_tablename(a... | Python | nomic_cornstack_python_v1 |
function group_contributions contributions features_groups
begin
set new_contributions = copy contributions
comment Computing features groups that are the sum of their corresponding features contributions
for group_name in keys features_groups
begin
set new_contributions at group_name = sum axis=1
end
comment Dropping ... | def group_contributions(contributions, features_groups):
new_contributions = contributions.copy()
# Computing features groups that are the sum of their corresponding features contributions
for group_name in features_groups.keys():
new_contributions[group_name] = new_contributions[features_groups[gro... | Python | nomic_cornstack_python_v1 |
function soma num1 num2
begin
set resultado = num1 + num2
return resultado
end function
function sub num1 num2
begin
return num1 - num2
end function
function multi num1 num2
begin
set resultado = num1 * num2
return resultado
end function
function divi num1 num2
begin
if num2 == 0
begin
print string Náo se divide por 0
... | def soma(num1, num2):
resultado = num1 + num2
return resultado
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
resultado = num1 * num2
return resultado
def divi(num1, num2):
if num2 == 0:
print('Náo se divide por 0')
else:
resultado = num1 / num2
retu... | Python | zaydzuhri_stack_edu_python |
function gcd a b
begin
while b != 0
begin
set temp = a
set a = b
set b = temp % b
end
return a
end function
print call gcd 20 45 | def gcd(a, b):
while b != 0:
temp = a
a = b
b = temp % b
return a
print(gcd(20,45)) | Python | iamtarun_python_18k_alpaca |
class MLFQ
begin
set Turn = 0
set Tw = 0
set Tr = 0
set Sum = 0
set Cpu = 0
end class
comment creates a running queue
set running = list
comment creates a queue for round robin1
set RR1 = list
comment creates a queue for round robin2
set RR2 = list
comment creates a queue for fcfs
set FCFS = list
comment tracks whi... | class MLFQ:
Turn = 0
Tw = 0
Tr = 0
Sum = 0
Cpu = 0
running = [] #creates a running queue
RR1 = [] #creates a queue for round robin1
RR2 =[] #creates a queue for round robin2
FCFS = [] #creates a queue for fcfs
state1 = 0 #tracks which queue is in progress and how long its taking
state2 = ... | Python | zaydzuhri_stack_edu_python |
function nice_preview x
begin
set x = x at tuple slice : : slice : : slice : : slice : 3 :
set axis = list 0 1 2
set stds = call reduce_std x axis=axis keepdims=true
set means = call reduce_mean x axis=axis keepdims=true
set mins = means - 2 * stds
set maxs = means + 2 * stds
set x = call divide x - mins max... | def nice_preview(x):
x = x[:, :, :, :3]
axis = [0, 1, 2]
stds = tf.math.reduce_std(x, axis=axis, keepdims=True)
means = tf.math.reduce_mean(x, axis=axis, keepdims=True)
mins = means - 2 * stds
maxs = means + 2 * stds
x = tf.divide(x - mins, maxs - mins)
x = tf.clip_by_value(x, clip_value... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed May 29 12:28:04 2019 @author: kaysm
import itertools as it
set Input = open string Find a Median String.txt string r
set Input = split read Input string
set k = integer Input at 0
set Dna = Input at slice 1 : :
function hamming pattern text
begin
set distance = 0
fo... | # -*- coding: utf-8 -*-
"""
Created on Wed May 29 12:28:04 2019
@author: kaysm
"""
import itertools as it
Input=open("Find a Median String.txt", "r")
Input=Input.read().split("\n")
k=int(Input[0])
Dna=Input[1:]
def hamming(pattern, text):
distance=0
for i in range(0,len(pattern)):
if... | Python | zaydzuhri_stack_edu_python |
function testZeroShift self
begin
for order in tuple 1 2
begin
for regularization in tuple 0 0.01
begin
for num_boundary_points in tuple 0 1
begin
call assertZeroShift order regularization num_boundary_points
end
end
end
end function | def testZeroShift(self):
for order in (1, 2):
for regularization in (0, 0.01):
for num_boundary_points in (0, 1):
self.assertZeroShift(order, regularization, num_boundary_points) | Python | nomic_cornstack_python_v1 |
import math
import time
function mean data
begin
if iterate data is data
begin
set data = list data
end
return sum data / length data
end function
function peakDetect y t dt thld tml tmm tmh
begin
if y at t >= thld at 1 and y at t < thld at 2
begin
set tmm = tmm + 1
return tuple none list tml tmm tmh
end
else
if y at t... | import math
import time
def mean(data):
if iter(data) is data:
data = list(data)
return sum(data)/len(data)
def peakDetect(y,t,dt,thld,tml,tmm,tmh):
if y[t] >= thld[1] and y[t] < thld[2]:
tmm += 1
return (None,[tml,tmm,tmh])
elif y[t] >= thld[1] and y[t] >= thld[2]:
tmh... | Python | zaydzuhri_stack_edu_python |
function execute self cmd cwd=none verbose=false test_mode=false return_out=false
begin
append history cmd
return call _pop_result
end function | def execute(self, cmd, cwd=None, verbose=False, test_mode=False
, return_out=False):
self.history.append(cmd)
return self._pop_result() | Python | nomic_cornstack_python_v1 |
function _maybe_assert_valid_sample self counts
begin
string Check counts for proper shape, values, then return tensor version.
if not validate_args
begin
return counts
end
set counts = call embed_check_nonnegative_integer_form counts
return call with_dependencies list call assert_equal total_count call reduce_sum inpu... | def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return distribution_util.with_dependencies([
assert_util.a... | Python | jtatman_500k |
from collections import deque
class Solution
begin
function longestOnes self A K
begin
set N = length A
set acc = 0
set D = deque
set ans = 0
for i in range N
begin
set c = A at i
if not c
begin
if not K
begin
set acc = - 1
end
else
if length D >= K
begin
set j = call popleft
set acc = i - j - 1
end
append D i
end
set ... | from collections import deque
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
N = len(A)
acc = 0
D = deque()
ans = 0
for i in range(N):
c = A[i]
if not c:
if not K:
acc = -1
elif ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
function ques1 df
begin
string Lợi nhuận và doanh số trong những năm qua :param df: :return:
set date_time = lambda date_string -> year
set date_times = lambda date_srtings -> call Series map date_time date_srtings
set ... | import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
def ques1(df):
"""
Lợi nhuận và doanh số trong những năm qua
:param df:
:return:
"""
date_time = lambda date_string: datetime.strptime(date_string, '%d/%m/%Y').year
date_times = lambda date_... | Python | zaydzuhri_stack_edu_python |
function add_request cls caller_id
begin
call appendleft caller_id
end function | def add_request(cls, caller_id):
cls.queue.appendleft(caller_id) | Python | nomic_cornstack_python_v1 |
function send_report self package
begin
if not trace_id
begin
if value_id in keys add_trace_to_report_list
begin
set trace_id = pop add_trace_to_report_list value_id
end
end
set trace_id = call create_trace network_id trace_id
set local_data = call get_rpc_state data network_id device_id value_id state_id string Report... | def send_report(self, package):
if not package.trace_id:
if package.value_id in self.add_trace_to_report_list.keys():
package.trace_id = (
self.add_trace_to_report_list.pop(package.value_id)
)
package.trace_id = self.create_trace(
... | Python | nomic_cornstack_python_v1 |
class Solution
begin
comment @param {integer[]} nums
comment @return {integer}
function rob self nums
begin
if not nums
begin
return 0
end
if length nums == 1
begin
return nums at 0
end
comment not rob house[0]
set pre1 = 0
set cru1 = 0
for i in range 1 length nums
begin
set temp = pre1
set pre1 = cru1
set cru1 = max n... | class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
if not nums:
return 0
if len(nums) == 1:
return nums[0]
# not rob house[0]
pre1 = cru1 = 0
for i in range(1, len(nums)):
temp = pre1
pre1... | Python | zaydzuhri_stack_edu_python |
function get_session_token self
begin
string Use the accession token to request a new session token
comment self.logging.info('Getting session token')
comment Rather than testing any previous session tokens to see if they are still valid, simply delete old tokens in
comment preparation of the creation of new ones
try
b... | def get_session_token(self):
"""
Use the accession token to request a new session token
"""
# self.logging.info('Getting session token')
# Rather than testing any previous session tokens to see if they are still valid, simply delete old tokens in
# preparation of the crea... | Python | jtatman_500k |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
comment Load the car dataset (assuming it's in a CSV file)
set car_data = read csv string car_dataset.csv
comment Split the dataset into features (X) and target variable (y)
set X = drop car_data s... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Load the car dataset (assuming it's in a CSV file)
car_data = pd.read_csv('car_dataset.csv')
# Split the dataset into features (X) and target variable (y)
X = car_data.drop('price', axis=1)
y =... | Python | jtatman_500k |
import tensorflow as tf
set L = layers
set K = backend
function get_encoder voc emb_size hid_size
begin
set emb = embedding length voc emb_size
set rnn = gru units=hid_size return_sequences=true return_state=false
set input_tokens = input list none dtype=string int32
set input_embs = call emb input_tokens
set states = ... | import tensorflow as tf
L = tf.keras.layers
K = tf.keras.backend
def get_encoder(voc, emb_size, hid_size):
emb = L.Embedding(len(voc), emb_size)
rnn = L.GRU(units=hid_size, return_sequences=True, return_state=False)
input_tokens = L.Input([None], dtype='int32')
input_embs = emb(input_tokens)
stat... | Python | zaydzuhri_stack_edu_python |
class TreeNode
begin
function __init__ self name value left=none right=none
begin
set name = name
set value = value
set left = left
set right = right
end function
end class | class TreeNode:
def __init__(self, name, value, left=None, right=None):
self.name = name
self.value = value
self.left = left
self.right = right | Python | jtatman_500k |
import argparse
from src.problem.regression_problem import RegressionProblem
from src.problem.classification_problem import ClassificationProblem
from src.problem.tsp_problem import TSPProblem
from src.algorithm.genetic_algorithm import genetic_algorithm , generate_report , plot_history
function build_problem problem_n... | import argparse
from src.problem.regression_problem import RegressionProblem
from src.problem.classification_problem import ClassificationProblem
from src.problem.tsp_problem import TSPProblem
from src.algorithm.genetic_algorithm import genetic_algorithm, generate_report, plot_history
def build_problem(probl... | Python | zaydzuhri_stack_edu_python |
function learn self Xtrain ytrain
begin
set Ktrain = none
comment YOUR CODE HERE
set Xless = Xtrain
set randomize = array range length ytrain
shuffle random randomize
set Xless = Xless at randomize
set kcentre = Xless at slice : params at string k :
comment ytrain = ytrain[randomize]
comment print (Xtrain.shape)
if p... | def learn(self, Xtrain, ytrain):
Ktrain = None
### YOUR CODE HERE
Xless = Xtrain
randomize = np.arange(len(ytrain))
np.random.shuffle(randomize)
Xless = Xless[randomize]
self.kcentre = Xless[:self.params['k']]
#ytrain = ytrain[randomize]
... | Python | nomic_cornstack_python_v1 |
function can_acquire self logger session guest_request
begin
comment First, check the parent class, maybe its tests already have the answer.
set r_answer = call can_acquire logger session guest_request
if is_error
begin
return error call unwrap_error
end
if call unwrap at 0 is false
begin
return r_answer
end
set r_dist... | def can_acquire(
self,
logger: gluetool.log.ContextAdapter,
session: sqlalchemy.orm.session.Session,
guest_request: GuestRequest
) -> Result[Tuple[bool, Optional[str]], Failure]:
# First, check the parent class, maybe its tests already have the answer.
r_answer = sup... | Python | nomic_cornstack_python_v1 |
import eng
class Longdesk
begin
set name = string longDesk
comment type = 'Item'
set visible = true
set aliases = list string desk string long desk string drawer
set descriptions = dict string LongDeskDesc string There is a long walnut desk along the wall that seats three. Looks to be a great place to read or study. Th... | import eng
class Longdesk:
name = 'longDesk'
#type = 'Item'
visible = True
aliases = ['desk', 'long desk', 'drawer']
descriptions = {'LongDeskDesc': "There is a long walnut desk along the wall that seats three. Looks to be a great place to read or study. There is a drawer on the left side of the desk. ",
'o... | Python | zaydzuhri_stack_edu_python |
function player_join self player_ip *args
begin
try
begin
comment IndexError
set player_ID = args at 0
comment IndexError
set team_name = args at 1
comment ValueError
set team_type = call team_get_type_by_name team_name
end
comment Invaild arguments
except IndexError
begin
call send_message player_ip string join fail
e... | def player_join(self, player_ip, *args):
try:
player_ID = args[0] # IndexError
team_name = args[1] # IndexError
team_type = self.team_get_type_by_name(team_name) # ValueError
except IndexError: # Invaild arguments
self._comm_server.send_message(player_ip, "join fail")
_logger.error("player-joi... | Python | nomic_cornstack_python_v1 |
function get_queryset self
begin
set posts = filter circle__members=user
set circle_pk = get query_params string circle none
if circle_pk is not none
begin
set posts = filter circle__pk=circle_pk
end
return posts
end function | def get_queryset(self):
posts = Post.objects.filter(circle__members=self.request.user)
circle_pk = self.request.query_params.get('circle', None)
if circle_pk is not None:
posts = posts.filter(circle__pk=circle_pk)
return posts | Python | nomic_cornstack_python_v1 |
function test_task_run self
begin
comment Create an instance of our patched app
comment DEV: No broker url is needed, we this task is run directly
set app = call Celery
comment Create our test task
set task_spy = call Mock __name__=string patched_task
set patched_task = call task task_spy
comment Call the run method
ru... | def test_task_run(self):
# Create an instance of our patched app
# DEV: No broker url is needed, we this task is run directly
app = celery.Celery()
# Create our test task
task_spy = mock.Mock(__name__='patched_task')
patched_task = app.task(task_spy)
# Call the ... | Python | nomic_cornstack_python_v1 |
function parse_file self file_path filename
begin
try
begin
set f = open file_path string r
print string { file_path } :
comment Returns JSON object as a dictionary
set data = load json f
comment Iterate over every model key/value pair in schema definitions list
set definitions = data at string definitions
for tuple ke... | def parse_file(self, file_path, filename):
try:
f = open(file_path, "r")
print(f"{file_path}:")
# Returns JSON object as a dictionary
data = json.load(f)
# Iterate over every model key/value pair in schema definitions list
definitions = d... | Python | nomic_cornstack_python_v1 |
function PrecededAccelerationWithTime marker_data time_within
begin
comment Get marker data that preceded an increase in velocity
set marker_data_preceding_acceleration = marker_data at call logical_and values <= values time_interval <= time_within
return marker_data_preceding_acceleration
end function | def PrecededAccelerationWithTime(marker_data,time_within):
#### Get marker data that preceded an increase in velocity
marker_data_preceding_acceleration = marker_data[np.logical_and(marker_data.velocity.values <= marker_data.shift(-1).velocity.fillna(0).values,marker_data.shift(-1).time_interval <= time_within)... | Python | nomic_cornstack_python_v1 |
comment 'German' element is removed
remove language string German
comment Updated language set
print string Updated language set: language | # 'German' element is removed
language.remove('German')
# Updated language set
print('Updated language set: ', language)
| Python | zaydzuhri_stack_edu_python |
function setChildAttributes self child **kwargs
begin
set attributes = call attributesOfChild child
for key in kwargs
begin
set attributes at key = kwargs at key
end
end function | def setChildAttributes(self,child,**kwargs):
attributes = self.attributesOfChild(child)
for key in kwargs:
attributes[key] = kwargs[key] | Python | nomic_cornstack_python_v1 |
function articles_dump_to_file titles filename compress=false compresslevel=9
begin
call ensure_dir filename
if compress
begin
set dump = open filename + string .gzip string w compresslevel=compresslevel
end
else
begin
set dump = open filename string w
end
call make_articles_dump titles dump
flush dump
close dump
end f... | def articles_dump_to_file(titles, filename, compress=False, compresslevel=9):
ensure_dir(filename)
if compress:
dump = gzip.open(filename + ".gzip", 'w', compresslevel=compresslevel)
else:
dump = open(filename ,'w')
make_articles_dump(titles, dump)
dump.flush()
dump.close(... | Python | nomic_cornstack_python_v1 |
function _function_matcher matcher_func
begin
comment This comment stops black style adding a blank line here, which causes flake8 D202.
function match node
begin
try
begin
return call matcher_func node
end
except tuple LookupError AttributeError ValueError TypeError
begin
return false
end
end function
return match
end... | def _function_matcher(matcher_func):
# This comment stops black style adding a blank line here, which causes flake8 D202.
def match(node):
try:
return matcher_func(node)
except (LookupError, AttributeError, ValueError, TypeError):
return False
return match | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment Decorator的使用
comment The usage of decorator in python
import functools | # -*- coding: utf-8 -*-
#Decorator的使用
#The usage of decorator in python
import functools
| Python | zaydzuhri_stack_edu_python |
string Definition of Soap Client used by all methods Handles caching of wsdl globally in memory A requests session exists through the lifetime of the client
import zeep
from requests import Session
from zeep.exceptions import Fault
from zeep.cache import InMemoryCache
from fenixlib.utils.soapfaults import check_fault
s... | """
Definition of Soap Client used by all methods
Handles caching of wsdl globally in memory
A requests session exists through the lifetime of the client
"""
import zeep
from requests import Session
from zeep.exceptions import Fault
from zeep.cache import InMemoryCache
from fenixlib.utils.soapfaults import check_fault
... | Python | zaydzuhri_stack_edu_python |
function testJobTRSetOverride databases
begin
set gen = call DataGenerator databases
set fwName = call createFramework string testfw1
set taskName = call createTask string task1 fwName
set tr1Name = call createTaskRunner capabilities=list fwName
set tr2Name = call createTaskRunner capabilities=list fwName
set config = ... | def testJobTRSetOverride(databases):
gen = DataGenerator(databases)
fwName = gen.createFramework('testfw1')
taskName = gen.createTask('task1', fwName)
tr1Name = gen.createTaskRunner(capabilities=[fwName])
tr2Name = gen.createTaskRunner(capabilities=[fwName])
config = gen.createConfiguration()
... | Python | nomic_cornstack_python_v1 |
function create self
begin
set stmts = list
set opt_clauses = list
if schema != string public
begin
append opt_clauses string SCHEMA %s % call quote_id schema
end
if has attribute self string version
begin
append opt_clauses string VERSION '%s' % version
end
append stmts string CREATE EXTENSION %s%s % tuple call quot... | def create(self):
stmts = []
opt_clauses = []
if self.schema != 'public':
opt_clauses.append("SCHEMA %s" % quote_id(self.schema))
if hasattr(self, 'version'):
opt_clauses.append("VERSION '%s'" % self.version)
stmts.append("CREATE EXTENSION %s%s" % (
... | Python | nomic_cornstack_python_v1 |
function _get_rssi self
begin
return __rssi
end function | def _get_rssi(self):
return self.__rssi | Python | nomic_cornstack_python_v1 |
function visualization samples
begin
set tuple n bins patches = histogram samples NUM_BINS color=string white histtype=string bar ec=string black
set ax = call gca
call set_xlim list 0 1
call set_major_locator call MaxNLocator integer=true prune=string lower
x label string Drawn values
y label string Frequency
save fig... | def visualization(samples):
n, bins, patches = plt.hist(samples, NUM_BINS, color='white', histtype='bar', ec='black')
ax = plt.gca()
ax.set_xlim([0,1])
ax.yaxis.set_major_locator(MaxNLocator(integer=True, prune='lower'))
plt.xlabel(r'Drawn values')
plt.ylabel(r'Frequency')
plt.savefig(PATH, bbox_inches='tigh... | Python | nomic_cornstack_python_v1 |
comment simulate rolling a pair of dice 100,000 times
comment accumulate the result of each roll in a list
comment print percentage of times each possible roll occurred
import random as r
set ROLLS = 100000
function main
begin
string TODO: Actual docstring
set rolls = list 0 * 11
for i in range 1 ROLLS + 1
begin
set d ... | # simulate rolling a pair of dice 100,000 times
# accumulate the result of each roll in a list
# print percentage of times each possible roll occurred
import random as r
ROLLS = 100000
def main():
"""
TODO: Actual docstring
"""
rolls = [0] * 11
for i in range(1, ROLLS + 1):
d = r.randi... | Python | zaydzuhri_stack_edu_python |
function get_phone_details self user_ids
begin
set pipeline = list dict string $match dict string userId dict string $in user_ids dict string $sort dict string time - 1 dict string $group dict string _id string $userId ; string data dict string $first dict string time string $time ; string model string $model ; string ... | def get_phone_details(self, user_ids):
pipeline = [
{'$match': # Get all records from last days
{'userId' :
{"$in": user_ids
}
}
},
{'$sort' : { 'time': -1 } # sort
},
{"$group": #... | Python | nomic_cornstack_python_v1 |
function ge_averaged_measurement cooldown_time n_avg
begin
set n = call declare int
set I = call declare fixed
set Q = call declare fixed
set Ig_st = call declare_stream
set Qg_st = call declare_stream
set Ie_st = call declare_stream
set Qe_st = call declare_stream
with call for_ n 0 n < n_avg n + 1
begin
comment Groun... | def ge_averaged_measurement(cooldown_time, n_avg):
n = declare(int)
I = declare(fixed)
Q = declare(fixed)
Ig_st = declare_stream()
Qg_st = declare_stream()
Ie_st = declare_stream()
Qe_st = declare_stream()
with for_(n, 0, n < n_avg, n + 1):
# Ground state calibration
alig... | Python | nomic_cornstack_python_v1 |
function mount self mount_point write_to_fstab=true
begin
set mount_point = call VolumeMountPoint device_path mount_point
call mount
if write_to_fstab
begin
call write_to_fstab
end
end function | def mount(self, mount_point, write_to_fstab=True):
mount_point = VolumeMountPoint(self.device_path, mount_point)
mount_point.mount()
if write_to_fstab:
mount_point.write_to_fstab() | Python | nomic_cornstack_python_v1 |
function resolve_defines self defines
begin
set resolved_defs = resolved_defs
set _defines = defines
while true
begin
set def_count = length resolved_defs
set finished = true
for key in sorted defines
begin
if not is instance defines at key dict
begin
set defines at key = dict string value defines at key
end
set val = ... | def resolve_defines(self, defines):
resolved_defs = self.resolved_defs
self._defines = defines
while True:
def_count = len(resolved_defs)
finished = True
for key in sorted(defines):
if not isinstance(defines[key], dict):
def... | Python | nomic_cornstack_python_v1 |
function unescape_and_save self in_file_name out_file_name
begin
set bytes_written = 0
comment open in and out files for reading in binary modem and writing in binary mode
set infile = open in_file_name string rb
set outfile = open out_file_name string wb
comment this is a bit more complicated than escape and save, we ... | def unescape_and_save(self, in_file_name, out_file_name):
bytes_written = 0
# open in and out files for reading in binary modem and writing in binary mode
infile = open(in_file_name, "rb")
outfile = open(out_file_name, "wb")
# this is a bit more complicated than escape and save... | Python | nomic_cornstack_python_v1 |
import discord
import random
import config
import requests
import json
from discord.ext import commands
set jokeUrl = string https://icanhazdadjoke.com/
set doggoUrl = string https://dog.ceo/api/breeds/image/random
set bot = call Bot command_prefix=string ! description=string A bot that does whatever I tell it to
decor... | import discord
import random
import config
import requests
import json
from discord.ext import commands
jokeUrl = "https://icanhazdadjoke.com/"
doggoUrl = "https://dog.ceo/api/breeds/image/random"
bot = commands.Bot(command_prefix='!', description='A bot that does whatever I tell it to')
@bot.event
async def on_read... | Python | zaydzuhri_stack_edu_python |
function crawl_by_project self project_name
begin
set pull_ids = call get_pull_request_ids project_name
for pull_id in pull_ids
begin
call crawl pull_id
end
end function | def crawl_by_project(self, project_name):
pull_ids = self.get_pull_request_ids(project_name)
for pull_id in pull_ids:
self.crawl(pull_id) | Python | nomic_cornstack_python_v1 |
comment To avoid integer division
from __future__ import division
from operator import itemgetter
with open string berp-POS-training.txt string r as f1 ; open string cleaned_file.txt string w as f2
begin
seek f1 0 0
set line = read line f1
for line in f1
begin
write f2 replace line at slice 2 : : string string /
end... | from __future__ import division #To avoid integer division
from operator import itemgetter
with open ("berp-POS-training.txt", "r") as f1, open ("cleaned_file.txt","w") as f2:
f1.seek(0,0)
line=f1.readline()
for line in f1:
f2.write(line[2:].replace("\t","/"))
with open ("cleaned_file.txt", "r") a... | Python | zaydzuhri_stack_edu_python |
function fill_dofs self node
begin
set dofs_per_cell = call n_dofs
if not node in __global_dofs
begin
comment Add node to dictionary if it's not there
set __global_dofs at node = none
end
set cell_dofs = __global_dofs at node
if cell_dofs is none
begin
comment Instantiate new list
set count = __dof_count
set __global_d... | def fill_dofs(self,node):
dofs_per_cell = self.element.n_dofs()
if not node in self.__global_dofs:
#
# Add node to dictionary if it's not there
#
self.__global_dofs[node] = None
cell_dofs = self.__global_dofs[node]
if cell_dofs is None:
... | Python | nomic_cornstack_python_v1 |
function configure_interface_switchport_access_vlan device interface vlan
begin
info format string Configuring switchport on {interface} with access_vlan = {vlan} interface=interface vlan=vlan
try
begin
call configure list format string interface {interface} interface=interface format string switchport access vlan {vla... | def configure_interface_switchport_access_vlan(device, interface, vlan):
log.info(
"Configuring switchport on {interface} with access_vlan = {vlan}".format(
interface=interface, vlan=vlan
)
)
try:
device.configure(
[
"interface {interface}".fo... | Python | nomic_cornstack_python_v1 |
function f a x
begin
return a ^ x + a ^ - x
end function
function calculate_sum
begin
comment Solve for 'a' from the equation: a + 1/a = 3
comment This rearranges to a^2 - 3a + 1 = 0
import sympy as sp
set a = call symbols string a positive=true
set eq = a + 1 / a - 3
comment Get the positive solution for 'a'
set a_val... | def f(a, x):
return a**x + a**(-x)
def calculate_sum():
# Solve for 'a' from the equation: a + 1/a = 3
# This rearranges to a^2 - 3a + 1 = 0
import sympy as sp
a = sp.symbols('a', positive=True)
eq = a + 1/a - 3
a_value = sp.solve(eq, a)[0] # Get the positive solution for 'a'
... | Python | dbands_pythonMath |
function initial_filter self group=string gwas window=none
begin
if window is none
begin
set window = MED_WINDOW
end
else
begin
set window = decimal window / 2
end
set candidates = list
comment Select middle 25% of GWAS group
set q_low = call percentile call asarray group_counts at group 50 - window
set q_high = call ... | def initial_filter(self, group="gwas", window=None):
if window is None:
window = self.MED_WINDOW
else:
window = float(window)/2
candidates = []
# Select middle 25% of GWAS group
q_low = np.percentile(np.asarray(self.group_counts[group]), 50 - window)
... | Python | nomic_cornstack_python_v1 |
if real_password == input
begin
print string Hello
end
if real_password != input
begin
print string who are you?
end
set input2 = 11
set real_password2 = 13
if real_password2 == input2
begin
print string Hello
end
else
begin
print string who are you?
end | if real_password == input:
print("Hello")
if real_password != input:
print("who are you?")
input2 = 11
real_password2 = 13
if real_password2 == input2:
print("Hello")
else:
print("who are you?") | Python | zaydzuhri_stack_edu_python |
from typing import Optional , Dict , Iterable , List , Any
import numpy as np
from assembly_gym.util import Transformation
from connection_point import ConnectionPoint
from template_connection_point import TemplateConnectionPoint
from template_part import TemplatePart
from util import calculate_aggregation_transform
cl... | from typing import Optional, Dict, Iterable, List, Any
import numpy as np
from assembly_gym.util import Transformation
from .connection_point import ConnectionPoint
from .template_connection_point import TemplateConnectionPoint
from .template_part import TemplatePart
from .util import calculate_aggregation_transform
... | Python | zaydzuhri_stack_edu_python |
function testSampleOutput self
begin
set beam_width = 3
set max_decode_length = 2
set smart_compose_model = call create_smart_compose_model embedding_layer_param empty_url min_len max_len beam_width max_decode_length feature_type_2_name min_seq_prob length_norm_power
comment {'exist_prefix': True,
comment 'predicted_sc... | def testSampleOutput(self):
beam_width = 3
max_decode_length = 2
smart_compose_model = model.create_smart_compose_model(self.embedding_layer_param, self.empty_url, self.min_len, self.max_len,
beam_width, max_decode_length, self.feat... | Python | nomic_cornstack_python_v1 |
function get_next_fileref self
begin
set last_fileref = call last
if last_fileref
begin
comment A prior fileref exists for this topic.
set next_filref_count = integer last_fileref at slice 1 : : + 1
set rjust = max 4 length string next_filref_count
end
else
begin
comment This is the first one.
set rjust = 4
set next_f... | def get_next_fileref(self):
last_fileref = (
Issue.objects.exclude(fileref="")
.filter(topic=self.topic)
.order_by("fileref")
.values_list("fileref", flat=True)
.last()
)
if last_fileref:
# A prior fileref exists for this to... | Python | nomic_cornstack_python_v1 |
import math
import copy
import time
import cProfile
comment Making move on board
function makeMove board move
begin
set L = integer square root length board
set copyBoard = copy copy board
set zI = index copyBoard L ^ 2 - 1
comment Calculating move index in 1D list based off of x/y coords
set moveI = move at 0 + L * mo... | import math
import copy
import time
import cProfile
#Making move on board
def makeMove(board, move):
L = int(math.sqrt(len(board)))
copyBoard = copy.copy(board)
zI = copyBoard.index(L**2-1)
#Calculating move index in 1D list based off of x/y coords
moveI = move[0] + L*move[1]
copyBo... | Python | zaydzuhri_stack_edu_python |
comment Primary Wave C of [IV] #
comment start wave I wave II wave III wave IV wave V
comment 14198 11730 13139 7450 9088 6450
import sys
append path string ../elliot
from elliot60 import *
function primaryC
begin
function create_intermediates primary
begin
call create_subwaves 14198 11730 13139 7450 9088 6450 Impulse ... | # Primary Wave C of [IV] #
# start wave I wave II wave III wave IV wave V
# 14198 11730 13139 7450 9088 6450
import sys
sys.path.append('../elliot')
from elliot60 import *
def primaryC():
def create_intermediates(primary):
primary.create_subwaves(14198,11730,1313... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2
set cap = call VideoCapture 0
comment Test for using camera by openCV
string while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.wa... | import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Test for using camera by openCV
'''
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',... | Python | zaydzuhri_stack_edu_python |
function test_vote_count self current_vote_status first_vote second_vote
begin
comment setup
set starting_vote_count = 0
if current_vote_status
begin
call register_get_user_response user upvoted_ids=list string test_comment
set starting_vote_count = 1
end
call register_comment_votes_response string test_comment
call re... | def test_vote_count(self, current_vote_status, first_vote, second_vote):
#setup
starting_vote_count = 0
if current_vote_status:
self.register_get_user_response(self.user, upvoted_ids=["test_comment"])
starting_vote_count = 1
self.register_comment_votes_response("t... | Python | nomic_cornstack_python_v1 |
function list_directories _
begin
try
begin
set response = call request method=string PROPFIND url=LIST_URL + PATH auth=LIST_AUTH data=xml_body
call raise_for_status
end
except Exception as e
begin
print e
end
set content = parse xmltodict text at string d:multistatus at string d:response
if not is instance content Lis... | def list_directories(_):
try:
response = requests.request(method='PROPFIND',
url=LIST_URL+PATH,
auth=LIST_AUTH,
data=xml_body)
response.raise_for_status()
except Exception as e:
pr... | Python | nomic_cornstack_python_v1 |
function clean_tslots self
begin
function isnull idx
begin
return t_slots at idx is none or all list comprehension team is none for pair in t_slots at idx at 2 for team in pair
end function
set t_slots = t_slots at slice next generator expression i for i in range length t_slots if not is null i : :
set idx = 0
while ... | def clean_tslots(self):
def isnull(idx):
return self.t_slots[idx] is None or all([team is None for pair in self.t_slots[idx][2] for team in pair])
self.t_slots = self.t_slots[next(i for i in range(len(self.t_slots)) if not isnull(i)):]
idx = 0
while idx < len(self.t_sl... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.