code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function sig_alg self
begin
return get pulumi self string sig_alg
end function | def sig_alg(self) -> pulumi.Output[str]:
return pulumi.get(self, "sig_alg") | Python | nomic_cornstack_python_v1 |
function test_template_new self
begin
set url = reverse string manage:template_new
set response = get client url
call eq_ status_code 200
set response_ok = post url dict string name string happy template ; string content string hello!
call assertRedirects response_ok reverse string manage:templates
call ok_ get objects... | def test_template_new(self):
url = reverse('manage:template_new')
response = self.client.get(url)
eq_(response.status_code, 200)
response_ok = self.client.post(url, {
'name': 'happy template',
'content': 'hello!'
})
self.assertRedirects(response_ok... | Python | nomic_cornstack_python_v1 |
function check_values hk_dict ref_dict k hrc_cm hrc_hv msid1 msid2
begin
set line = string
if hk_dict at msid1 at k != ref_dict at msid1 or hk_dict at msid2 at k != ref_dict at msid2
begin
set expected = call find_value hk_dict at msid1 at k hrc_cm hrc_hv
set range1 = expected - 1
set range2 = expected + 1
if hk_dict ... | def check_values(hk_dict, ref_dict, k, hrc_cm, hrc_hv, msid1, msid2):
line = ''
if(hk_dict[msid1][k] != ref_dict[msid1]) \
or (hk_dict[msid2][k] != ref_dict[msid2]):
expected = find_value(hk_dict[msid1][k], hrc_cm, hrc_hv)
range1 = expected - 1
range2 = expected ... | Python | nomic_cornstack_python_v1 |
function get_mean_anomaly_degs apse_position_degs mean_long_planet_degs
begin
comment ApsePosition - Mean Longitude of a planet (incl. Sun) is "Mean Anomaly"
set mean_anomaly_degs = call find_diff_degs apse_position_degs mean_long_planet_degs
return mean_anomaly_degs
end function | def get_mean_anomaly_degs(apse_position_degs, mean_long_planet_degs):
# ApsePosition - Mean Longitude of a planet (incl. Sun) is "Mean Anomaly"
mean_anomaly_degs = find_diff_degs(apse_position_degs,
mean_long_planet_degs)
return mean_anomaly_degs | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function maxProfit prices fee
begin
set n = length prices
if n < 2
begin
return 0
end
comment 第i天手上有股票时的最大收益
set dp1 = list comprehension 0 for _ in range n
comment 第i天手上无股票时的最大收益
set dp2 = list comprehension 0 for _ in range n
set dp1 at 0 = - prices at 0
for i in range 1 n... | from typing import List
class Solution:
def maxProfit( prices: List[int], fee: int) -> int:
n = len(prices)
if n<2:
return 0
dp1 = [0 for _ in range(n)] #第i天手上有股票时的最大收益
dp2 = [0 for _ in range(n)] #第i天手上无股票时的最大收益
dp1[0] = -prices[0]
for i in range(1,n):
... | Python | zaydzuhri_stack_edu_python |
import math
import sys
function getPrimes n
begin
set nPrimes = set
function factor x
begin
if x % 2 == 0
begin
return 2
end
for res in range 3 integer square root x + 1 2
begin
if x % res == 0
begin
return res
end
end
return x
end function
while n > 1
begin
set fact = call factor n
add nPrimes fact
set n = n // fact
e... | import math
import sys
def getPrimes(n):
nPrimes = set()
def factor(x):
if x % 2 == 0:
return 2
for res in range(3, int(math.sqrt(x)) + 1, 2):
if x % res == 0:
return res
return x
while n > 1:
fact = factor(n)
nPrimes.add(fact)... | Python | zaydzuhri_stack_edu_python |
comment modules
function addTax price tax
begin
set newPrice = price / 100 * 100 + tax
return newPrice
end function | #modules
def addTax(price,tax):
newPrice = price / 100 * (100 + tax)
return newPrice
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy
function distanceGraph mat metric=string Cosine
begin
set numRows = shape at 0
set graph = zeros tuple numRows numRows
set dist = zeros tuple numRows numRows
for row in range numRows
begin
for otherRow in range numRows
begin
if otherRow == row
begin
set dist at row at otherRow = 10000000... | import numpy as np
import scipy
def distanceGraph(mat,metric="Cosine"):
numRows = mat.shape[0]
graph = np.zeros((numRows,numRows))
dist = np.zeros((numRows,numRows))
for row in range(numRows):
for otherRow in range(numRows):
if(otherRow==row):
dist[row][ot... | Python | zaydzuhri_stack_edu_python |
import pymysql
set db = call connect host=string 127.0.0.1 user=string root passwd=string toshiba19 db=string lab6 charset=string utf8
set cursor = call cursor DictCursor
execute cursor string DELETE FROM Books WHERE id>0
execute cursor string INSERT INTO Books (id,name, author, description) VALUES (%s,%s, %s, %s), (%s... | import pymysql
db = pymysql.connect(
host="127.0.0.1",
user="root",
passwd="toshiba19",
db="lab6",
charset="utf8"
)
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute("DELETE FROM Books WHERE id>0")
cursor.execute("""INSERT INTO Books
(id,name, author, description)
... | Python | zaydzuhri_stack_edu_python |
if day == string monday
begin
print string It's Monday, the weekend is over
end
else
if day == string friday
begin
print string It's Friday, the weekend is close
end
else
if day == string saturday or string sunday
begin
print string It's the weekend, time to relax
end
else
begin
print string Its not the weekend yet
end | if day == "monday":
print("It's Monday, the weekend is over")
elif day == "friday":
print("It's Friday, the weekend is close")
elif day == "saturday" or "sunday":
print("It's the weekend, time to relax")
else:
print("Its not the weekend yet") | Python | zaydzuhri_stack_edu_python |
function source_endpoint_owner_id self
begin
return get pulumi self string source_endpoint_owner_id
end function | def source_endpoint_owner_id(self) -> str:
return pulumi.get(self, "source_endpoint_owner_id") | Python | nomic_cornstack_python_v1 |
string 定义一个学生类来形容学生
comment 定义一个空的类
class Student
begin
comment 一个空类,pass代表直接跳过
comment 此处pass必须有
pass
end class
comment 定义一个对象
set mingyue = call Student
comment 定义一个厅Python的学生
class PythonStudent
begin
comment 用None给不确定的值赋值
set name = none
set age = 18
set course = string Python
comment 需要注意:
comment 1 def的层级要小于class... | '''
定义一个学生类来形容学生
'''
# 定义一个空的类
class Student():
# 一个空类,pass代表直接跳过
# 此处pass必须有
pass
# 定义一个对象
mingyue = Student()
# 定义一个厅Python的学生
class PythonStudent():
# 用None给不确定的值赋值
name = None
age = 18
course = "Python"
# 需要注意:
# 1 def的层级要小于class的层级
# 2 系统默认室友一个self参数
def doHomework(sel... | Python | zaydzuhri_stack_edu_python |
import math
set limit = 30
comment Step 1
set primes = list
comment Step 2
comment Step 3
set is_prime = list true * limit + 1
comment Step 4
for num in range 2 call isqrt limit + 1
begin
if is_prime at num
begin
for multiple in range num ^ 2 limit + 1 num
begin
set is_prime at multiple = false
end
end
end
comment Ste... | import math
limit = 30
# Step 1
primes = []
# Step 2
# Step 3
is_prime = [True] * (limit + 1)
# Step 4
for num in range(2, math.isqrt(limit) + 1):
if is_prime[num]:
for multiple in range(num ** 2, limit + 1, num):
is_prime[multiple] = False
# Step 5
for num in range(2, limit + 1):
if is... | Python | jtatman_500k |
function test_textplot2
begin
set mp = call MapPlot sector=string iowa nocaption=true
call plot_values array range - 99 - 94 array range 40 45 array range 5 labels=range 5 10
return fig
end function | def test_textplot2():
mp = MapPlot(sector="iowa", nocaption=True)
mp.plot_values(
np.arange(-99, -94),
np.arange(40, 45),
np.arange(5),
labels=range(5, 10),
)
return mp.fig | Python | nomic_cornstack_python_v1 |
function normal_get url params=dict
begin
try
begin
return get requests url params=params
end
except ConnectionError
begin
exit call _ string Internet connection failed
end
end function | def normal_get(url, params={}):
try:
return requests.get(url, params=params)
except requests.exceptions.ConnectionError:
sys.exit(_('Internet connection failed')) | Python | nomic_cornstack_python_v1 |
function convolution self x nb_filters kernel_size strides=1 dilation_rate=1 padding=string same activation=string relu batch_norm=true block_name=none
begin
set x = call conv 2d nb_filters kernel_size=kernel_size strides=strides dilation_rate=dilation_rate padding=padding name=call layer_name block_name string _conv x... | def convolution(
self,
x,
nb_filters,
kernel_size,
strides=1,
dilation_rate=1,
padding="same",
activation="relu",
batch_norm=True,
block_name=None,
):
x = K.layers.Conv2D(
nb_filters,
kernel_size=kernel_s... | Python | nomic_cornstack_python_v1 |
function mine_pregame_stats
begin
set database_session = call open_session
set games = call get_game_lineups database_session
call update_ids games database_session
call get_pregame_hitting_stats games
call get_pregame_pitching_stats games
close database_session
end function | def mine_pregame_stats():
database_session = MlbDatabase().open_session()
games = get_game_lineups(database_session)
update_ids(games, database_session)
get_pregame_hitting_stats(games)
get_pregame_pitching_stats(games)
database_session.close() | Python | nomic_cornstack_python_v1 |
string https://leetcode.com/problems/minimum-depth-of-binary-tree/ 111. Minimum Depth of Binary Tree Easy --------------------- Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no c... | """
https://leetcode.com/problems/minimum-depth-of-binary-tree/
111. Minimum Depth of Binary Tree
Easy
---------------------
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no ch... | Python | zaydzuhri_stack_edu_python |
function report_name self
begin
return get pulumi self string report_name
end function | def report_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "report_name") | Python | nomic_cornstack_python_v1 |
function removeNthFromEnd self head n
begin
set length = 0
set pointer1 = head
set pointer2 = head
while pointer1
begin
set length = length + 1
set pointer1 = next
end
if length - n - 1 > 0
begin
for i in range length - n - 1
begin
set pointer2 = next
end
if next != none
begin
set next = next
end
end
else
if length == ... | def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length = 0
pointer1 = head
pointer2 = head
while pointer1:
length += 1
pointer1 = pointer1.next
if length-n-1 > 0:
for i in range(length-n-1):
pointer2 = pointer2.... | Python | zaydzuhri_stack_edu_python |
comment if 语句
set age = 20
if age < 20
begin
print string 是个年轻人
end
else
if age < 40
begin
print string 是个中年人
end
else
begin
print string 是个老年人
end
comment if 嵌套语句
set count = 0
if count
begin
if count < - 1000
begin
print string 小于一千
end
else
begin
print string 大于等于一千
end
end
else
if count > 1000
begin
print string 大于... | # if 语句
age = 20
if age < 20:
print("是个年轻人")
elif age < 40:
print("是个中年人")
else:
print("是个老年人")
# if 嵌套语句
count = 0
if count:
if count < -1000:
print("小于一千")
else:
print("大于等于一千")
else:
if count > 1000:
print("大于一千")
print("是个整数")
else:
print("小于等于一... | Python | zaydzuhri_stack_edu_python |
function load_matrix file_name path=string datos/ ext=string .npy dtype=float64
begin
if ext == string .npy
begin
return call matrix load np path + file_name + ext allow_pickle=true dtype=dtype
end
else
begin
string Sin fomato especifico, esperamoe esta en texto con condificacion estandar 'utf-8' e iran siendo ingresad... | def load_matrix(file_name: str,
path = "datos/", ext=".npy",
dtype=np.float64) -> np.matrix:
if ext == ".npy":
return np.matrix(np.load(path+file_name+ext,
allow_pickle=True),
dtype=dtype)
else:
"""... | Python | nomic_cornstack_python_v1 |
function log_info func
begin
if not LOG_INFO
begin
return func
end
function inner self *args **kwargs
begin
set result = call func self *args keyword kwargs
debug format string {0} __name__
debug string ============================
if __doc__
begin
debug format string """ {0} """ strip __doc__
end
debug string --------... | def log_info(func):
if not LOG_INFO:
return func
def inner(self, *args, **kwargs):
result = func(self, *args, **kwargs)
LOGGER.debug('\n{0}'.format(func.__name__))
LOGGER.debug('============================')
if func.__doc__:
LOGGER.debug('""" {0} """'.form... | Python | nomic_cornstack_python_v1 |
string Funções com retornos numeros =[ 1, 2, 3] ret_pop = numeros.pop() print(f"retorno de pop: {ret_pop}") ret_pr = print(numeros) print(f"retorno do print: {ret_pr}") #OBS: Em Python quando uma função nao retorna nenhum valor, o retorno é none def quadrado_de_7(): print(7 * 7)# aqui não tem retorno nenhum ret = quadr... | """
Funções com retornos
numeros =[ 1, 2, 3]
ret_pop = numeros.pop()
print(f"retorno de pop: {ret_pop}")
ret_pr = print(numeros)
print(f"retorno do print: {ret_pr}")
#OBS: Em Python quando uma função nao retorna nenhum valor, o retorno é none
def quadrado_de_7():
print(7 * 7)# aqui não tem retorno nenhum
ret = ... | Python | zaydzuhri_stack_edu_python |
import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class BasePage
begin
function __init__ self base_driver=none
begin
comment 注解,不是赋值操作。用作ide的类型提示
set ba... | import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class BasePage:
def __init__(self, base_driver=None):
# 注解,不是赋值操作。用作ide的类型提示
ba... | Python | zaydzuhri_stack_edu_python |
function to_xml_element self
begin
set element = call to_xml_element
set string cosine cosine
return element
end function | def to_xml_element(self):
element = super().to_xml_element()
element.set('cosine', self.cosine)
return element | Python | nomic_cornstack_python_v1 |
class Solution
begin
string This is classical example of dynamic programming. The algorithm involved here is called Kadane's algorithm and following is how it works:- 1. Take an index, i, in the array and check its value. 2. Now individually check sum of (i, i-1), (i,i-1, i-2) and so on till (i, i-1, i-2, 0) 3. Take th... | class Solution:
'''
This is classical example of dynamic programming.
The algorithm involved here is called Kadane's algorithm
and following is how it works:-
1. Take an index, i, in the array and check its value.
2. Now individually check sum of (i, i-1), (i,i-1, i-2) and so on till (i, i-1, i-... | Python | zaydzuhri_stack_edu_python |
function extract_references_from_wets wet_files metadata_dir out_dir tmp_dir=none
begin
comment Setup output files
set shard_files = call make_ref_shard_files out_dir
set num_refs = 0
for tuple i wet_file in enumerate wet_files
begin
set num_refs_in_wet = 0
info string Processing file %d i
comment Read metadata file
se... | def extract_references_from_wets(wet_files, metadata_dir, out_dir,
tmp_dir=None):
# Setup output files
shard_files = make_ref_shard_files(out_dir)
num_refs = 0
for i, wet_file in enumerate(wet_files):
num_refs_in_wet = 0
tf.logging.info("Processing file %d", i)
# R... | Python | nomic_cornstack_python_v1 |
import numpy as np
function gradient_func func x diff=1e-06
begin
set grad = list comprehension call func horizontal stack list x at slice : i : x at i + diff x at slice i + 1 : : - call func horizontal stack list x at slice : i : x at i - diff x at slice i + 1 : : / 2 * diff for i in range length x
return horizo... | import numpy as np
def gradient_func(func, x, diff=1e-6):
grad = [(func(np.hstack([x[:i], x[i] + diff, x[i + 1:]])) -
func(np.hstack([x[:i], x[i] - diff, x[i + 1:]]))) / (2 * diff)
for i in range(len(x))]
return np.hstack(grad)
def jacobian_func(func, x, diff=1e-6):
"""
if ... | Python | zaydzuhri_stack_edu_python |
while queue
begin
set x = queue at 0
del queue at 0
if x == k
begin
print dp at x
break
end
for nx in list x - 1 x + 1 x * 2
begin
if 0 <= nx <= MAX and not dp at nx
begin
set dp at nx = dp at x + 1
append queue nx
end
end
end
string MAX = 100000 n, k = map(int, input().split()) queue, visit = [[n, 0]], [0]*(MAX+1) whi... | while queue:
x = queue[0]
del queue[0]
if x == k:
print(dp[x])
break
for nx in [x-1, x+1, x*2]:
if 0 <= nx <= MAX and not dp[nx]:
dp[nx] = dp[x]+1
queue.append(nx)
'''
MAX = 100000
n, k = map(int, input().split())
queue, visit = [[n, 0]], [0]*... | Python | zaydzuhri_stack_edu_python |
function weak_repulsion Cents a k CV_matrix n_c L
begin
comment np.column_stack((Cents[:,1:3],Cents[:,0].reshape(-1,1,2)))
set CCW = call dstack tuple call roll_reverse Cents at tuple slice : : slice : : 0 call roll_reverse Cents at tuple slice : : slice : : 1
set displacement = call mod Cents - CCW + L / 2... | def weak_repulsion(Cents,a,k, CV_matrix,n_c,L):
CCW = np.dstack((roll_reverse(Cents[:,:,0]),roll_reverse(Cents[:,:,1])))#np.column_stack((Cents[:,1:3],Cents[:,0].reshape(-1,1,2)))
displacement = np.mod(Cents - CCW + L/2,L) - L/2
rij = np.sqrt(displacement[:,:,0]**2 + displacement[:,:,1]**2)
norm_disp = ... | Python | nomic_cornstack_python_v1 |
function post_order_nodes root
begin
if call get_left
begin
for node in call post_order_nodes call get_left
begin
yield node
end
end
if call get_right
begin
for node in call post_order_nodes call get_right
begin
yield node
end
end
yield root
end function | def post_order_nodes(root):
if root.get_left():
for node in post_order_nodes(root.get_left()):
yield node
if root.get_right():
for node in post_order_nodes(root.get_right()):
yield node
yield root | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot
comment n=x
comment t=y
set valores = list 1000 5000 10000 20000 50000 100000
set tempo = list 0.042882 1.461091 4.964721 19.078003 100.335626 400.812899
title pyplot string Selection-sort - Vetor de valores já ordenados
x label string Número de elementos
y label string Tempo gasto na ordenação... | import matplotlib.pyplot
#n=x
#t=y
valores = [1000,5000,10000,20000,50000,100000]
tempo = [0.042882,1.461091,4.964721,19.078003,100.335626,400.812899]
matplotlib.pyplot.title('Selection-sort - Vetor de valores já ordenados ')
matplotlib.pyplot.xlabel('Número de elementos')
matplotlib.pyplot.ylabel('Tempo gasto na or... | Python | zaydzuhri_stack_edu_python |
import geopandas as gpd
from Entires.FilesChecker import FilesChecker
class GeoData
begin
function __init__ self signal_message file_name
begin
set signal_message = signal_message
set file_name = file_name
end function
function read self
begin
set checker = call FilesChecker signal_message
if not call existence file_na... | import geopandas as gpd
from Entires.FilesChecker import FilesChecker
class GeoData:
def __init__(self, signal_message, file_name):
self.signal_message = signal_message
self.file_name = file_name
def read(self):
checker = FilesChecker(self.signal_message)
if not checke... | Python | zaydzuhri_stack_edu_python |
comment Initialize an empty list to store the positions of the substring occurrences
set positions = list
comment Start searching for the substring from index 0
set index = 0
comment Iterate over the string and search for the substring
while index < length string
begin
comment Find the position of the substring starti... | # Initialize an empty list to store the positions of the substring occurrences
positions = []
# Start searching for the substring from index 0
index = 0
# Iterate over the string and search for the substring
while index < len(string):
# Find the position of the substring starting from the current index
positi... | Python | greatdarklord_python_dataset |
class Cliente
begin
function __init__ self
begin
set tiempo_en_sistema = 0
end function
decorator staticmethod
function tiempo_promedio_espera clientes
begin
set res = 0
for cliente in clientes
begin
set res = res + tiempo_en_sistema
end
return res / length clientes
end function
end class | class Cliente():
def __init__(self):
self.tiempo_en_sistema = 0
@staticmethod
def tiempo_promedio_espera(clientes):
res = 0
for cliente in clientes:
res += cliente.tiempo_en_sistema
return res / len(clientes)
| Python | zaydzuhri_stack_edu_python |
function test
begin
set test = list dict string key string val1 list string key
assert call unwrap == string val1
end function | def test():
test = [{'key': 'val1'}, ['key']]
assert fetch_data_by_keys(*test).unwrap() == 'val1' | Python | nomic_cornstack_python_v1 |
function tree_build sv piece
begin
if piece == none
begin
return none
end
comment process various string expressions (or triplets without args for conditions and values)
comment convert to string
set piece = if expression type piece == tuple then strip piece at 0 Space else strip piece Space
set alphabetic = Alphakword... | def tree_build(sv, piece):
if piece==None: return None
# process various string expressions (or triplets without args for conditions and values)
piece=piece[0].strip(Space) if type(piece)==tuple else piece.strip(Space) # convert to string
alphabe... | Python | nomic_cornstack_python_v1 |
function setAlias self alias name plug add=string True
begin
pass
end function | def setAlias(self, alias, name, plug, add='True'):
pass | Python | nomic_cornstack_python_v1 |
function _delete_selected_records self
begin
comment Display a confirmation dialog to check that user wants to proceed with deletion
set quit_msg = string This operation cannot be undone. Are you sure you want to delete these record/s?
set reply = warning self string Confirm Delete quit_msg Yes No
comment If yes, find ... | def _delete_selected_records(self):
# Display a confirmation dialog to check that user wants to proceed with deletion
quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?"
reply = QtWidgets.QMessageBox.warning(self, 'Confirm Delete',
... | Python | nomic_cornstack_python_v1 |
import os
from PIL import Image
set input_dir = string frame
for tuple root dirs files in walk input_dir
begin
if files
begin
print root
end
sort files key=lambda file -> integer split base name path file string . at 0
for tuple i file in enumerate files
begin
set extension = call splitext file at - 1
set name = string... | import os
from PIL import Image
input_dir = 'frame'
for root, dirs, files in os.walk(input_dir):
if files:
print(root)
files.sort(key=lambda file: int(os.path.basename(file).split('.')[0]))
for i, file in enumerate(files):
extension = os.path.splitext(file)[-1]
name = f'{i}{extensio... | Python | zaydzuhri_stack_edu_python |
function commit_repo repo_dir message
begin
comment instantiate our repository
set repo = call Repo repo_dir
comment add all changes
try
begin
comment or A=True
add git string --all
end
except GitCommandError as e
begin
print string There was an error adding changes to { repo_dir } .
print e
end
comment get repo status... | def commit_repo(
repo_dir: str,
message: str,
):
# instantiate our repository
repo = Repo(repo_dir)
# add all changes
try:
repo.git.add("--all") # or A=True
except GitCommandError as e:
print(f"There was an error adding changes to {repo_dir}.")
print(e)
# get repo status with frontmatter r... | Python | nomic_cornstack_python_v1 |
class CharacterDTO
begin
function __init__ self character
begin
set layer = character at string layer
set name = character at string name
set width = character at string width
set height = character at string height
set rescale_x = character at string rescale_x
set rescale_y = character at string rescale_y
set sheet = ... | class CharacterDTO:
def __init__(self, character):
self.layer = character['layer']
self.name = character['name']
self.width = character['width']
self.height = character['height']
self.rescale_x = character['rescale_x']
self.rescale_y = character['rescale_y']
s... | Python | zaydzuhri_stack_edu_python |
function get_secret_output project=none secret_id=none opts=none
begin
Ellipsis
end function | def get_secret_output(project: Optional[pulumi.Input[Optional[str]]] = None,
secret_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetSecretResult]:
... | Python | nomic_cornstack_python_v1 |
import socket
function control msg
begin
set sock = call socket AF_INET SOCK_STREAM
set host = string 0.0.0.0
set port = 5455
call connect tuple host port
comment data = sock.recv(2048)
comment data = str(data, "utf-8")
call send bytes msg string utf-8
comment print(data)
close sock
end function | import socket
def control(msg):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '0.0.0.0'
port = 5455
sock.connect((host, port))
#data = sock.recv(2048)
#data = str(data, "utf-8")
sock.send(bytes(msg,'utf-8'))
#print(data)
sock.close()
| Python | zaydzuhri_stack_edu_python |
import os
import re
import numpy as np
from string import punctuation
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn import linear_model
from sources import stories
from cPickle import load , dump
from config import MODEL , GOOD , BAD
from nltk import clean_html
from html2text import html2te... | import os
import re
import numpy as np
from string import punctuation
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn import linear_model
from sources import stories
from cPickle import load, dump
from config import MODEL, GOOD, BAD
from nltk import clean_html
from html2text import html2text
... | Python | zaydzuhri_stack_edu_python |
function activate self window
begin
set _windows at window = call WindowInstance self window
end function | def activate(self, window):
self._windows[window] = me_window.WindowInstance(self, window) | Python | nomic_cornstack_python_v1 |
comment Recibe como parametro el numero a convertir y la base del sistema numerico
function conversion numero base
begin
comment Inicializa una variable para almacenar los residuos
set numConvertido = string
comment Divide el numero hasta que sea menor que la base
while numero >= base
begin
comment Si el residuo es ma... | def conversion(numero, base):#Recibe como parametro el numero a convertir y la base del sistema numerico
numConvertido = ""#Inicializa una variable para almacenar los residuos
while numero >= base:#Divide el numero hasta que sea menor que la base
if numero % base >= 10:#Si el residuo es mayor a 10
... | Python | zaydzuhri_stack_edu_python |
import datetime
from unittest import TestCase
from billreminder.api.v1.reminders.models import Reminder , ReminderDate
from billreminder.api.v1.reminders.schemas import ReminderSchema , ReminderDateSchema
from billreminder.settings import DATE_FORMAT
set __author__ = string Marcin Przepiórkowski
set __email__ = string ... | import datetime
from unittest import TestCase
from billreminder.api.v1.reminders.models import Reminder, ReminderDate
from billreminder.api.v1.reminders.schemas import ReminderSchema, ReminderDateSchema
from billreminder.settings import DATE_FORMAT
__author__ = 'Marcin Przepiórkowski'
__email__ = 'mprzepiorkowski@gma... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import scrapy
import datetime
from news_spider.items import NewsSpiderItem
from news_spider.pipelines import NewsSpiderPipeline
class NewsSpider extends Spider
begin
set name = string elecfans
set allowed_domains = list string www.elecfans.com
set start_urls = list string http://www.elecfa... | # -*- coding: utf-8 -*-
import scrapy
import datetime
from news_spider.items import NewsSpiderItem
from news_spider.pipelines import NewsSpiderPipeline
class NewsSpider(scrapy.Spider):
name = 'elecfans'
allowed_domains = ['www.elecfans.com']
start_urls = ['http://www.elecfans.com/rengongzhineng']
news... | Python | zaydzuhri_stack_edu_python |
from env import host , user , password
import seaborn as sns
import pandas as pd
import numpy as np
import os
function get_connection db user=user host=host password=password
begin
string This function uses my info from my env file to create a connection url to access the Codeup db.
return string mysql+pymysql:// { use... | from env import host, user, password
import seaborn as sns
import pandas as pd
import numpy as np
import os
def get_connection(db, user = user, host = host, password = password):
'''
This function uses my info from my env file to
create a connection url to access the Codeup db.
'''
return f'mysql... | Python | zaydzuhri_stack_edu_python |
comment https://atcoder.jp/contests/abc200/tasks/abc200_b
from typing import *
function solve n k
begin
for _ in range k
begin
if n % 200 == 0
begin
set n = n // 200
end
else
begin
set n = n * 1000 + 200
end
end
return n
end function
function main
begin
set tuple n k = map int split input
set ans = call solve n k
print... | # https://atcoder.jp/contests/abc200/tasks/abc200_b
from typing import *
def solve(n: int, k: int) -> int:
for _ in range(k):
if n % 200 == 0:
n //= 200
else:
n = n*1000 + 200
return n
def main() -> None:
n, k = map(int, input().split())
ans = solve(n, k)
p... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from skimage.util import view_as_windows
class LCADictionary
begin
function __init__ self
begin
comment patch size 8x8x3
set ps = array list 8 8 3
comment number of dictionary patches
set num_dict_patches = 200
set threshhold = 0.1
comment initialize sparse coefficients
set alpha = none
comment Initi... | import numpy as np
from skimage.util import view_as_windows
class LCADictionary():
def __init__(self):
self.ps = np.array([8, 8, 3]) # patch size 8x8x3
self.num_dict_patches = 200 # number of dictionary patches
self.threshhold = 0.1
self.alpha = None # initialize sparse coefficients
# Initializing dicti... | Python | zaydzuhri_stack_edu_python |
comment This script reads in a .plt measurement file and finds the corresponding
comment automated measurements from a FAVE-extract .txt file. The output is
comment a spreadsheet that contains information about both sets of measurements
comment for each matching word token.
import sys , argparse
from bs4 import Unicode... | # This script reads in a .plt measurement file and finds the corresponding
# automated measurements from a FAVE-extract .txt file. The output is
# a spreadsheet that contains information about both sets of measurements
# for each matching word token.
import sys, argparse
from bs4 import UnicodeDammit
from unidecode i... | Python | zaydzuhri_stack_edu_python |
function _setY y
begin
pass
end function | def _setY(y):
pass | Python | nomic_cornstack_python_v1 |
function test_hwx_breakpoint_are_on_all_thread self
begin
set TEST_CASE = self
set data = list 0
class MyDbg extends Debugger
begin
function on_create_thread self exception
begin
comment Check that later created thread have their HWX breakpoint :)
assert not equal Dr7 0
end function
end class
class TSTBP extends HXBrea... | def test_hwx_breakpoint_are_on_all_thread(self):
TEST_CASE = self
data = [0]
class MyDbg(windows.debug.Debugger):
def on_create_thread(self, exception):
# Check that later created thread have their HWX breakpoint :)
TEST_CASE.assertNotEqual(self.curre... | Python | nomic_cornstack_python_v1 |
function flock lockfile shared=false
begin
call flock lockfile if expression shared then LOCK_SH else LOCK_EX
try
begin
yield
end
finally
begin
call flock lockfile LOCK_UN
end
end function | def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]:
fcntl.flock(lockfile, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(lockfile, fcntl.LOCK_UN) | Python | nomic_cornstack_python_v1 |
function cookies self
begin
if _cookies != none
begin
return _cookies
end
set cookies = call SimpleCookie
load cookies call environ HTTP_COOKIE or string
set _cookies = cookies
return _cookies
end function | def cookies(self):
if self._cookies != None:
return self._cookies
cookies = SimpleCookie()
cookies.load(self.environ(self.HTTP_COOKIE) or "")
self._cookies = cookies
return self._cookies | Python | nomic_cornstack_python_v1 |
comment a[[1]] = 'python'
set a at 250 = string python
print a
print string - * 30
print string 문제 10
set a = dict string A 90 ; string B 80 ; string C 70
set result = pop a string B
print a
print result
print string - * 30
print string 문제 11
set a = list 1 1 1 2 2 3 3 3 4 4 5
set aSet = set a
set b = list aSet
print b... | # a[[1]] = 'python'
a[250] = 'python'
print(a)
print('-' * 30)
print('문제 10')
a = {'A': 90, 'B': 80, 'C': 70}
result = a.pop('B')
print(a)
print(result)
print('-' * 30)
print('문제 11')
a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5]
aSet = set(a)
b = list(aSet)
print(b)
print('-' * 30)
print('문제 12')
import copy
# a = b = [1, ... | Python | zaydzuhri_stack_edu_python |
function explode word
begin
if length word <= 1
begin
return word
end
else
begin
return word at 0 + string + call explode word at slice 1 : :
end
end function
set string = string Bazil
print call explode string | def explode(word):
if len(word) <= 1:
return word
else:
return word[0] + ' ' + explode(word[1:])
string = 'Bazil'
print(explode(string)) | Python | zaydzuhri_stack_edu_python |
function harshad num
begin
set res = 0
set temp = num
while num
begin
set r = num % 10
set num = num // 10
set res = res + r
end
if temp % res == 0
begin
return true
end
return false
end function
set num = integer input
print call harshad num | def harshad(num):
res=0
temp=num
while num:
r=num%10
num=num//10
res+=r
if temp%res==0:
return True
return False
num=int(input())
print(harshad(num))
| Python | zaydzuhri_stack_edu_python |
function test_server_timeouted_session self
begin
set session = call Mock
set timeout = call Mock
set is_active = false
set inactivity = SESSION_TIMEOUT + 1
set running = call Mock return_value=list session
start worker
sleep 1
call assert_any_call
call _close
end function | def test_server_timeouted_session(self):
session = Mock()
session.timeout = Mock()
session.is_active = False
session.inactivity = config.SESSION_TIMEOUT + 1
self.app.sessions.running = Mock(return_value=[session])
self.worker.start()
time.sleep(1)
sessio... | Python | nomic_cornstack_python_v1 |
function condenseGappyAlignment a thresh=0.9
begin
set a = call padAlignment a
set smat = call align2mat a
set gapSiteInd = mean np smat == b'-' axis=0 >= thresh
set keepSeqInd = all smat at tuple slice : : gapSiteInd == b'-' axis=1
print string Removing %d of %d sites and %d of %d sequences from the alignment. % tu... | def condenseGappyAlignment(a, thresh=0.9):
a = padAlignment(a)
smat = align2mat(a)
gapSiteInd = np.mean(smat == b'-', axis=0) >= thresh
keepSeqInd = np.all(smat[:, gapSiteInd] == b'-', axis=1)
print('Removing %d of %d sites and %d of %d sequences from the alignment.' % (gapSiteInd.sum(), smat.shape... | Python | nomic_cornstack_python_v1 |
function max_valid_parenthesis expression
begin
set max_value = 0
comment Keep a count of left parentheses
set count = 0
for char in expression
begin
if char == string (
begin
set count = count + 1
set max_value = max max_value count
end
else
begin
set count = count - 1
end
end
return max_value
end function | def max_valid_parenthesis(expression):
max_value = 0
# Keep a count of left parentheses
count = 0
for char in expression:
if char == '(':
count += 1
max_value = max(max_value, count)
else:
count -= 1
return max_value
| Python | flytech_python_25k |
function evaluate data predicate
begin
set order = call ispredicate predicate
if order == 1
begin
return call _eval_firstorder data predicate
end
if order == 2
begin
set children = tuple predicate at string apply
if not all generator expression call ispredicate child for child in children
begin
raise call TypeError str... | def evaluate(data: Any, predicate: Mapping) -> bool:
order = ispredicate(predicate)
if order == 1:
return _eval_firstorder(data, predicate)
if order == 2:
children = tuple(predicate['apply'])
if not all(ispredicate(child) for child in children):
raise TypeError(
... | Python | nomic_cornstack_python_v1 |
function token_is_valid self uidb64 token
begin
set uid = decode call urlsafe_base64_decode uidb64
set user = if expression pk == integer uid then member else none
return call check_token user token
end function | def token_is_valid(self, uidb64, token):
uid = urlsafe_base64_decode(uidb64).decode()
user = self.member if self.member.pk == int(uid) else None
return token_generator.check_token(user, token) | Python | nomic_cornstack_python_v1 |
function parse_packet3 filp
begin
set packets = list
for line in filp
begin
if not starts with line string #define
begin
continue
end
set line = strip line at slice 8 : :
if starts with line string PKT3_ and find line string 0x != - 1 and find line string ( == - 1
begin
append packets split line at 0
end
end
return p... | def parse_packet3(filp):
packets = []
for line in filp:
if not line.startswith('#define '):
continue
line = line[8:].strip()
if line.startswith('PKT3_') and line.find('0x') != -1 and line.find('(') == -1:
packets.append(line.split()[0])
return packets | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from textacy import preprocess
from datetime import datetime as dt
from Commons import *
import math
class KickOutGraph
begin
comment def __init__(self):
comment self.dataFilePath = filePath + 'Registration.csv'
comment self.stdFilePath = filePath + 'vStudents.csv'
comment self.da... | import pandas as pd
import numpy as np
from textacy import preprocess
from datetime import datetime as dt
from Commons import *
import math
class KickOutGraph():
# def __init__(self):
# self.dataFilePath = filePath + 'Registration.csv'
# self.stdFilePath = filePath + 'vStudents.csv'
# self.... | Python | zaydzuhri_stack_edu_python |
from Domain.obiect import toString
from Logic.CRUD import adaugaObiect , stergeObiect , modificaObiect
from Logic.funct import mutareObiecte , concatenare , PretMaximLocatie , OrdonareDupaPret , sumaPreturilor
function printMenu
begin
print string 1. Adaugare obiect
print string 2. Stergere obiect
print string 3. Modif... | from Domain.obiect import toString
from Logic.CRUD import adaugaObiect, stergeObiect, modificaObiect
from Logic.funct import mutareObiecte, concatenare, PretMaximLocatie, OrdonareDupaPret,sumaPreturilor
def printMenu():
print("1. Adaugare obiect ")
print("2. Stergere obiect ")
print("3. Modificare obiect ... | Python | zaydzuhri_stack_edu_python |
function is_divisible s t
begin
if length s % length t != 0
begin
return false
end
set i = 0
for ch in s
begin
if t at i != ch
begin
return false
end
set i = i + 1 % length t
end
return true
end function
function get_min_str_len s t
begin
if call is_divisible s t
begin
set min_str_len = length t
for i in range 1 length... | def is_divisible(s: str, t: str) -> bool:
if len(s) % len(t) != 0:
return False
i = 0
for ch in s:
if t[i] != ch:
return False
i = (i + 1) % len(t)
return True
def get_min_str_len(s: str, t: str):
if is_divisible(s, t):
min_str_len = len(t)
for i... | Python | zaydzuhri_stack_edu_python |
function is_registered self event_type callback
begin
set listeners = list get _listeners event_type list
for tuple cb _args _kwargs in listeners
begin
if call is_same_callback cb callback
begin
return true
end
end
return false
end function | def is_registered(self, event_type, callback):
listeners = list(self._listeners.get(event_type, []))
for (cb, _args, _kwargs) in listeners:
if reflection.is_same_callback(cb, callback):
return True
return False | Python | nomic_cornstack_python_v1 |
import time
import threading
class CountdownThread extends Thread
begin
function __init__ self name account
begin
call __init__ self
set name = name
set count = account
end function
function run self
begin
while count > 0
begin
print call getName string :Counting Down count
set count = count - 1
sleep 3
end
print strin... | import time
import threading
class CountdownThread(threading.Thread):
def __init__(self,name,account):
threading.Thread.__init__(self)
self.name = name
self.count = account
def run(self):
while self.count >0:
print(self.getName(),":Counting Down",self.count)
... | Python | zaydzuhri_stack_edu_python |
function upload_only_when_stable self
begin
return lower call getenv string CONAN_UPLOAD_ONLY_WHEN_STABLE string True in list string true string 1 string yes
end function | def upload_only_when_stable(self):
return os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", "True").lower() in ["true", "1", "yes"] | Python | nomic_cornstack_python_v1 |
function zonalStatsToRaster image zonesImage geometry maxPixels reducerType
begin
comment reducertype can be mean, max, sum, first. Count is always included for QA
comment the resolution of the zonesimage is used for scale
set reducer = call If call IsEqual reducerType string mean mean Reducer call If call IsEqual redu... | def zonalStatsToRaster(image,zonesImage,geometry,maxPixels,reducerType):
# reducertype can be mean, max, sum, first. Count is always included for QA
# the resolution of the zonesimage is used for scale
reducer = ee.Algorithms.If(ee.Algorithms.IsEqual(reducerType,"mean"),ee.Reducer.mean(),
ee.Algorithms... | Python | nomic_cornstack_python_v1 |
import datetime
from os.path import join , split
from jinja2 import Environment , FileSystemLoader
from monitor import PROJECT_FOLDER
class HTMLGenerator extends object
begin
function __init__ self config
begin
set tuple template_folder template_file = split join PROJECT_FOLDER template
set template_config = template_c... | import datetime
from os.path import (
join,
split
)
from jinja2 import (
Environment,
FileSystemLoader
)
from monitor import PROJECT_FOLDER
class HTMLGenerator(object):
def __init__(self, config):
self.template_folder, self.template_file = split(join(PROJECT_FOLDER, config.template))
... | Python | zaydzuhri_stack_edu_python |
set a = list 1 2 3
set b = list 4 5 6
set c = list 7 8 9
set j = list zip a b c
print string Список j = j
set tuple s1 s2 s3 = tuple sum j at 0 sum j at 1 sum j at 2
print string Cуми елементів з однаковим зсувом = s1 s2 s3 | a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
j = list(zip(a,b,c))
print("Список j =",j)
s1,s2,s3 = sum(j[0]),sum(j[1]),sum(j[2])
print("Cуми елементів з однаковим зсувом =",s1,s2,s3)
| Python | zaydzuhri_stack_edu_python |
comment OOP - Methods
class Circle extends object
begin
comment class object attributes
set pi = 3.14
function __init__ self radius=1
begin
set radius = radius
end function
function area self
begin
return radius ^ 2 * pi
end function
function set_radius self new_radius
begin
string This method takes in a radius and res... | # OOP - Methods
class Circle(object):
# class object attributes
pi = 3.14
def __init__(self, radius = 1):
self.radius = radius
def area(self):
return (self.radius ** 2) * Circle.pi
def set_radius(self, new_radius):
""" This method takes in a radius and resets the cur... | Python | zaydzuhri_stack_edu_python |
comment Perfect Matchings and RNA Secondary Structures
from itertools import permutations
from Bio import SeqIO
from collections import defaultdict
import sys , math
function readfasta inpath
begin
set tuple names seqs = tuple list list
with open inpath string rU as handle
begin
for record in parse SeqIO handle strin... | #Perfect Matchings and RNA Secondary Structures
from itertools import permutations
from Bio import SeqIO
from collections import defaultdict
import sys,math
def readfasta(inpath):
names,seqs=[],[]
with open(inpath,'rU') as handle:
for record in SeqIO.parse(handle,'fasta'):
names.append(rec... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
comment 读入数据/标签 生成x_train y_train
set df = read csv string dot.csv
set x_data = array df at list string x1 string x2
set y_data = array df at string y_c
comment 变为不知道多少行,两列
set x_train = reshape vertical stack x_data - 1 2
co... | import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#读入数据/标签 生成x_train y_train
df=pd.read_csv('dot.csv')
x_data=np.array(df[['x1','x2']])
y_data=np.array(df['y_c'])
x_train=np.vstack(x_data).reshape(-1,2)#变为不知道多少行,两列
y_train=np.vstack(y_data).reshape(-1,1)#变为N行,1列... | Python | zaydzuhri_stack_edu_python |
function resnet18 num_classes **kwargs
begin
set model = call ResNet num_classes BasicBlock list 2 2 2 2 keyword kwargs
return model
end function | def resnet18(num_classes, **kwargs):
model = ResNet(num_classes, BasicBlock, [2, 2, 2, 2], **kwargs)
return model | Python | nomic_cornstack_python_v1 |
set str = string 343 STATE ST ROCHESTER, NY 14650 (43.161256430000037, -77.619328871999983)
set strIn = row at 16
set str2 = split strIn string (
set add = str2 at 0
set addLen = length add
set add = add at slice 0 : addLen - 1 :
set str3 = split str2 at 1 string ,
set lat = str3 at 0
set longt = str3 at 1
set longt =... | str = "343 STATE ST ROCHESTER, NY 14650 (43.161256430000037, -77.619328871999983)"
strIn = row[16]
str2 = strIn.split("(")
add = str2[0]
addLen = len(add)
add = add[0:addLen-1]
str3 = str2[1].split(",")
lat = str3[0]
longt = str3[1]
longt = longt.strip()
longtLen = len(longt)
longt = longt[0:longtLen-1]
| Python | zaydzuhri_stack_edu_python |
import threading , socket , time
set UDP_IP = string 127.0.0.1
set UDP_PORT = 5678
comment 200 tick encoder on a 4x counter behind a 5.5x reduction to the bike
set ENCODER_TICKS_PER_DEGREE = - 200.0 / 360.0 * 4 * 5.5
class NetworkThread extends Thread
begin
string Handles input from the game and sets tells the serial t... | import threading, socket, time
UDP_IP = "127.0.0.1"
UDP_PORT = 5678
# 200 tick encoder on a 4x counter behind a 5.5x reduction to the bike
ENCODER_TICKS_PER_DEGREE = -200.0 / 360.0 * 4 * 5.5
class NetworkThread(threading.Thread):
"""Handles input from the game and sets tells the serial thread what
position c... | Python | zaydzuhri_stack_edu_python |
function __init__ self url token org bucket client_args=none write_api_args=none
begin
call __init__
set bucket = bucket
set client_args = if expression client_args is none then dict else client_args
set client = call InfluxDBClient url=url token=token org=org keyword client_args
set write_api_args = if expression wri... | def __init__(self, *, url, token, org, bucket, client_args=None, write_api_args=None):
super().__init__()
self.bucket = bucket
client_args = {} if client_args is None else client_args
self.client = InfluxDBClient(url=url, token=token, org=org, **client_args)
write_api_args = {... | Python | nomic_cornstack_python_v1 |
import math
import typing
from random import uniform
function my_random count freq
begin
return integer sigmoid uniform 1 / freq 1 - 1 * 2 * count
end function
function sigmoid z
begin
string Sigmoid function
if z > 100
begin
return 0
end
return 1.0 / 1.0 + exp z
end function | import math
import typing
from random import uniform
def my_random(count, freq):
return int(sigmoid(uniform(1 / freq, 1) - 1) * 2 * count)
def sigmoid(z: typing.Union[float, int]) -> float:
"""Sigmoid function"""
if z > 100:
return 0
return 1.0 / (1.0 + math.exp(z))
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
set dt = read csv string data_0905.csv index_col=string user_sid
set dt_X = drop dt list string weight string target axis=1
set dt_y = dt at string target
comment 逻辑回归
set clf =... | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
dt = pd.read_csv('data_0905.csv', index_col='user_sid')
dt_X = dt.drop(['weight', 'target'], axis=1)
dt_y = dt['target']
# 逻辑回归
clf = LogisticRegression().fit(dt_X, dt_y)
fea... | Python | zaydzuhri_stack_edu_python |
from turtle import Turtle
set FONT = tuple string Courier 24 string normal
class Scoreboard extends Turtle
begin
function __init__ self
begin
call __init__
call color string white
call penup
call hideturtle
set lifes = 3
call update_scoreboard
end function
function update_scoreboard self
begin
clear self
call goto - 10... | from turtle import Turtle
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.penup()
self.hideturtle()
self.lifes = 3
self.update_scoreboard()
def update_scoreboard(self):
self.c... | Python | zaydzuhri_stack_edu_python |
import argparse
from math import log , ceil
set parser = call ArgumentParser description=string Credit Calculator Project
call add_argument string --type help=string Indicates the type of payment
call add_argument string --payment type=float help=string Monthly payment
call add_argument string --principal type=int help... | import argparse
from math import log, ceil
parser = argparse.ArgumentParser(description="Credit Calculator Project")
parser.add_argument("--type", help="Indicates the type of payment")
parser.add_argument("--payment", type=float, help=" Monthly payment")
parser.add_argument("--principal", type=int, help="Credit princi... | Python | zaydzuhri_stack_edu_python |
function sample self nsamples=1 weighted=true
begin
set weights = if expression weighted then areas / sum areas else none
set index = random choice a=length geometries size=nsamples p=weights
set labels = list
set rows = list
set cols = list
for idx in index
begin
set polygon = geometries at idx at string polygon
se... | def sample(self, nsamples=1, weighted=True):
weights = self.areas / np.sum(self.areas) if weighted else None
index = np.random.choice(a=len(self.geometries), size=nsamples, p=weights)
labels = []
rows = []
cols = []
for idx in index:
polygon = self.geometries... | Python | nomic_cornstack_python_v1 |
function sample self M
begin
set tokens = string
for _ in array range M
begin
set tokens = tokens + random choice index p=values + string
end
return strip tokens
end function | def sample(self, M):
tokens = ''
for _ in np.arange(M):
tokens += np.random.choice(self.mdl.index, p = self.mdl.values) + ' '
return tokens.strip() | Python | nomic_cornstack_python_v1 |
comment Escribir una función que pida un número entero entre 1 y 10, lea el fichero tabla-n.txt con la tabla de multiplicar de ese número, done n es el número introducido, y la muestre por pantalla. Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello.
set numero = input string Introduce un n... | #Escribir una función que pida un número entero entre 1 y 10, lea el fichero tabla-n.txt con la tabla de multiplicar de ese número, done n es el número introducido, y la muestre por pantalla. Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello.
numero = input('Introduce un número entero entr... | Python | zaydzuhri_stack_edu_python |
function get_differences metadata tiffs
begin
set metadata = set list comprehension join string _ split m string _ at slice : - 1 : for m in metadata
set tiffs = set tiffs
return list difference set metadata tiffs
end function | def get_differences(metadata,tiffs):
metadata = set(['_'.join(m.split('_')[:-1]) for m in metadata])
tiffs = set(tiffs)
return list(set.difference(metadata,tiffs)) | Python | nomic_cornstack_python_v1 |
async function _close self
begin
if _closed_flag
begin
return
end
await call _rollback
end function | async def _close(self):
if self._closed_flag:
return
await self._rollback() | Python | nomic_cornstack_python_v1 |
function AutotestTarballsReady self autotest_tarballs
begin
put autotest_tarballs
end function | def AutotestTarballsReady(self, autotest_tarballs):
self._autotest_tarballs_queue.put(autotest_tarballs) | Python | nomic_cornstack_python_v1 |
class Positions extends object
begin
string Player position constants.
set QB = string QB
set RB = string RB
set WR = string WR
set TE = string TE
set DEF = string DST
decorator classmethod
function all cls
begin
string All positions returned as tuple.
return tuple QB RB WR TE DEF
end function
decorator classmethod
fun... | class Positions(object):
"""Player position constants."""
QB = 'QB'
RB = 'RB'
WR = 'WR'
TE = 'TE'
DEF = 'DST'
@classmethod
def all(cls):
"""All positions returned as tuple."""
return (cls.QB, cls.RB, cls.WR, cls.TE, cls.DEF)
@classmethod
def num_required(cls, position):
"""Number of a... | Python | zaydzuhri_stack_edu_python |
import smbus
import time
set bus = call SMBus 1
comment Sensor I2C address
set address = 104
comment Register address from MPU 9255 register map
set power_mgmt_1 = 107
set gyro_config = 27
set gyro_xout_h = 67
set gyro_yout_h = 69
set gyro_zout_h = 71
comment Setting power register to start getting sesnor data
call wri... | import smbus
import time
bus = smbus.SMBus(1)
address = 0x68 # Sensor I2C address
# Register address from MPU 9255 register map
power_mgmt_1 = 0x6b
gyro_config = 0x1b
gyro_xout_h = 0x43
gyro_yout_h = 0x45
gyro_zout_h = 0x47
# Setting power register to start getting sesnor data
bus.write_byte_data(address, powe... | Python | zaydzuhri_stack_edu_python |
function GetColumn self column
begin
if column < 0 or column >= call GetColumnCount
begin
raise exception string Invalid column
end
return _columns at column
end function | def GetColumn(self, column):
if column < 0 or column >= self.GetColumnCount():
raise Exception("Invalid column")
return self._columns[column] | Python | nomic_cornstack_python_v1 |
function train self mode=true
begin
train call super mode=mode
if mode
begin
set mean_module = none
set covar_module = none
set likelihood = none
set task_covar_module = none
end
end function | def train(self, mode: bool = True) -> None:
super().train(mode=mode)
if mode:
self.mean_module = None
self.covar_module = None
self.likelihood = None
self.task_covar_module = None | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_infarray_nannum_nannum_okarray_b_302 self
begin
comment The expected results.
set expected = list comprehension x * y + z for tuple x y z in zip infarrayx repeat nannumy repeat nannumz
comment Exceptions are turned off so we can use the results to test for correct values.
call fma infarrayx ... | def test_fma_nan_param_infarray_nannum_nannum_okarray_b_302(self):
# The expected results.
expected = [(x * y + z) for x,y,z in zip(self.infarrayx, itertools.repeat(self.nannumy), itertools.repeat(self.nannumz))]
# Exceptions are turned off so we can use the results to test for correct values.
arrayfunc.fma(se... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Jan 15 18:27:06 2019 @author: lg
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from math import sin , pi
comment pi=3.1415926
function logstic k x
begin
comment x1=0.6*x*(1-x)
set x1 = k * sin ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 18:27:06 2019
@author: lg
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from math import sin,pi
#pi=3.1415926
def logstic(k,x):
# x1=0.6*x*(1-x)
x1=k*sin(pi*x)
# x1=λ*sin(pi*x)
... | Python | zaydzuhri_stack_edu_python |
comment _*_ encode: utf-8 _*_
from __future__ import unicode_literals
class Graph extends object
begin
function __init__ self
begin
set g_dict = dict
end function
function __repr__ self
begin
return format string This graph's node values are {} keys g_dict
end function
function __getitem__ self idx
begin
return g_dict... | # _*_ encode: utf-8 _*_
from __future__ import unicode_literals
class Graph(object):
def __init__(self):
self.g_dict = {}
def __repr__(self):
return u"This graph's node values are {}".format(
self.g_dict.keys()
)
def __getitem__(self, idx):
return self.g_dict[... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.