code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function trace self
begin
with named temporary file delete=false prefix=TRACER_FILE_PREFIX as f
begin
set prog = code + string
write f encode prog string utf-8
flush f
set _fname = name
set should_trace = trace_lines or trace_reads
try
begin
set prog_bytecode = compile prog name string exec
if should_trace
begin
call ... | def trace(self):
with NamedTemporaryFile(delete=False, prefix=TRACER_FILE_PREFIX) as f:
prog = self.transformed_module.code + '\n'
f.write(prog.encode('utf-8'))
f.flush()
self._fname = f.name
should_trace = self.trace_lines or self.trace_reads
... | Python | nomic_cornstack_python_v1 |
function bind_namespaces graph
begin
for tuple prefix ns in items NAMESPACES
begin
call bind prefix ns
end
return graph
end function | def bind_namespaces(graph):
for prefix, ns in NAMESPACES.items():
graph.bind(prefix, ns)
return graph | Python | nomic_cornstack_python_v1 |
function template_test_component dash_threaded app_name assert_callback update_component_callback prop_name prop_value prop_type=none component_base=COMPONENT_PYTHON_BASE **kwargs
begin
set driver = driver
set simple_app = call Dash __name__
comment generate a simple app to test the component's prop
set layout = call c... | def template_test_component(
dash_threaded,
app_name,
assert_callback,
update_component_callback,
prop_name,
prop_value,
prop_type=None,
component_base=COMPONENT_PYTHON_BASE,
**kwargs
):
driver = dash_threaded.driver
simple_app = dash.Das... | Python | nomic_cornstack_python_v1 |
function maven_download
begin
comment The URL to download from.
set maven_urls = dict string cygwin string http://www.us.apache.org/dist/maven/maven-3/3.5.3/binaries/apache-maven-3.5.3-bin.zip
set maven_url = maven_urls at platform
comment The path to save the installer to.
set file_name = split path string / at - 1
se... | def maven_download():
# The URL to download from.
maven_urls = {
'cygwin': 'http://www.us.apache.org/dist/maven/maven-3/3.5.3/binaries/apache-maven-3.5.3-bin.zip'
}
maven_url = maven_urls[sys.platform]
# The path to save the installer to.
file_name = urlsplit(maven_url).path.sp... | Python | nomic_cornstack_python_v1 |
import pymysql
from tkinter import *
from tkinter import messagebox
comment Define Functions ##
function insertData
begin
comment 1 데이터 베이스 연결
set con = call connect host=host user=user password=pw db=string pydb charset=string utf8
comment 2. 커서 오픈
set cur = call cursor
set id = get edt1
set uname = get edt2
set sql =... | import pymysql
from tkinter import *
from tkinter import messagebox
## Define Functions ##
def insertData():
# 1 데이터 베이스 연결
con=pymysql.connect(host=host, user=user, password=pw, db='pydb', charset='utf8')
# 2. 커서 오픈
cur=con.cursor()
id=edt1.get()
uname=edt2.get()
sql="insert into naverT... | Python | zaydzuhri_stack_edu_python |
import datetime
set date = now
print format string {:0>2}/{:0>2}/{} {:0>2}:{:0>2} day month year hour minute | import datetime
date = datetime.datetime.now()
print("{:0>2}/{:0>2}/{} {:0>2}:{:0>2}".format(date.day, date.month, date.year, date.hour, date.minute)) | Python | iamtarun_python_18k_alpaca |
function CalibrGet self signal_index
begin
comment Make Header
set hex_rep = call make_header string Signals.CalibrGet body_size=4
comment Arguments
set hex_rep = hex_rep + call to_hex signal_index 4
call send_command hex_rep
set response = call receive_response 8
set calibration = call hex_to_float32 response at slice... | def CalibrGet(self,signal_index):
## Make Header
hex_rep = self.NanonisTCP.make_header('Signals.CalibrGet', body_size=4)
## Arguments
hex_rep += self.NanonisTCP.to_hex(signal_index,4)
self.NanonisTCP.send_command(hex_rep)
response = self.Nanonis... | Python | nomic_cornstack_python_v1 |
import pylab
import random
function runTrials numFlips
begin
set numHeads = 0
for n in range numFlips
begin
if random < 0.5
begin
set numHeads = numHeads + 1
end
end
set numTails = numFlips - numHeads
return tuple numHeads numTails
end function
function sdv L
begin
set mean = sum L / decimal length L
set tot = 0
for i ... | import pylab
import random
def runTrials(numFlips):
numHeads = 0
for n in range(numFlips):
if random.random() < 0.5:
numHeads += 1
numTails = numFlips - numHeads
return numHeads, numTails
def sdv(L):
... | Python | zaydzuhri_stack_edu_python |
import os , glob , sys
import numpy as np
import math
import multiprocessing as mp
from sklearn.preprocessing import Imputer , scale , robust_scale , StandardScaler , RobustScaler
function standadization X
begin
comment replace nan feature with the median of column values
comment imp = Imputer(missing_values='NaN', str... | import os, glob, sys
import numpy as np
import math
import multiprocessing as mp
from sklearn.preprocessing import Imputer, scale, robust_scale, StandardScaler, RobustScaler
def standadization(X):
# replace nan feature with the median of column values
# imp = Imputer(missing_values='NaN', strategy='median', ax... | Python | zaydzuhri_stack_edu_python |
class Student
begin
function __init__ self name id
begin
set name = name
set id = id
end function
function Display self
begin
print name end=string
print id
end function
end class
if __name__ == string __main__
begin
set St1 = call Student string Hasib 54
set St2 = call Student string Sabbir 55
write fpt string call Di... | class Student:
def __init__(self, name, id):
self.name=name
self.id=id
def Display(self):
print(self.name, end='\t')
print(self.id)
if __name__=='__main__' :
St1=Student('Hasib', 54)
St2=Student('Sabbir', 55)
fpt.write(str(St1.Display()))
fpt.... | Python | zaydzuhri_stack_edu_python |
import random
comment Generate a list of unique random integers from 0 to 5
set random_integers = random sample range 6 6
comment Sort the list in ascending order
set sorted_integers = sorted random_integers
comment Repeat the sorted list to create an array of size 10
set array = sorted_integers * 2
print array | import random
# Generate a list of unique random integers from 0 to 5
random_integers = random.sample(range(6), 6)
# Sort the list in ascending order
sorted_integers = sorted(random_integers)
# Repeat the sorted list to create an array of size 10
array = sorted_integers * 2
print(array)
| Python | jtatman_500k |
from random import randint
from time import sleep
import os
from prettytable import PrettyTable
from random import choice
from string import ascii_uppercase
from string import ascii_lowercase
import msvcrt
comment economy in the 20th century
class Persona
begin
function __init__ self name sex
begin
set name = name
set ... | from random import randint
from time import sleep
import os
from prettytable import PrettyTable
from random import choice
from string import ascii_uppercase
from string import ascii_lowercase
import msvcrt
# economy in the 20th century
class Persona:
def __init__(self, name, sex):
self.name = name
... | Python | zaydzuhri_stack_edu_python |
function fetch_attached_lc self
begin
set resp = call describe_auto_scaling_groups
set used_lc = list comprehension lc for asg in get resp string AutoScalingGroups list for lc in list get asg string LaunchConfigurationName string if length lc > 0
set resp = call describe_launch_configurations LaunchConfigurationNames=u... | def fetch_attached_lc(self):
resp = self.asg.describe_auto_scaling_groups()
used_lc = [lc for asg in resp.get("AutoScalingGroups", [])
for lc in [asg.get("LaunchConfigurationName", "")] if len(lc) > 0]
resp = self.asg.describe_launch_configurations(
LaunchCon... | Python | nomic_cornstack_python_v1 |
function create_model input_shape n_classes optimizer=string rmsprop fine_tune=0 n_model=1
begin
comment Pretrained convolutional layers are loaded using the Imagenet weights.
comment Include_top is set to False, in order to exclude the model's fully-connected layers.
if n_model == 4
begin
set conv_base = call VGG19 in... | def create_model(input_shape, n_classes, optimizer='rmsprop', fine_tune=0, n_model=1):
# Pretrained convolutional layers are loaded using the Imagenet weights.
# Include_top is set to False, in order to exclude the model's fully-connected layers.
if n_model == 4:
conv_base = VGG19(include_top=Fa... | Python | nomic_cornstack_python_v1 |
function remove_target_value nums target
begin
set removed_list = list
for num in nums
begin
if num != target
begin
append removed_list num
end
end
return removed_list
end function | def remove_target_value(nums, target):
removed_list = []
for num in nums:
if num != target:
removed_list.append(num)
return removed_list
| Python | jtatman_500k |
function validate_params self
begin
pass
end function | def validate_params(self) :
pass | Python | nomic_cornstack_python_v1 |
function write self headerText=none
begin
if not pairs
begin
return string
end
set tuple glyphGlyph glyphGroupDecomposed groupGlyphDecomposed glyphGroup groupGlyph groupGroup = call getSeparatedPairs pairs
comment write the classes
set groups = dictionary side1Groups
update groups side2Groups
set classes = call getCla... | def write(self, headerText=None):
if not self.pairs:
return ""
glyphGlyph, glyphGroupDecomposed, groupGlyphDecomposed, glyphGroup, groupGlyph, groupGroup = self.getSeparatedPairs(self.pairs)
# write the classes
groups = dict(self.side1Groups)
groups.update(self.side2G... | Python | nomic_cornstack_python_v1 |
import sys
append path string ../
from numpy import *
from nlab import *
import matplotlib.pyplot as plt
from mayavi import mlab
set NGrid = 2 ^ 10
set Nx = square root NGrid
set dt = 0.1
set alpha = 0.1
set l = 3
set I = 3.0
comment The phi function
function phi x1 y1 x2 y2 u v
begin
set l = 2
set R = 15
set W0 = - 0.... | import sys
sys.path.append('../')
from numpy import *
from nlab import *
import matplotlib.pyplot as plt
from mayavi import mlab
NGrid = 2**10
Nx = sqrt(NGrid)
dt = 0.1
alpha = 0.1
l = 3
I = 3.0
# The phi function
def phi(x1, y1, x2, y2, u, v):
l = 2
R = 15
W0 = -0.2
dst = sqrt((x1-x2-l*u)**2 + (y1-y2-l*v)**2... | Python | zaydzuhri_stack_edu_python |
comment 继承的语法
comment 在python中,任何类都有一个共同的父类叫object
class Person
begin
set name = string NoName
set age = 0
comment 考试成绩是秘密,只要自己知道
set __score = 0
comment 小名,是受保护的,子类可以用,但不能公用
set _petname = string chaolin
function sleep self
begin
print string Sleeping.....
end function
end class
comment 父类写在括号内
class Teacher extends P... | # 继承的语法
# 在python中,任何类都有一个共同的父类叫object
class Person():
name = 'NoName'
age = 0
__score = 0 #考试成绩是秘密,只要自己知道
_petname = 'chaolin' #小名,是受保护的,子类可以用,但不能公用
def sleep(self):
print('Sleeping.....')
# 父类写在括号内
class Teacher(Person):
teacher_id = 9999
def make_test(self): #子类可以拥有单独的属性
... | Python | zaydzuhri_stack_edu_python |
function removeCompartmentType self *args
begin
return call Model_removeCompartmentType self *args
end function | def removeCompartmentType(self, *args):
return _libsbml.Model_removeCompartmentType(self, *args) | Python | nomic_cornstack_python_v1 |
from sympy import *
import copy
variance list string A1 string A2 string A3 string A4 string beta string x string L string EI
variance list string d1 string d2 string d3 string d4 string a string c string s
set bxl = beta * x / L
comment First, prove that I know what I am doing for an undamped bean
comment (mainly prov... | from sympy import *
import copy
var(['A1', 'A2', 'A3', 'A4', 'beta', 'x', 'L', 'EI'])
var(['d1','d2','d3','d4', 'a', 'c', 's'])
bxl = beta*x/L
#First, prove that I know what I am doing for an undamped bean
#(mainly proving I can do the derivation correctly in sympy)
W_y = A1*sin(bxl)+A2*cos(bxl)+A3*sinh(bxl)+A4*cos... | Python | zaydzuhri_stack_edu_python |
function New *args **kargs
begin
set obj = call __New_orig__
import itkTemplate
call New obj *args keyword kargs
return obj
end function | def New(*args, **kargs):
obj = itkHConcaveImageFilterIUS3IUS3.__New_orig__()
import itkTemplate
itkTemplate.New(obj, *args, **kargs)
return obj | Python | nomic_cornstack_python_v1 |
function _url_split self
begin
try
begin
set urlsplit_res = call urlsplit url
assert all list scheme netloc path
end
except Exception as e
begin
set valid_url = false
raise call URLParsingError format string URL "{}" could not be parsed by urlsplit url
end
end function | def _url_split(self):
try:
self.urlsplit_res = urlsplit(self.url)
assert all([self.urlsplit_res.scheme, self.urlsplit_res.netloc,
self.urlsplit_res.path])
except Exception as e:
self.valid_url = False
raise URLParsingError(
... | Python | nomic_cornstack_python_v1 |
function initNodePath self dnaNode hotKey=none
begin
comment Determine dnaNode Class Type
set nodeClass = call DNAGetClassType dnaNode
comment Did the user hit insert or space?
if hotKey
begin
comment Yes, make a new copy of the dnaNode
set dnaNode = call __class__ dnaNode
comment And determine dnaNode type and perform... | def initNodePath(self, dnaNode, hotKey = None):
# Determine dnaNode Class Type
nodeClass = DNAGetClassType(dnaNode)
# Did the user hit insert or space?
if hotKey:
# Yes, make a new copy of the dnaNode
dnaNode = dnaNode.__class__(dnaNode)
# And determin... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string measure.py Any measurements of quantities on the network
import networkx_extended as nx
import matplotlib.pyplot as plt
import time
import numpy as np
comment Find degree distribution
function getDegreeDist WeightedGraph
begin
string Gets the degree distribution for a weighted graph... | # -*- coding: utf-8 -*-
"""
measure.py
Any measurements of quantities on the network
"""
import networkx_extended as nx
import matplotlib.pyplot as plt
import time
import numpy as np
#Find degree distribution
def getDegreeDist(WeightedGraph):
'''Gets the degree distribution for a weighted graph whe... | Python | zaydzuhri_stack_edu_python |
function get_accessions self ID
begin
try
begin
set record = database at ID
end
except KeyError
begin
return - 1
end
set raw_accessions = record at string accessions
set split_accessions = split raw_accessions string ;
set acc_list = list
for acc in split_accessions
begin
append acc_list strip acc
end
return acc_list
... | def get_accessions(self,ID):
try:
record = self.database[ID]
except KeyError:
return -1
raw_accessions = record['accessions']
split_accessions = raw_accessions.split(';')
acc_list = []
for acc in split_accessions:
acc_list.append(a... | Python | nomic_cornstack_python_v1 |
comment Import dependencies
import os
import csv
comment Set file path
set csvfile = join path string Resources string budget_data.csv
comment Set variables
set total_months = 0
set total_profit = 0
set previous_profit = 0
set average_change = 0
set greatest_inc = 0
set greatest_dec = 0
set changes = list
set profit =... | # Import dependencies
import os
import csv
# Set file path
csvfile = os.path.join("Resources", "budget_data.csv")
# Set variables
total_months = 0
total_profit = 0
previous_profit = 0
average_change = 0
greatest_inc = 0
greatest_dec = 0
changes = []
profit = []
greatest_inc_mo = ""
greatest_dec_mo = ""
first_loop = T... | Python | zaydzuhri_stack_edu_python |
function reconstruct_avg img nnf patch_size=5
begin
set final = zeros like img
for i in range shape at 0
begin
for j in range shape at 1
begin
set dx0 = patch_size // 2
set dy0 = patch_size // 2
set dx1 = patch_size // 2 + 1
set dy1 = patch_size // 2 + 1
set dx0 = min j dx0
set dx1 = min shape at 0 - j dx1
set dy0 = mi... | def reconstruct_avg(img, nnf, patch_size=5):
final = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
dx0 = dy0 = patch_size // 2
dx1 = dy1 = patch_size // 2 + 1
dx0 = min(j, dx0)
dx1 = min(img.shape[0] - j, dx1)
... | Python | nomic_cornstack_python_v1 |
function GetFileViewPath output_dir
begin
return join path call GetCoverageReportRootDirPath output_dir FILE_VIEW_INDEX_FILE
end function | def GetFileViewPath(output_dir):
return os.path.join(
GetCoverageReportRootDirPath(output_dir), FILE_VIEW_INDEX_FILE) | Python | nomic_cornstack_python_v1 |
function _check_fov img affine shape
begin
set img = call check_niimg img
return shape at slice : 3 : == shape and call allclose call get_affine affine
end function | def _check_fov(img, affine, shape):
img = check_niimg(img)
return (img.shape[:3] == shape and
np.allclose(img.get_affine(), affine)) | Python | nomic_cornstack_python_v1 |
function byteToPixel self x y byte
begin
set setVF = false
for i in range 7 - 1 - 1
begin
set mask = 1
if byte ? mask ? i != 0
begin
comment Pixel at (x, y) commanded on
if not call getPixel x + 7 - i % PIXEL_WIDTH y % PIXEL_HEIGHT
begin
comment Pixel is off, so turn on this pixel
call setPixel x + 7 - i % PIXEL_WIDTH ... | def byteToPixel(self, x, y, byte):
setVF = False
for i in range(7, -1, -1):
mask = 1
if (byte & (mask << i) != 0):
# Pixel at (x, y) commanded on
if (not self.getPixel((x + 7 - i) % PIXEL_WIDTH, y % PIXEL_HEIGHT)):
# Pixel is o... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
string [x+'='+y for x,y in d.items()] [x+'=' for x in d.keys()] [x+'=' for x in d.values()] [x+'=' for x in d.values()] d.lower
set L = list string Hello string World 18 string IBM string Apple
set l1 = list comprehension x for x in L if is instance x str
set l2 = list comprehension lower x for x i... | #coding:utf-8
"""[x+'='+y for x,y in d.items()]
[x+'=' for x in d.keys()]
[x+'=' for x in d.values()]
[x+'=' for x in d.values()]
d.lower"""
L = ['Hello',"World",18,'IBM','Apple']
l1 = [x for x in L if isinstance(x,str)]
l2 = [x.lower() for x in L if isinstance(x,str)] | Python | zaydzuhri_stack_edu_python |
function Connect self
begin
string Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008
if connection is none
begin
set connection = call connect *[] keyword info
end
if commitOnEnd is true
begin
call autocommit
end
call _updateCheckTime
end function | def Connect(self):
"""
Creates a new physical connection to the database
@author: Nick Verbeck
@since: 5/12/2008
"""
if self.connection is None:
self.connection = MySQLdb.connect(*[], **self.connectionInfo.info)
if self.connectionInfo.commitOnEnd is True:
self.connection.autocommit()
se... | Python | jtatman_500k |
function output_inline self mode content forced=false basename=none
begin
return call render_output mode dict string content content
end function | def output_inline(self, mode, content, forced=False, basename=None):
return self.render_output(mode, {"content": content}) | Python | nomic_cornstack_python_v1 |
from tools.future import Future
import asyncio
function fetch_user_order
begin
return sleep 2 string Large Latte
end function
async function main
begin
set f = call fetch_user_order
print string Fetching user order...
print await f
end function
run call main
comment output:
comment Fetching user order...
comment Large ... | from tools.future import Future
import asyncio
def fetch_user_order() -> Future[str]:
return asyncio.sleep(2, 'Large Latte')
async def main():
f = fetch_user_order()
print('Fetching user order...')
print(await f)
asyncio.run(main())
#output:
# Fetching user order...
# Large Latte | Python | zaydzuhri_stack_edu_python |
function getnodebeliefs self node_p=none
begin
comment Verify pointer.
set node_p = call getnodenamed node_p
set nstates = call getnodenumberstates node_p
set argtypes = list c_void_p
set restype = call ndpointer string float32 ndim=1 shape=tuple nstates flags=string C
comment (node_bn* node)
comment prob_bn
return cal... | def getnodebeliefs(self, node_p=None):
node_p = self.getnodenamed(node_p) # Verify pointer.
nstates = self.getnodenumberstates(node_p)
cnetica.GetNodeBeliefs_bn.argtypes = [c_void_p]
cnetica.GetNodeBeliefs_bn.restype = ndpointer(
'float32', ndim=1, shape=(nstates,), flags='... | Python | nomic_cornstack_python_v1 |
function set_read_only self value=true
begin
call setReadOnly value
end function | def set_read_only(self, value: bool = True):
self.setReadOnly(value) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3.5
comment updated by ...: Loreto Notarantonio
comment Version ......: 11-12-2017 08.17.47
comment -----------------------------------------------
string modulo che dovrà contenere tutte le variabili destinate ad essere condivise tra i vari moduli del progetto. Verrà riempito dinamicamente dai ... | #!/usr/bin/python3.5
#
# updated by ...: Loreto Notarantonio
# Version ......: 11-12-2017 08.17.47
#
# -----------------------------------------------
'''
modulo che dovrà contenere tutte le variabili
destinate ad essere condivise tra i vari moduli del progetto.
Verrà riempito dinamicamente dai vai moduli e... | Python | zaydzuhri_stack_edu_python |
comment If last bit enabled, odd else even
function even_or_odd number
begin
return if expression number ? 1 then string odd else string even
end function
print string even_or_odd(1): call even_or_odd 1
print string even_or_odd(2): call even_or_odd 2
print string even_or_odd(3): call even_or_odd 3
print string even_or_... | # If last bit enabled, odd else even
def even_or_odd(number : int):
return "odd" if (number & (1)) else "even"
print('even_or_odd(1): ', even_or_odd(1))
print('even_or_odd(2): ', even_or_odd(2))
print('even_or_odd(3): ', even_or_odd(3))
print('even_or_odd(4): ', even_or_odd(4)) | Python | zaydzuhri_stack_edu_python |
function fill_subparser subparser
begin
call add_argument string size type=int choices=tuple 16 28 help=string height/width of the datapoints
call set_defaults func=convert_silhouettes
end function | def fill_subparser(subparser):
subparser.add_argument(
"size", type=int, choices=(16, 28),
help="height/width of the datapoints")
subparser.set_defaults(func=convert_silhouettes) | Python | nomic_cornstack_python_v1 |
from page_objects import AuthPage , MainPage , BasePage
from utilities import ReadConfig
set username = call get_username
set password = call get_password
string Позитивный тест авторизации
function sleep_test_auth_positive browser
begin
info string ========== test auth positive start =========
set driver = browser
set... | from page_objects import AuthPage, MainPage, BasePage
from utilities import ReadConfig
username = ReadConfig.get_username()
password = ReadConfig.get_password()
""" Позитивный тест авторизации """
def sleep_test_auth_positive(browser):
BasePage.logger.info('========== test auth positive start =========')
dri... | Python | zaydzuhri_stack_edu_python |
from typing import List
from heapq import heappop , heappush
function words_diff word1 word2
begin
string all words are of the same length
set diff = 0
for i in range length word1
begin
if word1 at i != word2 at i
begin
set diff = diff + 1
end
end
return diff
end function
function solve all_words begin_word end_word
be... | from typing import List
from heapq import heappop, heappush
def words_diff(word1, word2):
"""
all words are of the same length
"""
diff = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
diff += 1
return diff
def solve(
all_words: List[str],
begin_word: st... | Python | zaydzuhri_stack_edu_python |
function plot arg1 arg2=none xrange=none yrange=none ps=0 thick=1 xtitle=none ytitle=none color=string black noerase=false overplot=false position=none ylog=false xlog=false xr=none yr=none title=none label=none nodata=false linestyle=none markersize=none xaxis_formatter=none yaxis_formatter=none autoscalex=false autos... | def plot (arg1, arg2=None, xrange=None, yrange=None, ps=0, thick=1, xtitle=None, ytitle=None,
color='black', noerase=False, overplot=False,position=None, ylog=False,
xlog=False, xr=None, yr=None, title=None, label=None, nodata=False,
linestyle=None, markersize=None, xaxis_formatter=None,
yaxis_formatter=None, a... | Python | nomic_cornstack_python_v1 |
function build_preprocessor self
begin
set train_preprocessor = call from_pretrained model_dir cfg_dict=cfg preprocessor_mode=TRAIN
set eval_preprocessor = call from_pretrained model_dir cfg_dict=cfg preprocessor_mode=EVAL
return tuple train_preprocessor eval_preprocessor
end function | def build_preprocessor(self) -> Tuple[Preprocessor, Preprocessor]:
train_preprocessor = Preprocessor.from_pretrained(
self.model_dir,
cfg_dict=self.cfg,
preprocessor_mode=ModeKeys.TRAIN)
eval_preprocessor = Preprocessor.from_pretrained(
self.model_dir, cfg... | Python | nomic_cornstack_python_v1 |
comment ler o arquivo como uma lista de linhas
set lista = read lines arquivo
print lista
close arquivo | #ler o arquivo como uma lista de linhas
lista = arquivo.readlines()
print(lista)
arquivo.close()
| Python | zaydzuhri_stack_edu_python |
comment Shows how to use argparse to handle script arguments in a standard. way.
comment SOME RULES/BEST PRACTICES
comment Postitional parameters are typically mandatory
comment Flags (one-letter or words (-v --verbose)) are typically optional
comment For more info:
comment https://docs.python.org/3/library/argparse.ht... | #
#
# Shows how to use argparse to handle script arguments in a standard. way.
#
# SOME RULES/BEST PRACTICES
# Postitional parameters are typically mandatory
# Flags (one-letter or words (-v --verbose)) are typically optional
#
# For more info:
# https://docs.python.org/3/library/argparse.html#the-add-argument-method
#... | Python | zaydzuhri_stack_edu_python |
function click_apply_keywords_button self
begin
call click_apply_keywords_button
end function | def click_apply_keywords_button(self):
self._basket.click_apply_keywords_button() | Python | nomic_cornstack_python_v1 |
import requests
import json
function recognize_wav_file wav_name recognize_service_url
begin
with open wav_name string rb as binary_file
begin
set wav_data = bytearray read binary_file
end
print format string Data saved to {} wav_name
try
begin
set rsp = post recognize_service_url data=wav_data
print format string Resp... | import requests
import json
def recognize_wav_file(wav_name, recognize_service_url):
with open(wav_name, "rb") as binary_file:
wav_data = bytearray(binary_file.read())
print("Data saved to {}".format(wav_name))
try:
rsp = requests.post(recognize_service_url, data=wav_data)
print... | Python | zaydzuhri_stack_edu_python |
function client args
begin
from jina.clients import Client
call Client args
end function | def client(args: 'Namespace'):
from jina.clients import Client
Client(args) | Python | nomic_cornstack_python_v1 |
from nltk.tree import *
from nltk.grammar import *
function get_seqs raw_oracle_file save_to
begin
comment if seqs==False:
comment raw_oracle_file = '/home/anh/rnng_all/rnng_self/data/oracle_new/dev.oracle'
set f_read = open raw_oracle_file string r
set raw_seqs = list
set pos_tokens = list
set raw_tokens = list
set... | from nltk.tree import *
from nltk.grammar import *
def get_seqs(raw_oracle_file, save_to):
# if seqs==False:
# raw_oracle_file = '/home/anh/rnng_all/rnng_self/data/oracle_new/dev.oracle'
f_read = open(raw_oracle_file, 'r')
raw_seqs = []
pos_tokens = []
raw_tokens = []
unk_tokens = []
l... | Python | zaydzuhri_stack_edu_python |
function cubeDirections n
begin
set r = list comprehension 2.0 * t / n + 1 - 1 for t in range 1 n + 1
return list comprehension v / square root dot v v for v in list comprehension array list 1 y z for y in r for z in r
end function | def cubeDirections(n):
r = [2.0*t/(n+1)-1 for t in range(1,n+1)]
return [v / math.sqrt(np.dot(v,v)) for v in [np.array([1,y,z]) for y in r for z in r]] | Python | nomic_cornstack_python_v1 |
function add_model_insight self model_insight
begin
call add_model_insight model_insight
end function | def add_model_insight(self, model_insight: ModelInsight):
self._underlying_persistence.add_model_insight(model_insight) | Python | nomic_cornstack_python_v1 |
function card_index self
begin
return call CardIndex _move
end function | def card_index(self):
return lib.CardIndex(self._move) | Python | nomic_cornstack_python_v1 |
import platform
function print_machine_details
begin
string Print current machine details.
comment Get system name
set system_name = call system
comment Get node name
set system_node = call node
comment Get release
set system_release = release platform
comment get architecture
set system_architecture = call architectur... | import platform
def print_machine_details():
"""Print current machine details."""
# Get system name
system_name = platform.system()
# Get node name
system_node = platform.node()
# Get release
system_release = platform.release()
# get architecture
system_architecture = platform.archi... | Python | flytech_python_25k |
import pygame
from setting import setting
from pygame.sprite import Sprite
class niao
begin
function __init__ self ai_setting screen
begin
set screen = screen
set ai_setting = ai_setting
comment 加载zpy图像并获取外接矩形
set image = call convert_alpha
set rect = call get_rect
set screen_rect = call get_rect
comment 将zpy放在屏幕顶部中央
s... | import pygame
from setting import setting
from pygame.sprite import Sprite
class niao():
def __init__(self,ai_setting,screen):
self.screen=screen
self.ai_setting=ai_setting
#加载zpy图像并获取外接矩形
self.image=pygame.image.load('image/zpy.png').convert_alpha()
self.rect=self... | Python | zaydzuhri_stack_edu_python |
function test_create_order_with_missing_size self
begin
set url = reverse string order:create
set data = dict string pizza 1 ; string customer_name string John Doe ; string customer_address string Nowhere
set response = post url data format=string json
assert equal status_code HTTP_400_BAD_REQUEST
end function | def test_create_order_with_missing_size(self):
url = reverse('order:create')
data = {
'pizza': 1,
'customer_name': 'John Doe',
'customer_address': 'Nowhere'
}
response = self.client.post(url, data, format='json')
self.assertEqual(response.statu... | Python | nomic_cornstack_python_v1 |
comment Sum of nth Fibonacci series = F(n+2) -1
function fibonacci_sum_naive n
begin
set n = n % 60
if n <= 1
begin
return n
end
set previous = 0
set current = 1
comment notice here range is 2 to n+3(finish at n+2)
for _ in range 2 n + 3
begin
set tuple previous current = tuple current previous + current % 20
end
retur... | # Sum of nth Fibonacci series = F(n+2) -1
def fibonacci_sum_naive(n):
n = n%60
if n <= 1:
return n
previous = 0
current = 1
# notice here range is 2 to n+3(finish at n+2)
for _ in range(2, n+3):
previous, current = current, (previous + current)%20
return (current - 1... | Python | zaydzuhri_stack_edu_python |
function get_starter_file_entries self course_id starter_file_group_id
begin
return get requests call _url string courses/ { course_id } /starter_file_groups/ { starter_file_group_id } /entries headers=_auth_header
end function | def get_starter_file_entries(self, course_id: int, starter_file_group_id: int) -> requests.Response:
return requests.get(
self._url(f"courses/{course_id}/starter_file_groups/{starter_file_group_id}/entries"),
headers=self._auth_header,
) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function nextGreatestLetter self letters target
begin
comment 二分查找
set n = length letters
set l = 0
set h = n - 1
while l <= h
begin
set m = integer l + h - l / 2
if letters at m <= target
begin
set l = m + 1
end
else
begin
set h = m - 1
end
end
if l < n
begin
return letters at l
end
else
begin
ret... | class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
#二分查找
n = len(letters)
l = 0
h = n-1
while (l <= h):
m = int(l + (h-l)/2)
if( letters[m] <= target ):
l = m+1
else:
... | Python | zaydzuhri_stack_edu_python |
set A = integer input
set B = integer input
set C = integer input
set D = integer input
set P = integer input
set X = A * P
set Y = if expression C < P then B + P - C * D else B
set M = if expression X < Y then X else Y
print M | A = int(input())
B = int(input())
C = int(input())
D = int(input())
P = int(input())
X = A*P
Y = B+(P-C)*D if C < P else B
M = X if X < Y else Y
print(M) | Python | zaydzuhri_stack_edu_python |
function build_export_filenames outdir filename_list order overwrite
begin
if order
begin
set filename_list = call order_filenames filename_list
end
else
begin
set filename_list = call unique_filenames filename_list
end
set filepath_list = list comprehension join path outdir filename for filename in filename_list
if no... | def build_export_filenames(outdir, filename_list, order, overwrite):
if order:
filename_list = order_filenames(filename_list)
else:
filename_list = unique_filenames(filename_list)
filepath_list = [os.path.join(outdir, filename)
for filename in filename_list]
if not ... | Python | nomic_cornstack_python_v1 |
comment or
print string The pet shop owner said "No,no,'e's uh,....he's resting".
print string "The pet shop owner said "No,no,'e's uh,....he's resting".
set anotherSplitString = string The string has beensplit overseveral lines
print anotherSplitString | # or
print("The pet shop owner said \"No,no,'e's uh,....he's resting\".")
print(""""The pet shop owner said "No,no,'e's uh,....he's resting".""")
anotherSplitString = """The string has been\
split over\
several \
lines """
print(anotherSplitString) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-"""
set V = string fish and chips
set W = string sushi
set X = string churros
set Y = string donuts
set Z = string paella
set sampleV = string static/fish_and_chips.jpg
set sampleW = string static/sushi.jpg
set sampleX = string static/eclairfull.png
set sampleY... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-"""
V = "fish and chips"
W = "sushi"
X = "churros"
Y = "donuts"
Z = "paella"
sampleV = "static/fish_and_chips.jpg"
sampleW = "static/sushi.jpg"
sampleX = "static/eclairfull.png"
sampleY = "static/eclair.png"
sampleZ = "static/paella.jpg"
UPLOAD_FOLDER = "static/uploads"
... | Python | zaydzuhri_stack_edu_python |
function findMultiples n
begin
set sum = 0
set count = 0
for i in range 1 1000
begin
if i % 3 == 0 or i % 5 == 0
begin
set sum = sum + i
set count = count + 1
end
end
print sum
print count
return sum
end function
call findMultiples 1000 | def findMultiples(n):
sum = 0
count = 0
for i in range (1, 1000):
if (i % 3 == 0 or i % 5 == 0):
sum += i
count = count + 1
print(sum)
print(count)
return sum
findMultiples(1000)
| Python | zaydzuhri_stack_edu_python |
string def gugu(dan): for i in range(1,10): print(dan,"x",i,"=",(dan*i)) dan=int(input('단을 입력하세요: ')) gugu(dan)
function oneInput msg
begin
set num = decimal input msg
return num
end function
function twoInput
begin
set width = decimal input string 가로 입력:
set height = decimal input string 세로 입력:
return tuple width heig... | '''def gugu(dan):
for i in range(1,10):
print(dan,"x",i,"=",(dan*i))
dan=int(input('단을 입력하세요: '))
gugu(dan)
'''
def oneInput(msg):
num=float(input(msg))
return num
def twoInput():
width=float(input('가로 입력: '))
height=float(input('세로 입력: '))
return width, height
'''def rectArea():
rli... | Python | zaydzuhri_stack_edu_python |
function json_output result json_file=join path absolute path path directory name path __file__ string OMDb_Ratings.txt
begin
with open json_file string w as f
begin
dump result f indent=4
end
print format string Query output created at {} json_file
end function | def json_output(result, json_file=os.path.join(os.path.abspath(os.path.dirname(__file__)),'OMDb_Ratings.txt')):
with open(json_file, 'w') as f:
json.dump(result, f, indent=4)
print('Query output created at {}'.format(json_file)) | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_okarray_nanarray_infarray_okarray_a_32 self
begin
comment This version is expected to pass.
call fma okarrayx okarrayy okarrayz arrayout matherrors=true
comment This should raise an error.
with assert raises ArithmeticError
begin
call fma okarrayx nanarrayy infarrayz arrayout
end
end functio... | def test_fma_nan_param_okarray_nanarray_infarray_okarray_a_32(self):
# This version is expected to pass.
arrayfunc.fma(self.okarrayx, self.okarrayy, self.okarrayz, self.arrayout, matherrors=True)
# This should raise an error.
with self.assertRaises(ArithmeticError):
arrayfunc.fma(self.okarrayx, self.nanarra... | Python | nomic_cornstack_python_v1 |
function next_move hunter_position hunter_heading target_measurement max_distance OTHER=none
begin
comment This function will be called after each time the target moves.
comment The OTHER variable is a place for you to store any historical information about
comment the progress of the hunt (or maybe some localization i... | def next_move(hunter_position, hunter_heading, target_measurement, max_distance, OTHER = None):
# This function will be called after each time the target moves.
# The OTHER variable is a place for you to store any historical information about
# the progress of the hunt (or maybe some localization informati... | Python | nomic_cornstack_python_v1 |
try
begin
print planets at integer n - 1
end
except any
begin
print string 존재하지 않는 숫자
end | try:
print(planets[int(n) - 1])
except:
print('존재하지 않는 숫자') | Python | zaydzuhri_stack_edu_python |
function sublist lista start fin
begin
set sub = list
for i in range start fin
begin
append sub lista at i
end
return sub
end function
function binary_search lista elem
begin
if length lista > 1
begin
return lista at 0
end
else
begin
set mitad = length lista // 2
end
end function | def sublist(lista,start,fin):
sub=[]
for i in range(start,fin):
sub.append(lista[i])
return sub
def binary_search(lista,elem):
if len(lista)>1:
return lista[0]
else:
mitad=len(lista)//2 | Python | zaydzuhri_stack_edu_python |
function listen self timeout=0
begin
set out = list
if not socket
begin
return out
end
set timeout = if expression not timeout then none else timeout * 1e-06
set t0 = time
while true
begin
try
begin
set tuple r w e = select _select list socket list list socket timeout
if length e
begin
raise call SendError string sel... | def listen(self, timeout=0):
out = []
if not self.socket: return out
timeout = None if not timeout else timeout*1E-6
t0 = _time.time()
while True:
try:
r,w,e = _select.select([self.socket], [], [self.socket], timeout)
if len(e): raise S... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Python 3.6
comment Import the Halite SDK, which will let you interact with the game.
import hlt
from hlt.task import Task
comment This library contains constant values.
from hlt import constants
comment This library contains direction metadata to better interface with the game.
fro... | #!/usr/bin/env python3
# Python 3.6
# Import the Halite SDK, which will let you interact with the game.
import hlt
from hlt.task import Task
# This library contains constant values.
from hlt import constants
# This library contains direction metadata to better interface with the game.
from hlt.positionals import Dire... | Python | zaydzuhri_stack_edu_python |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems openapi_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
function longest_word string
begin
set string = split string
return max string key=len
end function
print call longest_word string 012 3456 098765 65
function longest_word_loop string
begin
set string = split string
set max_s = 0
set result = string
for s in string
begin
if length s > max_s
begin
set max_s = length s
... | def longest_word(string):
string = string.split()
return max(string, key=len)
print(longest_word(' 012 3456 098765 65'))
def longest_word_loop(string):
string = string.split()
max_s = 0
result = ''
for s in string:
if len(s) > max_s:
max_s = len(s)
result = s... | Python | zaydzuhri_stack_edu_python |
function create_release config args
begin
yield call create_release tag_name name=name target_commitish=get args string target_commitish body=get args string body draft=call get_bool string draft prerelease=call get_bool string prerelease
end function | def create_release(config, args):
yield config.repo.create_release(args.tag_name, name=args.name,
target_commitish=args.get("target_commitish"), body=args.get("body"),
draft=args.get_bool("draft"), prerelease=args.get_bool("prerelease")) | Python | nomic_cornstack_python_v1 |
import sys
function returnExtend x y
begin
set z = x
extend z y
return z
end function
function returnAppend a l
begin
return call returnExtend list a l
end function
function allcomb l
begin
assert length l
if length l is 1
begin
return list l
end
set lrst = list
set s = set
for i in range length l
begin
if l at i in s... | import sys
def returnExtend(x,y):
z = x
z.extend(y)
return z
def returnAppend(a,l):
return returnExtend(list(a),l)
def allcomb(l):
assert len(l)
if len(l) is 1:
return [l]
lrst = []
s = set()
for i in range(len(l)):
if l[i] in s:
continue
a = l[:i]
a.extend(l[i+1:])
lsub = allcomb(a)
lnew =... | Python | zaydzuhri_stack_edu_python |
string Script for Tkinter GUI chat client.
from socket import AF_INET , socket , SOCK_STREAM
from threading import Thread , Lock
from tkinter import *
import chess
set BUFFER_SIZE = 1024
set LOCK = lock
class Connection
begin
function __init__ self host port
begin
set host = host
set port = port
set addr = tuple host p... | """Script for Tkinter GUI chat client."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread, Lock
from tkinter import *
import chess
BUFFER_SIZE = 1024
LOCK = Lock()
class Connection:
def __init__(self, host, port):
self.host = host
self.port = port
self.addr = ... | Python | zaydzuhri_stack_edu_python |
function dlt_homography I1pts I2pts
begin
comment --- FILL ME IN ---
comment Construct DLT Matrix A:
comment Iterating through all of the provided points:
for i in range 0 length I1pts at 0
begin
if i == 0
begin
set A = array list - I1pts at 0 at i - I1pts at 1 at i - 1 0 0 0 I1pts at 0 at i * I2pts at 0 at i I1pts at ... | def dlt_homography(I1pts, I2pts):
# --- FILL ME IN ---
# Construct DLT Matrix A:
# Iterating through all of the provided points:
for i in range(0, len(I1pts[0])):
if i == 0:
A = np.array([-I1pts[0][i], -I1pts[1][i], -1, 0, 0, 0,
I1pts[0][i] * I2pts[0][i], I... | Python | nomic_cornstack_python_v1 |
function output1 inputImg
begin
set finalArr1 = call empty shape=tuple length inputImg length inputImg at 0 dtype=string object
set finalArr1 at slice : : = string
for value in range 1 newLabel
begin
set flag = false
print string -------------------- value
set arr = call empty shape=tuple length inputImg length inp... | def output1(inputImg):
finalArr1 = np.empty(shape=(len(inputImg), len(inputImg[0])), dtype='object')
finalArr1[:] = ' '
for value in range(1, newLabel):
flag = False
print('--------------------',value)
arr = np.empty(shape=(len(inputImg), len(inputImg[0])), dtype='object')
ar... | Python | zaydzuhri_stack_edu_python |
function generate_best_split self ind dep wt=none
begin
set split = split none none none none 0
set relative_split_threshold = 1 - split_threshold
set all_dep = unique arr
for tuple i ind_var in enumerate ind
begin
set ind_var = call deep_copy
set unique = unique arr
set freq = dict
if wt is none
begin
for col in uniq... | def generate_best_split(self, ind, dep, wt=None):
split = Split(None, None, None, None, 0)
relative_split_threshold = 1 - self.split_threshold
all_dep = np.unique(dep.arr)
for i, ind_var in enumerate(ind):
ind_var = ind_var.deep_copy()
unique = np.unique(ind_var.a... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python3
comment -*- coding:utf-8 -*-
comment @Time: 2021/2/4
comment @Author: Lingchen
comment @Prescription: 编写测试用例.
comment 需要继承unittest.TestCase.
comment 方法必须以test_开头.
comment page_208.
import unittest
from name_fun import get_formatted_name
class NamesTestCase extends TestCase
begin
string 测试name... | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Time: 2021/2/4
# @Author: Lingchen
# @Prescription: 编写测试用例.
# 需要继承unittest.TestCase.
# 方法必须以test_开头.
# page_208.
import unittest
from name_fun import get_formatted_name
class NamesTestCase(unittest.TestCase):
""" 测试name_fun... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function lemonadeChange self bills
begin
set tuple i j = tuple 0 0
for num in bills
begin
if num == 5
begin
set i = i + 1
end
if num == 10
begin
set j = j + 1
set i = i - 1
end
if num == 20
begin
if j > 0
begin
set j = j - 1
set i = i - 1
end
else
begin
set i = i - 3
end
end
if i < 0
begin
return f... | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
i,j = 0,0
for num in bills:
if num==5:
i+=1
if num==10:
j+=1
i-=1
if num==20:
if j>0:
j-=1
i-=1
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set _contents = list
end function | def __init__(self) -> None:
self._contents = [] | Python | nomic_cornstack_python_v1 |
function handle self
begin
set response = response
set elts = url parse env at string PATH_INFO + string ? + env at string QUERY_STRING
set url = elts at 2
comment default
call add_header string Content-Type string text/html
set tuple kind arg = call resolve url
if kind == string file
begin
if not exists path arg
begin... | def handle(self):
response = self.response
self.elts = urllib.parse.urlparse(self.env["PATH_INFO"]+
"?"+self.env["QUERY_STRING"])
self.url = self.elts[2]
response.headers.add_header("Content-Type", "text/html") # default
kind, arg = self.resolve(self.url)
if ... | Python | nomic_cornstack_python_v1 |
function process self pubs
begin
for tuple position pub in enumerate pubs
begin
set entry = call processEntry pub
set position = position
add session entry
end
call fixBullets
commit session
end function | def process(self, pubs):
for position, pub in enumerate(pubs):
entry = self.processEntry(pub)
entry.position = position
self.session.add(entry)
self.fixBullets()
self.session.commit() | Python | nomic_cornstack_python_v1 |
function _evaluate_quality self fit_data
begin
set freq_increment = mean np diff np x_data
set fit_a = ufloat_params at string a
set fit_b = ufloat_params at string b
set fit_freq = ufloat_params at string freq
set fit_kappa = ufloat_params at string kappa
set snr = absolute n / square root absolute median y_data - n
s... | def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:
freq_increment = np.mean(np.diff(fit_data.x_data))
fit_a = fit_data.ufloat_params["a"]
fit_b = fit_data.ufloat_params["b"]
fit_freq = fit_data.ufloat_params["freq"]
fit_kappa = fit_data.ufloat_param... | Python | nomic_cornstack_python_v1 |
comment @Time : 2019/7/19 8:43
comment @Author : Xu Huipeng
comment @Blog : https://brycexxx.github.io/
import math
class Solution
begin
function computeArea self A B C D E F G H
begin
set area = C - A * D - B + G - E * H - F
if A >= G or B >= H or F >= D or E >= C
begin
return area
end
set x_min = max A E
set y_min = ... | # @Time : 2019/7/19 8:43
# @Author : Xu Huipeng
# @Blog : https://brycexxx.github.io/
import math
class Solution:
def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
area = (C - A) * (D - B) + (G - E) * (H - F)
if A >= G or B >= H or F >= D or E >=... | Python | zaydzuhri_stack_edu_python |
set arr = list map int split input
sort arr
print absolute arr at 0 - arr at 1 + absolute arr at 1 - arr at 2 | arr = list(map(int, input().split()))
arr.sort()
print(abs(arr[0]-arr[1])+abs(arr[1]-arr[2]))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Search result page
set __author__ = string Shixuan Li
set __credits__ = string Shixuan Li
set __version__ = string 1.0.1
set __maintainer__ = string Shixuan Li
set __email__ = string lishixuan001@berkeley.edu
set __status__ = string Test
import tkinter as tk
from tkinter import messa... | #!/usr/bin/env python
""" Search result page """
__author__ = "Shixuan Li"
__credits__ = "Shixuan Li"
__version__ = "1.0.1"
__maintainer__ = "Shixuan Li"
__email__ = "lishixuan001@berkeley.edu"
__status__ = "Test"
import tkinter as tk
from tkinter import messagebox
import pickle
import os
import webbrowser
"""
Star... | Python | zaydzuhri_stack_edu_python |
function _replaced __values **__replacements
begin
string Replace elements in iterable with values from an alias dict, suppressing empty values. Used to consistently enhance how certain fields are displayed in list and detail pages.
return tuple generator expression o for o in generator expression get __replacements na... | def _replaced(__values, **__replacements):
"""
Replace elements in iterable with values from an alias dict, suppressing empty values.
Used to consistently enhance how certain fields are displayed in list and detail pages.
"""
return tuple(o for o in (__replacements.get(name, name) for name in __val... | Python | jtatman_500k |
function find_lines_by_parent_line_id self parent_line_id
begin
for line in _data_lines
begin
if call text_type get line string parent_line_id == call text_type parent_line_id
begin
yield line
end
end
end function | def find_lines_by_parent_line_id(self, parent_line_id):
for line in self._data_lines:
if six.text_type(line.get("parent_line_id")) == six.text_type(parent_line_id):
yield line | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import re
import gzip
set file = open string /Users/anuragp/thoughtworks-repo/personal-workspace/home-test/06-python-script/pagecounts-20160101-000000.gz string rt
set Lines = read lines file
set count = 0
for line in Lines
begin
set lineList = split line string
set domain = lineList at 0
... | # -*- coding: utf-8 -*-
import re
import gzip
file = gzip.open('/Users/anuragp/thoughtworks-repo/personal-workspace/home-test/06-python-script/pagecounts-20160101-000000.gz', 'rt')
Lines = file.readlines()
count = 0;
for line in Lines:
lineList = line.split(" ")
domain = lineList[0]
if(dom... | Python | zaydzuhri_stack_edu_python |
function in_network scope prefixes destination default_pfxlen=list 24
begin
set needle = call ip2int destination at 0
for prefix in prefixes
begin
set tuple network pfxlen = call parse_prefix prefix default_pfxlen at 0
set mask = call pfxlen2mask_int pfxlen
if needle ? mask == call ip2int network ? mask
begin
return li... | def in_network(scope, prefixes, destination, default_pfxlen=[24]):
needle = ipv4.ip2int(destination[0])
for prefix in prefixes:
network, pfxlen = ipv4.parse_prefix(prefix, default_pfxlen[0])
mask = ipv4.pfxlen2mask_int(pfxlen)
if needle & mask == ipv4.ip2int(network) & mask:
... | Python | nomic_cornstack_python_v1 |
function combineBboxes bb1 bb2
begin
set tuple x1 x2 y1 y2 = bb1
set tuple x1b x2b y1b y2b = bb2
set bb = tuple min x1 x1b max x2 x2b min y1 y1b max y2 y2b
return bb
end function | def combineBboxes(bb1,bb2):
x1,x2,y1,y2 = bb1
x1b,x2b,y1b,y2b = bb2
bb = min(x1,x1b), max(x2,x2b), min(y1,y1b), max(y2,y2b)
return bb | Python | nomic_cornstack_python_v1 |
import flask , flask.views
import os
import functools
import requests
import json
import pprint
string def parse_rough_draft(json_dict_output): books = json_dict_output[u'book'] result_dict={} for i in books: book_name_variable = i[u'book_name'] current_book_value = result_dict.setdefault(book_name_variable, {}) chapte... | import flask, flask.views
import os
import functools
import requests
import json
import pprint
"""
def parse_rough_draft(json_dict_output):
books = json_dict_output[u'book']
result_dict={}
for i in books:
book_name_variable = i[u'book_name']
current_book_value = result_dict.setdefault(book_... | Python | zaydzuhri_stack_edu_python |
function getColumnSortedOutputAttributes self
begin
set outputAttributes = list
for attribute in values _attributes
begin
if call isOutputAttribute
begin
append outputAttributes attribute
end
end
return sorted outputAttributes key=lambda attribute -> outputOrder
end function | def getColumnSortedOutputAttributes(self):
outputAttributes = []
for attribute in self._attributes.values():
if (attribute.isOutputAttribute()):
outputAttributes.append(attribute)
return sorted (outputAttributes, key=lambda attribute: attribute.outputOrder) | Python | nomic_cornstack_python_v1 |
function make_discrete_forward_solutions info rr vbem trans_true trans_man subjects_dir source_ori=string random fn_fwd_disc_true=none fn_fwd_disc_man=none
begin
comment Construct source space normals as random vectors
set rnd_vectors = array list comprehension call random_three_vector for i in range shape at 0
if sour... | def make_discrete_forward_solutions(info, rr, vbem, trans_true, trans_man, subjects_dir,
source_ori='random', fn_fwd_disc_true=None, fn_fwd_disc_man=None):
###########################################################################
# Construct source space normals as random ... | Python | nomic_cornstack_python_v1 |
set x = 1
print x
call breakpoint
set x = 2
print x
call breakpoint
set x = 3
print x | x = 1
print(x)
breakpoint()
x = 2
print(x)
breakpoint()
x = 3
print(x)
| Python | zaydzuhri_stack_edu_python |
import h1.h1model.plot_functions as h1_plot
from scipy.interpolate import griddata as scipy_griddata
import numpy as np
import matplotlib.pyplot as pt
import BOOZER
comment Note mayavi.mlab is imported for certain functions
string This set of classes provides a way to determine the geometry of LOS diagnostics in Boozer... | import h1.h1model.plot_functions as h1_plot
from scipy.interpolate import griddata as scipy_griddata
import numpy as np
import matplotlib.pyplot as pt
import BOOZER
#Note mayavi.mlab is imported for certain functions
'''
This set of classes provides a way to determine the geometry of LOS
diagnostics in Boozer co-ordin... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
set dataset = read csv string 50_Startups.csv
comment The features
set x = values
set y = values
comment Create one hot encoder for the country
from sklearn.preprocessing import LabelEncoder , OneHotEncoder
comment In order to apply the onehotencode... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('50_Startups.csv')
# The features
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,4].values
#Create one hot encoder for the country
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#In order to apply the onehot... | 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.