code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function validate self json_data parent_schema=none
begin
set schema_name = call _full_name parent_schema
call _assert_schema_is_valid json_data schema_name
set json_data at string name = call _extract_name json_data
set expiration = call _extract_expiration json_data schema_name
call _assert_expiration_is_valid expira... | def validate(self, json_data, parent_schema=None):
schema_name = self._full_name(parent_schema)
self._assert_schema_is_valid(json_data, schema_name)
json_data['name'] = self._extract_name(json_data)
expiration = self._extract_expiration(json_data, schema_name)
self._assert_expi... | Python | nomic_cornstack_python_v1 |
function get_build_env self
begin
string Fetch or create the appropriate build Environment for this Executor.
try
begin
return _memo at string get_build_env
end
except KeyError
begin
pass
end
comment Create the build environment instance with appropriate
comment overrides. These get evaluated against the current
commen... | def get_build_env(self):
"""Fetch or create the appropriate build Environment
for this Executor.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
# Create the build environment instance with appropriate
# overrides. These... | Python | jtatman_500k |
comment Set KEYSPACE to the keyspace specified above
from data_utils.cassandra_utils import createKeySpace , createCassandraConnection
from data_utils.query_utils import query_to_df , insert_statement , execute_query
import csv
import pandas as pd
set dbsession = call createCassandraConnection
call createKeySpace strin... | # Set KEYSPACE to the keyspace specified above
from data_utils.cassandra_utils import createKeySpace, createCassandraConnection
from data_utils.query_utils import query_to_df, insert_statement, execute_query
import csv
import pandas as pd
dbsession = createCassandraConnection()
createKeySpace("ks1", dbsession)
try:
... | Python | zaydzuhri_stack_edu_python |
comment /usr/bin/env Python3
import EventDispatcher as ed
from sebastian_modules import TTS_Module as tts , STT_Module as stt
from AnimatedGif import *
import tkinter as gui
class SebastianInterface extends object
begin
function __init__ self
begin
comment Required Global Variables
set listener = call stt_engine
commen... | # /usr/bin/env Python3
import EventDispatcher as ed
from sebastian_modules import TTS_Module as tts, STT_Module as stt
from AnimatedGif import *
import tkinter as gui
class SebastianInterface(object):
def __init__(self):
# Required Global Variables
self.listener = stt.stt_engine()
self.i ... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ public_endpoint=none
begin
if public_endpoint is none
begin
set public_endpoint = false
end
if public_endpoint is not none
begin
set __self__ string public_endpoint public_endpoint
end
end function | def __init__(__self__, *,
public_endpoint: Optional[pulumi.Input[bool]] = None):
if public_endpoint is None:
public_endpoint = False
if public_endpoint is not None:
pulumi.set(__self__, "public_endpoint", public_endpoint) | Python | nomic_cornstack_python_v1 |
function enqueue_in_list self taskList=none argsList=none
begin
set result = none
assert taskList is not none msg string TaskList need be full
for i in taskList
begin
for arg in argsList
begin
set result = result + apply async _Pool i args=tuple arg
end
end
return result
end function | def enqueue_in_list(self, taskList=None, argsList=None):
result = None
assert taskList is not None, 'TaskList need be full'
for i in taskList:
for arg in argsList:
result += self._Pool.apply_async(i, args=(arg,) )
return result | Python | nomic_cornstack_python_v1 |
import requests
print string Hello
try
begin
set r = get requests string https://facebook.com
print status_code
if status_code == 200
begin
print text
end
end
except Exception as e
begin
print string Ada error bro e
end | import requests
print('Hello')
try:
r = requests.get('https://facebook.com')
print(r.status_code)
if r.status_code == 200:
print(r.text)
except Exception as e:
print('Ada error bro', e)
| Python | zaydzuhri_stack_edu_python |
function bill_to_street self
begin
return _bill_to_street
end function | def bill_to_street(self):
return self._bill_to_street | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys
import ftplib
import os
import threading
comment add the target ip here to proceed the bruteforce attack on the ftp server.
set target = string
set port = 21
function ftplogin username password
begin
global target port
end function | #!/usr/bin/python
import sys
import ftplib
import os
import threading
target = "" # add the target ip here to proceed the bruteforce attack on the ftp server.
port = 21
def ftplogin(username,password):
global target,port | Python | zaydzuhri_stack_edu_python |
comment !/usr/local/bin/python3
string Utility module for reading and writing fragment index files (.frag). A .frag file is an indexed group of arbitrarily sized named data fragments. .frag files consist of two parts, the index and the content body. The first four bytes of the index are a four byte unsigned little- end... | #!/usr/local/bin/python3
'''
Utility module for reading and writing fragment index files (.frag).
A .frag file is an indexed group of arbitrarily sized named data
fragments.
.frag files consist of two parts, the index and the content body.
The first four bytes of the index are a four byte unsigned little-
endian inte... | Python | zaydzuhri_stack_edu_python |
function is_repeating_queue self
begin
return _repeat_queue
end function | def is_repeating_queue(self):
return self._repeat_queue | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string # Purpose: Generate adds/deletes/updates from files exported from an SMS # Note: This script can use Basic or Advanced GAM: # https://github.com/GAM-team/GAM # https://github.com/taers232c/GAMADV-XTD3# Usage: # Customize: Set the field and file names as required/desired # Python: Us... | #!/usr/bin/env python3
"""
# Purpose: Generate adds/deletes/updates from files exported from an SMS
# Note: This script can use Basic or Advanced GAM:
# https://github.com/GAM-team/GAM
# https://github.com/taers232c/GAMADV-XTD3# Usage:
# Customize: Set the field and file names as required/desired
# Python: Use python o... | Python | zaydzuhri_stack_edu_python |
function sum_zero N
begin
comment create a list from -N to N range
set arr_list = range - 1 * N N + 1
comment Run a loop over all combinations of the list
for c in call combinations arr_list N
begin
comment return the combination whose sum of all elements is Zero and doesn't contain duplicates
if sum c == 0 and length ... | def sum_zero(N):
# create a list from -N to N range
arr_list = range((-1*N), N+1)
# Run a loop over all combinations of the list
for c in combinations(arr_list, N):
# return the combination whose sum of all elements is Zero and doesn't contain duplicates
if(sum(c)==0 ... | Python | nomic_cornstack_python_v1 |
function show_trailer self
begin
open trailer_youtube_url
end function | def show_trailer(self):
webbrowser.open(self.trailer_youtube_url) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function spiralOrder self matrix
begin
if matrix == list
begin
return list
end
set res = list
set m = length matrix
set n = length matrix at 0
for k in range min m n + 1 // 2
begin
for j in range k n - k
begin
append res matrix at k at j
end
print res
for i in range k + 1 m - k
begin
append res ... | class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if matrix ==[]:
return []
res = []
m = len(matrix)
n = len(matrix[0])
for k in range((min(m,n)+1)//2):
for j in range(k,n-k):
res.append(matrix[k][j])
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function removeElement self nums val
begin
set j = length nums
set extra = list
for i in range length nums
begin
if nums at i != val
begin
append extra nums at i
end
end
clear nums
sort extra
for each in extra
begin
append nums each
end
print extra
end function
end class
comment return (len(nums),... | class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
j = len(nums)
extra = []
for i in range(len(nums)):
if nums[i] != val:
extra.append(nums[i])
nums.clear()
extra.sort()
for each in extra:
... | Python | zaydzuhri_stack_edu_python |
function addLink self
begin
while true
begin
set dlg = call dlg_FormBearDistLink db auto at string FROMBEACON SQL_BEACONS at string UNIQUE parent=self
show
set dlg_ret = call exec_
if boolean dlg_ret
begin
set values = call getValues
append beardistChain list values string INSERT none
call updateBearDistChainDependants... | def addLink(self):
while True:
dlg = dlg_FormBearDistLink(
self.db,
self.auto["FROMBEACON"],
self.SQL_BEACONS["UNIQUE"],
parent = self
)
dlg.show()
dlg_ret = dlg.exec_()
if bool(dlg_ret)... | Python | nomic_cornstack_python_v1 |
function license_count self
begin
return get pulumi self string license_count
end function | def license_count(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "license_count") | Python | nomic_cornstack_python_v1 |
function setErrorThreshold self threshold
begin
return call _set errorThreshold=threshold
end function | def setErrorThreshold(self, threshold):
return self._set(errorThreshold=threshold) | Python | nomic_cornstack_python_v1 |
function __init__ self model
begin
set layer_id = length layers - 2
set model = model inputs=input outputs=output
set softmax = sequential
add softmax call Lambda lambda X -> softmax X axis=1 input_shape=tuple 10
end function | def __init__(self, model):
layer_id = len(model.layers)-2
self.model = Model(inputs=model.layers[0].input, outputs=model.layers[layer_id].output)
self.softmax = Sequential()
self.softmax.add(Lambda(lambda X: softmax(X, axis=1), input_shape=(10,))) | Python | nomic_cornstack_python_v1 |
function menu
begin
set msg = call hello
set msg = msg + string Current menu
set msg = msg + string [0] / (root) Hello+ this menu
set msg = msg + string [1] /helloHello World
set msg = msg + string [2] /extfun private : hw external fun
set msg = msg + string [3] /testsec Hello+ sec end point
set msg = msg + string [4] ... | def menu():
msg=hello()
msg=msg+'Current menu\n'
msg=msg+'[0] / (root) Hello+ this menu \n'
msg=msg+'[1] /helloHello World \n'
msg=msg+'[2] /extfun private : hw external fun\n'
msg=msg+'[3] /testsec Hello+ sec end point \n'
msg=msg+'[4] /testpatch Test patch w/out credentials \n'
msg=msg... | Python | nomic_cornstack_python_v1 |
import numpy as np
comment Create a 12 element vector and reshape into 3x4 matrix
set d = linear space 0 11 12
set shape = tuple 3 4 | import numpy as np
# Create a 12 element vector and reshape into 3x4 matrix
d = np.linspace( 0, 11, 12 )
d.shape = ( 3,4 ) | Python | zaydzuhri_stack_edu_python |
function test_valid self ip
begin
call validate_ip ip
end function | def test_valid(self, ip):
validate_ip(ip) | Python | nomic_cornstack_python_v1 |
function generate_filename_prefix self
begin
set email = call get_user_email
if not email
begin
return string
end
return string %s_ % call md5_hash email salt
end function | def generate_filename_prefix(self):
email = self.get_user_email()
if not email:
return ''
return '%s_' % md5_hash(email, self.salt) | Python | nomic_cornstack_python_v1 |
function generate cls
begin
raise call NotImplementedError
end function | def generate(cls):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function _no_detail self
begin
set best_exp = call BestParamsExperiment string Best_Params
try
begin
call _load_prev_experiment best_exp
end
except any
begin
pass
end
set tree_cross_scores = max grid_scores_ key=lambda x -> x at 1 at 2
set forest_cross_scores = max grid_scores_ key=lambda x -> x at 1 at 2
function _eva... | def _no_detail(self):
best_exp = BestParamsExperiment('Best_Params')
try:
self._load_prev_experiment(best_exp)
except:
pass
tree_cross_scores = max(best_exp._loaded_data['Tree'].grid_scores_,key= lambda x: x[1])[2]
forest_cross_scores = max(best_exp._loade... | Python | nomic_cornstack_python_v1 |
function to_dict cfg
begin
return dictionary comprehension lower s : dictionary cfg at s for s in sections cfg
end function | def to_dict(cfg: configparser.ConfigParser) -> dict:
return {s.lower(): dict(cfg[s]) for s in cfg.sections()} | Python | nomic_cornstack_python_v1 |
function _get_user_details self user_id
begin
try
begin
set user_entity : Optional at User = call get_by_id User user_id fields=list string *
end
except Exception as exc
begin
warning string Could not get user details - { exc }
return dict
end
if not user_entity
begin
return dict
end
set teams = teams
return dict str... | def _get_user_details(self, user_id: str) -> dict:
try:
user_entity: Optional[User] = self.metadata.get_by_id(
User,
user_id,
fields=["*"],
)
except Exception as exc:
logger.warning(f"Could not get user details - {exc}"... | Python | nomic_cornstack_python_v1 |
function neutron_l3_migration_after_destroy_vlan self
begin
call neutron_l3_migration_after_destroy
end function | def neutron_l3_migration_after_destroy_vlan(self):
super(self.__class__, self).neutron_l3_migration_after_destroy() | Python | nomic_cornstack_python_v1 |
function afcp request
begin
set name = string afcp
set lang_url = call get_lang_prefix request
set ctxt_dict = dict string page_name name
update ctxt_dict call _get_common_context_dict request
set ctxt = call Context ctxt_dict
set tmpl = call get_template string %s/project/%s/%s.html % tuple APP_NAME lang_url name
retu... | def afcp(request):
name = "afcp"
lang_url = Language.get_lang_prefix(request)
ctxt_dict = { "page_name" : name, }
ctxt_dict.update(_get_common_context_dict(request))
ctxt = Context(ctxt_dict)
tmpl = loader.get_template("%s/project/%s/%s.html" % (Config.APP_NAME, lang_url, name))
retu... | Python | nomic_cornstack_python_v1 |
comment 导入wtf扩展提供的表单及验证器
from flask_wtf import FlaskForm
from wtforms import StringField , PasswordField , SubmitField , SelectField , RadioField , DateField , IntegerField , DecimalField , SelectMultipleField , TextAreaField , BooleanField
from wtforms.validators import DataRequired , EqualTo , Length , Email , Number... | # 导入wtf扩展提供的表单及验证器
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField, RadioField, DateField, IntegerField, \
DecimalField, SelectMultipleField, TextAreaField, BooleanField
from wtforms.validators import DataRequired, EqualTo, Length, Email, NumberRange
from fla... | Python | zaydzuhri_stack_edu_python |
function move_ship
begin
set anim = call animate ship tween=string accel_decel pos=target duration=call distance_to target / 200 on_finished=next_ship_target
end function | def move_ship():
anim = animate(
ship,
tween='accel_decel',
pos=ship.target,
duration=ship.distance_to(ship.target) / 200,
on_finished=next_ship_target,
) | Python | nomic_cornstack_python_v1 |
from libsbml import *
from cudasim.relations import *
import os
import sys
from Writer import Writer
class GillespiePythonWriter extends Writer
begin
function __init__ self parser output_path=string
begin
call __init__ self
set parser = parser
set out_file = open join path output_path name + string .py string w
rename
... | from libsbml import *
from cudasim.relations import *
import os
import sys
from Writer import Writer
class GillespiePythonWriter(Writer):
def __init__(self, parser, output_path=""):
Writer.__init__(self)
self.parser = parser
self.out_file = open(os.path.join(output_path, self.parser.parsed... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
set __author__ = string ShdowWalker
import os
import jieba
import codecs
import chardet
comment 对某个文件进行分词,并保存到set中
function cutfiletoset filename
begin
set file = open filename string r encoding=string utf8
set filecontent = read file
set fileseglist = call cut filecontent
set filewords = s... | #-*- coding:utf-8 -*-
__author__ = 'ShdowWalker'
import os
import jieba
import codecs
import chardet
# 对某个文件进行分词,并保存到set中
def cutfiletoset(filename):
file = codecs.open(filename, "r", encoding = "utf8")
filecontent = file.read()
fileseglist = jieba.cut(filecontent)
filewords = set()
for eachword i... | Python | zaydzuhri_stack_edu_python |
from unidecode import unidecode
function remove_accents string
begin
return call unidecode string
end function
function get_file_content file
begin
set file_extention = call get_file_extention file
if file_extention != string .txt
begin
raise call NotImplementedError string Only .txt files are available
end
with open f... | from unidecode import unidecode
def remove_accents(string):
return unidecode(string)
def get_file_content(file):
file_extention = get_file_extention(file)
if file_extention != '.txt':
raise NotImplementedError('Only .txt files are available')
with open(file, 'r') as f:
file_string = f... | Python | zaydzuhri_stack_edu_python |
from paramiko import AutoAddPolicy
from paramiko import SSHClient
from sys import argv as arguments
function main server username port password public_rsa_key
begin
set client = call SSHClient
call set_missing_host_key_policy call AutoAddPolicy
call connect server username=username port=port password=password
call exec... | from paramiko import AutoAddPolicy
from paramiko import SSHClient
from sys import argv as arguments
def main(server,username,port,password,public_rsa_key):
client=SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(server,username=username,port=port,password=password)
client.exec_comman... | Python | zaydzuhri_stack_edu_python |
function get_sample self
begin
set df = call load_df sample_path
if name in index
begin
return loc at name
end
else
begin
set msg = string Sample { name } not located in index of DataFrame { background_path }
raise call RuntimeError msg
end
end function | def get_sample(self) -> pd.Series:
df = self.load_df(self.sample_path)
if self.name in df.index:
return df.loc[self.name]
else:
msg = f"Sample {self.name} not located in index of DataFrame {self.background_path}"
raise RuntimeError(msg) | Python | nomic_cornstack_python_v1 |
string lifetime & scope of variable: =============================
comment program1
function show
begin
global a
print a
set a = 20
print a
end function
set a = 10
print a
show
print a | """
lifetime & scope of variable:
=============================
"""
#program1
def show():
global a
print(a)
a=20
print(a)
a=10
print(a)
show()
print(a)
| Python | zaydzuhri_stack_edu_python |
comment encoding: utf-8
string @Project : @File: 953. 验证外星语词典.py @Author: liuwz @time: 2022/5/17 11:09 @desc:
from typing import List
string :cvar 某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。 示例 1: 输入:words = ["hello","leetcode"],... | # encoding: utf-8
"""
@Project :
@File: 953. 验证外星语词典.py
@Author: liuwz
@time: 2022/5/17 11:09
@desc:
"""
from typing import List
""":cvar
某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。
给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
示例 1:
输入:words = ["hello","leetcode"], ... | Python | zaydzuhri_stack_edu_python |
function test_tags_browse_updated_max_display_limit_no_page_links self
begin
set po = call load_pageobject string TagsBrowsePage
call goto_page
comment change the display limit to 'All'
set new_display_limit = string All
call display_limit new_display_limit
comment get the updated display limit
set display_limit = call... | def test_tags_browse_updated_max_display_limit_no_page_links(self):
po = self.catalog.load_pageobject('TagsBrowsePage')
po.goto_page()
# change the display limit to 'All'
new_display_limit = 'All'
po.form.footer.display_limit(new_display_limit)
# get the updated displa... | Python | nomic_cornstack_python_v1 |
import random
set tries = 0
set goal = random integer 1 100
while true
begin
set guess = integer input string Enter a number:
set tries = tries + 1
if guess == goal
begin
print format string You win! You guessed the number in {} tries. tries
break
end
else
if guess < goal
begin
print string Too low!
end
else
begin
prin... | import random
tries = 0
goal = random.randint(1,100)
while True:
guess = int(input('Enter a number: '))
tries += 1
if guess == goal:
print('You win! You guessed the number in {} tries.'.format(tries))
break
elif guess < goal:
print('Too low!')
else:
print('Too high... | Python | jtatman_500k |
import math
set r = 10
function calcula_volume_da_esfera r
begin
set y = 4 / 3 * pi * r ^ 2
return y
end function
print call calcula_volume_da_esfera r | import math
r=10
def calcula_volume_da_esfera(r):
y=(4/3)*math.pi*r**2
return y
print(calcula_volume_da_esfera(r))
| Python | zaydzuhri_stack_edu_python |
function autodownsample matrix max_pixels
begin
set size = call shape matrix at 0 * call shape matrix at 1
if size <= max_pixels
begin
return integer 0
end
set n = integer ceil log decimal size / max_pixels / log 4.0
return n
end function | def autodownsample(matrix, max_pixels):
size = np.shape(matrix)[0] * np.shape(matrix)[1]
if size <= max_pixels:
return int(0)
n = int(np.ceil(np.log(float(size) / max_pixels) / np.log(4.0)));
return n; | Python | nomic_cornstack_python_v1 |
comment PF-Assgn-60
from collections import OrderedDict
function remove_duplicates value
begin
set d = ordered dictionary
set st = string
for i in value
begin
set d at i = 0
end
for i in d
begin
set st = st + i
end
return st
end function
print call remove_duplicates string 11223445566666ababzzz@@@123#*#* | #PF-Assgn-60
from collections import OrderedDict
def remove_duplicates(value):
d = OrderedDict()
st=""
for i in value:
d[i]=0
for i in d:
st+=i
return st
print(remove_duplicates("11223445566666ababzzz@@@123#*#*"))
| Python | zaydzuhri_stack_edu_python |
comment !/user/bin/python
comment -*- coding:utf-8 -*-
import collections
class Solution
begin
comment kahn algorithm
import collections
function findOrder self numCourses prerequisites
begin
string :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
comment construct adj table
set adj = dictio... | #!/user/bin/python
#-*- coding:utf-8 -*-
import collections
class Solution:
#kahn algorithm
import collections
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
#construct adj ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
function parse_data filename=string input
begin
with open filename string r as f
begin
set data = list comprehension integer i for i in read lines f
end
return data
end function
function is_invalid preamble num
begin
for x in preamble
begin
for y in preamble at slice 1 : :
begin
if x == ... | #!/usr/bin/env python3
def parse_data(filename = 'input'):
with open(filename, 'r') as f:
data = [ int(i) for i in f.readlines() ]
return data
def is_invalid(preamble, num):
for x in preamble:
for y in preamble[1:]:
if x == y:
continue
elif x + y == ... | Python | zaydzuhri_stack_edu_python |
function getSubstitutions self
begin
set native_sequence = call sequence
set design_sequence = call sequence
set slist = call getSubstitutionPositions native_sequence design_sequence
set wordlist = list
for i in slist
begin
append wordlist string i
end
set diff_list = join string wordlist string ,
end function | def getSubstitutions(self):
native_sequence = self.native.sequence()
design_sequence = self.design.protein.sequence()
slist = getSubstitutionPositions(native_sequence, design_sequence)
wordlist = []
for i in slist:
wordlist.append(str(i))
diff_list = string.join(wordlist, ",") | Python | nomic_cornstack_python_v1 |
function linear_combination n
begin
set weighs = tuple 1 3 9 27
for factors in call factors_set
begin
set sum = 0
for i in range length factors
begin
set sum = sum + factors at i * weighs at i
end
if sum == n
begin
return factors
end
end
end function | def linear_combination(n):
weighs = (1, 3, 9, 27)
for factors in factors_set():
sum = 0
for i in range(len(factors)):
sum += factors[i] * weighs[i]
if sum == n:
return factors | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Jul 30 13:24:56 2019 @author: STEM
print string Hellow World
set sample = input string Hi
import math
directory math
power 6 0.5
set number = integer input string Please enter a value for your variable:
set answer = power number 1 / 3
print string The cubic root of nu... | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 30 13:24:56 2019
@author: STEM
"""
print("Hellow World")
sample = input("Hi")
import math
dir(math)
math.pow(6,0.5)
number=int(input('Please enter a value for your variable:'))
answer = math.pow(number,1/3)
print('The cubic root of' ,number, 'is' ,answer,... | Python | zaydzuhri_stack_edu_python |
function func1 x y
begin
string This is a doc statement
end function
comment x = int(x)
comment y = int(y)
comment if x>y:
comment print(x,"is maximum")
comment else:
comment print(y,"is maximum")
comment func1(3,5)
print __doc__ | def func1(x,y):
"""This is a doc statement """
# x = int(x)
# y = int(y)
#
# if x>y:
# print(x,"is maximum")
# else:
# print(y,"is maximum")
# func1(3,5)
print(func1.__doc__)
| Python | zaydzuhri_stack_edu_python |
function reset_position self
begin
set position = list
for x in range INITIAL_LENGTH
begin
insert position 0 tuple x 1
end
set direction = EAST
call set_speed INITIAL_SPEED
end function | def reset_position(self):
self.position = []
for x in range(INITIAL_LENGTH):
self.position.insert(0,(x,1))
self.direction = EAST
self.set_speed(INITIAL_SPEED) | Python | nomic_cornstack_python_v1 |
function prepare self
begin
if upper method == string POST
begin
if string expected_size in arguments
begin
call set_max_body_size integer call get_argument string expected_size
end
try
begin
set total = integer get headers string Content-Length string 0
end
except KeyError
begin
set total = 0
end
set multipart_streame... | def prepare(self):
if self.request.method.upper() == 'POST':
if 'expected_size' in self.request.arguments:
self.request.connection.set_max_body_size(
int(self.get_argument('expected_size')))
try:
total = int(self.request.headers.get("Co... | Python | nomic_cornstack_python_v1 |
function write_symbols args env
begin
print
end function | def write_symbols(args, env):
env.print() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: UTF-8 -*-
comment 移频
comment numpy.fft模块中的fftshift函数可以将FFT输出中的直流分量移动到频谱的中央。ifftshift函数则是其逆操作。
comment fft是一维傅里叶变换,即将时域信号转换为频域信号
comment fftshift
comment 是针对频域的,将FFT的DC分量移到频谱中心
comment 即对频域的图像,(假设用一条水平线和一条垂直线将频谱图分成四块)对这四块进行对角线的交换与反对角线的交换
import numpy as np
from matplotlib... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 移频
# numpy.fft模块中的fftshift函数可以将FFT输出中的直流分量移动到频谱的中央。ifftshift函数则是其逆操作。
# fft是一维傅里叶变换,即将时域信号转换为频域信号
# fftshift
# 是针对频域的,将FFT的DC分量移到频谱中心
# 即对频域的图像,(假设用一条水平线和一条垂直线将频谱图分成四块)对这四块进行对角线的交换与反对角线的交换
import numpy as np
from matplotlib.pyplot import plot, show
x = np.linspace(0, 2 *... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import argparse
import sys
import os
comment создаём парсер и описываем все параметры командной строки, которые может
comment принимать наша программа
set parser = call ArgumentParser description=string Отображает древовидную структуру катологов и файлов
call add_argument string directory ... | #!/usr/bin/env python3
import argparse
import sys
import os
# создаём парсер и описываем все параметры командной строки, которые может
# принимать наша программа
parser = argparse.ArgumentParser(
description='Отображает древовидную структуру катологов и файлов'
)
parser.add_argument(
# название поля в объект... | Python | zaydzuhri_stack_edu_python |
from sympy import *
function fx exp a
begin
set x = call symbols string x
set res = call subs x a
return res
end function
function derivar f n=1
begin
set df = call sympify f
set aux = df
set i = 0
while i < n
begin
set df = call doit
set aux = df
set i = i + 1
end
return aux
end function
function nR x tol f
begin
set ... | from sympy import *
def fx(exp, a):
x = symbols('x')
res = sympify(exp).subs(x, a)
return res
def derivar(f,n=1):
df = sympify(f)
aux = df
i = 0
while i<n:
df = Derivative(aux).doit()
aux = df
i+=1
return aux
def nR(x,tol,f):
deriv = derivar(f,1)
h = fx(... | Python | zaydzuhri_stack_edu_python |
function _request self domain type_name search_command db_method body=none
begin
string Make the API request for a Data Store CRUD operation Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim.... | def _request(self, domain, type_name, search_command, db_method, body=None):
"""Make the API request for a Data Store CRUD operation
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API... | Python | jtatman_500k |
function removeComments fileName
begin
set lines = read lines open fileName
for i in range 0 length lines
begin
if string # in lines at i
begin
set lines at i = split lines at i string # at 0
end
end
return lines
end function | def removeComments(fileName):
lines = open(fileName).readlines()
for i in range(0, len(lines)):
if "#" in lines[i]:
lines[i] = lines[i].split("#")[0]
return lines | Python | nomic_cornstack_python_v1 |
class Car extends object
begin
function __init__ self color position speed
begin
set color = color
set position = position
set speed = speed
end function
function accelerate self coeff=5 factor=10
begin
string Increase the speed by a value derived from the coefficient argument given (a value between 10 and -10).
if spe... | class Car(object):
def __init__(self, color, position, speed):
self.color = color
self.position = position
self.speed = speed
def accelerate(self, coeff=5, factor=10):
""" Increase the speed by a value derived from the coefficient
argument given (a value between ... | Python | zaydzuhri_stack_edu_python |
comment Crie um programa que imprime os números primos entre 0 e 200, imprimindo ao final a soma destes números.
set numeroAvaliado = 0
set limite = 200
set somaPrimos = 0
while numeroAvaliado <= limite
begin
set contador = 2
set isPrimo = true
if numeroAvaliado == 0 or numeroAvaliado == 1
begin
set isPrimo = false
end... | # Crie um programa que imprime os números primos entre 0 e 200, imprimindo ao final a soma destes números.
numeroAvaliado = 0
limite = 200
somaPrimos = 0
while numeroAvaliado <= limite:
contador = 2
isPrimo = True
if numeroAvaliado == 0 or numeroAvaliado == 1:
isPrimo = False
else:
while contador < num... | Python | zaydzuhri_stack_edu_python |
function create_contract self symbol
begin
set contract = call Contract
set symbol = symbol
set exchange = string SMART
set secType = string STK
set currency = string USD
return contract
end function | def create_contract(self, symbol):
contract = Contract()
contract.symbol = symbol
contract.exchange = 'SMART'
contract.secType = 'STK'
contract.currency = 'USD'
return contract | Python | nomic_cornstack_python_v1 |
function test_1
begin
for _ in range 10
begin
set tuple A b x_true = call get_random_problem
set x_solve = call backward_substitution A b
call assert_almost_equal x_solve x_true
end
end function | def test_1():
for _ in range(10):
A, b, x_true = get_random_problem()
x_solve = backward_substitution(A, b)
np.testing.assert_almost_equal(x_solve, x_true) | Python | nomic_cornstack_python_v1 |
function set_max_noutput_items self *args **kwargs
begin
return call layer_mapper_sptr_set_max_noutput_items self *args keyword kwargs
end function | def set_max_noutput_items(self, *args, **kwargs):
return _my_lte_swig.layer_mapper_sptr_set_max_noutput_items(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
function add_menu self menu
begin
set name = call get_name
set __menus at name = menu
end function | def add_menu(self, menu):
name = menu.get_name()
self.__menus[name] = menu | Python | nomic_cornstack_python_v1 |
import nltk
import enum
import math
import random
import pickle
class NGramConstants extends Enum
begin
set B_OF_SENTENCE = 1
set E_OF_SENTENCE = 2
set NONE = 3
set LAPLACE = 4
set DECIMAL = 5
set LOGARITHMIC = 6
end class
function detokenize tokens
begin
set s = string
for token in tokens
begin
if token in list B_OF_... | import nltk
import enum
import math
import random
import pickle
class NGramConstants(enum.Enum):
B_OF_SENTENCE = 1
E_OF_SENTENCE = 2
NONE = 3
LAPLACE = 4
DECIMAL = 5
LOGARITHMIC = 6
def detokenize(tokens):
s = ""
for token in tokens:
if (token in [NGramConstants.B_OF_SENTENCE, ... | Python | zaydzuhri_stack_edu_python |
function position self *args
begin
if length args == 0
begin
return __pos
end
else
if length args == 3
begin
set __pos at 0 = args at 0
set __pos at 1 = args at 1
set __pos at 2 = args at 2
pass
end
else
if __name__ == string list
begin
set __pos = args at 0
end
pass
end function | def position(self, *args):
if len(args) == 0:
return self.__pos
elif len(args) == 3:
self.__pos[0] = args[0]
self.__pos[1] = args[1]
self.__pos[2] = args[2]
pass
elif (type(args[0]).__name__) == 'list':
self.__pos = args[0]
pass | Python | nomic_cornstack_python_v1 |
function display_number n
begin
return string n + string is a number
end function | def display_number(n):
return str(n)+" is a number" | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string Author: Sanyk28 (san-heng-yi-shu@163.com) Date created: 10 June 2013 Rosalind problem: Transitions and Transversions Given: Two DNA strings s1 and s2 of equal length (at most 1 kbp). Return: The transition/transversion ratio R(s1,s2). Usage: python TRAN.py [Input File]
function Read_File... | #!/usr/bin/python
'''
Author:
Sanyk28 (san-heng-yi-shu@163.com)
Date created:
10 June 2013
Rosalind problem:
Transitions and Transversions
Given: Two DNA strings s1 and s2 of equal length (at most 1 kbp).
Return: The transition/transversion ratio R(s1,s2).
Usage:
python TRAN.py [Input File]
'''
def Read_F... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2
import enum
comment i, j indexing
set dir_offset = list comprehension call asarray list i j dtype=int32 for tuple i j in list tuple - 1 0 tuple 0 1 tuple 1 0 tuple 0 - 1
class Direction extends IntEnum
begin
set UP = 0
set RIGHT = 1
set DOWN = 2
set LEFT = 3
end class
class SBPuzzle
begin
... | import numpy as np
import cv2
import enum
# i, j indexing
dir_offset = [
np.asarray([i, j], dtype=np.int32) for i, j in [(-1, 0), (0, 1), (1, 0), (0, -1)]
]
class Direction(enum.IntEnum):
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class SBPuzzle:
def __init__(
self,
n: int = 3,
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Nov 13 2020 Vi skal lave et program som gør følgende: Brug CSV reader til at læse CSV filen studerende.csv. Print på hver linje navn, uddannelse og alder. F.eks.: Navn: Jens Hansen, Studieretning: Design, Alder: 22 år. Skriv et program som beder en studerende om input... | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 2020
Vi skal lave et program som gør følgende:
Brug CSV reader til at læse CSV filen studerende.csv. Print på hver linje navn, uddannelse og alder.
F.eks.: Navn: Jens Hansen, Studieretning: Design, Alder: 22 år.
Skriv et program som beder en studerende om input i fo... | Python | zaydzuhri_stack_edu_python |
import sqlite3
set conn = call connect string example.db
set c = call cursor
comment Create table
comment c.execute("INSERT INTO user VALUES (NULL, 'yyecust','姚远','信息工程','2015')")
comment Save (commit) the changes
comment conn.commit()
comment We can also close the connection if we are done with it.
comment Just be sur... | import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Create table
#c.execute("INSERT INTO user VALUES (NULL, 'yyecust','姚远','信息工程','2015')")
# Save (commit) the changes
#conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been commi... | Python | zaydzuhri_stack_edu_python |
set name = string ankush
set dots = string ...................
print name + dots
print left strip name + dots
print right strip name + dots | name=" ankush "
dots="..................."
print(name+dots)
print(name.lstrip() + dots)
print(name.rstrip() + dots)
| Python | zaydzuhri_stack_edu_python |
function digits_of_num n
begin
set digits = list
set count = 0
set temp = n
while temp > 0
begin
set count = count + 1
append digits temp % 10
set temp = integer temp / 10
end
sort digits
return digits
end function | def digits_of_num(n):
digits = []
count = 0
temp = n
while(temp > 0):
count = count + 1
digits.append(temp%10)
temp = int(temp/10)
digits.sort()
return digits | Python | zaydzuhri_stack_edu_python |
comment assignment2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from pandas.plotting import scatter_matrix
set house = read csv string https://drive.google.com/uc?export=download&id=1kgJseOaDUCG-p-IoLIKbnL23XHUZPEwm
set reg = linear regression... | ##assignment2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from pandas.plotting import scatter_matrix
house = pd.read_csv('https://drive.google.com/uc?export=download&id=1kgJseOaDUCG-p-IoLIKbnL23XHUZPEwm')
reg=LinearRegression()
##check correl... | Python | zaydzuhri_stack_edu_python |
function rotate_x p a=0
begin
comment turn value to radians
set a = call radians a
set translation_mat = call matrix list list 1 0 0 0 list 0 cos a sin a 0 list 0 - sin a cos a 0 list 0 0 0 1 dtype=string float32
set new_p = p @ translation_mat
return new_p
end function | def rotate_x(p, a=0):
# turn value to radians
a = math.radians(a)
translation_mat = np.matrix([
[1,0,0,0],
[0,math.cos(a),math.sin(a),0],
[0,-math.sin(a),math.cos(a),0],
[0,0,0,1],
], dtype="float32")
new_p = p @ translation_mat
return new_p | Python | nomic_cornstack_python_v1 |
import ui.common
from ui.button import QuestionButton
from ui.colors import Color
from ui.component import Component
import ui.fonts as fonts
class OverrideQuestion extends Component
begin
function __init__ self device
begin
call __init__ 0 0 480 229
set device = device
end function
function on_repaint self screen
begi... | import ui.common
from ui.button import QuestionButton
from ui.colors import Color
from ui.component import Component
import ui.fonts as fonts
class OverrideQuestion(Component):
def __init__(self, device):
super().__init__(0, 0, 480, 229)
self.device = device
def on_repaint(self, scr... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Apr 27 21:41:01 2020 @author: Raman
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file , client , tools
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html... | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 21:41:01 2020
@author: Raman
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_co... | Python | zaydzuhri_stack_edu_python |
function test_auth_xml self
begin
set config = call get_config
if call getboolean string auth_test string enabled
begin
comment Run only if enabled
try
begin
set timestamp = call getint string auth_test string timestamp
end
except ValueError
begin
comment If timestamp is set to a none-integer, we'll just assume
comment... | def test_auth_xml(self):
config = get_config()
if config.getboolean('auth_test', 'enabled'):
# Run only if enabled
try:
timestamp = config.getint('auth_test', 'timestamp')
except ValueError:
# If timestamp is set to a none-intege... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
comment @return a ListNode
function removeNthFromEnd self head n
begin
if next is none
begin
ret... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
if head.next is None:
return None
... | Python | zaydzuhri_stack_edu_python |
for i in B
begin
set toLook at i = 1
end
set l = 0
set r = 0
set freq = dict
set cnt = 0
set minm = 1000000
while l < n
begin
while r < n and cnt < k
begin
if A at r in toLook
begin
if A at r in freq
begin
if freq at A at r == 0
begin
set cnt = cnt + 1
end
set freq at A at r = freq at A at r + 1
end
else
begin
set fre... | for i in B:
toLook[i] = 1
l = 0
r = 0
freq = {}
cnt = 0
minm = 1000000
while l < n:
while r < n and cnt < k:
if A[r] in toLook:
if A[r] in freq:
if freq[A[r]] == 0:
cnt += 1
freq[A[r]] += 1
else:
... | Python | zaydzuhri_stack_edu_python |
function manhattan a b
begin
return absolute a at 0 - b at 0 + absolute a at 1 - b at 1
end function
function read_data
begin
with open string input.txt as wires
begin
return list comprehension split strip line string , for line in wires
end
end function
function parse wires
begin
set pathes = dict 0 dict ; 1 dict
fo... | def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def read_data():
with open('input.txt') as wires:
return [line.strip().split(',') for line in wires]
def parse(wires):
pathes = {0: {}, 1: {}}
for i, wire in enumerate(wires):
x = 0
y = 0
n = 1
fo... | Python | zaydzuhri_stack_edu_python |
function configure_logging_file logger format file
begin
set handler = call FileHandler file
call setFormatter format
call addHandler handler
return logger
end function | def configure_logging_file(logger, format, file):
handler = logging.FileHandler(file)
handler.setFormatter(format)
logger.addHandler(handler)
return logger | Python | nomic_cornstack_python_v1 |
import unittest
from Setup.T1 import Base_Setup
from Actions.T1.login_page import LoginpageActions
from Actions.T1.main_page import MainpageActions
from Elements.T1.center_page import AccountElement
from Input_Data.T1.center_page import AccountData
from selenium.webdriver.support import expected_conditions as EC
from s... | import unittest
from Setup.T1 import Base_Setup
from Actions.T1.login_page import LoginpageActions
from Actions.T1.main_page import MainpageActions
from Elements.T1.center_page import AccountElement
from Input_Data.T1.center_page import AccountData
from selenium.webdriver.support import expected_conditions as EC
from s... | Python | zaydzuhri_stack_edu_python |
function testBufferNormal self
begin
set agent = call TabaAgent
set max_buffer_size = 10
set max_request_events = 100
set max_pending_reqs = 1
set server_requests_pending = list 0
set server_event_url = string
set dummy_mode = false
set events_1 = list string mock_event_1 string mock_event_2 string mock_event_3
set ev... | def testBufferNormal(self):
agent = taba_agent.TabaAgent()
agent.max_buffer_size = 10
agent.max_request_events = 100
agent.max_pending_reqs = 1
agent.server_requests_pending = [0]
agent.server_event_url = ''
agent.dummy_mode = False
events_1 = ["mock_event_1", "mock_event_2", "mock_even... | Python | nomic_cornstack_python_v1 |
comment An example of two classes,
comment a child and a parent class.
class Person extends object
begin
function __init__ self name
begin
set name = name
end function
end class
class Employee extends Person
begin
function __init__ self name salary
begin
comment The __init__ method defines the parameters necessary to i... | # An example of two classes,
# a child and a parent class.
class Person(object):
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self, name, salary):
# The __init__ method defines the parameters necessary to instantiate
# the Employee object. Notice tha... | Python | zaydzuhri_stack_edu_python |
function __call__ self *pipeline_factories exceptions=none wait=true
begin
return run *pipeline_factories exceptions=exceptions wait=wait
end function | def __call__(self, *pipeline_factories, exceptions=None, wait=True):
return self.run(*pipeline_factories, exceptions=exceptions, wait=wait) | Python | nomic_cornstack_python_v1 |
from decimal import Decimal , ROUND_HALF_UP
function symbol_for number
begin
return if expression number in weather_symbols then weather_symbols at number else number
end function
function bar_for number
begin
return bars at max 0 min 8 number
end function
function arrow_for direction
begin
set index = integer call qua... | from decimal import Decimal, ROUND_HALF_UP
def symbol_for(number):
return weather_symbols[number] if number in weather_symbols else number
def bar_for(number):
return bars[max(0, min(8, number))]
def arrow_for(direction):
index = int((direction / Decimal('45')).quantize(Decimal('1.'), rounding=ROUND_... | Python | zaydzuhri_stack_edu_python |
import turtle
set tuple x1 y1 = eval input string 첫번째 점에 대한 x1, y1 값을 입력하세요:
set tuple x2 y2 = eval input string 두번째 점에 대한 x2, y2 값을 입력하세요:
set distance = x2 - x1 ^ 2 + y2 - y1 ^ 2 ^ 0.5
call penup
call goto x1 y1
call pendown
write turtle string 점1
call goto x2 y2
write turtle string 점2
call penup
call goto x1 + x2 / ... | import turtle
x1, y1 = eval(input("첫번째 점에 대한 x1, y1 값을 입력하세요: "))
x2, y2 = eval(input("두번째 점에 대한 x2, y2 값을 입력하세요: "))
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.write("점1")
turtle.goto(x2, y2)
turtle.write("점2")
turtle.penup()
turtle.goto((x1 + ... | Python | zaydzuhri_stack_edu_python |
function get_closest_match indices1 indices2
begin
if length indices1 == 1 and length indices2 == 1
begin
return tuple indices1 at 0 indices2 at 0
end
set closest_match = tuple indices1 at 0 indices2 at 0
set min_dist = absolute closest_match at 0 at 0 - closest_match at 1 at 0
for pair in product indices1 indices2
beg... | def get_closest_match(indices1, indices2):
if len(indices1) == 1 and len(indices2) == 1:
return indices1[0], indices2[0]
closest_match = (indices1[0], indices2[0])
min_dist = np.abs(closest_match[0][0] - closest_match[1][0])
for pair in itertools.product(indices1, indices2):
di... | Python | nomic_cornstack_python_v1 |
function Scene_RenderEx _dur _iobjs _opos _omag _oang _marker=0 _screen=0
begin
try
begin
call renderScene _dur _iobjs _opos _omag _oang _marker == 1
end
except StimException as e
begin
write Log string ERROR format string Scene_Render(Ex): {0}, {1} value e
end
return LastErrC
end function | def Scene_RenderEx(_dur, _iobjs, _opos, _omag, _oang, _marker=0,
_screen=0):
try:
_Stim.renderScene(_dur, _iobjs, _opos, _omag, _oang, (_marker==1))
except stm.StimException as e:
ssp.Log.write("ERROR", "Scene_Render(Ex): {0}, {1}".format(e.value, e))
return _Stim.LastErrC | Python | nomic_cornstack_python_v1 |
from BeautifulSoup import BeautifulSoup as bs
from urllib2 import urlopen , Request
from lxml import etree
import json , re
function createItem url currentNodeLevel currentNodeName
begin
string Create individual items with name, level, url, children attributes
comment Get all the urls in a single page in order
set resp... | from BeautifulSoup import BeautifulSoup as bs
from urllib2 import urlopen, Request
from lxml import etree
import json, re
def createItem(url, currentNodeLevel, currentNodeName):
'''Create individual items with name, level, url, children attributes'''
# Get all the urls in a single page in order
response =... | Python | zaydzuhri_stack_edu_python |
function collect_level_info annotation
begin
set iscrowd = if expression annotation at string legible then 0 else 1
set vertices = array annotation at string vertices
set polygon = call Polygon vertices
set area = area
set tuple min_x min_y max_x max_y = bounds
set bbox = list min_x min_y max_x - min_x max_y - min_y
se... | def collect_level_info(annotation):
iscrowd = 0 if annotation['legible'] else 1
vertices = np.array(annotation['vertices'])
polygon = Polygon(vertices)
area = polygon.area
min_x, min_y, max_x, max_y = polygon.bounds
bbox = [min_x, min_y, max_x - min_x, max_y - min_y]
segmentation = [i for j ... | Python | nomic_cornstack_python_v1 |
function exists self
begin
return boolean call lookup name
end function | def exists(self):
return bool(self.bucket.lookup(self.name)) | Python | nomic_cornstack_python_v1 |
function _field_replace self key
begin
if field_replacements
begin
for tuple x y in field_replacements
begin
set key = replace key x y
end
end
return key
end function | def _field_replace(self, key: str) -> str:
if self.field_replacements:
for x, y in self.field_replacements:
key = key.replace(x, y)
return key | Python | nomic_cornstack_python_v1 |
function _write_act_files self ref_fasta qry_fasta coords_file outprefix
begin
string Writes crunch file and shell script to start up ACT, showing comparison of ref and qry
if verbose
begin
print string Making ACT files from ref_fasta qry_fasta coords_file
end
set ref_fasta = call relpath ref_fasta
set qry_fasta = call... | def _write_act_files(self, ref_fasta, qry_fasta, coords_file, outprefix):
'''Writes crunch file and shell script to start up ACT, showing comparison of ref and qry'''
if self.verbose:
print('Making ACT files from', ref_fasta, qry_fasta, coords_file)
ref_fasta = os.path.relpath(ref_fa... | Python | jtatman_500k |
comment -
from urllib import request
set url = string http://www.baidu.com
string response = RequestMethods.urlopen(GET,url) response = request.RequestMethods().urlopen(method=GET,url=url) response = RequestMethods().request(GET,url) *-coding:utf-8-*- from urllib3.request import RequestMethods from urllib3 import reque... | # -
from urllib import request
url = 'http://www.baidu.com'
'''
response = RequestMethods.urlopen(GET,url)
response = request.RequestMethods().urlopen(method=GET,url=url)
response = RequestMethods().request(GET,url)
*-coding:utf-8-*-
from urllib3.request import RequestMethods
from urllib3 import request
'''
respons... | Python | zaydzuhri_stack_edu_python |
import abc
comment Klasa odpowiedzialna za obsługę IN/OUT
class Controller extends object
begin
set __metaclass__ = ABCMeta
decorator abstractclassmethod
comment Wyświetlenie na planszy
function print self xy text
begin
string :param xy: (int. int) :param text: string
end function
decorator abstractclassmethod
comment ... | import abc
# Klasa odpowiedzialna za obsługę IN/OUT
class Controller(object):
__metaclass__ = abc.ABCMeta
# Wyświetlenie na planszy
@abc.abstractclassmethod
def print(self, xy, text):
"""
:param xy: (int. int)
:param text: string
"""
# Czyszczenie informacji dodatk... | Python | zaydzuhri_stack_edu_python |
string Part 1 Module
import click
from day_15.repair import count_steps
from shared.opcodes import read_codes
decorator call command
decorator call option string --input string input_path type=call Path exists=true default=string inputs\day_15.txt
function part_01 input_path
begin
string Part 1
with open input_path as ... | """Part 1 Module"""
import click
from day_15.repair import count_steps
from shared.opcodes import read_codes
@click.command()
@click.option("--input", "input_path", type=click.Path(exists=True), default="inputs\\day_15.txt")
def part_01(input_path):
"""Part 1"""
with open(input_path) as file_input:
c... | Python | zaydzuhri_stack_edu_python |
function gcd a b
begin
set r = a % b
if r == 0
begin
return b
end
else
begin
return call gcd b r
end
end function
set a = 45
set b = 81 | def gcd(a,b):
r = a % b
if r == 0:
return b
else:
return gcd(b,r)
a = 45
b = 81 | Python | zaydzuhri_stack_edu_python |
function copy_how_tos
begin
set source = call get_test_directory
set destination = call get_how_to_directory + string /Source_Code/HowTos
if not exists path destination
begin
make directories destination
end
end function | def copy_how_tos():
source = get_test_directory()
destination = get_how_to_directory() + "/Source_Code/HowTos"
if not os.path.exists(destination):
os.makedirs(destination)
| Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.