code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function lfilter_zi b a
begin
set b = call atleast_1d b
if ndim != 1
begin
raise call ValueError string Numerator b must be 1-D.
end
set a = call atleast_1d a
if ndim != 1
begin
raise call ValueError string Denominator a must be 1-D.
end
while length a > 1 and a at 0 == 0.0
begin
set a = a at slice 1 : :
end
if size ... | def lfilter_zi(b, a):
b = cp.atleast_1d(b)
if b.ndim != 1:
raise ValueError("Numerator b must be 1-D.")
a = cp.atleast_1d(a)
if a.ndim != 1:
raise ValueError("Denominator a must be 1-D.")
while len(a) > 1 and a[0] == 0.0:
a = a[1:]
if a.size < 1:
raise ValueError... | Python | nomic_cornstack_python_v1 |
from pprint import pprint
set T = integer input
set data = list
for _ in range T
begin
set n = integer input
set board = list
for __ in range n
begin
append board list
set tmp = split input
for number in tmp
begin
if number == string 0
begin
append board at - 1 100000
end
else
begin
append board at - 1 integer number... | from pprint import pprint
T = int(input())
data = []
for _ in range(T):
n = int(input())
board = []
for __ in range(n):
board.append([])
tmp = input().split()
for number in tmp:
if number == "0":
board[-1].append(100000)
else:
b... | Python | zaydzuhri_stack_edu_python |
function compute_all_indicators self
begin
comment Moving data to Audit Temp
call audit_trail
comment Calculating indicators
call pupils_teachers_ratio
call newly_recruited_teachers
call teachers_percentage_female
call percentage_trained_teachers
call percentage_private_teachers
call percentage_non_permanent_teachers
c... | def compute_all_indicators(self):
### Moving data to Audit Temp
self.audit_trail()
##### Calculating indicators
self.pupils_teachers_ratio()
self.newly_recruited_teachers()
self.teachers_percentage_female()
self.percentage_trained_teachers()
self.... | Python | nomic_cornstack_python_v1 |
function register_view self path name=none urlname=none visible=true view=none app=none
begin
if view is not none
begin
append custom_views tuple path view name urlname visible app
return
end
function decorator fn
begin
append custom_views tuple path fn name urlname visible app
return fn
end function
return decorator
e... | def register_view(self, path, name=None, urlname=None, visible=True,
view=None, app=None):
if view is not None:
self.custom_views.append((path, view, name, urlname, visible, app))
return
def decorator(fn):
self.custom_views.append((path, fn, nam... | Python | nomic_cornstack_python_v1 |
function h_m_s num
begin
if is instance num int and num > 0
begin
return tuple num // 3600 num % 3600 // 60 num % 3600 % 60
end
else
begin
raise call ValueError string argumento invalido
end
end function | def h_m_s(num):
if isinstance(num,int) and num > 0:
return (num//3600,num%3600//60,num%3600%60)
else:
raise ValueError('argumento invalido') | Python | zaydzuhri_stack_edu_python |
import pandas as pd
string Build a DataFrame via a zipped list
set a = list 1980 1981 1982
set b = list string Blondie string Chistorpher Cross string Joan Jett
set c = list string Call Me string Arthurs Theme string I Love Rock and Roll
set d = list 6 3 7
set col_labels = list string year string artist string song str... | import pandas as pd
"""Build a DataFrame via a zipped list"""
a = [1980, 1981, 1982]
b = ['Blondie', 'Chistorpher Cross', 'Joan Jett']
c = ['Call Me', 'Arthurs Theme', 'I Love Rock and Roll']
d = [6, 3, 7]
col_labels = ['year', 'artist', 'song', 'chart weeks']
li_df = pd.DataFrame(list(zip(a, b, c, d)), columns=col_l... | Python | zaydzuhri_stack_edu_python |
comment Program to count the number of votes for each political party in an election.
comment Names of parties need to be entered (terminated by the word DONE) and votes per party should be kept track of.
comment No pre-determined party list so the list must be created as party names are encountered.
comment Names of t... | # Program to count the number of votes for each political party in an election.
# Names of parties need to be entered (terminated by the word DONE) and votes per party should be kept track of.
# No pre-determined party list so the list must be created as party names are encountered.
# Names of the parties and thei... | Python | zaydzuhri_stack_edu_python |
function create_variable name shape
begin
set initialiser = call xavier_initializer_conv2d dtype=float32
set variable = call Variable call initialiser shape=shape name=name
call histogram name variable
return variable
end function | def create_variable(name, shape):
initialiser = tf.contrib.layers.xavier_initializer_conv2d(dtype=tf.float32)
variable = tf.Variable(initialiser(shape=shape), name=name)
tf.summary.histogram(name, variable)
return variable | Python | nomic_cornstack_python_v1 |
function save_data data file_name
begin
set filename = file_name
set file = open filename string w
call truncate
set count = 0
for contour in data
begin
write file format string Contour Cluster {}: count
for key in keys contour
begin
set current_value = get contour key
call format_data_dict file current_value key 1
end... | def save_data(data,file_name):
filename = file_name
file = open(filename, 'w')
file.truncate()
count = 0
for contour in data:
file.write('Contour Cluster {}:\n'.format(count))
for key in contour.keys():
current_value = contour.get(key)
format_data_dict(file,cu... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
set time = linear space 0 1000 10001
set sol = fft sin time * 2 * pi
print shape at - 1 time at 1 - time at 0
set freq = call fftfreq shape at - 1 time at 1 - time at 0
plot freq real freq imag
show | import numpy as np
import matplotlib.pyplot as plt
time=np.linspace(0,1000,10001)
sol=np.fft.fft(np.sin(time*2*np.pi))
print(time.shape[-1],time[1]-time[0])
freq=np.fft.fftfreq(time.shape[-1],time[1]-time[0])
plt.plot(freq,sol.real,freq,sol.imag)
plt.show()
| Python | zaydzuhri_stack_edu_python |
comment Authors: David Yun, Anna Truelove, Joyce Zhong
comment Title: Easy PT
comment Purpose: MLH HackNC Fall 2018
from flask import Flask
from flask_ask import question , Ask , statement
set app = call Flask __name__
set ask = call Ask app string /
global stage
global send_track
global session_num
global brandnewsess... | #Authors: David Yun, Anna Truelove, Joyce Zhong
#Title: Easy PT
#Purpose: MLH HackNC Fall 2018
from flask import Flask
from flask_ask import question, Ask, statement
app = Flask(__name__)
ask = Ask(app, "/")
global stage
global send_track
global session_num
global brandnewsess
stage = "start"
send_t... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self data next=none
begin
set data = data
set next = next
end function
end class
class LinkedList
begin
function __init__ self head=none
begin
set head = head
end function
function append self data
begin
set new_node = call Node data
if head is none
begin
set head = new_node
return
en... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
ret... | Python | flytech_python_25k |
function single critic argument parameters
begin
return call setAsContext parameters call fetch critic rebase_id=call numeric_id argument
end function | def single(critic, argument, parameters):
return Rebases.setAsContext(parameters, api.log.rebase.fetch(
critic, rebase_id=jsonapi.numeric_id(argument))) | Python | nomic_cornstack_python_v1 |
function get_primitive name
begin
set type_dict = call get_primitive_name_dict
set name = call name_filter name
if name in type_dict
begin
return type_dict at name
end
else
begin
return none
end
end function | def get_primitive(name):
type_dict = Primitive.get_primitive_name_dict()
name = Primitive.name_filter(name)
if name in type_dict:
return type_dict[name]
else:
return None | Python | nomic_cornstack_python_v1 |
function search_fbm_warehouse self company_id
begin
set warehouse_obj = env at string stock.warehouse
set default_warehouse = call ref string stock.warehouse0
if active
begin
if company_id == company_id
begin
set warehouse_id = id
end
else
begin
set warehouse = search list tuple string company_id string = id tuple stri... | def search_fbm_warehouse(self, company_id):
warehouse_obj = self.env['stock.warehouse']
default_warehouse = self.sudo().env.ref('stock.warehouse0')
if default_warehouse.active:
if self.seller_id.company_id == default_warehouse.company_id:
warehouse_id = default_wareho... | Python | nomic_cornstack_python_v1 |
function predict_logger model_fn
begin
decorator wraps model_fn
function wrapper *args **kwargs
begin
set timer_start = performance counter
try
begin
set predictions = call model_fn *args keyword kwargs
end
except any
begin
set timer_end = performance counter
set run_time = timer_end - timer_start
set time_stamp = call... | def predict_logger(model_fn):
@functools.wraps(model_fn)
def wrapper(*args, **kwargs):
timer_start = time.perf_counter()
try:
predictions = model_fn(*args, **kwargs)
except:
timer_end = time.perf_counter()
run_time = timer_end - timer_start
... | Python | nomic_cornstack_python_v1 |
import requests
import prettytable
import os
from bs4 import BeautifulSoup
set r1 = get requests string https://www.cwb.gov.tw/V8/C/W/TemperatureTop/County_TMax_T.html params=dict string ID string Sat Aug 01 2020 09:46:08 GMT 0800 (台北標準時間)
set c1 = call BeautifulSoup text string html.parser
set table = call PrettyTable... | import requests
import prettytable
import os
from bs4 import BeautifulSoup
r1 = requests.get("https://www.cwb.gov.tw/V8/C/W/TemperatureTop/County_TMax_T.html",
params={
"ID": "Sat Aug 01 2020 09:46:08 GMT 0800 (台北標準時間)"
}
)
c1 = BeautifulSoup(r1.text,... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set a1 = array list list 200 30 list 50 100
set b1 = array list list 10 10 list 1 1
comment multiplicación elemento a elemento
set c1 = a1 * b1
comment multiplicación matricial
set d1 = matrix multiply a1 b1
print c1
comment la función where
set a2 = where a1 >= 60 255 0
print string MATRIZ a1 es : a... | import numpy as np
a1=np.array([[200,30],[50,100]])
b1=np.array([[10,10],[1,1]])
#multiplicación elemento a elemento
c1=a1*b1
#multiplicación matricial
d1=np.matmul(a1,b1)
print(c1)
#la función where
a2=np.where(a1>=60,255,0)
print("MATRIZ a1 es : \n",a1)
print("MATRIZ a2 es ; \n ",a2)
import cv2
cam=cv2... | Python | zaydzuhri_stack_edu_python |
function creator self
begin
return get pulumi self string creator
end function | def creator(self) -> str:
return pulumi.get(self, "creator") | Python | nomic_cornstack_python_v1 |
function connect self
begin
pass
end function | def connect(self) -> bool:
pass | Python | nomic_cornstack_python_v1 |
function _read_all_from_socket self timeout
begin
string Read all packets we currently can on the socket. Returns list of tuples. Each tuple contains a packet and the time at which it was received. NOTE: The receive time is the time when our recv() call returned, which greatly depends on when it was called. The time is... | def _read_all_from_socket(self, timeout):
"""
Read all packets we currently can on the socket.
Returns list of tuples. Each tuple contains a packet and the time at
which it was received. NOTE: The receive time is the time when our
recv() call returned, which greatly depends on w... | Python | jtatman_500k |
import time
set start = integer round time * 1000
comment orderspermute() takes a list of letters and a prefix and
comment returns all ordered permutations of those letters with the
comment prefix attached
function orderedpermute letters prefix
begin
set permutations = list
for x in range 0 length letters
begin
append ... | import time
start = int(round(time.time() * 1000))
# orderspermute() takes a list of letters and a prefix and
# returns all ordered permutations of those letters with the
# prefix attached
def orderedpermute(letters, prefix):
permutations = list()
for x in range(0, len(letters)):
permutations.append(prefix+le... | Python | zaydzuhri_stack_edu_python |
function SetSuperGridSize self *args
begin
return call itkSLICImageFilterIUS2IUS2_SetSuperGridSize self *args
end function | def SetSuperGridSize(self, *args) -> "void":
return _itkSLICImageFilterPython.itkSLICImageFilterIUS2IUS2_SetSuperGridSize(self, *args) | Python | nomic_cornstack_python_v1 |
function test_mass_properties_for_moon binary_ascii_path speedups
begin
set filename = join binary_ascii_path string Moon.stl
set mesh = call StlMesh string filename speedups=speedups
set tuple volume cog inertia = call get_mass_properties
assert absolute volume - 0.888723 < tolerance
assert call allclose cog array lis... | def test_mass_properties_for_moon(binary_ascii_path, speedups):
filename = binary_ascii_path.join('Moon.stl')
mesh = stl.StlMesh(str(filename), speedups=speedups)
volume, cog, inertia = mesh.get_mass_properties()
assert(abs(volume - 0.888723) < tolerance)
assert(numpy.allclose(cog,
numpy.... | Python | nomic_cornstack_python_v1 |
import json
import re
set fnames = list string ../data/snli_1.0/snli_1.0/snli_1.0_train.jsonl string ../data/snli_1.0/snli_1.0/snli_1.0_dev.jsonl string ../data/snli_1.0/snli_1.0/snli_1.0_test.jsonl string ../data/multinli_1.0/multinli_1.0/multinli_1.0_train.jsonl string ../data/multinli_1.0/multinli_1.0/multinli_1.0_d... | import json
import re
fnames = ['../data/snli_1.0/snli_1.0/snli_1.0_train.jsonl',
'../data/snli_1.0/snli_1.0/snli_1.0_dev.jsonl',
'../data/snli_1.0/snli_1.0/snli_1.0_test.jsonl',
'../data/multinli_1.0/multinli_1.0/multinli_1.0_train.jsonl',
'../data/multinli_1.0/multinli_1.0/mul... | Python | zaydzuhri_stack_edu_python |
function set_density_matrix self density_matrix_repr
begin
string Set the density matrix to a new density matrix. Args: density_matrix_repr: If this is an int, the density matrix is set to the computational basis state corresponding to this state. Otherwise if this is a np.ndarray it is the full state, either a pure st... | def set_density_matrix(self, density_matrix_repr: Union[int, np.ndarray]):
"""Set the density matrix to a new density matrix.
Args:
density_matrix_repr: If this is an int, the density matrix is set to
the computational basis state corresponding to this state. Otherwise
... | Python | jtatman_500k |
from bitstring import Bits
from classes_ga import *
from classes_misc import *
from random import randrange as numero_aleatorio , random , choice
class CromossomoQuadratico extends Cromossomo
begin
string Essa classe vai tratar do problema de encontrar o mínimo da função y = x^2 Os cromossomos são uma sequência de 7 bi... | from bitstring import Bits
from classes_ga import *
from classes_misc import *
from random import randrange as numero_aleatorio, random, choice
class CromossomoQuadratico(Cromossomo):
"""
Essa classe vai tratar do problema de encontrar o mínimo da função y = x^2
Os cromossomos são uma sequência de 7 bits,... | Python | zaydzuhri_stack_edu_python |
function draw_regional_fig make model year
begin
set listings = list
set make_model = format string {0} {1} make model
set min_auto_year = integer year - 2
set max_auto_year = integer year + 2
if max_auto_year > 2016
begin
set max_auto_year = 2016
end
for i in range 0 500 100
begin
set car_results = call fetch auto_ma... | def draw_regional_fig(make, model, year):
listings = []
make_model = "{0} {1}".format(make,model)
min_auto_year = int(year) - 2
max_auto_year = int(year) + 2
if max_auto_year > 2016:
max_auto_year = 2016
for i in range(0, 500, 100):
car_results = fetch(auto_make_model=make_model,... | Python | nomic_cornstack_python_v1 |
function sample_and_plot S0 K B T N u d q M barrier_type
begin
set paths = call sample_paths S0 N u d q M
set tuple p_valid p_invalid p_counts = call split_paths paths B K barrier_type option
set times = linear space 0 T N + 1
figure figsize=tuple 10 7
set ax1 = call subplot2grid tuple 1 1 tuple 0 0
call set_ylabel str... | def sample_and_plot(S0, K, B, T, N, u, d, q, M, barrier_type):
paths = sample_paths(S0, N, u, d, q, M)
p_valid, p_invalid, p_counts = split_paths(paths, B, K,
barrier_type, option)
times = np.linspace(0, T, N + 1)
plt.figure(figsize=(10, 7))
ax1 = plt... | Python | nomic_cornstack_python_v1 |
while c < 100
begin
set s = s + 1 / 2 ^ i
set c = c + 1
end
print s | while c<100:
s+=1/(2**i)
c+=1
print(s) | Python | zaydzuhri_stack_edu_python |
string list2=["kj","hv","jjl"] list1=["bir","iki"] answer={list1[i]:list2[i] for i in range(0,len(list1))} answer=dict(zip(list1,list2)) print(answer) numbers=(1,2,3,4) print(numbers) value=(1,) print(value) values=[10,20,30] static_values=tuple(values) print(static_values) staff=[1,2,3,2,3,2,1,2,3,4,5] unique_staff=se... | """list2=["kj","hv","jjl"]
list1=["bir","iki"]
answer={list1[i]:list2[i] for i in range(0,len(list1))}
answer=dict(zip(list1,list2))
print(answer)
numbers=(1,2,3,4)
print(numbers)
value=(1,)
print(value)
values=[10,20,30]
static_values=tuple(values)
print(static_values)
staff=[1,2,3,2,3,2,1,2,3,4,5]
un... | Python | zaydzuhri_stack_edu_python |
function synonyms curie
begin
set result = list
set ont = call get_ontology_service
try
begin
set normalized_curie = call curie_normalize curie
end
except AssertionError as error
begin
set error_msg = string error
return tuple call jsonify dict string validation error string { error_msg } . Curie provided : ` { curie ... | def synonyms (curie):
result = []
ont = get_ontology_service ()
try:
normalized_curie = curie_normalize(curie)
except AssertionError as error:
error_msg = str(error)
return jsonify({"validation error": f"{error_msg}. Curie provided : `{curie}`"}), 400
if ont:
syns = ont.synon... | Python | nomic_cornstack_python_v1 |
function isancestorwebcommand web
begin
set req = req
for k in tuple b'head' b'node'
begin
if k not in qsparams
begin
raise call ErrorResponse HTTP_NOT_FOUND b"missing parameter '%s'" % k
end
end
set head = qsparams at b'head'
set node = qsparams at b'node'
try
begin
set headctx = call revsingle repo head
end
except Re... | def isancestorwebcommand(web):
req = web.req
for k in (b'head', b'node'):
if k not in req.qsparams:
raise ErrorResponse(HTTP_NOT_FOUND, b"missing parameter '%s'" % k)
head = req.qsparams[b'head']
node = req.qsparams[b'node']
try:
headctx = scmutil.revsingle(web.repo, he... | Python | nomic_cornstack_python_v1 |
function getReferencePoint self
begin
return call Scale1DCommand_getReferencePoint self
end function | def getReferencePoint(self):
return _osgManipulator.Scale1DCommand_getReferencePoint(self) | Python | nomic_cornstack_python_v1 |
async function get_current_user token=call Depends oauth2_scheme
begin
try
begin
set payload = decode jwt token SECRET_KEY algorithms=list AUTH_JWT_ALGORITHM
end
except JWTError
begin
raise call CredentialsError
end
set username = get payload string sub
if username is none
begin
raise call CredentialsError
end
with cal... | async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.AUTH_JWT_ALGORITHM])
except JWTError:
raise CredentialsError()
username = payload.get("sub")
if username is None:
raise Credential... | Python | nomic_cornstack_python_v1 |
string Problem: How much I will pay for fuel?
set PriceofGasperLitre = 7
comment Firstly user should give the consumption of vehicle
comment and the way he or she go
set MyVehicleConsume = input string The vehicle consume the fuel in the type of Litre/100km?
set YourDestination = input string How many KM is your destio... | """
Problem: How much I will pay for fuel?
"""
PriceofGasperLitre = 7
#Firstly user should give the consumption of vehicle
# and the way he or she go
MyVehicleConsume = input("The vehicle consume the fuel in the type of Litre/100km? ")
YourDestination = input("How many KM is your destion?")
Fuelneeded = (float(YourDe... | Python | zaydzuhri_stack_edu_python |
import turtle
import time
set t = call Pen
call forward 50
call left 90
call forward 50
call left 90
call forward 50
call left 90
call forward 50
call left 90
call reset
backward t 100
call right 90
call forward 20
call left 90
call forward 100
call left 90
call forward 20
call reset
call forward 90
call left 135
call ... | import turtle
import time
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.reset()
t.backward(100)
t.right(90)
t.forward(20)
t.left(90)
t.forward(100)
t.left(90)
t.forward(20)
t.reset()
t.forward(90)
t.left(135)
t.forward(63)
t.left(90)
t.forward(... | Python | zaydzuhri_stack_edu_python |
function save self *args **kwargs
begin
if not slug
begin
set slug = call slugify call unidecode title
set duplications = filter slug=slug
if exists duplications
begin
set slug = string %s-%s % tuple slug hex
end
else
begin
set slug = slug
end
end
return save *args keyword kwargs
end function | def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(unidecode(self.title))
duplications = type(self).objects.filter(slug=slug)
if duplications.exists():
self.slug = "%s-%s" % (slug, uuid4().hex)
else:
self.slug = slug
... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[2]:
from __future__ import print_function , division
comment importing the modules that we will use
import pandas as pd
import numpy as np
import random
import thinkstats2
import thinkplot
import nsfg
from scipy import stats
comment In[23]:
comment The First Part
comment In this part we... | # coding: utf-8
# In[2]:
from __future__ import print_function, division
#importing the modules that we will use
import pandas as pd
import numpy as np
import random
import thinkstats2
import thinkplot
import nsfg
from scipy import stats
# In[23]:
# The First Part
# In this part we will get the access to the da... | Python | zaydzuhri_stack_edu_python |
class Calculator
begin
function __init__ self
begin
pass
end function
function add self a b
begin
return a + b
end function
function subtract self a b
begin
return a - b
end function
end class
comment Domain Layer / Model
class BankAccount
begin
function __init__ self account_number
begin
set account_number = account_n... | class Calculator:
def __init__(self):
pass
def add(self,a, b):
return a + b
def subtract(self,a, b):
return a - b
# Domain Layer / Model
class BankAccount:
def __init__(self, account_number):
self.account_number = account_number
self.balance =... | Python | zaydzuhri_stack_edu_python |
function next_state self previous_state user_response slate_docs
begin
del user_response
del slate_docs
return map Deterministic
end function | def next_state(self, previous_state, user_response,
slate_docs):
del user_response
del slate_docs
return previous_state.map(ed.Deterministic) | Python | nomic_cornstack_python_v1 |
function to_date timeobject
begin
string Returns the ``datetime.datetime`` object corresponding to the time value conveyed by the specified object, which can be either a UNIXtime, a ``datetime.datetime`` object or an ISO8601-formatted string in the format `YYYY-MM-DD HH:MM:SS+00``. :param timeobject: the object conveyi... | def to_date(timeobject):
"""
Returns the ``datetime.datetime`` object corresponding to the time value
conveyed by the specified object, which can be either a UNIXtime, a
``datetime.datetime`` object or an ISO8601-formatted string in the format
`YYYY-MM-DD HH:MM:SS+00``.
:param timeobject: the o... | Python | jtatman_500k |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import os
import json
function _merge data data_to_merge path=none
begin
string merges data_to_merge into data
comment see https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107
if path is none
begin
set path = lis... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
def _merge(data, data_to_merge, path=None):
"merges data_to_merge into data"
# see https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107
if path is None: path = []
for key in data_to... | Python | zaydzuhri_stack_edu_python |
function getTFIID all_id rp_id saga_id tfiid_id
begin
set data0 = open all_id string r
set data01 = list
for records in data0
begin
append data01 split records at 0
end
set data1 = open rp_id string r
set data11 = dict
for records in data1
begin
set tmp = split records
set data11 at tmp at 0 = string
end
set data2 =... | def getTFIID(all_id,rp_id,saga_id,tfiid_id):
data0=open(all_id,'r')
data01=[]
for records in data0:
data01.append(records.split()[0])
data1=open(rp_id,'r')
data11={}
for records in data1:
tmp=records.split()
data11[tmp[0]]=' '
data2=open(saga_id,'r')
for records in data2:
tmp=records.split()
data1... | Python | zaydzuhri_stack_edu_python |
function from_hdf5 cls group
begin
set dist = call cls
if string angle in group
begin
set angle = call from_hdf5 group at string angle
end
if string energy in group
begin
set energy = call from_hdf5 group at string energy
end
return dist
end function | def from_hdf5(cls, group):
dist = cls()
if 'angle' in group:
dist.angle = AngleDistribution.from_hdf5(group['angle'])
if 'energy' in group:
dist.energy = EnergyDistribution.from_hdf5(group['energy'])
return dist | Python | nomic_cornstack_python_v1 |
string *************************** TITLE ****************************
string 587 Two Sum - Unique pairs.py
string *************************** DESCRIPTION ****************************
string Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target number. Plea... | """*************************** TITLE ****************************"""
"""587 Two Sum - Unique pairs.py"""
"""*************************** DESCRIPTION ****************************"""
"""
Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target number. Pl... | Python | zaydzuhri_stack_edu_python |
function user_stats df
begin
print string Calculating User Stats...
set start_time = time
comment Display counts of user types
set num_types = count group by df at string User Type df at string User Type
print num_types
comment Display counts of gender
set num_gender = count group by df at string Gender df at string Ge... | def user_stats(df):
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
num_types=df['User Type'].groupby(df['User Type']).count()
print(num_types)
# Display counts of gender
num_gender=df['Gender'].groupby(df['Gender']).count()
print(num_gen... | Python | nomic_cornstack_python_v1 |
import collections
class Solution extends object
begin
function readBinaryWatch self num
begin
string :type num: int :rtype: List[str]
set time = list
for i in range 12
begin
for j in range 60
begin
set b = binary i ? 6 ? j
set count = 0
for k in range 2 length b
begin
if b at k == string 1
begin
set count = count + 1... | import collections
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
time=[]
for i in range(12):
for j in range(60):
b=bin(i<<6 | j)
count=0
for k in range(2,len... | Python | zaydzuhri_stack_edu_python |
function of cls o
begin
if is instance o Run
begin
return run path=path df=df
end
else
if is instance o DataFrame
begin
return call from_dataframe o
end
raise call TypeError format string Unknown type {} type o
end function | def of(cls, o):
if isinstance(o, Run):
return Run(path=o.path, df=o.df)
elif isinstance(o, pd.DataFrame):
return cls.from_dataframe(o)
raise TypeError("Unknown type {}".format(type(o))) | Python | nomic_cornstack_python_v1 |
function eap_email
begin
comment skip authorization
set data = call get_json
set email_address = data at string email_address
comment email address validation
if not call check_valid_email_address email_address
begin
return tuple dumps dict string success false 403
end
comment create object
set subject = string [EAP] -... | def eap_email():
# skip authorization
data = request.get_json()
email_address = data['email_address']
# email address validation
if not check_valid_email_address(email_address):
return json.dumps({"success": False}), 403
# create object
subject = '[EAP] - New Inquiry from %s' % em... | Python | nomic_cornstack_python_v1 |
for i in range 0 cases
begin
set num = integer input
set line = string input
set line = split line
comment for convert string list to int list
set line = list map int line
set prv = line at 0
set count_1 = 0
set count_2 = 0
set rata_found = false
set maxdef = 0
for j in range 1 length line
begin
if prv > line at j
begi... | for i in range (0,cases):
num=int(input())
line=str(input())
line=line.split()
line=list(map(int,line))#for convert string list to int list
prv=line[0];count_1=0;count_2=0;rata_found=False;maxdef=0
for j in range(1,len(line)):
if prv > line[j]:
sub=prv-line[j]
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
pass
end function | def __init__(self):
pass | Python | nomic_cornstack_python_v1 |
import PyPDF2
import datetime
import os
set TIME_STAMP = string round timestamp now
function merge_pdfs list_of_pdfs
begin
set pdfMergeHelper = call PdfFileMerger
comment merging pdf one by one
for pdf in list_of_pdfs
begin
append pdfMergeHelper pdf
end
comment Path to original PDFS
set WB_PATH = list_of_pdfs at 0
comm... | import PyPDF2
import datetime
import os
TIME_STAMP = str(round(datetime.datetime.now().timestamp()))
def merge_pdfs(list_of_pdfs):
pdfMergeHelper = PyPDF2.PdfFileMerger()
# merging pdf one by one
for pdf in list_of_pdfs:
pdfMergeHelper.append(pdf)
# Path to original PDFS
WB_PATH... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import getopt
import string | #!/usr/bin/python
import sys
import getopt
import string
| Python | zaydzuhri_stack_edu_python |
function resize_and_crop img_path modified_path size crop_type=string middle
begin
comment If height is higher we resize vertically, if not we resize horizontally
set img = open img_path
comment Get current and desired ratio for the images
set img_ratio = size at 0 / decimal size at 1
set ratio = size at 0 / decimal si... | def resize_and_crop(img_path, modified_path, size, crop_type='middle'):
# If height is higher we resize vertically, if not we resize horizontally
img = Image.open(img_path)
# Get current and desired ratio for the images
img_ratio = img.size[0] / float(img.size[1])
ratio = size[0] / float(size[1])
... | Python | nomic_cornstack_python_v1 |
function __init__ self x n_src fs r=0.5 alpha=1.0 *args **kwargs
begin
call __init__ x n_src fs *args keyword kwargs
set loss_function = call LehmerMeanDSFLoss n_freq n_chan n_src r=r alpha=alpha n_frames=n_frames distance_func=phase_invariant_cosine_squared_distance time_pooling_func=reduce_mean freq_pooling_func=redu... | def __init__(
self,
x: Union[np.ndarray, tf.Tensor],
n_src: int,
fs: int,
r: float = 0.5,
alpha: float = 1.0,
*args,
**kwargs,
):
super().__init__(x, n_src, fs, *args, **kwargs)
self.loss_function = LehmerMeanDSFLoss(
self.... | Python | nomic_cornstack_python_v1 |
function exists self code
begin
if not WORKDIR
begin
raise call QError string Ticket storage directory WORKDIR is not set.
end
if is directory path root_path + string / + code
begin
return true
end
return false
end function | def exists(self, code):
if not self.settings.WORKDIR:
raise QError("Ticket storage directory WORKDIR is not set.")
if os.path.isdir(self.root_path + "/" + code):
return True
return False | Python | nomic_cornstack_python_v1 |
function get_name_service_by_hostname hdfs_site host_name
begin
comment there has to be a name service - we are in HA at least
set name_services_string = hdfs_site at string dfs.internal.nameservices
if call is_empty name_services_string
begin
return none
end
set name_services = split name_services_string string ,
if l... | def get_name_service_by_hostname(hdfs_site, host_name):
#there has to be a name service - we are in HA at least
name_services_string = hdfs_site['dfs.internal.nameservices']
if is_empty(name_services_string):
return None
name_services = name_services_string.split(',')
if len(name_services) == 1:
retur... | Python | nomic_cornstack_python_v1 |
string Funciones Estructura.- def NOMBRE(PARAMETRO1, PARAMETRO2, ...): INSTRUCCIONES [return RESULTADO]
comment Ejemplos
comment Funcion sin parametros
function imprime_hola
begin
print string Hola
end function
comment Funcion con parametros
function imprime_nombre nombre
begin
print string Hola, + nombre
end function
... | '''
Funciones
Estructura.-
def NOMBRE(PARAMETRO1, PARAMETRO2, ...):
INSTRUCCIONES
[return RESULTADO]
'''
#Ejemplos
#Funcion sin parametros
def imprime_hola():
print('Hola')
#Funcion con parametros
def imprime_nombre(nombre):
print('Hola, '+nombre)
#Funcion que recibe un parametro y ... | Python | zaydzuhri_stack_edu_python |
function _swig_call self method request response
begin
set list response_str error_message status_code = call method _metadata_store call SerializeToString
if status_code != 0
begin
raise call _make_exception error_message status_code
end
call ParseFromString response_str
end function | def _swig_call(self, method, request, response) -> None:
[response_str, error_message, status_code] = method(
self._metadata_store, request.SerializeToString())
if status_code != 0:
raise _make_exception(error_message, status_code)
response.ParseFromString(response_str) | Python | nomic_cornstack_python_v1 |
function test_append_to_flowgram_file self
begin
set tuple fh tmp_filename = call init_flowgram_file n=100 l=400
call assert_ exists tmp_filename
set tmp_filename = tmp_filename
set flow1 = call Flowgram string 0 1.2 2.1 3.4 0.02 0.01 1.02 0.08
call append_to_flowgram_file string test_id flow1 fh
set flow2 = call Flowg... | def test_append_to_flowgram_file(self):
fh, tmp_filename = init_flowgram_file(n=100, l=400)
self.assert_(exists(tmp_filename))
self.tmp_filename = tmp_filename
flow1 = Flowgram("0 1.2 2.1 3.4 0.02 0.01 1.02 0.08")
append_to_flowgram_file("test_id", flow1, fh)
... | Python | nomic_cornstack_python_v1 |
comment to view saved data
import mysql.connector
comment for creating GUI application
from tkinter import *
comment for showing message after insertion
from tkinter import messagebox
set db = call connect host=string localhost user=string root password=string root database=string hospital
comment for creating connecti... | import mysql.connector #to view saved data
from tkinter import * #for creating GUI application
from tkinter import messagebox #for showing message after insertion
db=mysql.connector.connect(host='localhost',
... | Python | zaydzuhri_stack_edu_python |
function cosine self vector1 vector2
begin
if normalisation_type is not none
begin
set vector1 = call normalise vector1
set vector2 = call normalise vector2
end
set similarity = call calc_cosine vector1 vector2
if bidirectional
begin
set similarity = absolute similarity
end
return similarity
end function | def cosine(self, vector1: np.ndarray, vector2: np.ndarray) -> float:
if self.normalisation_type is not None:
vector1 = self.normalise(vector1)
vector2 = self.normalise(vector2)
similarity = self.calc_cosine(vector1, vector2)
if self.bidirectional:
similarity ... | Python | nomic_cornstack_python_v1 |
comment import numpy as np
comment import tensorflow as tf
comment xdata=np.random.rand(1).astype(np.float32)
comment ydata=3*xdata+2
comment print(xdata)
comment w=tf.Variable(1.0)
comment b=tf.Variable(0.2)
comment y=w*xdata+b
comment learning_rate=0.1
comment loss=tf.reduce_mean(tf.square(y-ydata))
comment train=tf.... | # import numpy as np
# import tensorflow as tf
# xdata=np.random.rand(1).astype(np.float32)
# ydata=3*xdata+2
# print(xdata)
# w=tf.Variable(1.0)
# b=tf.Variable(0.2)
# y=w*xdata+b
# learning_rate=0.1
# loss=tf.reduce_mean(tf.square(y-ydata))
# train=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
import os
import hashlib
set cache_path = string cache_files
if not exists path cache_path
begin
make directory os cache_path
end
function getMD5 cache_name
begin
return hex digest md5 bytes cache_name string utf-8
end function
function get_cache cache_name
begin
set m... | #!/usr/bin/env python
# coding: utf-8
import os
import hashlib
cache_path = 'cache_files'
if (not os.path.exists(cache_path)):
os.mkdir(cache_path)
def getMD5(cache_name):
return hashlib.md5(bytes(cache_name, 'utf-8')).hexdigest()
def get_cache(cache_name):
md5 = getMD5(cache_name)
... | Python | zaydzuhri_stack_edu_python |
comment author ben lawson <balawson@bu.edu>
comment Edited by: Craig Einstein <einstein@bu.edu>
comment Some code adapted from
comment CodeHandBook at http://codehandbook.org/python-web-application-development-using-flask-and-mysql/
comment and MaxCountryMan at https://github.com/maxcountryman/flask-login/
comment and ... | ######################################
# author ben lawson <balawson@bu.edu>
# Edited by: Craig Einstein <einstein@bu.edu>
######################################
# Some code adapted from
# CodeHandBook at http://codehandbook.org/python-web-application-development-using-flask-and-mysql/
# and MaxCountryMan at https://... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment https://leetcode-cn.com/problems/implement-trie-prefix-tree
comment 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
comment 说明:
comment 你可以假设所有的输入都是由小写字母 a-z 构成的。
comment 保证所有输入均为非空字符串。
class Trie
begin
function __init__ self
begin
set preSet = set
set wordSet = set
end func... | #!/usr/bin/env python3
# https://leetcode-cn.com/problems/implement-trie-prefix-tree
# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
#
# 说明:
# 你可以假设所有的输入都是由小写字母 a-z 构成的。
# 保证所有输入均为非空字符串。
class Trie:
def __init__(self):
self.preSet = set()
self.wordSet = set()
def insert(self, word:... | Python | zaydzuhri_stack_edu_python |
function genCarts_tetramer internals
begin
set fullCart = zeros tuple 13 3
set tuple ro1o2 ro1o3 ro2o3 = internals at slice - 6 : - 3 :
set beginX = call outerOxygenFrame ro1o2 ro1o3 ro2o3
set beginX = array list beginX beginX
set tuple com eckVecs killList = call eckartRotate beginX planar=true lst=list 1 - 1 2 - 1 3... | def genCarts_tetramer(internals):
fullCart = np.zeros((13,3))
ro1o2, ro1o3, ro2o3 = internals[-6:-3]
beginX = outerOxygenFrame(ro1o2, ro1o3, ro2o3)
beginX = np.array([beginX, beginX])
com, eckVecs, killList = Wfn.molecule.eckartRotate(beginX, planar=True, lst=[1 - 1, 2 - 1, 3 - 1], dip=True)
beg... | Python | nomic_cornstack_python_v1 |
comment function is set of statements that us used for performing a particular task
comment eg: print(),input(),type()
comment user defined functions
comment syntax
comment def functionname(argument 1,argument 2 ...........)
comment function body
comment return stmnt
comment we can create function in 3 ways:
comment 1)... | #function is set of statements that us used for performing a particular task
#eg: print(),input(),type()
#user defined functions
#syntax
#def functionname(argument 1,argument 2 ...........)
#function body
#return stmnt
#we can create function in 3 ways:
#1) function with no argument and no return type
#def ad... | Python | zaydzuhri_stack_edu_python |
function merge_cycles self
begin
string Work on this graph and remove cycles, with nodes containing concatonated lists of payloads
while true
begin
comment remove any self edges
set own_edges = call get_self_edges
if length own_edges > 0
begin
for e in own_edges
begin
call remove_edge e
end
end
set c = call find_cycle
... | def merge_cycles(self):
"""Work on this graph and remove cycles, with nodes containing concatonated lists of payloads"""
while True:
### remove any self edges
own_edges = self.get_self_edges()
if len(own_edges) > 0:
for e in own_edges: self.remove_edge(e)
c = ... | Python | jtatman_500k |
function is_request_sent self request relations
begin
set states = call get_request_states request relations
for rid in keys states
begin
if not states at rid at string sent
begin
return false
end
end
return true
end function | def is_request_sent(self, request, relations):
states = self.get_request_states(request, relations)
for rid in states.keys():
if not states[rid]['sent']:
return False
return True | Python | nomic_cornstack_python_v1 |
comment Anh Duong, Nguyen
from helper import *
comment automatic rotation of model?
set rotate_flag = true
comment keep track of passing time, for automatic rotation
set time = 0
set vertices = list
set corners = list
set faces = list
set randomMode = false
set randomList = list
set flatMode = true
function hasV ci... | # Anh Duong, Nguyen
from helper import *
rotate_flag = True # automatic rotation of model?
time = 0 # keep track of passing time, for automatic rotation
vertices = []
corners = []
faces = []
randomMode = False
randomList = []
flatMode = True
def hasV(cid1, cid2, cid3, vid):
global corners
c1, c2, c3 = cor... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import tensorflow as tf
set city_names = call Series list string San Francisco string San Jose string Sacramento
set populations = call Series list 854269 1015785 485199
set data = call DataFrame dict string City Name city_names ; string Population populations
print data
print data at string City Na... | import pandas as pd
import tensorflow as tf
city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
populations = pd.Series([854269, 1015785, 485199])
data = pd.DataFrame({'City Name': city_names, "Population": populations})
print(data)
print(data['City Name'])
print(data[['City Name']])
californ... | Python | zaydzuhri_stack_edu_python |
function get_gp_post_mu_cov_single self x
begin
set tuple mu_arr std_arr = call get_gp_post_mu_cov list x full_cov=false
return tuple mu_arr at 0 std_arr at 0
end function | def get_gp_post_mu_cov_single(self, x):
mu_arr, std_arr = self.get_gp_post_mu_cov([x], full_cov=False)
return mu_arr[0], std_arr[0] | Python | nomic_cornstack_python_v1 |
import time
import rp2
from machine import Pin
decorator call asm_pio autopush=true push_thresh=17 set_init=IN_HIGH
comment PIO State machine for recieving Wiegand data
comment Needs two to cover D0 and D1
comment set x = 0 for D0 and &ff for D1
comment uses autpush with threshold of 17 bits to pish the date in two pie... | import time
import rp2
from machine import Pin
# PIO State machine for recieving Wiegand data
# Needs two to cover D0 and D1
# set x = 0 for D0 and &ff for D1
# uses autpush with threshold of 17 bits to pish the date in two pieces
@rp2.asm_pio(autopush=True, push_thresh=17, set_init=rp2.PIO.IN_HIGH)
def wiegand_bit()... | Python | zaydzuhri_stack_edu_python |
function generate_datetime self
begin
return string format time now string %d/%b/%Y:%X + string + string format time string %z call gmtime
end function | def generate_datetime(self):
return datetime.now().strftime('%d/%b/%Y:%X') + ' ' + strftime("%z", gmtime()) | Python | nomic_cornstack_python_v1 |
function peek self
begin
string peek the very first of the node
if Stack is none
begin
raise call ValueError string nothing to peek, the stack is empty
end
else
begin
return data
end
end function | def peek(self):
"""peek the very first of the node"""
if Stack is None:
raise ValueError("nothing to peek, the stack is empty")
else:
return self.head.data | Python | nomic_cornstack_python_v1 |
with open string input/menu.csv encoding=string utf-8 as f
begin
for row in f
begin
print row
end
end | with open('input/menu.csv', encoding='utf-8') as f:
for row in f:
print(row) | Python | zaydzuhri_stack_edu_python |
import AssignmentHelper
import MeasureAccuracy
import Constant
if __name__ == string __main__
begin
set data_raw_train = call read_sentences_from_file string ..\data\twt.train.json
set data_raw_dev = call read_sentences_from_file string ..\data\twt.dev.json
set data_raw_test = call read_sentences_from_file string ..\da... | import AssignmentHelper
import MeasureAccuracy
import Constant
if __name__ == '__main__':
data_raw_train = AssignmentHelper.read_sentences_from_file('..\\data\\twt.train.json')
data_raw_dev = AssignmentHelper.read_sentences_from_file('..\\data\\twt.dev.json')
data_raw_test = AssignmentHelper.read_sentences... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask import render_template , redirect , request , flash
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
import pymysql
comment import secrets
import os
set dbuser = get environ string DBUSE... | from flask import Flask
from flask import render_template, redirect, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
import pymysql
#import secrets
import os
dbuser = os.environ.get('DBUSER')
dbpass = os.... | Python | zaydzuhri_stack_edu_python |
import yaml
from pythoncodings.calculator import Calculator
import pytest
function get_data
begin
with open string data.yml encoding=string utf-8 as f
begin
set datas = call safe_load f
end
set add_datas = datas at string add at string datas
set sub_datas = datas at string sub at string datas
set mul_datas = datas at s... | import yaml
from pythoncodings.calculator import Calculator
import pytest
def get_data():
with open("data.yml", encoding='utf-8') as f:
datas = yaml.safe_load(f)
add_datas = datas["add"]["datas"]
sub_datas = datas["sub"]["datas"]
mul_datas = datas["mul"]["datas"]
div_datas = datas["div"][... | Python | zaydzuhri_stack_edu_python |
function status
begin
set result = call details_namespace
function print_value name current total
begin
call echo format string {}: {} of {} call format_text name HEADER call format_text current OKGREEN call format_text total OKGREEN
end function
call echo format string Namespace: {} result at string name
call print_va... | def status():
result = details_namespace()
def print_value(name, current, total):
click.echo("{}: {} of {}".format(
format_text(name, TextStyle.HEADER),
format_text(current, TextStyle.OKGREEN),
format_text(total, TextStyle.OKGREEN),
))
click.echo('Namesp... | Python | nomic_cornstack_python_v1 |
string 8/16/2017 Author: Fang Ren
string Change a binary tree to a circular double linked list
class TreeNode
begin
function __init__ self value
begin
set val = value
set left = none
set right = none
end function
end class
class DoubleLinkedList
begin
function __init__ self value
begin
set val = value
set previous = no... | """
8/16/2017
Author: Fang Ren
"""
"""
Change a binary tree to a circular double linked list
"""
class TreeNode():
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class DoubleLinkedList():
def __init__(self, value):
self.val = value
self.... | Python | zaydzuhri_stack_edu_python |
function python_to_matlab code
begin
set outline = code
set outline = replace outline string ** string .^
set outline = replace outline string * string .*
set outline = replace outline string dot(b, string b'*(
set outline = replace outline string dot(bhat, string bhat'*(
set outline = replace outline string dot(Ahat, ... | def python_to_matlab(code):
outline=code
outline=outline.replace("**",".^")
outline=outline.replace("*",".*")
outline=outline.replace("dot(b,","b'*(")
outline=outline.replace("dot(bhat,","bhat'*(")
outline=outline.replace("dot(Ahat,","Ahat*(")
outline=outline.replace("dot(A,","(A*")
outl... | Python | nomic_cornstack_python_v1 |
import cv2
from SerialCommunication.SerialCom import *
class FaceRecognition
begin
function __init__ self
begin
set detectorFace = call CascadeClassifier string FaceRecognition/haarcascade-frontalface-default.xml
set reconhecedor = call EigenFaceRecognizer_create
read reconhecedor string FaceRecognition/classificadorEi... | import cv2
from SerialCommunication.SerialCom import *
class FaceRecognition():
def __init__(self) -> object:
self.detectorFace = cv2.CascadeClassifier("FaceRecognition/haarcascade-frontalface-default.xml")
self.reconhecedor = cv2.face.EigenFaceRecognizer_create()
self.reconhecedor.read("F... | Python | zaydzuhri_stack_edu_python |
function live_feed_all_stats self
begin
set response = get requests string { game_url } / { game_id } /feed/live
if status_code != 200
begin
return dict string error string Game with id ' { game_id } ' not found.
end
return dict string gamePk json response at string gamePk ; string gameData json response at string game... | def live_feed_all_stats(self):
response = requests.get(f"{self.game_url}/{self.game_id}/feed/live")
if response.status_code != 200:
return {"error": f"Game with id '{self.game_id}' not found."}
return ({
"gamePk": response.json()['gamePk'],
"gameData": respo... | Python | nomic_cornstack_python_v1 |
function __init__ self initial_step_size=0.01 * angstroms
begin
set timestep = 1.0 * femtoseconds
call __init__ timestep
call addGlobalVariable string step_size initial_step_size / nanometers
call addGlobalVariable string energy_old 0
call addGlobalVariable string energy_new 0
call addGlobalVariable string delta_energy... | def __init__(self, initial_step_size=0.01 * units.angstroms):
timestep = 1.0 * units.femtoseconds
super(GradientDescentMinimizationIntegrator, self).__init__(timestep)
self.addGlobalVariable("step_size", initial_step_size / units.nanometers)
self.addGlobalVariable("energy_old", 0)
... | Python | nomic_cornstack_python_v1 |
function test_navigation_intermediate_stop_novars self pareto_front ideal nadir
begin
set method = call NautilusNavigator pareto_front ideal nadir
set _steps_remaining = 10
set request = start method
while true
begin
set response = dict string reference_point array list 0.7 2.2 1.1 1.9 ; string speed 5 ; string go_to_p... | def test_navigation_intermediate_stop_novars(self, pareto_front, ideal, nadir):
method = NautilusNavigator(pareto_front, ideal, nadir)
method._steps_remaining = 10
request = method.start()
while True:
response = {
"reference_point": np.array([0.7, 2.2, 1.1, 1... | Python | nomic_cornstack_python_v1 |
for x in adj
begin
for y in var
begin
print x y
end
end | for x in adj :
for y in var:
print(x,y) | Python | zaydzuhri_stack_edu_python |
comment Based off of ex7.4 solution
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
from prob2_integrators import *
comment -----------------------------------------------------------------------
comment Define the problem.
function deriv2 x y
begin
comment y[2] is the eigenvalue, z
return - 2... | #Based off of ex7.4 solution
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
from prob2_integrators import *
#-----------------------------------------------------------------------
#
# Define the problem.
def deriv2(x, y):
return -(2.0*y[1] + y[0] - 10.0*y[0]**2. + 5.0*y[0]**3.)# y[2] i... | Python | zaydzuhri_stack_edu_python |
from math import gcd
from base64 import b64encode , b64decode
from Cryptodome.Util.number import getPrime as random_prime
from lab4.aes_tests import current_ms , duration_ms
from forbiddenfruit import curse
string Int extenstion for zfilling.
call curse int string zpad lambda self zeroes -> call zfill zeroes
function a... | from math import gcd
from base64 import b64encode, b64decode
from Cryptodome.Util.number import getPrime as random_prime
from lab4.aes_tests import current_ms, duration_ms
from forbiddenfruit import curse
""" Int extenstion for zfilling.
"""
curse(int, 'zpad', lambda self, zeroes: str(self).zfill(zeroes))
def are_... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , request , jsonify
from flask_sqlalchemy import SQLAlchemy
import json
set app = call Flask __name__
comment Restaurant DB configuration
set config at string SQLALCHEMY_DATABASE_URI = string mysql+mysqlconnector://root@localhost:3306/reservation
set config at string SQLALCHEMY_TRACK_MODIFICATIO... | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import json
app = Flask(__name__)
#Restaurant DB configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/reservation'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
dbr = SQLAlchemy... | Python | zaydzuhri_stack_edu_python |
comment https://www.lintcode.com/problem/binary-tree-paths/description?_from=ladder&&fromId=1
comment 使用 Divider Conquer 版本的 DFS
string Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None
class Solution
begin
string @param root: the root of the binary tree ... | # https://www.lintcode.com/problem/binary-tree-paths/description?_from=ladder&&fromId=1
# 使用 Divider Conquer 版本的 DFS
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the ... | Python | zaydzuhri_stack_edu_python |
class WordsGameDictionary
begin
function __init__ self lang theme
begin
set theme = theme
set lang = lang
set used_letters = list
set alphabet = string
set used_words = list
set dictionary = list
set path = call get_path
call make_dictionary
end function
comment Initialize the dictionary from the file
function make... | class WordsGameDictionary():
def __init__(self, lang, theme):
self.theme = theme
self.lang = lang
self.used_letters = []
self.alphabet = ''
self.used_words = []
self.dictionary = []
self.path = self.get_path()
self.make_dictionary()
# Initializ... | Python | zaydzuhri_stack_edu_python |
function addCategory self categoryName
begin
set curCategories = call _loadCategories
if categoryName in curCategories
begin
set msg = string Duplicate Category names are not allowed
comment logger.warning(msg)
comment raise Exception([340, msg])
call _exception 101 msg
return
end
comment return -1
append curCategories... | def addCategory(self, categoryName):
curCategories = self._loadCategories()
if categoryName in curCategories:
msg = "Duplicate Category names are not allowed"
# logger.warning(msg)
# raise Exception([340, msg])
self._exception(101, msg)
return
... | Python | nomic_cornstack_python_v1 |
from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework import status
from SendItApp.models import *
class GymTypeSerializer extends HyperlinkedModelSerializer
begin
string JSON se... | from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework import status
from SendItApp.models import *
class GymTypeSerializer(serializers.HyperlinkedModelSerializer):
"""JSON ... | Python | zaydzuhri_stack_edu_python |
comment jyothi
set n = integer call raw_input
set m = list map int split call raw_input
for i in m
begin
if count m i == 1
begin
print i
end
end | #jyothi
n=int(raw_input())
m=list(map(int,raw_input().split()))
for i in m:
if(m.count(i)==1):
print(i)
| Python | zaydzuhri_stack_edu_python |
function is_palindrome s
begin
comment Strip punctuation and make input lowercase
set s = join string generator expression lower e for e in s if is alphanumeric e
comment Check if the string is a palindrome
return s == s at slice : : - 1
end function
comment Driver Code
set string = string A man, a plan, a canal: Pa... | def is_palindrome(s):
# Strip punctuation and make input lowercase
s = ''.join(e.lower() for e in s if e.isalnum())
# Check if the string is a palindrome
return s == s[::-1]
# Driver Code
string = "A man, a plan, a canal: Panama"
print(is_palindrome(string)) # Output: true
| Python | flytech_python_25k |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Oct 14 09:50:23 2020 @author: SEMBLANET Tom
import os
import cppad_py
import math
import numpy as np
import matplotlib.pyplot as plt
from src.problem import Problem
from src.optimization import Optimization
class GeocentricTransfer extend... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 09:50:23 2020
@author: SEMBLANET Tom
"""
import os
import cppad_py
import math
import numpy as np
import matplotlib.pyplot as plt
from src.problem import Problem
from src.optimization import Optimization
class GeocentricTransfer(Problem):
... | Python | zaydzuhri_stack_edu_python |
string Module to read a file in subdirectory.
import os
set script_dir = directory name path __file__
set rel_path = string ham/0004.1999-12-14.farmer.ham.txt
set abs_file_path = join path string ham string 0002.1999-12-13.farmer.ham.txt
set f = open rel_path string r
set content = read f
comment transform the string i... | """Module to read a file in subdirectory."""
import os
script_dir = os.path.dirname(__file__)
rel_path = "ham/0004.1999-12-14.farmer.ham.txt"
abs_file_path = os.path.join('ham', '0002.1999-12-13.farmer.ham.txt')
f = open(rel_path, "r")
content = f.read()
# transform the string into lower and then split
print(content... | 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.