code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment real signature unknown; restored from __doc__
function svn_client_ctx_t_log_msg_func2_get svn_client_ctx_t_self
begin
pass
end function | def svn_client_ctx_t_log_msg_func2_get(svn_client_ctx_t_self): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys
call reload sys
call setdefaultencoding string utf-8
set states = dictionary
set symbols = list
set functions = list
set initial = string
set Osymbols = list
set Ofunctions = list
comment final = []
function newReadline f
begin
return strip read line f
end function
function ... | #-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
states = dict()
symbols = []
functions = []
initial = str()
Osymbols = []
Ofunctions = []
# final = []
def newReadline(f):
return f.readline().strip()
def getDFA():
fDFA = open("resource/mearly.txt", "r")
### read state
... | Python | zaydzuhri_stack_edu_python |
comment haar
comment 1.什么是haar特征?特征 = 像素 运算 得到的 某个结果(具体值 向量 矩阵 多维)
comment 2.如何利用特征 区分目标?阈值判决
comment 3.如何得到判决? 机器学习得到判决
comment 三个问题 1.特征 2.判决 3 得到判决
comment Haar特征
comment 特征=白色-黑色 特征=整个区域*权重+黑色*权重 特征=(p1-p2-p3+p4)*w
comment 积分图 特征=(p1-p2-p3+p4)*w
comment adaboost 分类器
comment 1 分类器的结构 2 adaboost计算过程 3 xml文件结构
comment... | # haar
# 1.什么是haar特征?特征 = 像素 运算 得到的 某个结果(具体值 向量 矩阵 多维)
# 2.如何利用特征 区分目标?阈值判决
# 3.如何得到判决? 机器学习得到判决
# 三个问题 1.特征 2.判决 3 得到判决
# Haar特征
# 特征=白色-黑色 特征=整个区域*权重+黑色*权重 特征=(p1-p2-p3+p4)*w
# 积分图 特征=(p1-p2-p3+p4)*w
# adaboost 分类器
# 1 分类器的结构 2 adaboost计算过程 3 xml文件结构
# haar > T1 and haar > T2
# 整体流程 haar->Node z1 z2 z3 Z=sum(z1,z2... | Python | zaydzuhri_stack_edu_python |
function get_options self
begin
set dict = call all_trickers tickers=tickers keyword_list=keyword_list func=string options
end function | def get_options(self) -> None:
self.dict = self.all_trickers(
tickers=self.tickers,
keyword_list=self.keyword_list,
func="options",
) | Python | nomic_cornstack_python_v1 |
comment 3. COMPARACION
comment 1.Comparar si las dos cadenas son iguales
set xat = string hola
set yet = string como estas
print xat == yet
comment 2.Comparar si las dos cadenas son diferentes
set frut = string uva
set verd = string apio
print verd != frut
comment 3.Comparar si las dos cadenas son iguales
set acc = str... | #3. COMPARACION
# 1.Comparar si las dos cadenas son iguales
xat="hola"
yet="como estas"
print(xat == yet)
# 2.Comparar si las dos cadenas son diferentes
frut="uva"
verd="apio"
print(verd != frut)
# 3.Comparar si las dos cadenas son iguales
acc="correr"
curso="programacion"
print(acc == curso)
# 4.Comparar si las do... | Python | zaydzuhri_stack_edu_python |
function fibonacci_number n
begin
if n <= 1
begin
return n
end
set f = list 0 * n + 1
set tuple f at 0 f at 1 = tuple 0 1
for i in range 2 length f
begin
set f at i = f at i - 1 + f at i - 2
end
return f at n
end function
function pisano_period m
begin
set m_lst = list
append m_lst 0
append m_lst 1
set tuple previous ... | def fibonacci_number(n):
if n <= 1:
return n
f = [0] * (n+1)
f[0], f[1] = 0, 1
for i in range(2, len(f)):
f[i] = f[i-1] + f[i-2]
return f[n]
def pisano_period(m):
m_lst = []
m_lst.append(0)
m_lst.append(1)
previous, current = 0, 1
while not ((m_lst[previous] == 0... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import math
string Class Circle
class Circle
begin
function __init__ self radius
begin
set __color = list
set __center = list
set name = list
set __radius = radius
end function
function get_color self
begin
return __color
end function
function set_color self color
begin
set __color = color
e... | #!/usr/bin/python
import math
''' Class Circle '''
class Circle():
def __init__(self, radius):
self.__color = []
self.__center = []
self.name = []
self.__radius = radius
def get_color(self):
return self.__color
def set_color(self, color):
self.__color = col... | Python | zaydzuhri_stack_edu_python |
function get_directory_list directory
begin
set gui_names = list
set mangled_dir = call manglepath string directory
set filenames = list directory mangled_dir
for filename in filenames
begin
if starts with filename string .
begin
comment skip special directories/files
continue
end
set file_path = call append_to_path m... | def get_directory_list(directory):
gui_names = []
mangled_dir = servers.get_file_server().manglepath( str(directory) )
filenames = os.listdir( mangled_dir )
for filename in filenames:
if filename.startswith("."):
# skip special directories/files
continue
f... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Escribir un programa que pida ingresar coordenadas (x,y) que representan puntos en el plano. Informar cuántos puntos se han ingresado en el primer, segundo, tercer y cuarto cuadrante. Al comenzar el programa se pide que se ingrese la cantidad de puntos ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Escribir un programa que pida ingresar coordenadas (x,y) que representan puntos en el plano.
Informar cuántos puntos se han ingresado en el primer, segundo, tercer y cuarto cuadrante. Al comenzar el programa se pide que se ingrese la cantidad de puntos a procesar."""
... | Python | zaydzuhri_stack_edu_python |
import os.path
import sys
from state import State
set filename = argv at 1
set file = open filename string r
set record_list = list
set game = call State | import os.path
import sys
from state import State
filename = sys.argv[1]
file = open(filename, "r")
record_list = list()
game = State() | Python | zaydzuhri_stack_edu_python |
string 82. Remove Duplicates from Sorted List II Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Example 2: Input: head = [1,1,1,2,3... | '''
82. Remove Duplicates from Sorted List II
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Example 2:
Input: head = [1,1,... | Python | zaydzuhri_stack_edu_python |
function listenerViewHasDimensions self dim1 dim2
begin
return call hasDimensions dim1 dim2
end function | def listenerViewHasDimensions(self,dim1,dim2):
return self.listenerView.hasDimensions(dim1, dim2) | Python | nomic_cornstack_python_v1 |
function grow_actions_to_json cls list_of_grow_actions
begin
set result = list
for grow_action in list_of_grow_actions
begin
set result = result + list attribute species_board_index trade_card_index
end
return result
end function | def grow_actions_to_json(cls, list_of_grow_actions):
result = []
for grow_action in list_of_grow_actions:
result += [grow_action.attribute, grow_action.species_board_index, grow_action.trade_card_index]
return result | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import requests
from jingdongspider.items import JingdongspiderItem
import scrapy
import re
import json
from scrapy import Request
class JingdongSpider extends Spider
begin
set name = string jingdong
set allowed_domains = list string jd.com
set start_urls = list string https://www.jd.com
f... | # -*- coding: utf-8 -*-
import requests
from jingdongspider.items import JingdongspiderItem
import scrapy
import re
import json
from scrapy import Request
class JingdongSpider(scrapy.Spider):
name = 'jingdong'
allowed_domains = ['jd.com']
start_urls = ['https://www.jd.com']
def parse(self, response)... | Python | zaydzuhri_stack_edu_python |
import keyboard , time , easygui
set flag = 0
function mouse
begin
while true
begin
sleep 1
if call is_pressed string select
begin
if flag == 0
begin
set flag = 1
call press string shift
call msgbox string shift has been pressed title=string alert
end
else
begin
set flag = 0
release keyboard string shift
call msgbox st... | import keyboard, time, easygui
flag = 0
def mouse():
while True:
time.sleep(1)
if keyboard.is_pressed('select'):
if flag == 0:
flag = 1
keyboard.press('shift')
easygui.msgbox('shift has been pressed', title="alert")
else:
flag = 0
keyboard.release('shift')
easygui.msgbox('sh... | Python | zaydzuhri_stack_edu_python |
function scrapeSurfSpots spots
begin
comment Create empty DataFrame
set df = call DataFrame list
comment Retrieve data for each surf spot from msw api
for tuple idx row in call iterrows
begin
print string Getting forecast info for row at string spot
comment Access MSW API
set df = concat list df call processJson target... | def scrapeSurfSpots(spots : pd.DataFrame):
# Create empty DataFrame
df = pd.DataFrame([])
# Retrieve data for each surf spot from msw api
for idx, row in spots.iterrows():
print('\nGetting forecast info for', row['spot'])
# Access MSW API
df = pd.concat([df, processJson(target_ur... | Python | nomic_cornstack_python_v1 |
function update_node self node
begin
pass
end function | def update_node(self, node: Node):
pass | Python | nomic_cornstack_python_v1 |
import re
function capitalize_sentences text
begin
string Return text capitalizing the sentences. Note that sentences can end in dot (.), question mark (?) and exclamation mark (!)
set matched = sub string ([\.|\?|\!]\s)(\w+) title_match capitalize text
return matched
end function
function title_match matchobj
begin
re... | import re
def capitalize_sentences(text: str) -> str:
"""Return text capitalizing the sentences. Note that sentences can end
in dot (.), question mark (?) and exclamation mark (!)"""
matched = re.sub('([\.|\?|\!]\s)(\w+)', title_match, text.capitalize())
return matched
def title_match(matchobj):
... | Python | zaydzuhri_stack_edu_python |
function name_list qbo_session
begin
return call name_list
end function | def name_list(qbo_session):
return qbo_session.name_list() | Python | nomic_cornstack_python_v1 |
comment to check whether number is prime or not
set i = 2
set flag = 0
while i < num
begin
if num % i == 0
begin
set flag = 1
break
end
else
begin
set i = i + 1
end
end
if flag == 0
begin
print string num + string is a prime number
end
else
begin
print string num + string is not a prime number
end | #to check whether number is prime or not
i = 2
flag = 0
while i< num:
if num%i == 0:
flag=1
break
else:
i+=1
if flag == 0:
print(str(num)+" is a prime number")
else:
print(str(num)+" is not a prime number") | Python | zaydzuhri_stack_edu_python |
import copy
import random
set board = list string ......... string ......... string ......... string ......... string ......... string ......... string ......... string ......... string .........
function main
begin
global board
for tuple idx line in enumerate board
begin
set board at idx = list line
end
call solve
cal... | import copy
import random
board = [
".........",
".........",
".........",
".........",
".........",
".........",
".........",
".........",
"........."
]
def main():
global board
for idx,line in enumerate(board):
board[idx] = list(line)
solve()
prin... | Python | zaydzuhri_stack_edu_python |
function save_global self obj name=none
begin
set cls = type obj
if name is not none
begin
comment __reduce__ can return a string, which means, "save me as this
comment global name"; respect that by delegating to upstream.
call save_global obj name
end
else
if is subclass cls type
begin
comment TODO: flag to try/except... | def save_global(self, obj, name=None):
cls = type(obj)
if name is not None:
# __reduce__ can return a string, which means, "save me as this
# global name"; respect that by delegating to upstream.
super().save_global(obj, name)
elif issubclass(cls, type):
... | Python | nomic_cornstack_python_v1 |
import sys
if length argv < 2
begin
print string Not enougn arguement
end
set filename = argv at 1
set input = open filename string r
set line = read line input
set words = split line
set id = 0
set id_word = dict
set word_cnt = dict
for word in words
begin
if word in word_cnt
begin
set word_cnt at word = word_cnt at... | import sys
if len(sys.argv) < 2:
print('Not enougn arguement')
filename = sys.argv[1]
input = open(filename, 'r')
line = input.readline()
words = line.split()
id = 0
id_word = {}
word_cnt = {}
for word in words:
if word in word_cnt:
word_cnt[word] += 1
else:
id_word[id] = word
id ... | Python | zaydzuhri_stack_edu_python |
function curriculum_weights base slope max_seq_length name=none
begin
with call name_scope name string curriculum_weights list base as scope
begin
set base = call convert_to_tensor base name=string base
set steps = call to_float range max_seq_length - 1
set weights = sigmoid - slope * steps - base name=scope
return wei... | def curriculum_weights(base, slope, max_seq_length, name=None):
with tf.name_scope(name, 'curriculum_weights', [base]) as scope:
base = tf.convert_to_tensor(base, name='base')
steps = tf.to_float(tf.range(max_seq_length - 1))
weights = tf.sigmoid(-(slope * (steps - base)), name=scope)
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
import logging
from typing import Union , List
from robots.setting import BOT_COMMUNICATE_RANGE , BOT_MOVING_RANGE , PROFIT_RATIO , PHE_RATIO , BOT_SENSOR_RANGE , MAP_SIZE
import robots
from robots.maps import ExploreMap , PheMap , Node
from robots.a_star import AStar
set logger = call ... | import numpy as np
import random
import logging
from typing import Union, List
from robots.setting import (
BOT_COMMUNICATE_RANGE,
BOT_MOVING_RANGE,
PROFIT_RATIO,
PHE_RATIO,
BOT_SENSOR_RANGE,
MAP_SIZE,
)
import robots
from robots.maps import ExploreMap, PheMap, Node
from robots.a_star import ... | Python | zaydzuhri_stack_edu_python |
function test_unassignedError self
begin
assert raises unassignedError save_pdf 1 strufile
end function | def test_unassignedError(self):
self.assertRaises(pdffit2.unassignedError, self.P.save_pdf, 1,
self.strufile) | Python | nomic_cornstack_python_v1 |
function num_messages self
begin
pass
end function | def num_messages(self):
pass | Python | nomic_cornstack_python_v1 |
from numpy import *
set arr1 = array list 1 2 3 4 5 6
set arr2 = view arr1
set arr1 at 1 = 7
print call id arr1
print call id arr2
print arr1
print arr2 | from numpy import *
arr1 = array([1,2,3,4,5,6])
arr2 = arr1.view()
arr1[1] = 7
print(id(arr1))
print(id(arr2))
print(arr1)
print(arr2) | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function convertBST self root
begin
comment if not root:
comment return []
comment print(root.val)
comment print(root.right)
comment print(root.left)
comment if root.left and root.right:
comment root.left.val = root.val + root.left.val + root.right.val
comment root.val = root.val + r... | class Solution(object):
def convertBST(self, root):
# if not root:
# return []
# print(root.val)
# print(root.right)
# print(root.left)
# if root.left and root.right:
#
# root.left.val = root.val + root.left.val + root.right.val
... | Python | zaydzuhri_stack_edu_python |
import re
from collections import defaultdict
import jieba
import numpy as np
from jieba import posseg
class DictClassifier
begin
string docstring for DictClassifier
function __init__ self
begin
set __root_filepath = string dict/
call load_userdict string dict/user.dict
set __positive_dict = call __get_dict __root_file... | import re
from collections import defaultdict
import jieba
import numpy as np
from jieba import posseg
class DictClassifier:
"""docstring for DictClassifier"""
def __init__(self):
self.__root_filepath = "dict/"
jieba.load_userdict("dict/user.dict")
self.__positive_dict = self.__get_d... | Python | zaydzuhri_stack_edu_python |
function random_color value=0
begin
set r = random integer 0 value
set g = random integer value 255
set b = random integer 0 255 - value
set rgbl = list r g b
shuffle random rgbl
return string #%02x%02x%02x % tuple rgbl
end function | def random_color(value=0):
r = random.randint(0, value)
g = random.randint(value, 255)
b = random.randint(0, 255-value)
rgbl = [r, g, b]
random.shuffle(rgbl)
return '#%02x%02x%02x' % tuple(rgbl) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
function fturbo f
begin
set col = list 1 0 2 14 18 19
comment f=open(fname,'r')
set h = split read line f
set lo = string sec
for c in col
begin
set lo = lo + string + h at c
end
print lo
set s = 0
while true
begin
set l = read line f
set lo = string s
set e = split l
try
begin... | #!/usr/bin/env python3
import sys
def fturbo(f) :
col=[1,0,2,14,18,19]
# f=open(fname,'r')
h = f.readline().split()
lo = 'sec'
for c in col:
lo+=' '+h[c]
print(lo)
s=0
while True :
l= f.readline()
lo = str(s)
e=l.split()
try :
for c in col:
lo+=' '+e[c]
... | Python | zaydzuhri_stack_edu_python |
function text self
begin
return _text
end function | def text(self) -> str:
return self._text | Python | nomic_cornstack_python_v1 |
function set_timezone timezone
begin
set timezone = replace string timezone string - string /
comment print timezone
call setSession request string timezone timezone
end function | def set_timezone(timezone):
timezone = str(timezone).replace('-', '/')
# print timezone
setSession(request, "timezone", timezone) | Python | nomic_cornstack_python_v1 |
function prune_cluster_id_sets self timestamp
begin
set obj_keys = list keys clustered_oid_map
for obj_id in obj_keys
begin
set this_ts = clustered_oid_map at obj_id at string update_ts
set delta_time = call total_seconds
if delta_time > CLUSTERED_OBJ_ID_PRUNETIME_SEC
begin
del clustered_oid_map at obj_id
end
end
end f... | def prune_cluster_id_sets(self, timestamp):
obj_keys = list(self.state.clustered_oid_map.keys())
for obj_id in obj_keys:
this_ts = self.state.clustered_oid_map[obj_id]["update_ts"]
delta_time = (timestamp - this_ts).total_seconds()
if delta_time > constants.CLUSTERED... | Python | nomic_cornstack_python_v1 |
function test_entity_user_data self
begin
set measurement_1 = call Measurement call metric sources=list dict string source_uuid SOURCE_ID ; string type string azure_devops ; string entity_user_data dict string key dict
set measurement_2 = call Measurement call metric sources=list dict string source_uuid SOURCE_ID ; str... | def test_entity_user_data(self):
measurement_1 = Measurement(
self.metric(),
sources=[
{
"source_uuid": SOURCE_ID,
"type": "azure_devops",
"entity_user_data": {"key": {}},
},
],
... | Python | nomic_cornstack_python_v1 |
function gen_static_session self set_choice session_len num_sessions
begin
set return_seq = list
set chosen_set = split_data at set_choice
for tuple user_index group in group by chosen_set string user_index
begin
set group = reset index group drop=true
set start_i = group at iloc at 0 at string datetime + time delta h... | def gen_static_session(self, set_choice, session_len, num_sessions):
return_seq = []
chosen_set = self.split_data[set_choice]
for user_index, group in chosen_set.groupby('user_index'):
group = group.reset_index(drop=True)
start_i = group[(group.iloc[0]['datetime'] + pd.T... | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
set data = dict string timestamp string 1598641153 ; string Submit string Convert
set r = post string https://www.unixtimestamp.com/index.php data=data
if status_code == ok
begin
set soup = call BeautifulSoup text string html.parser
print call prettify
end | import requests
from bs4 import BeautifulSoup
data = {'timestamp': '1598641153', 'Submit': 'Convert'}
r = requests.post('https://www.unixtimestamp.com/index.php', data=data)
if r.status_code == requests.codes.ok:
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.prettify())
| Python | zaydzuhri_stack_edu_python |
for _ in range integer call raw_input
begin
set tuple u v = map int split call raw_input
set n = u + v
set start_index = n * n + 1 / 2
set offset = n + 1 - v
end | for _ in range(int(raw_input())):
u, v = map(int, raw_input().split())
n = u+v
start_index = (n * (n+1)) / 2
offset = n+1 - v | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
import struct
import array
import pe
from strpatchwork import StrPatchwork
import logging
from collections import defaultdict
set log = call getLogger string peparse
set console_handler = call StreamHandler
call setFormatter call Formatter string %(levelname)-5s: %(message)s
call addHandle... | #! /usr/bin/env python
import struct
import array
import pe
from strpatchwork import StrPatchwork
import logging
from collections import defaultdict
log = logging.getLogger("peparse")
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(levelname)-5s: %(message)s"))
log.addHandle... | Python | zaydzuhri_stack_edu_python |
function preposition source=false target=false
begin
if source
begin
return string Source.
end
else
if target
begin
return string Target.
end
else
begin
return string
end
end function
class Query extends object
begin
function __init__ self table
begin
set select_attributes = list
set where_attributes = list
set orde... | def preposition(source = False, target = False) :
if source: return "Source."
elif target: return "Target."
else: return ""
class Query(object):
def __init__(self,table):
self.select_attributes = []
self.where_attributes = []
self.orderby_attributes = []
se... | Python | zaydzuhri_stack_edu_python |
function fact a
begin
if a < 2
begin
return 1
end
set a = a * call fact a - 1
return a
end function | def fact(a):
if a < 2:
return 1
a *= fact(a - 1)
return a | Python | zaydzuhri_stack_edu_python |
function configure cls cfg
begin
comment Base languages
for x in base_languages
begin
set x_drv = call import_component string model x
comment pragma: debug
if not call is_configured
begin
comment This shouldn't actually be called because configuration should
comment occur on import
call configure cfg
end
end
comment S... | def configure(cls, cfg):
# Base languages
for x in cls.base_languages:
x_drv = import_component('model', x)
if not x_drv.is_configured(): # pragma: debug
# This shouldn't actually be called because configuration should
# occur on import
... | Python | nomic_cornstack_python_v1 |
import cv2
function draw_str dst target s
begin
set tuple x y = target
call putText dst s tuple x + 1 y + 1 FONT_HERSHEY_PLAIN 1.0 tuple 0 0 0 thickness=2 lineType=LINE_AA
call putText dst s tuple x y FONT_HERSHEY_PLAIN 1.0 tuple 255 255 255 thickness=2 lineType=LINE_AA
end function | import cv2
def draw_str(dst, target, s):
x, y = target
cv2.putText(dst, s, (x + 1, y + 1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness=2, lineType=cv2.LINE_AA)
cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), thickness=2, lineType=cv2.LINE_AA) | Python | zaydzuhri_stack_edu_python |
function dict_to_label dict_data doc_dates
begin
set labels = list
set dict_dates = list comprehension string parse time d string %Y%m%d for d in keys dict_data
for dt in doc_dates
begin
set last_date = max list comprehension d for d in dict_dates if dt > d
set labels = labels + list dict_data at string format time da... | def dict_to_label(dict_data, doc_dates):
labels = []
dict_dates = [datetime.datetime.strptime(d,'%Y%m%d') for d in dict_data.keys()]
for dt in doc_dates:
last_date = max([d for d in dict_dates if dt > d])
labels+=[dict_data[datetime.datetime.strftime(last_date,'%Y%m%d')]]
re... | Python | nomic_cornstack_python_v1 |
function get_best_action self s
begin
set action_value = call forward s
set action = item argument maximum action_value
return action
end function | def get_best_action(self, s: torch.Tensor) -> torch.Tensor:
action_value = self.forward(s)
action = torch.argmax(action_value).item()
return action | Python | nomic_cornstack_python_v1 |
function create_crab_cfg_from_template template varstr dataset outdir=string
begin
set input = call read_template template
set input = replace input string CUTVALS varstr
set input = replace input string DATASET dataset
set input = replace input string DSNAME datasetnames at dataset
if length outdir
begin
set outdir = ... | def create_crab_cfg_from_template(template, varstr, dataset, outdir = ""):
input = read_template(template)
input = input.replace("CUTVALS", varstr)
input = input.replace("DATASET", dataset)
input = input.replace("DSNAME", datasetnames[dataset])
if len(outdir):
outdir = outdir + "/"
... | Python | nomic_cornstack_python_v1 |
function main level to_file
begin
set log_level = level
if not to_file
begin
call basicConfig level=log_level
end
else
begin
call basicConfig level=log_level format=string %(asctime)s %(name)-12s %(levelname)-8s %(message)s filename=string adhoc.log filemode=string a
end
comment NOTE: The executed command is added to t... | def main(level, to_file):
log_level = level
if not to_file:
logging.basicConfig(level=log_level)
else:
logging.basicConfig(level=log_level,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
filename='adhoc.log',
... | Python | nomic_cornstack_python_v1 |
function provide_mpm_for_recipe recipe
begin
print string Providing mpm for package "%s" into result directory %s % tuple name RESULTS_DIR
print string capstan package build
set p = popen split string capstan package build cwd=result_dir stdout=PIPE stderr=PIPE
set tuple output error = communicate p
if returncode != 0
... | def provide_mpm_for_recipe(recipe):
print('Providing mpm for package "%s" into result directory %s' % (recipe.name, RESULTS_DIR))
print('capstan package build')
p = subprocess.Popen(
'capstan package build'.split(),
cwd=recipe.result_dir,
stdout=subprocess.PIPE,
stderr=subpr... | Python | nomic_cornstack_python_v1 |
function _naf mult
begin
set ret = list
while mult
begin
if mult % 2
begin
set nd = mult % 4
if nd >= 2
begin
set nd = nd - 4
end
set ret = ret + list nd
set mult = mult - nd
end
else
begin
set ret = ret + list 0
end
set mult = mult // 2
end
return ret
end function | def _naf(mult):
ret = []
while mult:
if mult % 2:
nd = mult % 4
if nd >= 2:
nd = nd - 4
ret += [nd]
mult -= nd
else:
ret += [0]
mult //= 2
return ret | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
comment 一个集合里面求a+b+c=target最相近的总和
import sys
class Solution
begin
function threeSum self num target
begin
set length = length num
sort num
set near = num at 0 + num at 1 + num at 2
for i in range length
begin
comment 用来去掉重复数据
if i > 0 and num at i == num at i - 1
begin
continue
end
set tuple j k... | #encoding: utf-8
#一个集合里面求a+b+c=target最相近的总和
import sys
class Solution:
def threeSum(self, num, target):
length=len(num)
num.sort()
near=num[0]+num[1]+num[2]
for i in range(length):
if i>0 and num[i]==num[i-1]: continue#用来去掉重复数据
j,k=i+1,length-1
while j<k:
if j>i+1 and num[j]==num[j-1]:
j = j... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string Code to quantize RGB image using k-means clustering
comment Importing Modules
import imageio
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.vq import kmeans2
from skimage import img_as_ubyte as convertToInt
comment Authorship Information
set __author__ = string Ha... | #!/usr/bin/python3
"""Code to quantize RGB image using k-means clustering"""
# Importing Modules
import imageio
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.vq import kmeans2
from skimage import img_as_ubyte as convertToInt
# Authorship Information
__author__ = "Harsh Bhate"
__email__ = "bhat... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
function extract_data data
begin
set f = list
for tuple line n in zip data range length data
begin
set line = strip line string
set cols = split line string ,
set country = strip cols at 0
set alpha2 = strip cols at 1
set alpha3 = strip cols at 2
set code = s... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def extract_data(data):
f = []
for line, n in zip(data, range(len(data))):
line = line.strip('\n ')
cols = line.split(',')
country = cols[0].strip()
alpha2 = cols[1].strip()
alpha3 = cols[2].strip()
code = cols[3].s... | Python | zaydzuhri_stack_edu_python |
function bfs self starting_vertex destination_vertex
begin
comment Create a queue and enqueue starting vertex
set qq = queue
call enqueue list starting_vertex
comment Create a set of traversed vertices
set visited = set
comment While queue is not empty:
while size qq > 0
begin
comment Dequeue/pop the first vertex
set p... | def bfs(self, starting_vertex, destination_vertex):
# Create a queue and enqueue starting vertex
qq = Queue()
qq.enqueue([starting_vertex])
# Create a set of traversed vertices
visited = set()
# While queue is not empty:
while qq.size() > 0:
# Dequeue/... | Python | nomic_cornstack_python_v1 |
function _parse_function example_proto
begin
comment with tf.variable_scope('DataFeedingHelper/parse_function'):
set keys_to_features = dict string x call FixedLenFeature list 39 float32 ; string y call FixedLenFeature list 1 float32
set parsed_features = call parse_single_example example_proto keys_to_features
comment... | def _parse_function(example_proto):
# with tf.variable_scope('DataFeedingHelper/parse_function'):
keys_to_features = {'x': tf.FixedLenFeature([39], tf.float32),
'y': tf.FixedLenFeature([1], tf.float32)}
parsed_features = tf.parse_single_example(example_proto, keys_to_features)
... | Python | nomic_cornstack_python_v1 |
comment FUNCIÓN PARA AÑADIR DOBLE BARRA A UNA RUTA
function funcion_para_añadir_una_barra string
begin
set result = replace string string \ string \\
print result
return result
end function
comment FUNCIÓN PARA SEPARAR UNA COLUMNA EN DOS
function split_columna df columna objeto_separacion numero_veces
begin
set separad... | #FUNCIÓN PARA AÑADIR DOBLE BARRA A UNA RUTA
def funcion_para_añadir_una_barra(string):
result = string.replace("\\", r"\\")
print(result)
return result
#FUNCIÓN PARA SEPARAR UNA COLUMNA EN DOS
def split_columna(df, columna, objeto_separacion, numero_veces):
separado = df[columna].str.split(objeto_sep... | Python | zaydzuhri_stack_edu_python |
from pyspark import SparkConf , SparkContext
from pyspark.sql import SparkSession
from pyspark.mllib.recommendation import ALS
from pyspark.sql.functions import lit
from pyspark.ml.feature import StringIndexer
comment 创建SparkContext和SparkSession
function create_spark_context
begin
set spark_conf = call setMaster string... | from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from pyspark.mllib.recommendation import ALS
from pyspark.sql.functions import lit
from pyspark.ml.feature import StringIndexer
# 创建SparkContext和SparkSession
def create_spark_context():
spark_conf = SparkConf().setAppName('m... | Python | zaydzuhri_stack_edu_python |
function sort_alphabetically my_list
begin
return sorted my_list
end function
comment ['C++', 'Java', 'JavaScript', 'Python']
print call sort_alphabetically my_list | def sort_alphabetically(my_list):
return sorted(my_list)
print(sort_alphabetically(my_list)) # ['C++', 'Java', 'JavaScript', 'Python'] | Python | iamtarun_python_18k_alpaca |
function aggregate uniqueName tag epocTime
begin
if uniqueName not in data
begin
set data at uniqueName = dict
end
if tag in data at uniqueName and data at uniqueName at tag at string time == epocTime
begin
set data at uniqueName at tag = dict string count data at uniqueName at tag at string count + 1 ; string time ep... | def aggregate(uniqueName, tag, epocTime):
if uniqueName not in data:
data[uniqueName] = {}
if tag in data[uniqueName] and data[uniqueName][tag]['time'] == epocTime:
data[uniqueName][tag] = {'count': data[uniqueName][tag]['count'] + 1, 'time': epocTime}
else:
data[uniqueName][tag] = {... | Python | zaydzuhri_stack_edu_python |
from data_structures.node import BinaryTreeNode
function in_order_constant_space root
begin
set temp = root
while temp
begin
if not left
begin
print val end=string
set temp = right
end
else
begin
set left_subtree = left
set left = none
set in_order_parent = call find_in_order_parent left_subtree
set right = temp
set te... | from data_structures.node import BinaryTreeNode
def in_order_constant_space(root):
temp = root
while temp:
if not temp.left:
print(temp.val, end=' ')
temp = temp.right
else:
left_subtree = temp.left
temp.left = None
in_order_parent =... | Python | zaydzuhri_stack_edu_python |
comment Dependencies ###
import argparse
import numpy as np
comment Dependencies ###
comment Create Example Input ###
function Create_Example_Input Rack_Dimensions Initial_Num_Tubes Num_Operations Operation_1_Probability Operation_2_Probability File_Name=string Example_Input
begin
if sum Operation_1_Probability + Opera... | ### Dependencies ###
import argparse
import numpy as np
### Dependencies ###
### Create Example Input ###
def Create_Example_Input(Rack_Dimensions,Initial_Num_Tubes,Num_Operations,Operation_1_Probability,Operation_2_Probability,File_Name="Example_Input"):
if np.sum(Operation_1_Probability+Operation_2_Probability)... | Python | zaydzuhri_stack_edu_python |
function test_delete_list self
begin
call delete_list list_name
set expected_url = string %saudience_lists/%s % tuple base_url quote list_name
set expected_args at string _method = string delete
set expected_args = url encode expected_args
call assert_called_with expected_url expected_args
end function | def test_delete_list(self):
self.mimi.delete_list(self.list_name)
expected_url = '%saudience_lists/%s' % (
self.mimi.base_url, quote(self.list_name))
self.expected_args['_method'] = 'delete'
expected_args = urlencode(self.expected_args)
self.mimi.urlopen.... | Python | nomic_cornstack_python_v1 |
function getAttribute self root
begin
set reuse_values = 0
set func_name = string
set indexVars = dict
for node in walk root
begin
comment Check if a variable is used and assigned in a loop; this is then done repeatedly
if is instance node While or is instance node For
begin
if call checkSubTreeForVarName node is not... | def getAttribute(self, root):
reuse_values = 0
func_name = ""
indexVars = {}
for node in ast.walk(root):
# Check if a variable is used and assigned in a loop; this is then done repeatedly
if isinstance(node, ast.While) or isinstance(node, ast.For):
... | Python | nomic_cornstack_python_v1 |
function get_token client image service
begin
debug string Retrieving access token for image %r and service %r. image service
set data = json get client params=dict string scope string repository: { image } :pull ; string service service
assert is instance data dict
return string data at string token
end function | def get_token(client: Client, image: str, service: str) -> str:
logger.debug("Retrieving access token for image %r and service %r.", image, service)
data = client.get(
params={"scope": f"repository:{image}:pull", "service": service}
).json()
assert isinstance(data, dict)
return str(data["tok... | Python | nomic_cornstack_python_v1 |
function get_table_name all_text
begin
set first_line = call partition string at 0
set match = search string USE \[(\w+)\] first_line IGNORECASE
if match
begin
return call group 1
end
else
begin
return none
end
end function | def get_table_name(all_text):
first_line = all_text.partition("\n")[0]
match = re.search(r"USE \[(\w+)\]", first_line, re.IGNORECASE)
if match:
return match.group(1)
else:
return None | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
from math import ceil
with open string input as f
begin
set ws = list comprehension split replace l string , string for l in read lines f
end
set d = dict
for w in ws
begin
set a = list
set i = 0
while i < length w - 3
begin
append a tuple w at i + 1 integer w at i
set i = i + 2
en... | from collections import defaultdict
from math import ceil
with open('input') as f:
ws = [l.replace(',', '').split() for l in f.readlines()]
d = {}
for w in ws:
a = []
i = 0
while i < len(w)-3:
a.append((w[i+1], int(w[i])))
i += 2
d[w[-1]] = (int(w[-2]), a)
def minbyel(el, needed... | Python | zaydzuhri_stack_edu_python |
string Formatting Template Created on Mon Jan 23 17:32:28 2017 @author: USERNAME and USER Template for formatting raw hospital data. Follow the instructions in the comments and ensure that the code is relevant to your particular source. --potentially more years on the way-- URL
import pandas as pd
import platform
impor... | """
Formatting Template Created on Mon Jan 23 17:32:28 2017
@author: USERNAME and USER
Template for formatting raw hospital data. Follow the instructions in the
comments and ensure that the code is relevant to your particular source.
--potentially more years on the way--
URL
"""
import pandas as pd
import platform
i... | Python | zaydzuhri_stack_edu_python |
function LoadMult *args
begin
comment Getter
if length args == 0
begin
return call CheckForError call Solution_Get_LoadMult
end
comment Setter
set tuple Value = args
call CheckForError call Solution_Set_LoadMult Value
end function | def LoadMult(*args):
# Getter
if len(args) == 0:
return CheckForError(lib.Solution_Get_LoadMult())
# Setter
Value, = args
CheckForError(lib.Solution_Set_LoadMult(Value)) | Python | nomic_cornstack_python_v1 |
function refreshTextItems self
begin
comment If the self.convertObj is None, then try to use the scene if the
comment scene isn't None.
set scene = call scene
if convertObj == none
begin
if scene != none
begin
debug string self.convertObj wasn't set, but self.scene() + string is not None, so we're going to set + string... | def refreshTextItems(self):
# If the self.convertObj is None, then try to use the scene if the
# scene isn't None.
scene = self.scene()
if self.convertObj == None:
if scene != None:
self.log.debug("self.convertObj wasn't set, but self.scene() " +
... | Python | nomic_cornstack_python_v1 |
from app.db import Base
from sqlalchemy import Column , Integer , String
from sqlalchemy.orm import validates
import bcrypt
set salt = call gensalt
class User extends Base
begin
set __tablename__ = string users
set id = call Column Integer primary_key=true
set username = call Column call String 50 nullable=false
set em... | from app.db import Base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import validates
import bcrypt
salt = bcrypt.gensalt()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(50), nullable=False)
email = Column(String(50), nul... | Python | zaydzuhri_stack_edu_python |
set a = integer input string Enter number for start of range
set b = integer input string Enter number for end of range
set i = a
while i <= b
begin
if i % 5 == 0
begin
print i
end
set i = i + 1
end | a=int(input("Enter number for start of range"))
b=int(input("Enter number for end of range"))
i=a
while(i<=b):
if(i%5==0):
print(i)
i=i+1
| Python | zaydzuhri_stack_edu_python |
function _validate_createami_args_ami_compatibility args
begin
set ami_info = call get_info_for_amis list base_ami_id at 0
comment Validate the compatibility of the base_ami to the implied architectures
set ami_architecture = get ami_info string Architecture
if not instance_type
begin
set instance_type = call _get_defa... | def _validate_createami_args_ami_compatibility(args):
ami_info = utils.get_info_for_amis([args.base_ami_id])[0]
# Validate the compatibility of the base_ami to the implied architectures
ami_architecture = ami_info.get("Architecture")
if not args.instance_type:
args.instance_type = _get_default_... | Python | nomic_cornstack_python_v1 |
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
set trainer = call ChatBot string MyChatBot
train trainer ListTrainer
set conversation = read lines open string chats.txt string r
train trainer conversation
while true
begin
set message = input string You:
if strip message != string Bye
begin
s... | from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
trainer = ChatBot('MyChatBot')
trainer.train(ListTrainer)
conversation = open('chats.txt', 'r').readlines()
trainer.train(conversation)
while True:
message = input('You:')
if message.strip() != 'Bye':
reply = tra... | Python | zaydzuhri_stack_edu_python |
comment ???Forgot what this does???###
import json
class Person extends object
begin
function __init__ self firstname lastname
begin
set firstname = firstname
set lastname = lastname
end function
comment Takes the users input and changes it to to dictionary format
function toDictionary self
begin
comment returns the us... | import json ###???Forgot what this does???###
class Person(object):
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
def toDictionary(self): ##Takes the users input and changes it to to dictionary format
#returns the user input class and change... | Python | zaydzuhri_stack_edu_python |
function _isInAllowedRange self testval refval reltol=1e-05
begin
set denom = refval
if refval == 0
begin
if testval == 0
begin
return true
end
else
begin
set denom = testval
end
end
set rdiff = testval - refval / denom
del denom testval refval
return absolute rdiff <= reltol
end function | def _isInAllowedRange( self, testval, refval, reltol=1.0e-5 ):
denom = refval
if refval == 0:
if testval == 0:
return True
else:
denom = testval
rdiff = (testval-refval)/denom
del denom,testval,refval
return (abs(rdiff) <= r... | Python | nomic_cornstack_python_v1 |
import os
import urllib
import urlparse
import shutil
import logging
function fetchArtifact fileUrl destDir
begin
set parsedUrl = url parse fileUrl
set protocol = parsedUrl at 0
set filename = split fileUrl string / at - 1
set filepath = destDir + string / + filename
if not is directory path destDir
begin
make director... | import os
import urllib
import urlparse
import shutil
import logging
def fetchArtifact(fileUrl, destDir):
parsedUrl = urlparse.urlparse(fileUrl)
protocol = parsedUrl[0]
filename = fileUrl.split("/")[-1]
filepath = destDir + '/' + filename
if not os.path.isdir(destDir):
os.makedirs(destDir... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader , RequestContext
from booktest.models import BookInfo
comment Create your views here.
function my_render request html_path context_dict=dict
begin
string # 将使用模板过程封装
comment 1.加载模板文件,返回模板对象
set tem = call get_tem... | from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,RequestContext
from booktest.models import BookInfo
# Create your views here.
def my_render(request, html_path, context_dict={}):
"""# 将使用模板过程封装"""
# 1.加载模板文件,返回模板对象
tem = loader.get_template(html... | Python | zaydzuhri_stack_edu_python |
function log self
begin
set header_dict = dictionary headers
try
begin
set tracker_id = header_dict at string tracker_id
end
except Exception
begin
set tracker_id = none
end
try
begin
set user_agent = header_dict at string User-Agent
end
except Exception
begin
set user_agent = none
end
try
begin
set language = header_d... | def log(self):
header_dict = dict(request.headers)
try:
tracker_id = header_dict["tracker_id"]
except Exception:
tracker_id = None
try:
user_agent = header_dict["User-Agent"]
except Exception:
user_agent = None
try:
language = header_dict["Accept-Language"]
except Exception:
langua... | Python | nomic_cornstack_python_v1 |
function setEventPtr self evPtr
begin
return call LHEF3FromPythia8_setEventPtr self evPtr
end function | def setEventPtr(self, evPtr):
return _pythia8.LHEF3FromPythia8_setEventPtr(self, evPtr) | Python | nomic_cornstack_python_v1 |
comment This is the code for Problem 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import ParameterGrid
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
function generate_dateset num save_file_name fig_title fig_name
begin
comment ------- for... | ### This is the code for Problem 2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import ParameterGrid
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
def generate_dateset(num, save_file_name, fig_title, fig_name):
#------- for negative ... | Python | zaydzuhri_stack_edu_python |
function get_method_returning_field_value self field_name
begin
string Field values can be obtained from view or core.
return call get_method_returning_field_value field_name or call get_method_returning_field_value field_name
end function | def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | Python | jtatman_500k |
function get_attr_value self name
begin
string Retrieve the ``value`` for the attribute ``name``. The ``name`` can be nested following the :ref:`double underscore <tutorial-underscore>` notation, for example ``group__name``. If the attribute is not available it raises :class:`AttributeError`.
if name in dfields
begin
r... | def get_attr_value(self, name):
'''Retrieve the ``value`` for the attribute ``name``. The ``name``
can be nested following the :ref:`double underscore <tutorial-underscore>`
notation, for example ``group__name``. If the attribute is not available it
raises :class:`AttributeError`.'''
if name in self._me... | Python | jtatman_500k |
function edit_profile request
begin
set username = username
set form_class = ProfileForm
if method == string POST
begin
set form = call form_class user=user data=POST
if call is_valid
begin
save
call success request call _ string Successfully edited profile.
return call HttpResponseRedirect reverse string edit_profile
... | def edit_profile(request):
username = request.user.username
form_class = ProfileForm
if request.method == 'POST':
form = form_class(user=request.user, data=request.POST)
if form.is_valid():
form.save()
messages.success(request, _('Successfully edited profile.'))
... | Python | nomic_cornstack_python_v1 |
import sys
set input_ = string read line stdin
function justine input_
begin
comment base case where only 1 character
if length input_ == 1
begin
return string no hiss
end
for x in call xrange 1 length input_
begin
if input_ at x is input_ at x - 1 and input_ at x is string s
begin
return string hiss
end
end
return str... | import sys
input_ = str(sys.stdin.readline())
def justine(input_):
# base case where only 1 character
if len(input_) == 1: return "no hiss"
for x in xrange(1, len(input_)):
if input_[x] is input_[x-1] and input_[x] is 's':
return "hiss"
return "no hiss"
| Python | zaydzuhri_stack_edu_python |
function emitcost t v
begin
set p = op
if kind == TERM
begin
for i in range 0 length children
begin
call emitcost children at i string %s.children[%d] % tuple v i
end
end
else
begin
call printf string ~s.cost[~P~S_NT] + v p
end
end function | def emitcost(t, v):
p = t.op
if p.kind == TERM:
for i in range(0,len(t.children)):
emitcost(t.children[i], "%s.children[%d]" % (v,i))
else:
printf("~s.cost[~P~S_NT] + ", v, p) | Python | nomic_cornstack_python_v1 |
function setup
begin
size 400 400
end function
set lines = list
set index = 0
class myLine
begin
function __init__ self y length
begin
set x = - length
set y = y
set length = length
set speed = random 10 15
set weight = random 1 4
set color = call color random 0 255 0 random 0 255
end function
end class
function creat... | def setup():
size(400, 400)
lines = []
index = 0
class myLine:
def __init__(self, y, length):
self.x = -length
self.y = y
self.length = length
self.speed = random(10, 15)
self.weight = random(1, 4)
self.color = color(random(0, 255), 0, random(0, 255))
def crea... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return string { git_hash } - { sub_revision }
end function | def __str__(self) -> str:
return f'{self.git_hash}-{self.sub_revision}' | Python | nomic_cornstack_python_v1 |
function _step self
begin
comment Retrieve a batch of data from replay.
set inputs : ReplaySample = next _iterator
set data = call batch_to_sequence data
set tuple observations actions rewards discounts extra = tuple observation action reward discount extras
set core_state = call map_structure lambda s -> s at 0 extra ... | def _step(self) -> Dict[str, tf.Tensor]:
# Retrieve a batch of data from replay.
inputs: reverb.ReplaySample = next(self._iterator)
data = tf2_utils.batch_to_sequence(inputs.data)
observations, actions, rewards, discounts, extra = (data.observation,
... | Python | nomic_cornstack_python_v1 |
function pagination self
begin
return _pagination
end function | def pagination(self):
return self._pagination | Python | nomic_cornstack_python_v1 |
comment python indexedSearch.py P.txt T.txt
comment El output debiesen ser los numeros:
comment 123456789 tercero
comment 405487351 noveno
comment 875484321 veintiunavo
comment Cargo P en memoria
comment Armamos arreglo s con primer elemento de cada bloque (leemos 10, avanzamos B - 10, hasta el final)
comment Busqueda ... | #python indexedSearch.py P.txt T.txt
# El output debiesen ser los numeros:
# 123456789 tercero
# 405487351 noveno
# 875484321 veintiunavo
# Cargo P en memoria
# Armamos arreglo s con primer elemento de cada bloque (leemos 10, avanzamos B - 10, hasta el final)
# Busqueda binaria de elementos de P en s para encont... | Python | zaydzuhri_stack_edu_python |
import gevent
from gevent import Timeout
set seconds = 6
set timeout = call Timeout seconds
start timeout
function wait
begin
sleep 5
print string success
end function
try
begin
join call spawn wait
end
except Timeout
begin
print string Could not complete
end
comment style 2
import gevent
from gevent import Timeout
com... | import gevent
from gevent import Timeout
seconds = 6
timeout = Timeout(seconds)
timeout.start()
def wait():
gevent.sleep(5)
print('success')
try:
gevent.spawn(wait).join()
except Timeout:
print('Could not complete')
############ style 2
import gevent
from gevent import Timeout
time_to_wait = 5 # ... | Python | zaydzuhri_stack_edu_python |
function find_input_usage self full_usage_id
begin
string Check if full usage Id included in input reports set Parameters: full_usage_id Full target usage, use get_full_usage_id Returns: Report ID as integer value, or None if report does not exist with target usage. Nottice that report ID 0 is a valid report.
for tuple... | def find_input_usage(self, full_usage_id):
"""Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist with
targe... | Python | jtatman_500k |
function subarraysDivByK A K
begin
set solution = list
set first = 0
set second = 1
while first < length A
begin
set sub_sum = sum A at slice first : second :
if sub_sum % K
begin
append solution sub_sum
end
if sub_sum < K / 2
begin
set second = second + 1
end
if sub_sum >= K / 2
begin
set first = first + 1
end
end
re... | def subarraysDivByK(A, K):
solution = []
first = 0
second = 1
while first < len(A):
sub_sum = sum(A[first:second])
if sub_sum % K:
solution.append(sub_sum)
if sub_sum < K / 2:
second += 1
if sub_sum >= K / 2:
first += 1
return... | Python | zaydzuhri_stack_edu_python |
import sys
import math
set stdin = open string discuss.in string r
set stdout = open string discuss.out string w
set z = integer call raw_input
set ans = z
set div = list 0 * 205
function calc x y
begin
set ans = 1
for i in range 1 y + 1
begin
set ans = ans * x + 1 - i
end
set ans = ans / div at y
return ans
end functi... | import sys
import math
sys.stdin = open("discuss.in", "r")
sys.stdout = open("discuss.out", "w")
z = int(raw_input())
ans = z
div = [0] * 205
def calc(x, y):
ans = 1
for i in range(1, y + 1):
ans = ans * (x + 1 - i)
ans = ans / div[y]
return ans
def pow_mod(a, b):
ans = 1
while b:
... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment WARNING: you must use send_back() to return data to the parent process.
set instruction = argv at 1
set data = loads join string read lines stdin
if instruction == string build3d
begin
from qmt.geometry.freecad.objectConstruction import build
call activate_doc_from data at string current_op... | def main():
# WARNING: you must use send_back() to return data to the parent process.
instruction = sys.argv[1]
data = pickle.loads(''.join(sys.stdin.readlines()))
if instruction == 'build3d':
from qmt.geometry.freecad.objectConstruction import build
activate_doc_from(data['current_opt... | Python | nomic_cornstack_python_v1 |
string For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. Example 1: Input: A = [1,2,0,0], K = 34 Output: [1,2,3,4] E... | '''
For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.
Example 1:
Input: A = [1,2,0,0], K = 34
Output: [1,2,3,... | Python | zaydzuhri_stack_edu_python |
class Book
begin
function __init__ self title author year genre
begin
set title = title
set author = author
set year = year
set genre = genre
set ratings = list
end function
function add_rating self rating
begin
append ratings rating
end function
function average_rating self
begin
if length ratings == 0
begin
return 0... | class Book:
def __init__(self, title, author, year, genre):
self.title = title
self.author = author
self.year = year
self.genre = genre
self.ratings = []
def add_rating(self, rating):
self.ratings.append(rating)
def average_rating(self):
if len(self.... | Python | jtatman_500k |
comment Daniel Pingrey
comment 1/20
comment Vacation Planner
import datetime
import math
import random
comment tuple of activities and their costs
set options = tuple string Snorkeling string Scuba Diving string Fishing string Sunbathing string Shopping string Helicopter Ride string Sleeping
set prices = tuple 10.0 150... | #Daniel Pingrey
#1/20
#Vacation Planner
import datetime
import math
import random
#tuple of activities and their costs
options = ("Snorkeling","Scuba Diving","Fishing","Sunbathing","Shopping","Helicopter Ride","Sleeping")
prices = (10.00, 150.00, 25.00, 0.00, 200.00, 450.00, 0.00)
#Gets and converts starting date
s... | Python | zaydzuhri_stack_edu_python |
function generate_ftp_fqn file_path
begin
set u = cfg at string ftp at string username
set p = cfg at string ftp at string passwd
set h = cfg at string ftp at string host
return format string ftp://{u}:{p}@{h}{file_path} u=u p=p h=h file_path=file_path
end function | def generate_ftp_fqn(file_path):
u = cfg['ftp']['username']
p = cfg['ftp']['passwd']
h = cfg['ftp']['host']
return 'ftp://{u}:{p}@{h}{file_path}'.format(u=u, p=p, h=h, file_path=file_path) | Python | nomic_cornstack_python_v1 |
class Chore
begin
comment Is the task completed or not
comment Task List
function __init__ self description completed user
begin
set description = description
set completed = completed
set user = user
end function
function isCompleted self
begin
return completed
end function
function setCompleted self completed
begin
s... | #
#
#
#
class Chore:
# Is the task completed or not
# Task List
def __init__ (self,description, completed, user):
self.description = description
self.completed = completed
self.user = user
def isCompleted(self):
return self.completed
def setCompleted(self, completed):
self.completed = completed
def ge... | 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.