code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function sort_nicely self names
begin
set convert = lambda text -> if expression is digit text then integer text else lower text
set alphanum_key = lambda key -> list comprehension call convert c for c in split re string ([0-9]+) key
sort names key=alphanum_key
end function | def sort_nicely(self, names):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
names.sort(key=alphanum_key) | Python | nomic_cornstack_python_v1 |
function _get_type self obj
begin
set typever = obj at string Type
set typesplit = split typever string .
return typesplit at 0 + string . + typesplit at 1
end function | def _get_type(self, obj):
typever = obj['Type']
typesplit = typever.split('.')
return typesplit[0] + '.' + typesplit[1] | Python | nomic_cornstack_python_v1 |
class Mathematician
begin
function square_nums self squared
begin
set squared = squared
set squared = list comprehension s ^ 2 for s in squared
return squared
end function
function remove_positives self positives
begin
set positives = positives
set positives = list comprehension p for p in positives if p < 0
return pos... | class Mathematician:
def square_nums(self, squared):
self.squared = squared
self.squared = [s**2 for s in self.squared]
return self.squared
def remove_positives(self, positives):
self.positives = positives
self.positives = [p for p in self.positives if p < 0]
re... | Python | zaydzuhri_stack_edu_python |
import re
from util import timer , read_chunks
set ANSWER_PATTERN = compile string [a-z]
function read_group_answers path
begin
set group_answers = list
for chunk in call read_chunks path
begin
set answers = set
for line in chunk
begin
for letter in line
begin
if match ANSWER_PATTERN letter
begin
add answers letter
en... | import re
from util import timer, read_chunks
ANSWER_PATTERN = re.compile(r"[a-z]")
def read_group_answers(path: str) -> list:
group_answers = []
for chunk in read_chunks(path):
answers = set()
for line in chunk:
for letter in line:
if re.match(ANSWER_PATTERN, let... | Python | zaydzuhri_stack_edu_python |
comment https://atcoder.jp/contests/abs/tasks/abc081_b
set n = integer input
set A_n_list = list comprehension integer s for s in split input
set count = 0
set ans = 0
while 1
begin
for A_n in A_n_list
begin
if A_n % 2 == 0
begin
set count = count + 1
end
end
if count == n
begin
set i = 0
for A_n in A_n_list
begin
set ... | # https://atcoder.jp/contests/abs/tasks/abc081_b
n = int(input())
A_n_list = [int(s) for s in input().split()]
count = 0
ans = 0
while(1):
for A_n in A_n_list:
if A_n % 2 == 0:
count += 1
if count == n:
i = 0
for A_n in A_n_list:
A_n_list[i] = A_n // 2
... | Python | zaydzuhri_stack_edu_python |
import csv
import pandas as pd
import json
comment Load descriptive data on cities:
set cities_data = read csv string cities_data_clean.csv encoding=string utf-8 lineterminator=string
set cities_locs = list
for tuple index row in call iterrows
begin
set lat = loc at tuple index string Latitude
set lng = loc at tuple i... | import csv
import pandas as pd
import json
# Load descriptive data on cities:
cities_data = pd.read_csv('cities_data_clean.csv',encoding='utf-8',
lineterminator='\n')
cities_locs = []
for index,row in cities_data.iterrows():
lat = cities_data.loc[index,'Latitude']
lng = cities_data.loc[index,'Longitude']... | Python | zaydzuhri_stack_edu_python |
function revcomp sequence
begin
return join string generator expression get rc_dict c c for c in reversed upper sequence
end function | def revcomp(sequence):
return ''.join(revcomp.rc_dict.get(c, c) for c in reversed(sequence.upper())) | Python | nomic_cornstack_python_v1 |
function generate_cache_key value
begin
string Generates a cache key for the *args and **kwargs
if call is_bytes value
begin
return hex digest md5 value
end
else
if call is_text value
begin
return call generate_cache_key call to_bytes text=value
end
else
if call is_boolean value or call is_null value or call is_number ... | def generate_cache_key(value):
"""
Generates a cache key for the *args and **kwargs
"""
if is_bytes(value):
return hashlib.md5(value).hexdigest()
elif is_text(value):
return generate_cache_key(to_bytes(text=value))
elif is_boolean(value) or is_null(value) or is_number(value):
... | Python | jtatman_500k |
comment !/usr/bin/env python
from spf.mr.lambda_.term import Term
from spf.mr.lambda_.visitor.api import LogicalExpressionVisitorI
class LogicalExpressionToString extends LogicalExpressionVisitorI
begin
function __init__ self
begin
set output_string = string
set variable_naming_list = list
set defined_variables = set... | #!/usr/bin/env python
from spf.mr.lambda_.term import Term
from spf.mr.lambda_.visitor.api import LogicalExpressionVisitorI
class LogicalExpressionToString(LogicalExpressionVisitorI):
def __init__(self):
self.output_string = ""
self.variable_naming_list = []
self.defined_variables = set()
... | Python | zaydzuhri_stack_edu_python |
function mscan fp
begin
set data = load json fp
set suite = none
set calls = list
set rel = call TestSet split string suite calls path testnum shared
for testcase in data at string testcases
begin
set name = testcase at string name
set tuple tsuite rest = split name string - 1
if suite is none
begin
set suite = tsuite... | def mscan(fp):
data = json.load(fp)
suite = None
calls = []
rel = TestSet('suite calls path testnum shared'.split())
for testcase in data['testcases']:
name = testcase['name']
tsuite, rest = name.split('-', 1)
if suite is None:
suite = tsuite
elif suite... | Python | nomic_cornstack_python_v1 |
function list_provider_traits self rp_uuid
begin
set url = string /resource_providers/%s/traits % rp_uuid
set tuple resp body = get self url
call expected_success 200 status
set body = loads body
return call ResponseBody resp body
end function | def list_provider_traits(self, rp_uuid):
url = '/resource_providers/%s/traits' % rp_uuid
resp, body = self.get(url)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body) | Python | nomic_cornstack_python_v1 |
function get_object_fields_from_dict self data defaults=none saved_objects=none
begin
from models import Repository
set url = get data string url
set fields = call get_object_fields_from_dict data defaults saved_objects
if not fields
begin
return none
end
comment add the repository if needed
if not get fields at string... | def get_object_fields_from_dict(self, data, defaults=None, saved_objects=None):
from .models import Repository
url = data.get('url')
fields = super(WithRepositoryManager, self).get_object_fields_from_dict(
data, defaults, saved_objects)
i... | Python | nomic_cornstack_python_v1 |
function output_imap_message_parts parts body_encoding
begin
comment MMDF delimiter
print string
print call extract_imap_message_parts parts body_encoding
comment MMDF delimiter
print string
end function | def output_imap_message_parts(parts, body_encoding):
print('\1\1\1\1') # MMDF delimiter
print(extract_imap_message_parts(parts, body_encoding))
print('\1\1\1\1') # MMDF delimiter | Python | nomic_cornstack_python_v1 |
for tuple item price in items_with_price
begin
set total = total + price
end
print string The total cost is $ { total } | for item, price in items_with_price:
total += price
print(f'The total cost is ${total}') | Python | jtatman_500k |
comment !/usr/bin/env python
comment -*-coding:utf-8 -*-
string Name:HD Twsited是一个时间驱动的网络框架,其中包含了诸多功能m例如:网络协议,线程,数据库管理,网络操作,电子邮件等
string Protocols Protocols 描述了如何以异步的方式处理网络中的事件,http,SND以及IMAP是应用层协议中的例子 Protocols 实现了IProtoco接口,它包含如下的方法: makeConnection 在transport对象和服务器之间建立一条连接 connectionMade 连接建立起来之后调用 dataReceived 接受数据时... | #!/usr/bin/env python
#-*-coding:utf-8 -*-
'''
Name:HD
Twsited是一个时间驱动的网络框架,其中包含了诸多功能m例如:网络协议,线程,数据库管理,网络操作,电子邮件等
'''
r'''
Protocols
Protocols 描述了如何以异步的方式处理网络中的事件,http,SND以及IMAP是应用层协议中的例子
Protocols 实现了IProtoco接口,它包含如下的方法:
makeConnection 在transport对象和服务器之间建立一条连接
conne... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Open data file and create a new data file with pseudo-random data selected from the original file. Input file should have rows with columns of format: n Vs1 Vs2 Vp WARNING: NOT FINISHED YET To be done: -Problem: The output file can contain any number of data points -Generalize file l... | #!/usr/bin/env python
'''
Open data file and create a new data file with pseudo-random data selected from the original file.
Input file should have rows with columns of format:
n Vs1 Vs2 Vp
WARNING: NOT FINISHED YET
To be done:
-Problem: The output file can contain any number of data points
-Gene... | Python | zaydzuhri_stack_edu_python |
comment '''
comment from bs4 import BeautifulSoup
import requests
import re
set input_arr = list string 666039017
set req = get requests string http://allegro.pl/samsung-galaxy-s2-i9100-bialy-wysylka-z-polski-i7014133170.html
set data = string text
set p = compile string \d\d\d\s*\d\d\d\s*\d\d\d
set m = find all data
s... | #'''
#from bs4 import BeautifulSoup
import requests
import re
input_arr = ["666039017"]
req = requests.get("http://allegro.pl/samsung-galaxy-s2-i9100-bialy-wysylka-z-polski-i7014133170.html")
data = str(req.text)
p = re.compile("\d\d\d\s*\d\d\d\s*\d\d\d")
m = p.findall(data)
delArr = []
for i in range(len(m)):
... | Python | zaydzuhri_stack_edu_python |
function deleteById id
begin
set data : dict = dict
set data = delete
commit session
set data = dict string status string Deleted
return data
end function | def deleteById(id) -> dict:
data: dict = {}
data = Cart.query.filter_by(id=id).delete()
db.session.commit()
data = {
'status': 'Deleted ' ,
}
return data | Python | nomic_cornstack_python_v1 |
set a = list 0 1 2 3 4 5 6 7 8 9
print list permutations a |
a=[0,1,2,3,4,5,6,7,8,9]
print(list(itertools.permutations(a))) | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
string 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: - 所有数字(包括 target)都是正整数。 - 解集不能包含重复的组合。 思路: 回溯+剪枝 控制迭代的此说: target-i<0 则跳过 res[-1]>i 则跳过
class Solution extends object
begin
function combinationSum self candidates target
begin
string :t... | # coding:utf-8
'''
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
- 所有数字(包括 target)都是正整数。
- 解集不能包含重复的组合。
思路:
回溯+剪枝
控制迭代的此说:
target-i<0 则跳过
res[-1]>i 则跳过
'''
class Solution(object):
def combinationSum(self, candidates, target):
"""
:t... | Python | zaydzuhri_stack_edu_python |
function ping self
begin
string send ping packet to tarantool server and receive response with empty body
set d = call get_ping
set packet = call RequestPing charset errors
write transport bytes packet
return call addCallback handle_reply charset errors none
end function | def ping(self):
"""
send ping packet to tarantool server and receive response with empty body
"""
d = self.replyQueue.get_ping()
packet = RequestPing(self.charset, self.errors)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charse... | Python | jtatman_500k |
function reorder_examples self
begin
call example_wise_shrink Ordering key=sort_key
end function | def reorder_examples(self):
self.example_wise_shrink(Ordering, key=sort_key) | Python | nomic_cornstack_python_v1 |
import pyautogui
comment 点击过快时会导致失控,所以禁用
set FAILSAFE = false
set tuple width hight = size pyautogui
print width hight
comment 获取鼠标的当前位置
set tuple x y = call position
print x y
comment duration是移动的时间
call moveTo 300 300 duration=1
set tuple x y = call position
print x y
comment 用键盘输入,第二个入口参数时延时的时间
call typewrite string... | import pyautogui
#点击过快时会导致失控,所以禁用
pyautogui.FAILSAFE = False
width,hight=pyautogui.size()
print(width,hight)
#获取鼠标的当前位置
x, y = pyautogui.position()
print(x,y)
#duration是移动的时间
pyautogui.moveTo(300,300,duration=1)
x, y = pyautogui.position()
print(x,y)
#用键盘输入,第二个入口参数时延时的时间
pyautogui.typewrite('Hello world!', 0.25)
pyauto... | Python | zaydzuhri_stack_edu_python |
function area_rect
begin
set length = integer input string Enter the length =
set breadth = integer input string Enter the breadth =
set result = length * breadth
return result
end function
function area_circle
begin
set pie = 3.14
set radius = integer input string Enter the radius :
set result = pie * radius * radius
... | def area_rect():
length =int(input("Enter the length ="))
breadth=int(input("Enter the breadth ="))
result=length*breadth
return result
def area_circle():
pie=3.14
radius=int(input("Enter the radius :"))
result=pie*radius*radius
return result
def area_triangle():
length =int(input("Enter the le... | Python | zaydzuhri_stack_edu_python |
for i in range 1 d + 1
begin
for ele in ls
begin
if i % ele == 0
begin
append lsf i
end
end
end
print length set lsf | for i in range(1, d + 1):
for ele in ls:
if (i % ele == 0):
lsf.append(i)
print(len(set(lsf)))
| Python | zaydzuhri_stack_edu_python |
function add_validator self validator
begin
if not callable validator
begin
raise call TypeError string Argument "validator" must be Callable.
end
append validators validator
return validator
end function | def add_validator(self, validator: ValidatorType):
if not callable(validator):
raise TypeError('Argument "validator" must be Callable.')
self.validators.append(validator)
return validator | Python | nomic_cornstack_python_v1 |
function bootstrapObservations df dmatFunc clusterFunc bootstraps=100 rseed=110820
begin
seed rseed
set dmat = call dmatFunc df
set Nobs = shape at 0
set N = shape at 1
assert N == shape at 0
assert N == shape at 1
set pwrel = zeros tuple N N
string Keep track of the number of times that two variables are sampled toget... | def bootstrapObservations(df, dmatFunc, clusterFunc, bootstraps = 100, rseed = 110820):
np.random.seed(rseed)
dmat = dmatFunc(df)
Nobs = df.shape[0]
N = df.shape[1]
assert N == dmat.shape[0]
assert N == dmat.shape[1]
pwrel = np.zeros((N, N))
"""Keep track of the number of times that ... | Python | nomic_cornstack_python_v1 |
function get self request format=none
begin
set wfs = keys reg
set out = list
for w in wfs
begin
append out call get_workflow_meta w
end
return call Response out
end function | def get(self, request, format=None):
wfs = wf_register.reg.keys()
out = []
for w in wfs:
out.append(get_workflow_meta(w))
return Response(out) | Python | nomic_cornstack_python_v1 |
function bu_machine_count bu_id
begin
comment Get the BusinessUnit
set business_unit = call get_object_or_404 BusinessUnit pk=bu_id
set machine_groups = all
set count = 0
for machinegroup in machine_groups
begin
set count = count + count filter deployed=true
end
return count
end function | def bu_machine_count(bu_id):
# Get the BusinessUnit
business_unit = get_object_or_404(BusinessUnit, pk=bu_id)
machine_groups = business_unit.machinegroup_set.all()
count = 0
for machinegroup in machine_groups:
count = count + machinegroup.machine_set.filter(deployed=True).count()
return ... | Python | nomic_cornstack_python_v1 |
function ram_usage self
begin
set proc = process call getpid
return format string Ram : {0} MB | round call memory_info at 0 / 1024 * 1024 1
end function | def ram_usage(self):
proc = psutil.Process(os.getpid())
return "Ram : {0} MB |".format(round(proc.memory_info()[0]/(1024*1024), 1)) | Python | nomic_cornstack_python_v1 |
function test_project_contributor_cannot_update self
begin
set collaborator = first call order_by string ?
comment Authenticate the client as an contributor of the project
call authenticateAsProjectContributor project
comment This should be permission denied as the user is permitted to view the collaborator
call assert... | def test_project_contributor_cannot_update(self):
collaborator = Collaborator.objects.order_by('?').first()
# Authenticate the client as an contributor of the project
self.authenticateAsProjectContributor(collaborator.project)
# This should be permission denied as the user is permitted t... | Python | nomic_cornstack_python_v1 |
function is_unique_use g node args
begin
set users = graph_users
return length users == 1 and sum values users == 1
end function | def is_unique_use(g, node, args):
users = g.graph_users
return len(users) == 1 and sum(users.values()) == 1 | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
comment -*- author: liupeng -*-
comment -*- fileName: work4-5.py -*-
comment -*- data: 2019-11-04 -*-
set n = integer input
if n % 2 == 0
begin
print integer 0 - n / 2
end
else
begin
print 1 + integer n / 2
end | # -*- coding: UTF-8 -*-
# -*- author: liupeng -*-
# -*- fileName: work4-5.py -*-
# -*- data: 2019-11-04 -*-
n = int(input())
if n%2==0:
print(int(0-n/2))
else:
print(1+int(n/2)) | Python | zaydzuhri_stack_edu_python |
function csv_writer data path
begin
with open path string wb as csv_file
begin
set writer = writer csv_file delimiter=string ,
comment for line in data:
comment writer.writerow(line)
for item in data at 0
begin
set new_list = list
append new_list item
append new_list list1 at item - 1
append new_list list2 at item - 1... | def csv_writer(data, path):
with open(path, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
# for line in data:
# writer.writerow(line)
for item in data[0]:
new_list = []
new_list.append(item)
new_list.append(list1[item - 1])
... | Python | nomic_cornstack_python_v1 |
comment Code to automatically refresh Power BI dataset
comment Takes environment variables as inputs
comment Meant to be triggered as Kubernetes task
comment Version history
comment 1.0 10.10.2019 Mika Heino - First working version using Kubernetes ENV and secrets
comment 1.1 12.10.2019 Heino - Added environment parame... | # Code to automatically refresh Power BI dataset
#
# Takes environment variables as inputs
# Meant to be triggered as Kubernetes task
#
#
# Version history
# 1.0 10.10.2019 Mika Heino - First working version using Kubernetes ENV and secrets
# 1.1 12.10.2019 Heino - Added environment parameters This package is for Power... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ scripts=none
begin
if scripts is not none
begin
set __self__ string scripts scripts
end
end function | def __init__(__self__, *,
scripts: Optional['outputs.ScriptsToExecuteResponse'] = None):
if scripts is not None:
pulumi.set(__self__, "scripts", scripts) | Python | nomic_cornstack_python_v1 |
string Exceptions which may occur within this automation framework.
class FrameworkException extends Exception
begin
string Base framework exception.
function __init__ self message=none stacktrace=none
begin
set message = message
set stacktrace = stacktrace
end function
function __str__ self
begin
set exception_message... | """Exceptions which may occur within this automation framework."""
class FrameworkException(Exception):
"""Base framework exception."""
def __init__(self, message: str = None, stacktrace: str = None):
self.message = message
self.stacktrace = stacktrace
def __str__(self):
exceptio... | Python | zaydzuhri_stack_edu_python |
comment CREATE YOUR STATE FUNCTIONS HERE ###########################
import my_ui
function _init
begin
call _init
return string main_menu
end function
function _error
begin
call _error
return string main_menu
end function
function _exit
begin
_exit
exit
end function
function main_menu
begin
call main_menu
try
begin
set... | ################### CREATE YOUR STATE FUNCTIONS HERE ###########################
import my_ui
def _init():
my_ui._init()
return 'main_menu'
def _error():
my_ui._error()
return 'main_menu'
def _exit():
my_ui._exit
exit()
def main_menu():
my_ui.main_menu()
try:
next_state = in... | Python | zaydzuhri_stack_edu_python |
string ------------------------------------------------------------------------------ Course: CSE 251 Lesson Week: 02 File: assignment.py Author: Brother Comeau Purpose: Retrieve Star Wars details from a website Instructions: - each API call must only retrieve one piece of information - You are not allowed to use any o... | """
------------------------------------------------------------------------------
Course: CSE 251
Lesson Week: 02
File: assignment.py
Author: Brother Comeau
Purpose: Retrieve Star Wars details from a website
Instructions:
- each API call must only retrieve one piece of information
- You are not allowed to use any... | Python | zaydzuhri_stack_edu_python |
function test_create self
begin
set f = open string ./tests/increatetest.txt string r
set cmdp = call HBNBCommand stdin=f stdout=outbuffer
set use_rawinput = false
set prompt = string
with redirect stdout outbuffer
begin
call cmdloop
end
close f
set ids = call getvalue
set ids = split ids string
set objects = all
end ... | def test_create(self):
f = open("./tests/increatetest.txt", "r")
cmdp = console.HBNBCommand(stdin=f, stdout=outbuffer)
cmdp.use_rawinput = False
cmdp.prompt = ""
with redirect_stdout(outbuffer):
cmdp.cmdloop()
f.close()
ids = outbuffer.getvalue()
... | Python | nomic_cornstack_python_v1 |
function identities self identities
begin
set _identities = identities
end function | def identities(self, identities):
self._identities = identities | Python | nomic_cornstack_python_v1 |
function find_causes data
begin
comment identify the root cause of the bug
set causes = set
for line in data
begin
for cause in get line string causes list
begin
add causes cause
end
end
comment filter insignificant causes
set causes = list comprehension cause for cause in causes if cause not in insignificant_causes
re... | def find_causes(data):
# identify the root cause of the bug
causes = set()
for line in data:
for cause in line.get('causes', []):
causes.add(cause)
# filter insignificant causes
causes = [cause for cause in causes if cause not in insignificant_causes]
return causes | Python | jtatman_500k |
while true
begin
set line = call raw_input string Enter a number :
if line == string done
begin
break
end
try
begin
set tes = decimal line
end
except any
begin
print string Invalid number
end
try else
begin
set jumlah = jumlah + decimal line
set lst = lst + 1
end
end | while True:
line = raw_input('Enter a number : ')
if line == 'done':
break
try:
tes = float(line)
except:
print ('Invalid number')
else :
jumlah = jumlah + float(line)
lst = lst + 1
| Python | zaydzuhri_stack_edu_python |
import discord
set client = call Client
decorator event
async function on_ready
begin
print string Logged in as { user }
end function
decorator event
async function on_message message
begin
if content == string !hello
begin
await call send string Hello!
end
end function
run string your_token_here
comment This will crea... | import discord
client = discord.Client()
@client.event
async def on_ready():
print(f'Logged in as {client.user}')
@client.event
async def on_message(message):
if message.content == '!hello':
await message.channel.send('Hello!')
client.run('your_token_here')
# This will create a Discord bot that responds... | Python | flytech_python_25k |
comment !/usr/bin/python3.8
comment 7. В одномерном массиве целых чисел определить два наименьших элемента.
comment Они могут быть как равны между собой (оба являться минимальными), так и различаться.
from random import randint
set array = list comprehension random integer 1 20 for i in range 10
print array
set min1 = ... | #!/usr/bin/python3.8
# 7. В одномерном массиве целых чисел определить два наименьших элемента.
# Они могут быть как равны между собой (оба являться минимальными), так и различаться.
from random import randint
array = [randint(1, 20) for i in range(10)]
print(array)
min1 = min(array)
array.remove(min1)
min2 = mi... | Python | zaydzuhri_stack_edu_python |
function get_delivery_vehicles_available vehicles
begin
set available_delivery_vehicles = list
for vehicle_type in vehicles
begin
extend available_delivery_vehicles all
end
return available_delivery_vehicles
end function | def get_delivery_vehicles_available(vehicles):
available_delivery_vehicles = []
for vehicle_type in vehicles:
available_delivery_vehicles.extend(
DeliveryVehicle.objects.filter(vehicle_type=vehicle_type).all()
)
return available_delivery_vehicles | Python | nomic_cornstack_python_v1 |
import sys
set MASTERPASSWORD = string opensesame
set password = input string Please enter the super secret password:
set attempt_count = 1
while password != MASTERPASSWORD
begin
if attempt_count > 3
begin
exit string Too many invalid password attempts
end
set password = input string Invalid password, please try again:... | import sys
MASTERPASSWORD = 'opensesame'
password = input("Please enter the super secret password: ")
attempt_count = 1
while password != MASTERPASSWORD:
if attempt_count > 3:
sys.exit("Too many invalid password attempts")
password = input("Invalid password, please try again: ")
attempt_count += 1
... | Python | zaydzuhri_stack_edu_python |
function skydiving_iterate v t dt X Y
begin
return v + dt * call X t / 1 + dt * call Y t * absolute v
end function | def skydiving_iterate(v, t, dt, X, Y):
return (v + dt*X(t))/(1 + dt*Y(t)*abs(v)) | Python | nomic_cornstack_python_v1 |
comment 初始化cell狀態
call dynamic_rnn cell inputs sequence_length=none initial_state=none dtype=none parallel_iterations=none swap_memory=false time_major=false scope=none | #初始化cell狀態
tf.nn.dynamic_rnn(
cell,
inputs,
sequence_length=None,
initial_state=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None
) | Python | zaydzuhri_stack_edu_python |
function test_visibility_of_popup_elements self
begin
set login_popup = call LoginPopup
assert call is_email_field_visible is true msg string The email field is not visible
assert call is_pass_field_visible is true msg string The password field is not visible
assert call is_submit_btn_visible is true msg string The "Su... | def test_visibility_of_popup_elements(self):
login_popup = LoginPopup()
assert login_popup.is_email_field_visible() is True, 'The email field is not visible'
assert login_popup.is_pass_field_visible() is True, 'The password field is not visible'
assert login_popup.is_submit_btn_visible()... | Python | nomic_cornstack_python_v1 |
import numpy as np
set one_point_array = array list 0.166 0.164 0.168 0.168 0.169 0.167 0.167 0.168 0.17 0.169
set around_neck_array = array list 0.169 0.17 0.187 0.177 0.196 0.191 0.197 0.176
set error_mean_one_point = standard deviation np one_point_array / square root length one_point_array
set error_mean_around_nec... | import numpy as np
one_point_array = np.array([0.166, 0.164, 0.168, 0.168, 0.169, 0.167, 0.167, 0.168, 0.170, 0.169])
around_neck_array = np.array([0.169, 0.170, 0.187, 0.177, 0.196, 0.191, 0.197, 0.176])
error_mean_one_point = np.std(one_point_array) / np.sqrt(len(one_point_array))
error_mean_around_neck = np.std(ar... | Python | zaydzuhri_stack_edu_python |
function mass self
begin
return data
end function | def mass(self) -> SparseVector|SparseArray:
return self.imass.data | Python | nomic_cornstack_python_v1 |
function recursively_rename_files
begin
set ordered_equipts = call get_directory_definition
comment Iterates each equipement folder
for ii in ordered_equipts
begin
call iterate_dir ii index ordered_equipts ii
end
end function | def recursively_rename_files():
ordered_equipts = get_directory_definition()
# Iterates each equipement folder
for ii in ordered_equipts:
iterate_dir(ii, ordered_equipts.index(ii)) | Python | nomic_cornstack_python_v1 |
function lr_schedule epoch
begin
set learning_rate = 0.02
if epoch > 2
begin
set learning_rate = 0.0002
end
if epoch > 5
begin
set learning_rate = 0.0001
end
if epoch > 8
begin
set learning_rate = 5e-05
end
if epoch > 12
begin
set learning_rate = 1e-05
end
comment tf.summary.scalar('learning rate', data=learning_rate, ... | def lr_schedule(epoch):
learning_rate = 0.02
if epoch > 2:
learning_rate = 0.0002
if epoch > 5:
learning_rate = 0.0001
if epoch > 8:
learning_rate = 0.00005
if epoch > 12:
learning_rate = 0.00001
#tf.summary.scalar('learning rate', data=learning_rate, step=epoch)... | Python | nomic_cornstack_python_v1 |
comment Squared in list
set list1 = list 4 6 1 2 5 6
set squaredList = list comprehension x ^ 2 for x in list1
print squaredList
comment conversion in dict
set dict_list = dictionary comprehension x : x ^ 2 for x in list1
print dict_list
comment combining multiple list in one
set a = list 1 2 3
set b = list 5 6 7
set c... | # Squared in list
list1 = [4, 6, 1, 2, 5, 6]
squaredList = [x**2 for x in list1]
print(squaredList)
# conversion in dict
dict_list = {x: x**2 for x in list1}
print(dict_list)
# combining multiple list in one
a = [1, 2, 3]
b = [5, 6, 7]
combined_List = [(x+y) for (x, y) in zip(a, b)]
print(combined_List)
print(a + b)... | Python | zaydzuhri_stack_edu_python |
function Merhaba isim soyisim
begin
print string Hoşgeldiniz isim soyisim
end function
call Merhaba string Said string Katmerlikaya | def Merhaba (isim,soyisim):
print ("Hoşgeldiniz",isim,soyisim)
Merhaba ("Said","Katmerlikaya")
| Python | zaydzuhri_stack_edu_python |
function pobj_globals pcode_obj
begin
set html_str = list
comment no multiple pcode blocks - no delimiter
set pcode = call asDict at string pcode at 0
comment {:::: } # pcodeopts = pcode['pcodeopts']
set pcodeopts = pop pcode string pcodeopts list list string
end function | def pobj_globals(pcode_obj):
html_str = []
pcode = (pcode_obj.asDict())['pcode'][0] # no multiple pcode blocks - no delimiter
pcodeopts = pcode.pop('pcodeopts', [['']]) # {:::: } # pcodeopts = pcode['pcodeopts'] | Python | nomic_cornstack_python_v1 |
comment python script to create loading diagram
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy import integrate
comment import big ass list
comment Ldistr = [......]
function genLoadDiagram Ldistr
begin
set Ldistr at 0 = 0
append Ldistr 0
set LdistrArr = - 1 * array Ldistr
set Ldistr =... | # python script to create loading diagram
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy import integrate
# import big ass list
# Ldistr = [......]
def genLoadDiagram(Ldistr):
Ldistr[0] = 0
Ldistr.append(0)
LdistrArr = -1 * np.array(Ldistr)
Ldistr = list(... | Python | zaydzuhri_stack_edu_python |
function select_items keyword
begin
import connect
import pymysql
set conn = call connect
set cur = call cursor DictCursor
set keyword = string % + keyword + string %
set sql = string select 商品情報一覧テーブル.商品コード, 商品情報一覧テーブル.商品名, 商品詳細, 現在価格, (定価 - 現在価格) as '割引額', 分類名, CAST(在庫数 AS SIGNED) AS 在庫数,税率 from 商品情報一覧テーブル inner join... | def select_items(keyword):
import connect
import pymysql
conn = connect.connect()
cur = conn.cursor(pymysql.cursors.DictCursor)
keyword = "%" + keyword + "%"
sql = ("select 商品情報一覧テーブル.商品コード, 商品情報一覧テーブル.商品名, 商品詳細, 現在価格, (定価 - 現在価格) as '割引額', 分類名, CAST(在庫数 AS SIGNED) AS 在庫数,税率 from 商品... | Python | zaydzuhri_stack_edu_python |
from multiprocessing import Pool
from time import sleep , ctime
import os
comment def fun():
comment os.mkdir('/home/tarena/PycharmProjects/official courses/month02/day12/备份文件练习')
comment list_file=os.listdir('/home/tarena/PycharmProjects/official courses/month02/day12')
comment for name in list_file:
comment f1=open('... | from multiprocessing import Pool
from time import sleep,ctime
import os
#
# def fun():
# os.mkdir('/home/tarena/PycharmProjects/official courses/month02/day12/备份文件练习')
# list_file=os.listdir('/home/tarena/PycharmProjects/official courses/month02/day12')
# for name in list_file:
# f1=open('/home/tar... | Python | zaydzuhri_stack_edu_python |
import sys
class User
begin
set __username = string
set __userID = none
set __lastname = string
set __firstname = string
function __init__ self username id firstname lastname
begin
set __username = username
set __userID = id
set __firstname = firstname
set __lastname = lastname
end function
function get_name self
be... | import sys
class User():
__username = ""
__userID = None
__lastname = ""
__firstname = ""
def __init__(self, username, id, firstname, lastname):
self.__username = username
self.__userID = id
self.__firstname = firstname
self.__lastname = lastname
def get_name(... | Python | zaydzuhri_stack_edu_python |
function _parse_internal internal shape
begin
set tuple internal *shape_config = split internal string : maxsplit=1
assert not shape_config or shape is none
if shape_config
begin
set shape = integer shape_config at 0
end
return tuple internal shape
end function | def _parse_internal(internal, shape):
internal, *shape_config = internal.split(':', maxsplit=1)
assert not shape_config or shape is None
if shape_config:
shape = int(shape_config[0])
return internal, shape | Python | nomic_cornstack_python_v1 |
function iphlpapi_CreatePersistentUdpPortReservation jitter
begin
set tuple ret_ad args = call func_args_stdcall list string StartPort string NumberOfPorts string Token
raise call RuntimeError string API not implemented
call func_ret_stdcall ret_ad ret_value
end function | def iphlpapi_CreatePersistentUdpPortReservation(jitter):
ret_ad, args = jitter.func_args_stdcall(["StartPort", "NumberOfPorts", "Token"])
raise RuntimeError('API not implemented')
jitter.func_ret_stdcall(ret_ad, ret_value) | Python | nomic_cornstack_python_v1 |
function book_detail request id
begin
try
begin
set book = get objects pk=id active__exact=true
end
except DoesNotExist
begin
return call HttpResponse status=404
end
if method == string GET
begin
set serializer = call BookSerializer book
return call JSONResponse data
end
else
if method == string PUT
begin
set data = pa... | def book_detail(request, id):
try:
book = Book.objects.get(pk=id, active__exact=True)
except Book.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = BookSerializer(book)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(reque... | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import pandas as pd
from nltk.corpus import stopwords
from tqdm import tqdm
from tensorflow.python.keras.preprocessing.text import Tokenizer
from tensorflow.python.keras import utils
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import Sequential
from ... | import os
import numpy as np
import pandas as pd
from nltk.corpus import stopwords
from tqdm import tqdm
from tensorflow.python.keras.preprocessing.text import Tokenizer
from tensorflow.python.keras import utils
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import Sequ... | Python | zaydzuhri_stack_edu_python |
function send_message conversation_id message
begin
comment defining the api-endpoint
set send_api_endpoint = API_ENDPOINT + string / + conversation_id + string /activities
set headers = dict string Authorization string Bearer + API_KEY ; string Content-Type string application/json
set data = dict string type string me... | def send_message(conversation_id, message):
# defining the api-endpoint
send_api_endpoint = API_ENDPOINT +'/'+ conversation_id + "/activities"
headers = {'Authorization': 'Bearer '+API_KEY, 'Content-Type': 'application/json'}
data = {
"type": "message",
"from": {
"id": "user1... | Python | nomic_cornstack_python_v1 |
function calibrate_sta self sta
begin
if sta < 0
begin
if sta < spec at string sta_min
begin
return spec at string sta_min
end
else
begin
return sta
end
end
else
if sta > 0
begin
if sta > spec at string sta_max
begin
return spec at string sta_max
end
else
begin
return sta
end
end
return 0
end function | def calibrate_sta(self, sta):
if sta < 0:
if sta < self.spec['sta_min']:
return self.spec['sta_min']
else:
return sta
elif sta > 0:
if sta > self.spec['sta_max']:
return self.spec['sta_max']
else:
... | Python | nomic_cornstack_python_v1 |
function get self code
begin
set out = call __submit code
return loads read out
end function | def get(self, code):
out = self.__submit(code)
return json.loads(out.read()) | Python | nomic_cornstack_python_v1 |
function labels self
begin
return get pulumi self string labels
end function | def labels(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "labels") | Python | nomic_cornstack_python_v1 |
import MySQLdb
from Model.squads import Squads
comment ---- Criação da classe Squads_dao
class Squads_dao
begin
set conexao = call connect host=string mysql.padawans.dev database=string padawans14 user=string padawans14 passwd=string jm2019
set cursor = call cursor
comment ---- Função para Inserir/Criar
function Create... | import MySQLdb
from Model.squads import Squads
#---- Criação da classe Squads_dao
class Squads_dao:
conexao = MySQLdb.connect(host='mysql.padawans.dev', database='padawans14', user='padawans14', passwd='jm2019')
cursor = conexao.cursor()
#---- Função para Inserir/Criar
def Create (self, squads:Squad... | Python | zaydzuhri_stack_edu_python |
comment if there are three types of edits, insert, delete replace given two strings
comment write a function to check if they are one edit, zero edits away
function one_away str1 str2
begin
set lst1 = list str1
set lst2 = list str2
if length lst1 == length lst2
begin
if lst1 == lst2
begin
return true
end
set edit = 0
f... | #if there are three types of edits, insert, delete replace given two strings
#write a function to check if they are one edit, zero edits away
def one_away(str1, str2):
lst1 = list(str1)
lst2 = list(str2)
if len(lst1) == len(lst2):
if lst1 == lst2:
return True
edit = 0
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
comment Database handler class for the World Universities database
import sys
import sqlite3
import os.path
from pprint import pprint
class DbHandler extends object
begin
set __TABLE_UNIVERSITIES = dict string name string universities ; string fields dict string id dict string name string i... | # -*- coding:utf-8 -*-
# Database handler class for the World Universities database
import sys
import sqlite3
import os.path
from pprint import pprint
class DbHandler(object):
__TABLE_UNIVERSITIES = {
'name': 'universities',
'fields': {
'id': {'name': 'id', 'type': 'INTEGER'},
... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
class FEMNIST extends Module
begin
function __init__ self
begin
call __init__
set global_feature = sequential conv 2d in_channels=1 out_channels=8 kernel_size=5 padding=2 relu inplace=true call MaxPool2d 2 2
comment nn.Conv2d(in_channels=8, out_channels=16, kernel_size=5, padding=2),
... | import torch
import torch.nn as nn
class FEMNIST(nn.Module):
def __init__(self):
super(FEMNIST, self).__init__()
self.global_feature = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=8, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2... | Python | zaydzuhri_stack_edu_python |
function _render_history self req page
begin
if not exists
begin
raise call TracError call _ string Page %(name)s does not exist name=name
end
set data = call _page_data req page string history
set history = list
for tuple version date author comment ipnr in call get_history
begin
append history dict string version ve... | def _render_history(self, req, page):
if not page.exists:
raise TracError(_("Page %(name)s does not exist", name=page.name))
data = self._page_data(req, page, 'history')
history = []
for version, date, author, comment, ipnr in page.get_history():
history.append(... | Python | nomic_cornstack_python_v1 |
function minimum_edit str1 str2
begin
set col = length str1 + 1
set row = length str2 + 1
set mat = list comprehension list comprehension 1 for i in range col for j in range row
for i in range row
begin
set mat at i at 0 = i
end
for i in range col
begin
set mat at 0 at i = i
end
for i in range 1 row
begin
for j in rang... | def minimum_edit(str1,str2):
col=len(str1)+1
row=len(str2)+1
mat=[[1 for i in range(col)] for j in range(row) ]
for i in range(row):
mat[i][0]=i
for i in range(col):
mat[0][i]=i
for i in range(1,row):
for j in range(1,col):
if str2[i-1]==str1[j-1]:
... | Python | zaydzuhri_stack_edu_python |
function __init__ self column position=none
begin
set _column = column
set _position = position
end function | def __init__(self, column: Column, position: Union[str, bool] = None):
self._column = column
self._position = position | Python | nomic_cornstack_python_v1 |
function db_home self db_home
begin
set _db_home = db_home
end function | def db_home(self, db_home):
self._db_home = db_home | Python | nomic_cornstack_python_v1 |
function make_row_network network_row distance row_number
begin
set total = length network_row
set row = pop network_row 0
if _multiprocess
begin
set name = format string < {} > row_number
end
comment find the maximum required overlap
set conv = pi / 180.0
set small_rad = cos max absolute row at string top absolute row... | def make_row_network(network_row, distance, row_number):
total = len(network_row)
row = network_row.pop(0)
if _multiprocess:
logger.name = '< {} >'.format(row_number)
# find the maximum required overlap
conv = math.pi/180.0
small_rad = math.cos(max(abs(row['top']), abs(row['bottom'])) *... | Python | nomic_cornstack_python_v1 |
function update self request pk=none parent_lookup_organization=none
begin
string Add a user to an organization.
set user = call get_object_or_404 User pk=pk
set org = call get_object_or_404 SeedOrganization pk=parent_lookup_organization
call check_object_permissions request org
add users user
return call Response stat... | def update(self, request, pk=None, parent_lookup_organization=None):
'''Add a user to an organization.'''
user = get_object_or_404(User, pk=pk)
org = get_object_or_404(
SeedOrganization, pk=parent_lookup_organization)
self.check_object_permissions(request, org)
org.us... | Python | jtatman_500k |
comment coding:utf-8
import numpy as np
from matplotlib import pyplot
set attribute = list comprehension list * 10 for i in range 10
set filename = string magic04.txt
function read_file
begin
set count = 0
with open filename string r as file_to_read
begin
while true
begin
set lines = read line file_to_read
set count =... | # coding:utf-8
import numpy as np
from matplotlib import pyplot
attribute = [([] * 10) for i in range(10)]
filename = 'magic04.txt'
def read_file():
count = 0
with open(filename, 'r') as file_to_read:
while True:
lines = file_to_read.readline()
count += 1
if not li... | Python | zaydzuhri_stack_edu_python |
function __neg__ self
begin
return complement
end function | def __neg__(self):
return self[::-1].complement | Python | nomic_cornstack_python_v1 |
function Rotation_EQJ_ECL
begin
comment ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians.
comment cos(ob)
set c = 0.9174821430670688
comment sin(ob)
set s = 0.3977769691083922
return call RotationMatrix list list 1 0 0 list 0 + c - s list 0 + s + c
end function | def Rotation_EQJ_ECL():
# ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians.
c = 0.9174821430670688 # cos(ob)
s = 0.3977769691083922 # sin(ob)
return RotationMatrix([
[ 1, 0, 0],
[ 0, +c, -s],
[ 0, +s, +c]
]) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import unittest
from collections import defaultdict
from copy import copy
class Solution extends object
begin
function shortestCompletingWord self licensePlate words
begin
string :type licensePlate: str :type words: List[str] :rtype: str
set alpha = default dictionary int
for c in licensePl... | #!/usr/bin/env python
import unittest
from collections import defaultdict
from copy import copy
class Solution(object):
def shortestCompletingWord(self, licensePlate, words):
"""
:type licensePlate: str
:type words: List[str]
:rtype: str
"""
alpha = defaultdict(int... | Python | zaydzuhri_stack_edu_python |
function input_signature self
begin
return call invert_bit_sptr_input_signature self
end function | def input_signature(self):
return _spacegrant_swig.invert_bit_sptr_input_signature(self) | Python | nomic_cornstack_python_v1 |
from state import State
import torch
from nnet import Net
import chess
import chess.svg
import time
import base64
import traceback
import os
import collections
class Valuator extends object
begin
function __init__ self
begin
comment these lines make sure that the CPU is used instead of the GPU.
set vals = load torch st... | from state import State
import torch
from nnet import Net
import chess
import chess.svg
import time
import base64
import traceback
import os
import collections
class Valuator(object):
def __init__(self):
vals = torch.load("nets/value_100K.pth", map_location=lambda storage, loc: storage) # these lines m... | Python | zaydzuhri_stack_edu_python |
function register cls request_handler name apptable_name
begin
set data = call make_request string POST format string /datatables/register/{}/{} name apptable_name
return data at string resourceIdentifier == name
end function | def register(cls, request_handler, name, apptable_name):
data = request_handler.make_request(
'POST',
'/datatables/register/{}/{}'.format(name, apptable_name)
)
return data['resourceIdentifier'] == name | Python | nomic_cornstack_python_v1 |
function fire_rule self rule
begin
comment Set next state
set state = state2
comment Fire action with signal as the relevant symbol
call action signal
end function
comment TODO THIS ONE FIRES RIGHT ACTION? TWO ARGS, SELF.AGENT?
comment added two args instead of just signal, to many args | def fire_rule(self, rule):
# Set next state
self.state = rule.state2
# Fire action with signal as the relevant symbol
rule.action(self.signal)
# TODO THIS ONE FIRES RIGHT ACTION? TWO ARGS, SELF.AGENT?
# added two args instead of just signal, to many args | Python | nomic_cornstack_python_v1 |
function _set_env_from_extras self extras
begin
string Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either: - The path to the keyfile from the specified connection id - A generated file's path if the user specified JSON in the connection id. The file is assumed to be deleted after the process die... | def _set_env_from_extras(self, extras):
"""
Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either:
- The path to the keyfile from the specified connection id
- A generated file's path if the user specified JSON in the connection id. The
file is assumed t... | Python | jtatman_500k |
function human_firendly_print_repository_scheduled_tasks scheduled
begin
set name_pad = 5
for name in scheduled
begin
if length name > name_pad
begin
set name_pad = length name
end
end
set name_pad = name_pad + 1
set header = string { string Name } | Task type | Next run
print string Scheduled tasks:
print header
print... | def human_firendly_print_repository_scheduled_tasks(scheduled):
name_pad = 5
for name in scheduled:
if len(name) > name_pad:
name_pad = len(name)
name_pad += 1
header = f'{"Name":<{name_pad}}| Task type | Next run'
print('Scheduled tasks:')
pr... | Python | nomic_cornstack_python_v1 |
import tkinter as tk
import string
import random
function random_password
begin
set password = list
for i in range 4
begin
set alpha = random choice ascii_letters
set symbol = random choice punctuation
set numbers = random choice digits
append password alpha
append password symbol
append password numbers
set passwords... | import tkinter as tk
import string
import random
def random_password() :
password = []
for i in range(4):
alpha = random.choice(string.ascii_letters)
symbol = random.choice(string.punctuation)
numbers = random.choice(string.digits)
password.append(alpha)
passwor... | Python | zaydzuhri_stack_edu_python |
function post self request *args **kwargs
begin
return call create request *args keyword kwargs
end function | def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
import time
class GPIOController
begin
function __init__ self
begin
comment GPIO Nummer via Board Nummern
call setmode BOARD
end function
function readFromGPIO self gpioPin
begin
setup GPIO gpioPin OUT
call output gpioPin LOW
sleep 0.1
setup GPIO gpioPin IN
set count = 0
while input gpioPin == L... | import RPi.GPIO as GPIO
import time
class GPIOController:
def __init__(self):
GPIO.setmode(GPIO.BOARD) # GPIO Nummer via Board Nummern
def readFromGPIO(self, gpioPin):
GPIO.setup(gpioPin, GPIO.OUT)
GPIO.output(gpioPin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(gpioPin, G... | Python | zaydzuhri_stack_edu_python |
from cryptography.fernet import Fernet
set key = call generate_key
set cipher = call Fernet key
set message = string hello world
set encrypted_message = call encrypt encode message
print string Encrypted: { encrypted_message }
comment Code executed. | from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
message = 'hello world'
encrypted_message = cipher.encrypt(message.encode())
print(f'Encrypted: {encrypted_message}')
# Code executed.
| Python | flytech_python_25k |
comment !/usr/bin/python2.7
import optparse
from collections import defaultdict
from copy import deepcopy
function trace stTrakov trenutniOpisi
begin
set beseda = string
for tuple stanje trakovi index in trenutniOpisi
begin
set beseda = beseda + stanje + string -
for i in range stTrakov
begin
set tr = trakovi at i at ... | #!/usr/bin/python2.7
import optparse
from collections import defaultdict
from copy import deepcopy
def trace(stTrakov, trenutniOpisi):
beseda = ''
for stanje, trakovi, index in trenutniOpisi:
beseda += stanje+' -\t'
for i in range(stTrakov):
tr = trakovi[i][:]
tr.insert(index[i]+1,']')
tr.insert(index[... | Python | zaydzuhri_stack_edu_python |
function coverage_report self
begin
set verbose = string --quiet not in argv
call stop
if verbose
begin
info string Coverage Report:
end
end function | def coverage_report(self):
verbose = '--quiet' not in sys.argv
self.cov.stop()
if verbose:
log.info("\nCoverage Report:") | Python | nomic_cornstack_python_v1 |
function readInstance self
begin
set file = open fName string r
set genSize = integer read line file
set data = dict
for line in file
begin
set tuple id x y = split line
set data at integer id = tuple integer x integer y
end
close file
end function | def readInstance(self):
file = open(self.fName, 'r')
self.genSize = int(file.readline())
self.data = {}
for line in file:
(id, x, y) = line.split()
self.data[int(id)] = (int(x), int(y))
file.close() | Python | nomic_cornstack_python_v1 |
class Animal
begin
function __init__ self
begin
set name = string
set age = 0
set sound = string
set weight = 0.0
end function
function set_name self name
begin
set name = name
end function
function set_age self age
begin
set age = age
end function
function set_sound self sound
begin
set sound = sound
end function
fu... | class Animal:
def __init__(self):
self.name = ""
self.age = 0
self.sound = ""
self.weight = 0.0
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
def set_sound(self, sound):
self.sound = sound
... | Python | jtatman_500k |
string @Description: @Version: 2.0 @Autor: 吴宇辉 @Date: 2020-05-27 17:20:45 @LastEditors: 吴宇辉 @LastEditTime: 2020-05-27 23:06:08
import os
import re
function generateTXT filePath geneTXTname
begin
string fileName为输入文件名称,geneTXTname为生成txt格式文件名称
set fl = open geneTXTname + string .txt string a+
for i in walk filePath
begin... | '''
@Description:
@Version: 2.0
@Autor: 吴宇辉
@Date: 2020-05-27 17:20:45
@LastEditors: 吴宇辉
@LastEditTime: 2020-05-27 23:06:08
'''
import os
import re
def generateTXT(filePath, geneTXTname):
'''fileName为输入文件名称,geneTXTname为生成txt格式文件名称'''
fl = open(geneTXTname+'.txt', 'a+')
for i in os.walk( filePath ):
... | Python | zaydzuhri_stack_edu_python |
function selectConfigurations self menu
begin
for i in options
begin
if type == string pump_selection
begin
set key = attributes at string key
if pump_configuration at key at string value == attributes at string value
begin
set name = string %s %s % tuple attributes at string name string *
end
else
begin
set name = att... | def selectConfigurations(self, menu):
for i in menu.options:
if (i.type == "pump_selection"):
key = i.attributes["key"]
if (self.pump_configuration[key]["value"] == i.attributes["value"]):
i.name = "%s %s" % (i.attributes["name"], "*")
else:
i.name = i.attributes["name"]
elif (i.type == "m... | Python | nomic_cornstack_python_v1 |
import cv2
import os
from PIL import Image
from collections import namedtuple
import numpy
set CASCADE = join path split path absolute path path __file__ at 0 string haarcascade_frontalface_default.xml
set SOONERLATER = join path split path absolute path path __file__ at 0 string soonerlater.png
set Coordinate = named ... | import cv2
import os
from PIL import Image
from collections import namedtuple
import numpy
CASCADE = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'haarcascade_frontalface_default.xml')
SOONERLATER = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'soonerlater.png')
Coordinate = namedtuple('Co... | 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.