code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
with open string input/21.txt as f
begin
set lines = read lines f
set rules = list
set all_ingredients = set list
for l in lines
begin
set spl = split strip l string (
set ingredients = split spl at 0 string
update all_ingredients set ingredients
set allergens = split spl at 1 at slice 9 : - 1 : string ,
append rules... | with open('input/21.txt') as f:
lines = f.readlines()
rules = []
all_ingredients = set([])
for l in lines:
spl = l.strip().split(' (')
ingredients = spl[0].split(' ')
all_ingredients.update(set(ingredients))
allergens = spl[1][9:-1].split(', ')
rules.append((ingre... | Python | zaydzuhri_stack_edu_python |
function test_numerical_answer_to_str self
begin
set mock_module = call create
set get = dict string response1 string 4
set parsed = call numerical_answer_to_str get
assert true parsed == string 4
end function | def test_numerical_answer_to_str(self):
mock_module = CHModuleFactory.create()
get = {'response1': '4'}
parsed = mock_module.numerical_answer_to_str(get)
self.assertTrue(parsed == '4') | Python | nomic_cornstack_python_v1 |
import sys
append path string /usr/local/lib/python2.7/site-packages
from lxml import html
import requests
comment **************************************
comment ********* MAIN PROGRAM ***************
comment **************************************
function main
begin
set counties = list string Antrim string Armagh stri... | import sys
sys.path.append("/usr/local/lib/python2.7/site-packages")
from lxml import html
import requests
#**************************************
#********* MAIN PROGRAM ***************
#**************************************
def main():
counties = ["Antrim","Armagh","Carlow","Cavan","Clare","Cork",
... | Python | zaydzuhri_stack_edu_python |
string The entrypoint for the locust docker image. :env LOCUST_MODE: One of 'standalone', 'master', or 'slave'. :env LOCUST_FILE: String of the python locust file which will be used by locust.This string should include the newlines. Docker run command will probably include '-e LOCUST_FILE="$(cat locustfile.py)"'. :env ... | """
The entrypoint for the locust docker image.
:env LOCUST_MODE: One of 'standalone', 'master', or 'slave'.
:env LOCUST_FILE: String of the python locust file which will be used by locust.This string should include the
newlines.
Docker run command will probably include '-e LOCUST_FILE="$(cat locustfile.py)"'.
:env LO... | Python | zaydzuhri_stack_edu_python |
while 1
begin
if y == 1
begin
set y1 = y1 + string 1
break
end
if y % 2 == 1
begin
set y1 = y1 + string 1
set y = y // 2
end
else
begin
set y1 = y1 + string 0
set y = y // 2
end
end
set y = list y1
comment reversed
reverse y
set trash = x % z
for i in range 1 length y
begin
if y at i == string 0
begin
set trash = trash... | while 1:
if y == 1:
y1 += "1"
break
if y%2 == 1:
y1 += "1"
y = y//2
else:
y1 += "0"
y = y//2
y = list(y1)
y.reverse() #reversed
trash = x%z
for i in range(1,len(y)):
if y[i] == '0':
trash = (trash**2)%z
else:
trash = (x*(trash**2))%z
pr... | Python | zaydzuhri_stack_edu_python |
function clickTeam self
begin
comment self.webScroll(direction="down")
call scrollIntoView locator=_userProfile_team locatorType=string xpath
call waitForElement locator=_userProfile_team locatorType=string xpath
call elementClick locator=_userProfile_team locatorType=string xpath
sleep 2
end function | def clickTeam(self):
# self.webScroll(direction="down")
self.scrollIntoView(locator=self._userProfile_team, locatorType="xpath")
self.waitForElement(locator=self._userProfile_team, locatorType="xpath")
self.elementClick(locator=self._userProfile_team, locatorType="xpath")
pp.time... | Python | nomic_cornstack_python_v1 |
function __init__ self env parent=none bindings=none
begin
set _env = env
set parent = parent
set _focus = list
set _bindings = bindings or dict
if parent
begin
set _focus = _focus at slice : :
end
end function | def __init__(self, env, parent=None, bindings=None):
self._env = env
self.parent = parent
self._focus = []
self._bindings = bindings or {}
if parent:
self._focus = parent._focus[:] | Python | nomic_cornstack_python_v1 |
function update_learning_rate self
begin
for scheduler in schedulers
begin
if lr_policy == string plateau
begin
step scheduler metric
end
else
begin
step scheduler
end
end
set lr = param_groups at 0 at string lr
print string learning rate = %.7f % lr
end function | def update_learning_rate(self):
for scheduler in self.schedulers:
if self.opt.lr_policy == 'plateau':
scheduler.step(self.metric)
else:
scheduler.step()
lr = self.optimizers[0].param_groups[0]['lr']
print('learning rate = %.7f' % lr) | Python | nomic_cornstack_python_v1 |
function test_correct_empty_lambda_definition assert_errors parse_ast_tree inner_def default_options
begin
set tree = call parse_ast_tree format template string lambda inner_def
set visitor = call UselessLambdaDefinitionVisitor default_options tree=tree
run
call assert_errors visitor list
end function | def test_correct_empty_lambda_definition(
assert_errors,
parse_ast_tree,
inner_def,
default_options,
):
tree = parse_ast_tree(template.format('lambda', inner_def))
visitor = UselessLambdaDefinitionVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, []) | Python | nomic_cornstack_python_v1 |
import math
set x = decimal input
set SUM = 0
set k = 0
set term = 10 ^ - 8
set status = true
while status == true
begin
set term = - 1 ^ k * x ^ 2 * k / call factorial 2 * k
if absolute term >= 10 ^ - 8
begin
set k = k + 1
set SUM = SUM + term
end
else
begin
set status = false
end
end
print SUM k - 1 | import math
x=float(input())
SUM=0
k=0
term=10**-8
status = True
while status == True:
term=((-1)**(k)*(x**(2*k)))/(math.factorial(2*k))
if abs(term)>=10**(-8):
k+=1
SUM+=term
else:
status=False
print(SUM,k-1)
| Python | zaydzuhri_stack_edu_python |
comment Prediction System
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import Ridge
from sklearn.linear_model ... | # Prediction System
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import Ridge
from sklearn.linear_model i... | Python | zaydzuhri_stack_edu_python |
comment from distutils.dir_util import copy_tree
import os
import shutil
function copy_rename source dest newName oldName
begin
set src_file = join path source oldName
set new_dst_file_name = join path dest newName
move src_file new_dst_file_name
end function
function labelScratch working_directory
begin
set newfilenam... | #from distutils.dir_util import copy_tree
import os
import shutil
def copy_rename(source, dest,newName,oldName):
src_file = os.path.join(source, oldName)
new_dst_file_name = os.path.join(dest,newName)
shutil.move(src_file,new_dst_file_name)
def labelScratch(working_directory):
newfilename=''
imageCoun... | Python | zaydzuhri_stack_edu_python |
function red_zone_touches self red_zone_touches
begin
set _red_zone_touches = red_zone_touches
end function | def red_zone_touches(self, red_zone_touches):
self._red_zone_touches = red_zone_touches | Python | nomic_cornstack_python_v1 |
function login_email
begin
comment Prevent a CSRF attack from replacing a logged-in user's account with the
comment attacker's.
set current_user = call get_current_user
if current_user
begin
return call jsonify dict string message string A user is already logged in.
end
set params = copy form
comment Don't log the pass... | def login_email():
# Prevent a CSRF attack from replacing a logged-in user's account with the
# attacker's.
current_user = view_helpers.get_current_user()
if current_user:
return api_util.jsonify({'message': 'A user is already logged in.'})
params = flask.request.form.copy()
# Don't lo... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import operator
import readline
from termcolor import colored , cprint
import colorama
set operators = dict string + add ; string - sub ; string * mul ; string / truediv ; string ^ pow
set mode = dict string log false ; string color true
function calculate myarg
begin
set stack = list
for ... | #!/usr/bin/env python3
import operator
import readline
from termcolor import colored, cprint
import colorama
operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'^': operator.pow,
}
mode = {
"log": False,
"color": True,
}
def calculate(my... | Python | zaydzuhri_stack_edu_python |
import csv
import glob
import os
import numpy as np
import time
import random as rd
from sklearn import linear_model
import operator
from sklearn.ensemble import RandomForestClassifier
function openFile filename
begin
set matfeature = list
end function | import csv
import glob
import os
import numpy as np
import time
import random as rd
from sklearn import linear_model
import operator
from sklearn.ensemble import RandomForestClassifier
def openFile(filename):
matfeature = [] | Python | zaydzuhri_stack_edu_python |
function permute s l r
begin
if l == r
begin
print join string s
end
else
begin
for i in range l r + 1
begin
set tuple s at l s at i = tuple s at i s at l
permute s l + 1 r
set tuple s at l s at i = tuple s at i s at l
end
end
end function
function generate_all_permutations s
begin
set n = length s
permute list s 0 n ... | def permute(s, l, r):
if l == r:
print(''.join(s))
else:
for i in range(l, r+1):
s[l], s[i] = s[i], s[l]
permute(s, l + 1, r)
s[l], s[i] = s[i], s[l]
def generate_all_permutations(s):
n = len(s)
permute(list(s), 0, n-1)
s = 'ABC'
generate_all_permutations(s) | Python | jtatman_500k |
string Generate PDF reports from data included in several Pandas DataFrames From pbpython.com
from __future__ import print_function
import pandas as pd
import numpy as np
import argparse
from jinja2 import Environment , FileSystemLoader
from weasyprint import HTML
function create_pivot df infile index_list=list string ... | """
Generate PDF reports from data included in several Pandas DataFrames
From pbpython.com
"""
from __future__ import print_function
import pandas as pd
import numpy as np
import argparse
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
def create_pivot(df, infile, index_list=["Manager", "... | Python | zaydzuhri_stack_edu_python |
function compareNormals
begin
set computeNormals = false
if computeNormals
begin
set tuple r1 r2 r3 = tuple read string r1 read string r2 read string r3
set r = list r1 r2 r3
set x2 = list call like r1 call like r1 call like r1
set x3 = list call like r1 call like r1 call like r1
set v = list call like r1 call like r1 ... | def compareNormals():
computeNormals = False
if computeNormals:
r1,r2,r3 = read('r1'),read('r2'),read('r3')
r = [r1,r2,r3]
x2 = [like(r1),like(r1),like(r1)]
x3 = [like(r1),like(r1),like(r1)]
v = [like(r1),like(r1),like(r1)]
FlattenerUtil.getFrame(r,None,x2,x3)
FlattenerUtil.cross(x3,x2,... | Python | nomic_cornstack_python_v1 |
function check_color self output_information=true
begin
set size_tree = size_tree
for i in range 1 size_tree + 1
begin
set node = select self i
comment check from every end node
if size_tree == 1
begin
set pointer = node
while parent
begin
if color == RED and color == RED
begin
raise call ValueError string The tree has... | def check_color(self, output_information=True):
size_tree = self.root.size_tree
for i in range(1, size_tree + 1):
node = self.select(i)
# check from every end node
if node.size_tree == 1:
pointer = node
while pointer.parent:
... | Python | nomic_cornstack_python_v1 |
function is_templated self
begin
for table in tables
begin
if is instance table SettingTable
begin
for row in rows
begin
if lower row at 0 == string test template
begin
return true
end
end
end
end
return false
end function | def is_templated(self):
for table in self.parent.tables:
if isinstance(table, SettingTable):
for row in table.rows:
if row[0].lower() == "test template":
return True
return False | Python | nomic_cornstack_python_v1 |
function _train_on_tpu_system ctx model_fn_wrapper dequeue_fn
begin
set iterations_per_loop_var = call _create_or_get_iterations_per_loop
set tuple single_tpu_train_step host_call captured_scaffold_fn = call convert_to_single_tpu_train_step dequeue_fn
function multi_tpu_train_steps_on_single_shard
begin
return repeat i... | def _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn):
iterations_per_loop_var = _create_or_get_iterations_per_loop()
single_tpu_train_step, host_call, captured_scaffold_fn = (
model_fn_wrapper.convert_to_single_tpu_train_step(dequeue_fn))
def multi_tpu_train_steps_on_single_shard():
return trai... | Python | nomic_cornstack_python_v1 |
import re
import subprocess
class Git extends object
begin
string Handles the shell parsing of git revisions to generate a unified diff.
decorator staticmethod
function emailToHtml addr
begin
set addr = strip addr
set m = match string ([^<]+) <([^>]+)> addr
set name = call group 1
set email = call group 2
return string... | import re
import subprocess
class Git(object):
'''Handles the shell parsing of git revisions to generate a unified diff.'''
@staticmethod
def emailToHtml(addr):
addr = addr.strip()
m = re.match('([^<]+) <([^>]+)>', addr)
name = m.group(1)
email = m.group(2)
return '... | Python | zaydzuhri_stack_edu_python |
comment a, bをfixしてcを探索
comment n*n*logn
comment c_i < a+b をにぶたん
function binary_search list item
begin
comment listからitem未満の最大のindexを取得
set low = 0
set high = length list - 1
if list at high < item
begin
return high + 1
end
if list at low >= item
begin
return low
end
while true
begin
set mid = low + high // 2
set guess... | # a, bをfixしてcを探索
# n*n*logn
# c_i < a+b をにぶたん
def binary_search(list, item):
# listからitem未満の最大のindexを取得
low = 0
high = len(list) - 1
if list[high] < item:
return high+1
if list[low] >= item:
return low
while True:
mid = (low + high) //2
guess = list[mid]
i... | Python | zaydzuhri_stack_edu_python |
function are_strings_equal string1 string2
begin
comment Remove leading and trailing whitespace characters
set string1 = strip string1
set string2 = strip string2
comment Check if the lengths of the strings are equal
if length string1 != length string2
begin
return false
end
comment Check if the strings are equal chara... | def are_strings_equal(string1, string2):
# Remove leading and trailing whitespace characters
string1 = string1.strip()
string2 = string2.strip()
# Check if the lengths of the strings are equal
if len(string1) != len(string2):
return False
# Check if the strings are equal character by c... | Python | jtatman_500k |
function chain *iterables
begin
for it in iterables
begin
for value in it
begin
yield value
end
end
end function
function chain_from *iterables
begin
for it in iterables
begin
yield from it
end
end function
string data = list(chain("hello", ["world"], ("tuple", "of", "values"))) print(data) data2 = list(chain_from("hel... | def chain(*iterables):
for it in iterables:
for value in it:
yield value
def chain_from(*iterables):
for it in iterables:
yield from it
'''data = list(chain("hello", ["world"], ("tuple", "of", "values")))
print(data)
data2 = list(chain_from("hello", ["world"], ("tuple", "of", "val... | Python | zaydzuhri_stack_edu_python |
class Squad
begin
function __init__ self
begin
set idsquad = 0
set nome = string
set descricao = string
set numeropessoas = 0
set linguagembackend = call BackEnd
set frameworkfrontend = call FrontEnd
set sgbd = call Sgbd
end function
function __str__ self
begin
return string { idsquad } ; { nome } ; { descricao } ; {... | class Squad:
def __init__(self):
self.idsquad = 0
self.nome = ''
self.descricao= ''
self.numeropessoas = 0
self.linguagembackend = BackEnd()
self.frameworkfrontend = FrontEnd()
self.sgbd = Sgbd()
def __str__(self):
return f'{self.idsquad};{self.n... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import input_data
set mnist = call read_data_sets string MNIST_data/ one_hot=true
set x = call placeholder string float list none 784
set W = call Variable zeros list 784 10
set b = call Variable zeros list 10
comment 生成概率模型
set y = softmax matrix multiply x W + b
comment 正确值
set y_ = call place... | import tensorflow as tf
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# 生成概率模型
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 正确值
y_ = tf.placeholder("float", [None, 10])
# 计算交... | Python | zaydzuhri_stack_edu_python |
function test_write_memoryfile profile_first_coutwildrnp_shp
begin
set tuple profile first = profile_first_coutwildrnp_shp
set profile at string driver = string GeoJSON
with call MemoryFile as memfile
begin
with open keyword profile as col
begin
write col first
end
seek memfile 0
set data = read memfile
end
with call M... | def test_write_memoryfile(profile_first_coutwildrnp_shp):
profile, first = profile_first_coutwildrnp_shp
profile['driver'] = 'GeoJSON'
with MemoryFile() as memfile:
with memfile.open(**profile) as col:
col.write(first)
memfile.seek(0)
data = memfile.read()
with Memor... | Python | nomic_cornstack_python_v1 |
from sklearn import metrics
from Knn import Knn
import os
import numpy as np
class EmgModel
begin
function __init__ self labels
begin
set model = call Knn k=5
set labels = labels
set all_data = list
set all_target = list
for pose in labels
begin
set label = labels at pose
set data = call load_data label
set target = li... | from sklearn import metrics
from Knn import Knn
import os
import numpy as np
class EmgModel:
def __init__(self, labels):
self.model = Knn(k=5)
self.labels = labels
self.all_data = list()
self.all_target = list()
for pose in labels:
label = labels[pose]
... | Python | zaydzuhri_stack_edu_python |
function edit_run runlines rtdir
begin
with open rtdir + string /run string w+ as f
begin
for el in runlines
begin
write f el
write f string
end
end
return none
end function | def edit_run(runlines: List[Text], rtdir: Text) -> None:
with open(rtdir + "/run", "w+") as f:
for el in runlines:
f.write(el)
f.write("\n")
return None | Python | nomic_cornstack_python_v1 |
function get_latest_pack_zip_from_blob pack blobs
begin
set blob = none
set blobs = list comprehension b for b in blobs if call splitext base name path name at 0 == pack and ends with name string .zip
if blobs
begin
set blobs = sorted blobs key=lambda b -> call LooseVersion base name path directory name path name rever... | def get_latest_pack_zip_from_blob(pack, blobs):
blob = None
blobs = [b for b in blobs if os.path.splitext(os.path.basename(b.name))[0] == pack and b.name.endswith('.zip')]
if blobs:
blobs = sorted(blobs, key=lambda b: LooseVersion(os.path.basename(os.path.dirname(b.name))), reverse=True)
blo... | Python | nomic_cornstack_python_v1 |
from Floor import Floor
from Vehicle import Vehicle
from ParkController import ParkingController
comment Creating floor objects for Floor Class##
set floor1 = floor string floor1
call set_slot string Car 10
call set_slot string Bike 10
call set_slot string Van 10
call set_slot string Bus 10
set floor2 = floor string fl... | from Floor import Floor
from Vehicle import Vehicle
from ParkController import ParkingController
##Creating floor objects for Floor Class##
floor1 = Floor("floor1")
floor1.set_slot("Car", 10)
floor1.set_slot("Bike", 10)
floor1.set_slot("Van", 10)
floor1.set_slot("Bus", 10)
floor2 = Floor("floor2")
floor2.set_slot("B... | Python | zaydzuhri_stack_edu_python |
function get_mask self method split
begin
with call File h5_path string r as f
begin
return as type f at string run_flag at tuple method_idx at method split bool
end
end function | def get_mask(self, method, split):
with h5py.File(self.h5_path, 'r') as f:
return f['run_flag'][self.method_idx[method], split].astype(bool) | Python | nomic_cornstack_python_v1 |
function _cache_response self packet
begin
call update_message message_id from_node ret_parameters
end function | def _cache_response(self, packet):
self.operator.update_message(packet.message_id, packet.from_node, packet.ret_parameters) | Python | nomic_cornstack_python_v1 |
function lobbyist_xml_to_df input_dir filename batch_dict=none lobbyist_df=none
begin
function lobbyist_df_generator input_dir filename
begin
for name in glob glob join path input_dir filename + string *.xml
begin
with open name string r encoding=string utf-8 as filein
begin
print string Beginning soup on file name
try... | def lobbyist_xml_to_df(input_dir, filename, batch_dict=None, lobbyist_df=None):
def lobbyist_df_generator(input_dir, filename):
for name in glob.glob(os.path.join(input_dir,filename+"*.xml")):
with open(name, "r", encoding="utf-8") as filein:
print("\nBeginning soup on ... | Python | nomic_cornstack_python_v1 |
function __init__ self data start end
begin
set _data = data
set _start = start
set _end = end
set _stock = call retype read csv call StringIO call chart2csv data
end function | def __init__(self, data, start, end):
self._data = data
self._start = start
self._end = end
self._stock = StockDataFrame.retype(pandas.read_csv(io.StringIO(chart2csv(data)))) | Python | nomic_cornstack_python_v1 |
function getNextTrial self trialResult
begin
set newTrial = copy copy random choice trialSet
if currentTrial == none
begin
set currentTrial = random choice trialSet
return currentTrial
end
else
if trialResult == HIT or trialResult == CORRECT_REJECT
begin
comment pick a new trial (possibly the same one again)
set curren... | def getNextTrial(self, trialResult):
newTrial = copy.copy(random.choice(self.trialSet))
if self.currentTrial == None:
self.currentTrial = random.choice(self.trialSet)
return self.currentTrial
else:
if trialResult == Results.HIT or trialResult == Resu... | Python | nomic_cornstack_python_v1 |
comment getInput.py
comment Simple Python script that demonstrates
comment elementary command-line commands
import sys
import os
call system string CLS
set str = string Demo of elementary Python commands
set message = string You typed
comment print("Enter text: ", end='')
print string Please type something (press Enter... | ##getInput.py
##Simple Python script that demonstrates
##elementary command-line commands
import sys
import os
os.system('CLS')
str = "Demo of elementary Python commands"
message = "\nYou typed "
##print("Enter text: ", end='')
print("Please type something (press Enter when done): ", end='')
input_line = ... | Python | zaydzuhri_stack_edu_python |
function dameNum1
begin
print string Ingrese el primer numero:
set num1 = integer input
return num1
end function
function dameNum2
begin
print string Ingrese el segundo numero:
set num2 = integer input
return num2
end function
function dameOperador
begin
print string Ingrese el operador:
set operador = input
return ope... | def dameNum1():
print("Ingrese el primer numero: ")
num1=int(input())
return num1
def dameNum2():
print("Ingrese el segundo numero: ")
num2=int(input())
return num2
def dameOperador():
print("Ingrese el operador: ")
operador=input()
return operador
def operar(a,b,operador):
... | Python | zaydzuhri_stack_edu_python |
function average array
begin
set distinct_values = set array
set average_height = sum distinct_values / length distinct_values
return average_height
end function
set n = integer input
set arr = list map int split input
set result = call average arr
print result | def average(array):
distinct_values = set(array)
average_height = sum(distinct_values) / len(distinct_values)
return average_height
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) | Python | zaydzuhri_stack_edu_python |
function Ti2 self i
begin
assert 1 <= i <= n
if i == 1
begin
return call Si2 1
end
comment Note: in the "Rigorous benchmarking in reasonable time" paper, the
comment expression belown was incorrectly shown as being equivalent to:
comment return self.Si2(i) - self.Ti2(i - 1) / self.r(i - 1)
comment This has since been c... | def Ti2(self, i):
assert 1 <= i <= self.n
if i == 1:
return self.Si2(1)
# Note: in the "Rigorous benchmarking in reasonable time" paper, the
# expression belown was incorrectly shown as being equivalent to:
# return self.Si2(i) - self.Ti2(i - 1) / self.r(i - 1)
... | Python | nomic_cornstack_python_v1 |
function volume_down self **kwargs
begin
set newvolume = max _volume - 0.05 0.01
call set_volume_level newvolume
end function | def volume_down(self, **kwargs):
newvolume = max(self._volume - 0.05, 0.01)
self.set_volume_level(newvolume) | Python | nomic_cornstack_python_v1 |
comment @see https://leetcode.cn/problems/counting-bits/?favorite=2cktkvj
from typing import List
class Solution
begin
function countBit self n
begin
set result = 0
while n > 0
begin
if n ? 1
begin
set result = result + 1
end
set n = n ? 1
end
return result
end function
function countBits self n
begin
set result = list... | # @see https://leetcode.cn/problems/counting-bits/?favorite=2cktkvj
from typing import List
class Solution:
def countBit(self, n: int) -> int:
result = 0
while n > 0:
if n & 0b1:
result += 1
n = n >> 1
return result
def countBits(self, n: int) -... | Python | zaydzuhri_stack_edu_python |
from dxfwrite.const import CENTER
import dxfwrite
from dxfwrite import DXFEngine as dxf
import os
import csv
import sys
set K_MAX_ITER = 100
set K_NAME = string Trophy
set __author__ = string Shovel, Jack, and Archie @sydneyboyshigh.com All Rights Unreserved
set __version__ = string Beta 1.2
set h1 = 155.5
set h2 = 225... | from dxfwrite.const import CENTER
import dxfwrite
from dxfwrite import DXFEngine as dxf
import os
import csv
import sys
K_MAX_ITER = 100
K_NAME = 'Trophy'
__author__ = 'Shovel, Jack, and Archie @sydneyboyshigh.com All Rights Unreserved'
__version__ = 'Beta 1.2'
h1=155.5
h2= 225
w = 90.4
BLACK = 250
file_out = []... | Python | zaydzuhri_stack_edu_python |
comment ######################### Serial use #######################################
comment ************************* endianness **************************************
comment endian = little
comment defaults to @ which uses native endian
comment native of windows OS is little
comment FRDM board set to little endian i... | # ######################### Serial use #######################################
# ************************* endianness **************************************
# endian = little
# defaults to @ which uses native endian
# native of windows OS is little
# FRDM board set to little endian in model config
# < will be f... | Python | zaydzuhri_stack_edu_python |
function nonLinearSmooth h2
begin
for x in range call GetNbinsX - 2
begin
for y in range call GetNbinsY - 2
begin
set centerBin = x + 2 + y + 2 * call GetNbinsX + 2
set surroundingBins = list centerBin - 1 centerBin + 1 centerBin - 1 - call GetNbinsX + 2 centerBin - call GetNbinsX + 2 centerBin + 1 - call GetNbinsX + 2... | def nonLinearSmooth(h2):
for x in range( h2.GetNbinsX()-2 ):
for y in range( h2.GetNbinsY()-2 ):
centerBin = x+2 + (y+2)*(h2.GetNbinsX()+2)
surroundingBins = [
centerBin-1, #this row
centerBin+1,
centerBin-1 - (h2.GetNbinsX()+2), # row above
cen... | Python | nomic_cornstack_python_v1 |
from AllPiece import *
class identify extends pawn rook bishop knight queen king
begin
function __init__ self
begin
return
end function
function pieceType self InfoList BoardInfo
begin
if string InfoList at 8 == string B_pawn----|
begin
set bpawn = call pawn
if call BlackForward InfoList BoardInfo == true
begin
return ... | from AllPiece import *
class identify(__pawn__.pawn,__rook__.rook,__bishop__.bishop,__knight__.knight,__queen__.queen,__king__.king):
def __init__(self):
return
def pieceType(self,InfoList,BoardInfo):
if (str(InfoList[8]) == "B_pawn----|"):
bpawn=__pawn__.pawn()
if (bpaw... | Python | zaydzuhri_stack_edu_python |
comment https://projecteuler.net/problem=10
import math
import unittest
from multiprocessing import Pool , Process
function is_prime m
begin
set acc = 0
for n in range 1 m + 1
begin
set acc = acc + if expression m % n == 0 then 1 else 0
if acc > 2
begin
return false
end
end
return true
end function
function get_primes ... | # https://projecteuler.net/problem=10
import math
import unittest
from multiprocessing import Pool, Process
def is_prime(m):
acc = 0
for n in range(1, m+1):
acc += 1 if m%n == 0 else 0
if acc > 2:
return False
return True
def get_primes(nth_start, nth_end):
primes =... | Python | zaydzuhri_stack_edu_python |
function NoOfBIERSubDomains self
begin
return call _get_attribute string noOfBIERSubDomains
end function | def NoOfBIERSubDomains(self):
return self._get_attribute('noOfBIERSubDomains') | Python | nomic_cornstack_python_v1 |
function test_depth_1_should_ignore_variables_and_literals self
begin
call script string # script.py def f(): x = 1 x += 2 f() depth=1
assert is none call get_evaluation name=string x
assert is none call get_evaluation name=string 1
assert is none call get_evaluation name=string 2
set var_f = call get_evaluation name=s... | def test_depth_1_should_ignore_variables_and_literals(self):
self.script("# script.py\n"
"def f():\n"
" x = 1\n"
" x += 2\n"
"f()\n", depth=1)
self.assertIsNone(self.get_evaluation(name="x"))
self.assertIsNone(... | Python | nomic_cornstack_python_v1 |
set sentence_lengths = list comprehension length word for word in split sentence | sentence_lengths = [len(word) for word in sentence.split()]
| Python | flytech_python_25k |
comment # class A:
comment #
comment # def __init__(self,id):
comment # self.id=id
comment # id=999
comment #
comment # a=A(100)
comment # print(a.id)
comment # x=3
comment #
comment # def f():
comment # print(x)
comment # x=5
comment # print(x)
comment #
comment # f()
comment # chs="|'\''-'|"
comment # for i in range(... | #
# # class A:
# #
# # def __init__(self,id):
# # self.id=id
# # id=999
# #
# # a=A(100)
# # print(a.id)
#
#
# # x=3
# #
# # def f():
# # print(x)
# # x=5
# # print(x)
# #
# # f()
#
# # chs="|'\''-'|"
# # for i in range(6):
# # for ch in chs[i]:
# # print(ch,end='')
#
#
... | Python | zaydzuhri_stack_edu_python |
function batch_get_dev_endpoints self DevEndpointNames
begin
pass
end function | def batch_get_dev_endpoints(self, DevEndpointNames: List) -> Dict:
pass | Python | nomic_cornstack_python_v1 |
function coarse_hddmin hdd_tree reduce_class reduce_config tester_class tester_config test_name work_dir hdd_star=true cache=none
begin
function collect_level_nodes level
begin
function _collect_level_nodes node current_level
begin
if current_level == level and state == KEEP
begin
append level_nodes node
end
return cur... | def coarse_hddmin(hdd_tree, reduce_class, reduce_config, tester_class, tester_config, test_name, work_dir,
*, hdd_star=True, cache=None):
def collect_level_nodes(level):
def _collect_level_nodes(node, current_level):
if current_level == level and node.state == node.KEEP:
... | Python | nomic_cornstack_python_v1 |
function verify_filename filename
begin
if call is_fileobj filename
begin
raise call ValueError string %r not a filename % filename
end
end function | def verify_filename(filename):
if is_fileobj(filename):
raise ValueError("%r not a filename" % filename) | Python | nomic_cornstack_python_v1 |
import csv
import DataTransform
import datetime
import os.path
import time
import urllib.request
set filename = string data/history.csv
set findStartString = string it will take <strong>
set findEndString = string days</strong>
function Load
begin
set history = dict
try
begin
if is file path filename
begin
comment rea... | import csv
import DataTransform
import datetime
import os.path
import time
import urllib.request
filename = 'data/history.csv'
findStartString = "it will take <strong>"
findEndString = "days</strong>"
def Load():
history = {}
try:
if os.path.isfile(filename):
# read and parse the history.... | Python | zaydzuhri_stack_edu_python |
function add_waste self x y z width height depth
begin
call _add_section call Cuboid x y z width height depth
end function | def add_waste(self, x, y, z, width, height, depth):
self._add_section(Cuboid(x, y, z, width, height, depth)) | Python | nomic_cornstack_python_v1 |
comment Enter your code here. Read input from STDIN. Print output to STDOUT
import math
function isPrime n
begin
if n < 1 or n > 2 * 10 ^ 9
begin
return 0
end
if n == 1
begin
return 0
end
if n == 2
begin
return 1
end
for i in range 2 n
begin
if n % i == 0
begin
return 0
end
end
return 1
end function
function isPrime2 n... | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(n):
if n<1 or n>2*(10**9):
return 0
if n == 1:
return 0
if n == 2:
return 1
for i in range(2,n):
if n%i == 0:
return 0
return 1
def isPrime... | Python | zaydzuhri_stack_edu_python |
function domain self
begin
set tuple lower upper = sorted tuple x1 x2
return call FloatRange lower=lower upper=upper
end function | def domain(self):
lower, upper = sorted((self.x1, self.x2))
return FloatRange(lower=lower, upper=upper) | Python | nomic_cornstack_python_v1 |
function composite lon lat
begin
if not - 90 <= lat <= 90
begin
raise call ValueError string illegal lat value, did you switch coordinates
end
return ? gta * call TransformPoint lat lon at slice : 2 :
end function | def composite(lon, lat):
if not -90 <= lat <= 90:
raise ValueError('illegal lat value, did you switch coordinates')
return (~gta * transform.TransformPoint(lat, lon)[:2]) | Python | nomic_cornstack_python_v1 |
from tkinter import *
from tkinter.font import BOLD
from HillCipher import *
from tkinter import ttk
import numpy as np
comment INPUT: KEY1, KEY2, PLAINTEXT
comment OUTPUT: TABLE CIPHERTEXT (CLASSICAL, IMPROVED), TIME (CLASSICAL, IMPROVED)
comment main Window which get input, process and show result
comment in this we'... | from tkinter import *
from tkinter.font import BOLD
from HillCipher import *
from tkinter import ttk
import numpy as np
# INPUT: KEY1, KEY2, PLAINTEXT
#OUTPUT: TABLE CIPHERTEXT (CLASSICAL, IMPROVED), TIME (CLASSICAL, IMPROVED)
# main Window which get input, process and show result
# in this we'll get 2 Key matrix and ... | Python | zaydzuhri_stack_edu_python |
function join self timeout=none
begin
return wait _finished timeout
end function | def join(
self, timeout: Optional[Union[float, datetime.timedelta]] = None
) -> Awaitable[None]:
return self._finished.wait(timeout) | Python | nomic_cornstack_python_v1 |
function ControllerExpandVolume self request context
begin
call set_code UNIMPLEMENTED
call set_details string Method not implemented!
raise call NotImplementedError string Method not implemented!
end function | def ControllerExpandVolume(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Python | nomic_cornstack_python_v1 |
from datetime import datetime
from recognizer import RecognizerInterface
class Waiter
begin
function __init__ self recognizer key_phrase
begin
comment type: (RecognizerInterface, str) -> Waiter
set _recognizer = recognizer
set _key_phrase = lower key_phrase
end function
function wait self wait_time=none
begin
set start... | from datetime import datetime
from recognizer import RecognizerInterface
class Waiter:
def __init__(self, recognizer, key_phrase):
# type: (RecognizerInterface, str) -> Waiter
self._recognizer = recognizer
self._key_phrase = key_phrase.lower()
def wait(self, wait_time=None):
... | Python | zaydzuhri_stack_edu_python |
function classify_queryset self queryset=none category=none to_tag=true **kwargs
begin
if category not in AVAILABLE_CATEGORIES
begin
return queryset
end
set profiles = call queryset_iterator queryset
set ids = set
for profile in profiles
begin
set biography = get api_data string biography
if biography is not none and c... | def classify_queryset(self, queryset=None, category=None, to_tag=True, **kwargs):
if category not in self.AVAILABLE_CATEGORIES:
return queryset
profiles = queryset_iterator(queryset)
ids = set()
for profile in profiles:
biography = profile.api_data.get('biogra... | Python | nomic_cornstack_python_v1 |
function __call__ self z
begin
return call spline z * scale at tuple slice : : none
end function | def __call__(self, z):
return self.spline(z)*self.scale[:,None] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment 转矩
string 1 2 3 1 4 4 5 6 --> 2 5 3 6
comment 方法1
string lst1 = [1, 2, 3, 4] lst2 = [5, 6, 7, 8] row = 2 column = 4 N_list = [] for i in range(column): for j in [lst1,lst2]: N_list.append(j[i]) for x in range(len(N_list)): if (x+1) % row == 0: print(N_list[x], end=' ') else: print(... | #!/usr/bin/env python3
# 转矩
"""
1 2 3 1 4
4 5 6 --> 2 5
3 6
"""
# 方法1
"""
lst1 = [1, 2, 3, 4]
lst2 = [5, 6, 7, 8]
row = 2
column = 4
N_list = []
for i in range(column):
for j in [lst1,lst2]:
N_list.append(j[i])
for x in range(len(N_list)):
if (x+1) % row == 0:
print(N_list[... | Python | zaydzuhri_stack_edu_python |
import json
comment list to Array (json)
print dumps list string Harsh string 12 list string python string html
comment tuple to array (json)
print dumps tuple string Harsh string 12 list string python string html
comment string to String (json)
print dumps string Harsh
comment int to Number (json)
print dumps 12
comme... | import json
# list to Array (json)
print(json.dumps(['Harsh', '12', ['python', 'html']]))
# tuple to array (json)
print(json.dumps(("Harsh", "12", ["python", "html"])))
# string to String (json)
print(json.dumps("Harsh"))
# int to Number (json)
print(json.dumps(12))
# float to Number (json)
print(json.dumps(12.03)... | Python | zaydzuhri_stack_edu_python |
import Tkinter as tk
import ttk
import recorder_main
import re
comment from multiprocessing import Process, Queue
comment most of this code is writen by slobacartoonac@hotmail.com
import Queue
comment not this function
set que = queue
set is_recording = false
function parsegeometry geometry
begin
set m = match string (... | import Tkinter as tk
import ttk
import recorder_main
import re
#from multiprocessing import Process, Queue
#most of this code is writen by slobacartoonac@hotmail.com
import Queue
#not this function
que=Queue.Queue()
is_recording=False
def parsegeometry(geometry):
m = re.match("(\d+)x(\d+)([-+]\d+)([-+]\d+)", geomet... | Python | zaydzuhri_stack_edu_python |
import numpy
import pygame
from pygame.locals import *
from sys import exit
import random
import pygame.surfarray as surfarray
call init
call init
set screen = call set_mode tuple 640 480 0 32
comment Variaveis do jogo // Game variables
set jogo = call Surface tuple 640 480
set fundo = call convert
call fill tuple 0 0 ... | import numpy
import pygame
from pygame.locals import *
from sys import exit
import random
import pygame.surfarray as surfarray
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((640,480),0,32)
#Variaveis do jogo // Game variables
jogo = pygame.Surface((640,480))
fundo = jogo.convert()
fundo.fill((0,... | Python | zaydzuhri_stack_edu_python |
comment is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est
function order sentence
begin
if sentence in list 0 string 0
begin
return string
end
set words = split sentence string
set ret = range length words
for w in words
begin
for l in w
begin
if is digit l
begin
set ret at integer l - 1 = w
end
end
e... | # is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est
def order(sentence):
if sentence in [0, "0"]:
return ''
words = sentence.split(" ")
ret = range(len(words))
for w in words:
for l in w:
if l.isdigit():
ret[int(l)-1] = w
return " ".join(... | Python | zaydzuhri_stack_edu_python |
import random
set hello = list 1 2 3 4 5
print pop hello 0 | import random
hello=[1,2,3,4,5]
print(hello.pop(0)) | Python | zaydzuhri_stack_edu_python |
function calculate_best_15_players self
begin
try
begin
set value_to_use_for_optimisation = call currentText
set names = useful_player_attributes at string first_name + string + useful_player_attributes at string second_name
set names = call tolist
set positions = call tolist
set values = call tolist
set prices = call... | def calculate_best_15_players(self):
try:
value_to_use_for_optimisation = self.main_window.select_best_15_value_button.currentText()
names = self.useful_player_attributes["first_name"] + ' ' + self.useful_player_attributes["second_name"]
names = names.tolist()
pos... | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine , select , Table , Column , String , MetaData , ForeignKey , Date
import datetime
set meta = call MetaData
set raspisanie = call Table string Raspisanie meta call Column string date Date primary_key=true call Column string first call String 10 nullable=false call Column string first... | from sqlalchemy import create_engine, select, Table, Column, String, MetaData, ForeignKey, Date
import datetime
meta = MetaData()
raspisanie = Table('Raspisanie', meta,
Column('date', Date, primary_key=True),
Column('first', String(10), nullable=False), Column('first_office', Stri... | Python | zaydzuhri_stack_edu_python |
function get_model N forced_rank shrink raise_if_no_weights=false freeze_internal_layers=false
begin
call _maybe_enable_debug
set model = call get_non_initialized_model N forced_rank shrink freeze_internal_layers
set weights_path = call _get_weights_path N forced_rank
try
begin
print string Loading weights from %s % we... | def get_model(N, forced_rank, shrink, raise_if_no_weights=False,
freeze_internal_layers=False):
_maybe_enable_debug()
model = get_non_initialized_model(N, forced_rank, shrink,
freeze_internal_layers)
weights_path = _get_weights_path(N, forced_rank)
try:
prin... | Python | nomic_cornstack_python_v1 |
function SetInput2 self input
begin
return call itkMorphologicalWatershedFromMarkersImageFilterISS3IUS3_SetInput2 self input
end function | def SetInput2(self, input: 'itkImageUS3') -> "void":
return _itkMorphologicalWatershedFromMarkersImageFilterPython.itkMorphologicalWatershedFromMarkersImageFilterISS3IUS3_SetInput2(self, input) | Python | nomic_cornstack_python_v1 |
function get_info from_=none to_=none short=false
begin
set short = if expression short then short_filename else lambda path -> path
set res = string
if from_ is not none
begin
set res = res + string ' { call short from_ } ', { call get_size from_ } MB
end
if to_ is not none
begin
set res = res + boolean from_ * strin... | def get_info(from_: Path = None,
to_: Path = None,
*,
short: bool = False) -> str:
short = short_filename if short else (lambda path: path)
res = ''
if from_ is not None:
res += f"'{short(from_)}', {get_size(from_)}MB"
if to_ is not None:
res += bo... | Python | nomic_cornstack_python_v1 |
function check_events screen settings ship bullets
begin
for event in get event
begin
if type == QUIT
begin
call quit
exit 1
end
if type == KEYDOWN
begin
call check_keydown_events event screen settings ship bullets
end
if type == KEYUP
begin
call check_keyup_events event ship
end
end
end function | def check_events(screen, settings, ship, bullets):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(1)
if event.type == pygame.KEYDOWN:
check_keydown_events(event, screen, settings, ship, bullets)
if event.type == pygam... | Python | nomic_cornstack_python_v1 |
function move2goal self
begin
set goal_pose = call Pose
for flag in range 0 length Path
begin
set x = xvals at flag
set y = yvals at flag
set distance_tolerance = 0.09
set vel_msg = call Twist
while call euclidean_distance goal_pose >= decimal distance_tolerance
begin
set x = 1.5 * call euclidean_distance goal_pose
set... | def move2goal(self):
goal_pose = Pose()
for flag in range (0, len(Path)):
goal_pose.x = xvals[flag]
goal_pose.y = yvals[flag]
distance_tolerance = 0.09
vel_msg = Twist()
while self.euclidean_distance(goal_pose) >= flo... | Python | nomic_cornstack_python_v1 |
function get_entities_by_component self component
begin
set comp_set = get _components __class__ list
return generator expression e for e in comp_set if comp_set at e == component
end function | def get_entities_by_component(self, component):
comp_set = self._components.get(component.__class__, [])
return (e for e in comp_set if comp_set[e] == component) | Python | nomic_cornstack_python_v1 |
function test_validate_domain_to_record self
begin
assert equal call validate_domain_to_record string _acme-challenge.foo.baidu.com string _acme-challenge.foo
assert equal call validate_domain_to_record string google.com string
assert equal call validate_domain_to_record string *.python.org string
end function | def test_validate_domain_to_record(self):
self.assertEqual(
validate_domain_to_record('_acme-challenge.foo.baidu.com'), '_acme-challenge.foo'
)
self.assertEqual(validate_domain_to_record('google.com'), '')
self.assertEqual(validate_domain_to_record('*.python.org'), '') | Python | nomic_cornstack_python_v1 |
function submit_workflow subject_files version subject_name user job_run_id multicore=true options=none workflow=string diamond
begin
if multicore
begin
set cores = 8
end
else
begin
set cores = 2
end
set logger = call get_logger
debug format string Processing workflow using {0} as input subject_files
set dax = call ADA... | def submit_workflow(subject_files, version, subject_name, user, job_run_id,
multicore=True, options=None, workflow='diamond'):
if multicore:
cores = 8
else:
cores = 2
logger = fsurfer.log.get_logger()
logger.debug("Processing workflow using {0} as input".format(subje... | Python | nomic_cornstack_python_v1 |
comment noqa: D401
function min self
begin
return _min
end function | def min(self) -> Optional[str]: # noqa: D401
return self._min | Python | nomic_cornstack_python_v1 |
function stop_data self
begin
set recording = false
end function | def stop_data(self):
self.recording = False | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment EE201A Winter 2018 Course Project
comment This script automates the complete pin assignment flow.
import sys
import os
import re
comment ==========================================================================================
comment Complete list of benchmarks stored as ["design_... | #!/usr/bin/env python
# EE201A Winter 2018 Course Project
# This script automates the complete pin assignment flow.
import sys
import os
import re
#==========================================================================================
# Complete list of benchmarks stored as ["design_name", has_clk], and list of... | Python | zaydzuhri_stack_edu_python |
set tuple A B C D = map int split input
set max = max A B C D
set min = min A B C D
set group1 = max + min
set group2 = A + B + C + D - group1
print absolute group1 - group2 | A,B,C,D = map(int, input().split())
max = max(A,B,C,D)
min = min(A,B,C,D)
group1 = max+min
group2 = A+B+C+D - group1
print(abs(group1-group2)) | Python | zaydzuhri_stack_edu_python |
function _log2 input_tensor
begin
return log call maximum input_tensor 1e-06 / log 2.0
end function | def _log2(input_tensor):
return K.log(K.maximum(input_tensor, 1e-6)) / K.log(2.) | Python | nomic_cornstack_python_v1 |
function add_hist self df bins=50 histtype=string step color=string k lw=2 weights=none **kwargs
begin
for i in range nax
begin
set diag_ax = call _make_twin_axes sharex=axes at tuple i i frameon=false
call set_axis_off
call set_yticks list
histogram iloc at tuple slice : : i bins=bins weights=weights histtype=histt... | def add_hist(self, df, bins=50, histtype='step', color='k', lw=2, weights=None, **kwargs):
for i in range(self.nax):
diag_ax = self.axes[i, i]._make_twin_axes(
sharex=self.axes[i, i], frameon=False)
diag_ax.set_axis_off()
diag_ax.set_yticks([])
d... | Python | nomic_cornstack_python_v1 |
function get_price self qty
begin
comment getting the base total times qty
set total = call get_base_price * qty
comment imported is 1.5 times the total
set total = total * call check_import
comment square cost 2 times
set total = total * 2
return total
end function | def get_price(self, qty):
total = self.get_base_price() * qty # getting the base total times qty
total *= self.check_import() # imported is 1.5 times the total
total *= 2 # square cost 2 times
return total | Python | nomic_cornstack_python_v1 |
function test_compilablefiles_sass temp_builds_dir
begin
set basedir = join temp_builds_dir string watcher_success_002
set tuple bdir inspector settings_object watcher_opts = call start_env basedir
call build_sass_sample_structure settings_object basedir
comment Init handler
set project_handler = call UnitTestableProje... | def test_compilablefiles_sass(temp_builds_dir):
basedir = temp_builds_dir.join('watcher_success_002')
bdir, inspector, settings_object, watcher_opts = start_env(basedir)
build_sass_sample_structure(settings_object, basedir)
# Init handler
project_handler = UnitTestableProjectEventHandler(
... | Python | nomic_cornstack_python_v1 |
import cv2
import matplotlib.pyplot as plt
set o = call imread string m2.jpg
set histb = call calcHist list o list 0 none list 256 list 0 255
plot histb color=string b
show | import cv2
import matplotlib.pyplot as plt
o = cv2.imread('m2.jpg')
histb = cv2.calcHist([o], [0], None, [256], [0,255])
plt.plot(histb, color='b')
plt.show() | Python | zaydzuhri_stack_edu_python |
import cv2
set faceCascade = call CascadeClassifier string Resources/haarcascade_frontalface_default.xml
set path = string Resources/lena.png
set img = call imread path
if img is not none
begin
set imgGray = call cvtColor img COLOR_BGR2GRAY
set faces = call detectMultiScale imgGray 1.1 4
for tuple x y width height in f... | import cv2
faceCascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml")
path = "Resources/lena.png"
img = cv2.imread(path)
if img is not None:
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray, 1.1, 4)
for (x, y, width, height) in face... | Python | zaydzuhri_stack_edu_python |
function collect_noise data_path=DATA_PATH
begin
while true
begin
for tuple stream_name stream_base in items ORCASOUND_STREAMS
begin
try
begin
comment get the ID of the latest stream and build URL to load
set latest = string { stream_base } /latest.txt
set stream_id = replace decode read url open latest string utf-8 st... | def collect_noise(data_path=orca_params.DATA_PATH):
while True:
for stream_name, stream_base in orca_params.ORCASOUND_STREAMS.items():
try:
# get the ID of the latest stream and build URL to load
latest = f'{stream_base}/latest.txt'
stream_id... | Python | nomic_cornstack_python_v1 |
function check_delimiters expr
begin
set s = stack
set newExpr = replace expr string string
if length newExpr == 1
begin
return false
end
else
begin
for c in newExpr
begin
if c in delim_openers
begin
call push c
end
else
if c in delim_closers
begin
set toCheck = delim_openers at index delim_closers c
if toCheck in s a... | def check_delimiters(expr):
s = Stack()
newExpr = expr.replace(" ", "")
if len(newExpr) ==1:
return False
else:
for c in newExpr:
if c in delim_openers:
s.push(c)
elif c in delim_closers:
toCheck = delim_openers[delim_closers.index(... | Python | nomic_cornstack_python_v1 |
function setVault self vault
begin
comment must be called before setCurator()
assert _priv_depositories is none
set _priv_vault = vault
return
end function | def setVault(self, vault):
assert self._priv_depositories is None # must be called before setCurator()
self._priv_vault = vault
return | Python | nomic_cornstack_python_v1 |
function variant1 self
begin
set var = _x
set var = var ? var - 1
return var
end function | def variant1(self):
var = self._x
var |= var - 1
return var | Python | nomic_cornstack_python_v1 |
import numpy as np
import os
import librosa
class Preprocess
begin
function __init__ self
begin
set folder_list = list string yes string no string go string up string down string one string two string three string bed string cat string dog string happy
set DATA_PATH = string speech_commands/
set max_length = 40
set num... | import numpy as np
import os
import librosa
class Preprocess():
def __init__(self):
self.folder_list = ['yes', 'no', 'go', 'up', 'down', 'one', 'two', 'three','bed' , 'cat', 'dog', 'happy']
self.DATA_PATH = 'speech_commands/'
self.max_length = 40
self.numpy_files = os.listdir('numpy_files/')
self.numpy_pa... | Python | zaydzuhri_stack_edu_python |
function make_filled_legend
begin
call figtext 0.8 0.18 algos_names at 0 backgroundcolor=colors at 0 color=string black weight=string roman size=string x-small
call figtext 0.8 0.145 algos_names at 1 backgroundcolor=colors at 1 color=string white weight=string roman size=string x-small
call figtext 0.8 0.11 algos_names... | def make_filled_legend():
plt.figtext(0.80, 0.18, algos_names[0],
backgroundcolor=colors[0], color='black', weight='roman',
size='x-small')
plt.figtext(0.80, 0.145, algos_names[1],
backgroundcolor=colors[1], color='white', weight='roman',
size='x... | Python | nomic_cornstack_python_v1 |
function initializeUniformly self gameState
begin
if index == 1
begin
call initialize gameState legalPositions
end
call addGhostAgent ghostAgent
end function | def initializeUniformly(self, gameState):
if self.index == 1:
jointInference.initialize(gameState, self.legalPositions)
jointInference.addGhostAgent(self.ghostAgent) | 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.