code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from scipy.special import binom
from numpy import linspace
import math
set threshold = 1000000000
function probab f threshold
begin
set threshold_value = 0
if f == 1
begin
return 1 / 2 ^ 1000
end
else
begin
for n in range 1 1001
begin
set final_amount = 1 + 2 * f ^ n * 1 - f ^ 1000 - n
if final_amount > threshold
begin... | from scipy.special import binom
from numpy import linspace
import math
threshold = 1000000000
def probab(f, threshold):
threshold_value = 0
if f == 1:
return 1/2**1000
else:
for n in range(1,1001):
final_amount = (1 + 2*f)**n * (1-f)**(1000-n)
if final_amount > th... | Python | zaydzuhri_stack_edu_python |
function generate_tclloader_script dirname batchfile shfile wipe=true
begin
copy shutil batchfile join path dirname string flashall.bat
copy shutil shfile join path dirname string flashall.sh
if not wipe
begin
call tclloader_nowipe join path dirname string flashall.bat
call tclloader_nowipe join path dirname string fla... | def generate_tclloader_script(dirname, batchfile, shfile, wipe=True):
shutil.copy(batchfile, os.path.join(dirname, "flashall.bat"))
shutil.copy(shfile, os.path.join(dirname, "flashall.sh"))
if not wipe:
tclloader_nowipe(os.path.join(dirname, "flashall.bat"))
tclloader_nowipe(os.path.join(dir... | Python | nomic_cornstack_python_v1 |
function prepare_session self master init_op=none saver=none checkpoint_dir=none checkpoint_filename_with_path=none wait_for_checkpoint=false max_wait_secs=7200 config=none init_feed_dict=none init_fn=none
begin
set tuple sess is_loaded_from_checkpoint = call _restore_checkpoint master saver checkpoint_dir=checkpoint_d... | def prepare_session(self,
master,
init_op=None,
saver=None,
checkpoint_dir=None,
checkpoint_filename_with_path=None,
wait_for_checkpoint=False,
max_wait... | Python | nomic_cornstack_python_v1 |
comment void
function set_verb_features self verb_node
begin
set verb_lemma = lemma
if feats at string VerbForm != string
begin
set verb_form = feats at string VerbForm
end
if feats at string Voice != string
begin
set voice = feats at string Voice
end
end function | def set_verb_features( self, verb_node): # void
self.verb_lemma = verb_node.lemma
if verb_node.feats[ "VerbForm" ] != "":
self.verb_form = verb_node.feats[ "VerbForm" ]
if verb_node.feats[ "Voice" ] != "":
self.voice = verb_node.feats[ "Voice" ] | Python | nomic_cornstack_python_v1 |
function plot self r theta vectors=false arrowhead=true normalize=false sort=false **kwds
begin
comment sort r, theta by r
set rs = array r
set thetas = array theta
if sort
begin
set indx = call argsort thetas
set theta = thetas
if not is instance indx int64
begin
for tuple i j in enumerate indx
begin
set rs at i = r a... | def plot(self, r, theta, vectors=False, arrowhead=True, normalize=False, sort=False, **kwds):
# sort r, theta by r
rs = np.array(r)
thetas = np.array(theta)
if sort:
indx = np.argsort(thetas)
theta = thetas
if not isinstance(indx, np.int64):... | Python | nomic_cornstack_python_v1 |
function render_error_page request error_msg=false
begin
if not error_msg
begin
set error_msg = string An error has occurred. Please contact Athletic Compliance.
end
error request error_msg
return call HttpResponseRedirect reverse string compliance_error
end function | def render_error_page(request, error_msg=False):
if not error_msg:
error_msg = 'An error has occurred. Please contact Athletic Compliance.'
messages.error(request, error_msg)
return HttpResponseRedirect(reverse('compliance_error')) | Python | nomic_cornstack_python_v1 |
comment gfg_queue_checkSorted.py
from queue import Queue
function checkSorted n q
begin
set st = list
set expected = 1
set front = none
while not call empty
begin
set front = queue at 0
get q
if front == expected
begin
set expected = expected + 1
end
else
if length st == 0
begin
append st front
end
else
if length st !... | # gfg_queue_checkSorted.py
from queue import Queue
def checkSorted(n, q):
st = []
expected = 1
front = None
while not q.empty():
front = q.queue[0]
q.get()
if front == expected:
expected += 1
else:
if len(st) == 0:
... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
set url = string http://www.biqugew.com/book/9/4446.html
set req = get requests url
set encoding = string gbk
set html = text
set bf = call BeautifulSoup html string html.parser
set text = find all string div id=string content
set result = replace text string * 4 string
wi... | import requests
from bs4 import BeautifulSoup
url = "http://www.biqugew.com/book/9/4446.html"
req = requests.get(url)
req.encoding = "gbk"
html = req.text
bf = BeautifulSoup(html,"html.parser")
text = bf.findAll("div",id="content")
result = text[0].text.replace("\xa0"*4,"")
with open("cha1.txt","w",encoding="utf-8") ... | Python | zaydzuhri_stack_edu_python |
function valid_passport passport
begin
set byr = length passport at string byr == 4 and 1920 <= integer passport at string byr <= 2002
set iyr = length passport at string iyr == 4 and 2010 <= integer passport at string iyr <= 2020
set eyr = length passport at string eyr == 4 and 2020 <= integer passport at string eyr <... | def valid_passport(passport):
byr = len(passport['byr']) == 4 and 1920 <= int(passport['byr']) <= 2002
iyr = len(passport['iyr']) == 4 and 2010 <= int(passport['iyr']) <= 2020
eyr = len(passport['eyr']) == 4 and 2020 <= int(passport['eyr']) <= 2030
if passport['hgt'][-2:] == 'cm':
hgt = 150 <= i... | Python | zaydzuhri_stack_edu_python |
function test_validate_search_no_query
begin
set result = call validate_search_payload none
assert result at string errors == string No query parameter received.
end function | def test_validate_search_no_query():
result = validate_search_payload(None)
assert result["errors"] == "No query parameter received." | Python | nomic_cornstack_python_v1 |
function description self
begin
return get pulumi self string description
end function | def description(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "description") | Python | nomic_cornstack_python_v1 |
function dataset_id self
begin
return get pulumi self string dataset_id
end function | def dataset_id(self) -> str:
return pulumi.get(self, "dataset_id") | Python | nomic_cornstack_python_v1 |
function test_api_file_depository_delete_instructor self
begin
set file_depository = call FileDepositoryFactory
set jwt_token = call InstructorOrAdminLtiTokenFactory playlist=playlist
assert equal count objects 1
set response = delete string /api/filedepositories/ { id } / HTTP_AUTHORIZATION=string Bearer { jwt_token }... | def test_api_file_depository_delete_instructor(self):
file_depository = FileDepositoryFactory()
jwt_token = InstructorOrAdminLtiTokenFactory(playlist=file_depository.playlist)
self.assertEqual(FileDepository.objects.count(), 1)
response = self.client.delete(
f"/api/filedepos... | Python | nomic_cornstack_python_v1 |
comment https://leetcode.com/problems/string-to-integer-atoi/
comment 8. String to Integer (atoi)
class Solution
begin
function myAtoi self str
begin
set lst = list strip str
if not lst
begin
return 0
end
set sign = if expression lst at 0 == string - then - 1 else 1
if lst at 0 in list string - string +
begin
del lst a... | # https://leetcode.com/problems/string-to-integer-atoi/
# 8. String to Integer (atoi)
class Solution:
def myAtoi(self, str: str) -> int:
lst = list(str.strip())
if not lst: return 0
sign = -1 if lst[0] == "-" else 1
if lst[0] in ["-", "+"]: del lst[0]
res, i = 0, 0
while ... | Python | zaydzuhri_stack_edu_python |
import re
comment only 5 digit number
print match string [0-9]{5}$ string 14598778
print match string [0-9]{5}$ string 14598778
print match string [0-9]{5}$ string ABDgvhs@ghffs.com | import re
print(re.match("[0-9]{5}$","14598778")) #only 5 digit number
print(re.match("[0-9]{5}$","14598778"))
print(re.match("[0-9]{5}$","ABDgvhs@ghffs.com"))
| Python | zaydzuhri_stack_edu_python |
function _api_endpoint self
begin
return value
end function | def _api_endpoint(self) -> str:
return ApiEndpoints.TAGS.value | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import json
import requests
set PAGE_SIZE = 10
set URL = string http://mp.hudoufun.cn/tenement/js/listview_h5.ashx?op=1&r=0.6620256237220019&table=tenement_rooms1&city=%E6%88%90%E9%83%BD&lng=0&lat=0&filter=&order2=auto&PADDING=0&refable=false&page=js%2Flistview_h5.ashx&search=&order=&totalnum=-1&ra... | # coding=utf-8
import json
import requests
PAGE_SIZE = 10
URL = 'http://mp.hudoufun.cn/tenement/js/listview_h5.ashx?' \
'op=1' \
'&r=0.6620256237220019' \
'&table=tenement_rooms1' \
'&city=%E6%88%90%E9%83%BD&lng=0' \
'&lat=0' \
'&filter=' \
'&order2=auto' \
'&PADDING=0'... | Python | zaydzuhri_stack_edu_python |
function prune_seqs_matching_alignment seqs aln
begin
set ret = dict
set exclude_names = set comprehension name for s in aln
for tuple name seq in items seqs
begin
if name in exclude_names
begin
print format string Excluding {} as it is already present in the alignment name
end
else
begin
set ret at name = seq
end
end... | def prune_seqs_matching_alignment(seqs, aln):
ret = {}
exclude_names = {s.name for s in aln}
for name, seq in seqs.items():
if name in exclude_names:
print("Excluding {} as it is already present in the alignment".format(name))
else:
ret[name] = seq
return ret | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
import time
set driver = call Chrome
call implicitly_wait 3
get driver string https://www.baidu.com
comment 获得百度搜索窗口句柄
set sreach_windows = current_window_handle
call click
call click
comment 获得当前所有打开的窗口的句柄
set all_handles = window_handles
comment 进入注册窗口
for handle in all_handles
begin
if... | from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(3)
driver.get("https://www.baidu.com")
# 获得百度搜索窗口句柄
sreach_windows = driver.current_window_handle
driver.find_element_by_link_text('登录').click()
driver.find_element_by_link_text("立即注册").click()
# 获得当前所有打开的窗口的句柄
all_handles... | Python | zaydzuhri_stack_edu_python |
class Student
begin
function __init__ self name=string
begin
set name = name
print string Student
end function
function __str__ self
begin
return string Student + name
end function
function print_name self
begin
print name
end function
end class
class MITstudent extends Student
begin
function __init__ self name=string
... | class Student:
def __init__(self, name = ''):
self.name = name
print("Student")
def __str__(self):
return 'Student ' + self.name
def print_name(self):
print(self.name)
class MITstudent(Student):
def __init__(self, name = ''):
super().__init__(name)
prin... | Python | zaydzuhri_stack_edu_python |
comment Classe principal
class Funcionario
begin
function __init__ self nome setor=1 valor_hora=5 num_faltas=0 matricula=0
begin
comment Atributos
set setor = setor
set valor_hora = valor_hora
set num_faltas = num_faltas
set matricula = matricula
set l_func = l_func
set nome = input string Digite o nome do Funcionário:... | class Funcionario: #Classe principal
def __init__(self, nome, setor = 1, valor_hora = 5, num_faltas = 0, matricula = 0,):
#Atributos
self.setor = setor
self.valor_hora = valor_hora
self.num_faltas = num_faltas
self.matricula = matricula
self.l_func = l_func
s... | Python | zaydzuhri_stack_edu_python |
comment A[] represents coefficients of first polynomial
comment B[] represents coefficients of second polynomial
comment m and n are sizes of A[] and B[] respectively
function multiply A B m n
begin
set prod = list 0 * m + n - 1
comment Multiply two polynomials term by term
comment Take ever term of first polynomial
fo... | # A[] represents coefficients of first polynomial
# B[] represents coefficients of second polynomial
# m and n are sizes of A[] and B[] respectively
def multiply(A, B, m, n):
prod = [0] * (m+n-1)
# Multiply two polynomials term by term
# Take ever term of first polynomial
for i in range... | Python | zaydzuhri_stack_edu_python |
from qiskit import QuantumRegister
from qiskit.extensions.standard.x import XGate
from AbstractGates.qiwiGate import qiwiGate
from BinaryOracles.Boolean_preparation import to_list
from AbstractGates.ControlGate import ControlGate
class OracleGate extends qiwiGate
begin
string Oracle gate. If the input is: - an int, it ... | from qiskit import QuantumRegister
from qiskit.extensions.standard.x import XGate
from AbstractGates.qiwiGate import qiwiGate
from BinaryOracles.Boolean_preparation import to_list
from AbstractGates.ControlGate import ControlGate
class OracleGate(qiwiGate):
"""Oracle gate.
If the input is:
- an int, ... | Python | zaydzuhri_stack_edu_python |
function _callback result_future
begin
print format string Inference scores {} outputs at string scores
set exception = exception
if exception
begin
print exception
end
else
begin
comment print("From Callback",result_future.result().outputs['dense_2/Softmax:0'])
set response = array float_val
comment print("Probabiltie... | def _callback(result_future):
print ("\nInference scores {}".format(result_future.result().outputs['scores']) )
exception = result_future.exception()
if exception:
print(exception)
else:
#print("From Callback",result_future.result().outputs['dense_2/Softmax:0'])
response = np.array(
... | Python | nomic_cornstack_python_v1 |
from collections import namedtuple , Counter
set Test = named tuple string Test string S
set DIGITS = split string ZERO ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE
set DIGITS = dictionary comprehension i : counter s for tuple i s in enumerate DIGITS
function read line
begin
return call Test strip line
end function
fun... | from collections import namedtuple, Counter
Test = namedtuple('Test', 'S')
DIGITS = 'ZERO ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE'.split()
DIGITS = {i: Counter(s) for i, s in enumerate(DIGITS)}
def read(line):
return Test(line.strip())
def solve(test):
letters = Counter(test.S)
counts =... | Python | zaydzuhri_stack_edu_python |
function __is_normal_service self
begin
if current_service
begin
return not is_float
end
return false
end function | def __is_normal_service(self):
if self.current_service:
return not self.current_service.is_float
return False | Python | nomic_cornstack_python_v1 |
comment Author: Behzad Moumbeini
comment how to run: python bam_to_wig.py -o outfile infile.bam
import os
import HTSeq
import argparse
function empty_array_from_file bam_file stranded=true typecode=string i
begin
set cov_array = call GenomicArray string auto stranded=stranded typecode=typecode
set myheader = call get_h... | #Author: Behzad Moumbeini
#how to run: python bam_to_wig.py -o outfile infile.bam
import os
import HTSeq
import argparse
def empty_array_from_file(bam_file,stranded=True, typecode="i"):
cov_array=HTSeq.GenomicArray("auto", stranded = stranded, typecode = typecode)
myheader = HTSeq.BAM_Reader(bam_file).get_header_... | Python | zaydzuhri_stack_edu_python |
function act self states
begin
set tuple logits _ = call forward states
return call sample_action logits
end function | def act(self, states):
logits, _ = self.forward(states)
return self.sample_action(logits) | Python | nomic_cornstack_python_v1 |
class StockHolding
begin
function __init__ self icon tshare stprice
begin
set icon = icon
set tshare = tshare
set stprice = stprice
end function
function getNumShares self
begin
return tshare
end function
function getstprice self
begin
return stprice
end function
function sellShares self sellshare
begin
set sellshare =... | class StockHolding:
def __init__( self, icon, tshare, stprice ):
self.icon = icon
self.tshare = tshare
self.stprice = stprice
def getNumShares(self):
return self.tshare
def getstprice(self):
return self.stprice
def sellShares(self, sellshare ):... | Python | zaydzuhri_stack_edu_python |
function dcg_score_at_k ground_truth predictions k=5 pos_label=1
begin
assert length ground_truth == length predictions msg string DCG@k: Length mismatch
comment ::-1 reverses array
set desc_order = call argsort predictions at slice : : - 1
comment the top indices
set ground_truth = call take ground_truth desc_order ... | def dcg_score_at_k(ground_truth, predictions, k=5, pos_label=1):
assert len(ground_truth) == len(predictions), "DCG@k: Length mismatch"
desc_order = np.argsort(predictions)[::-1] # ::-1 reverses array
ground_truth = np.take(ground_truth, desc_order[:k]) # the top indices
gains = 2 ** ground_truth - 1... | Python | nomic_cornstack_python_v1 |
import re
function reDemo
begin
set pattern = compile string world
set match = search string helloworld 3 10
comment match
print format string string:{},re:{},po:{},endPo:{},start:{},end:{} string re pos endpos start match call end
if match
begin
print call group 0
pass
end
pass
comment search
set match = search string... | import re
def reDemo():
pattern=re.compile(r'world')
match= pattern.search('helloworld',3,10)
# match
print('string:{},re:{},po:{},endPo:{},start:{},end:{}'.format(match.string,match.re,match.pos,match.endpos,match.start(),match.end()))
if match:
print(match.group(0))
pass
pass
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string noah olmstead harvey baccarat 21102020 this script calculates baccarat odds
comment IMPORTS #################################################################################################################
from random import random
import matplotlib
call use string Agg
from matplotlib i... | #!/usr/bin/python3
"""
noah olmstead harvey
baccarat
21102020
this script calculates baccarat odds
"""
#### IMPORTS #################################################################################################################
from random import random
import matplotlib
matplotlib.use("Agg")
from ... | Python | zaydzuhri_stack_edu_python |
import gym
import math
import numpy as np
import numpy.random as nprnd
import matplotlib.pyplot as plt
comment bounds inputted x between (-1,1)
function sigmoid x
begin
return 1 / 1 + exp - x
end function
comment selects a random output, favoring the largest one
function makeChoice outputs
begin
return integer outputs ... | import gym
import math
import numpy as np
import numpy.random as nprnd
import matplotlib.pyplot as plt
#bounds inputted x between (-1,1)
def sigmoid(x):
return ( 1/(1 + np.exp(-x)) )
#selects a random output, favoring the largest one
def makeChoice(outputs):
return int( outputs[1] > nprnd.random()*(outputs[1]... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
set base = format string {} ; {} : {} -> loaned_copy borrower loan_start
if date_returned
begin
return base + string date_returned
end
return base + string open
end function | def __str__(self):
base = '{} ; {} : {} -> '.format(self.loaned_copy, self.borrower, self.loan_start)
if self.date_returned:
return base + str(self.date_returned)
return base + 'open' | Python | nomic_cornstack_python_v1 |
comment 1564 Brazil World Cup
while true
begin
try
begin
set num = integer input
if 0 <= num <= 100
begin
if num == 0
begin
print string vai ter copa!
end
else
begin
print string vai ter duas!
end
end
end
except any
begin
break
end
end | #1564 Brazil World Cup
while True:
try:
num = int(input())
if 0<=num <=100:
if num == 0:
print("vai ter copa!")
else:
print("vai ter duas!")
except:
break
| Python | zaydzuhri_stack_edu_python |
function test_psf_image_view
begin
import time
set t1 = time
set array = call psf array_shape=testshape
set image = call psf_image array_shape=testshape
call assert_array_almost_equal as type array float32 array decimal
set t2 = time
end function | def test_psf_image_view():
import time
t1 = time.time()
array = galsim.optics.psf(array_shape=testshape)
image = galsim.optics.psf_image(array_shape=testshape)
np.testing.assert_array_almost_equal(array.astype(np.float32), image.array, decimal)
t2 = time.time() | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
import sys
set tuple name surname fathername = split input string Будь ласка скажіть своє прізвище, ім'я та по-батькові? sep=string
print string Радий познайомитись, + name + string + surname + string + fathername | #! /usr/bin/env python3
import sys
name, surname, fathername = input("Будь ласка скажіть своє прізвище, ім'я та по-батькові? ").split(sep =' ')
print("Радий познайомитись, " + name + " " + surname + " " + fathername)
| Python | zaydzuhri_stack_edu_python |
string Helper classes for tests.
import unittest
from bs4 import BeautifulSoup
from bs4.element import Comment , SoupStrainer
from bs4.builder import LXMLTreeBuilder
class SoupTest extends TestCase
begin
decorator property
function default_builder self
begin
return call LXMLTreeBuilder
end function
function soup self m... | """Helper classes for tests."""
import unittest
from bs4 import BeautifulSoup
from bs4.element import Comment, SoupStrainer
from bs4.builder import LXMLTreeBuilder
class SoupTest(unittest.TestCase):
@property
def default_builder(self):
return LXMLTreeBuilder()
def soup(self, markup, **kwargs):
... | Python | zaydzuhri_stack_edu_python |
function from_environ cls environ
begin
return call from_base64 environ at __name__
end function | def from_environ(cls, environ):
return cls.from_base64(environ[cls.__name__]) | Python | nomic_cornstack_python_v1 |
from grid import Grid
from btree import BinaryTree
from sidewinder import Sidewinder
from aldous_brouder import AldousBroder
from wilson import Wilson
from hunt_kill import HuntAndKill
set algos = list BinaryTree Sidewinder AldousBroder Wilson HuntAndKill
set tries = 100
set size = 20
set avgs = dict
for algo in algos... | from grid import Grid
from btree import BinaryTree
from sidewinder import Sidewinder
from aldous_brouder import AldousBroder
from wilson import Wilson
from hunt_kill import HuntAndKill
algos = [ BinaryTree, Sidewinder, AldousBroder, Wilson, HuntAndKill ]
tries = 100
size = 20
avgs = {}
for algo in algos:
name =... | Python | zaydzuhri_stack_edu_python |
function pointInPolygon x y poly
begin
comment do this using try:...except rather than hasattr() for speed
try
begin
comment we want to access this only once
set poly = verticesPix
end
except any
begin
pass
end
set nVert = length poly
if nVert < 3
begin
set msg = string pointInPolygon expects a polygon with 3 or more v... | def pointInPolygon(x, y, poly):
try: #do this using try:...except rather than hasattr() for speed
poly = poly.verticesPix #we want to access this only once
except:
pass
nVert = len(poly)
if nVert < 3:
msg = 'pointInPolygon expects a polygon with 3 or more vertices'
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import Stemmer
import unicodedata
set stop_words = list
set stop_words_path = string
function process_text word tam=3
begin
set word = call strip_accents word
try
begin
set word = decode word string utf-8
set characters = list string . string : string ; strin... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import Stemmer
import unicodedata
stop_words = []
stop_words_path = ""
def process_text(word,tam=3):
word = strip_accents(word)
try:
word = word.decode("utf-8")
characters = [u".",u":",u";",u"\'",u"\"",u"!",u")",u"(",u"{",u"}",u"[",u"]",u"*",u",",u"<",u">",u"?",u"=... | Python | zaydzuhri_stack_edu_python |
function add_edge self A B source_polygons=list
begin
assert A in _nodes
assert B in _nodes
comment Don't add any edges that already exist. Update the edge's
comment source polygons list to include the new polygon. Care needs
comment to be taken here to not create an Edge until we know we need
comment one, otherwise th... | def add_edge(self, A, B, source_polygons=[]):
assert A in self._nodes
assert B in self._nodes
# Don't add any edges that already exist. Update the edge's
# source polygons list to include the new polygon. Care needs
# to be taken here to not create an Edge until we know we nee... | Python | nomic_cornstack_python_v1 |
function wncond left right window
begin
string Contract each of the intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncond_c.html :param left: Amount added to each left endpoint. :type left: float :param right: Amount subtracted from each right endpoint. :type right: floa... | def wncond(left, right, window):
"""
Contract each of the intervals of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncond_c.html
:param left: Amount added to each left endpoint.
:type left: float
:param right: Amount subtracted from each right endpoint. ... | Python | jtatman_500k |
function set_config self config_file section
begin
set config_file = config_file
set section = section
comment instantiate config manager
set config = call Config config_file section
end function | def set_config(self, config_file, section):
self.config_file = config_file
self.section = section
# instantiate config manager
self.config = Config(self.config_file, self.section) | Python | nomic_cornstack_python_v1 |
import urllib.request as req
import urllib.parse as par
from bs4 import BeautifulSoup as bsoup
import sys
set serviceUrl = string http://auctions.search.yahoo.co.jp/search?
if argv at 1 == string
begin
print string auction.py <key words> <number of page>
exit - 1
end
if argv at 2 == string
begin
print string auction.... | import urllib.request as req
import urllib.parse as par
from bs4 import BeautifulSoup as bsoup
import sys
serviceUrl = 'http://auctions.search.yahoo.co.jp/search?'
if sys.argv[1] == '':
print('auction.py <key words> <number of page>')
sys.exit(-1)
if sys.argv[2] == '':
print('auction.py <key words> <num... | Python | zaydzuhri_stack_edu_python |
function saccade_to_boundary self label event_queue=none report=EL_TIME_END
begin
if not event_queue
begin
set event_queue = call get_event_queue list EL_SACCADE_END
end
if not length event_queue
begin
return false
end
for e in event_queue
begin
if e == none or call get_event_type e != EL_SACCADE_END
begin
continue
end... | def saccade_to_boundary(self, label, event_queue=None, report=EL_TIME_END):
if not event_queue:
event_queue = self.get_event_queue([EL_SACCADE_END])
if not len(event_queue):
return False
for e in event_queue:
if e == None or self.get_event_type(e) != EL_SACCA... | Python | nomic_cornstack_python_v1 |
comment 156 / 156 test cases passed.
comment Status: Accepted
comment Runtime: 39 ms
class Solution extends object
begin
function firstMissingPositive self nums
begin
string :type nums: List[int] :rtype: int
if nums
begin
set m = max nums
from collections import Counter
set c = counter nums
for i in range 1 m + 2
begin... | # 156 / 156 test cases passed.
# Status: Accepted
# Runtime: 39 ms
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums:
m = max(nums)
from collections import Counter
c = Counter(n... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime as dt
from packets import ZTPacket
class Profiler extends object
begin
function __init__ self start_ts=none
begin
set __packet_transmission_times = dictionary
set __lost_packets_freq = dictionary
set __start_ts = start_ts
if __start_ts is none
begin
set __start_ts = timestamp now
end
end f... | from datetime import datetime as dt
from .packets import ZTPacket
class Profiler(object):
def __init__(self, start_ts: float = None):
self.__packet_transmission_times = dict()
self.__lost_packets_freq = dict()
self.__start_ts = start_ts
if self.__start_ts is None:
sel... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
from tkinter import ttk
class FloatingWindow extends Toplevel
begin
function __init__ self *args **kwargs
begin
call __init__ self *args keyword kwargs
call overrideredirect true
set grip = call Label self
call pack side=string top fill=string x
call bind string <ButtonPress-1> StartMove
call bind ... | import tkinter as tk
from tkinter import ttk
class FloatingWindow(tk.Toplevel):
def __init__(self, *args, **kwargs):
tk.Toplevel.__init__(self, *args, **kwargs)
self.overrideredirect(True)
self.grip = tk.Label(self)
self.grip.pack(side="top", fill="x")
self.grip.b... | Python | zaydzuhri_stack_edu_python |
function search_hash apikey hashdigest user_agent proxies=none verify_ssl=true
begin
set url = string https://www.hybrid-analysis.com/api/v2/search/hash
with call ssl_verification verify=verify_ssl
begin
set headers = dict string User-Agent user_agent ; string accept string application/json ; string api-key apikey ; st... | def search_hash(
apikey: Text,
hashdigest: Text,
user_agent: Text,
proxies: Optional[Dict[Text, Text]] = None,
verify_ssl: bool = True,
) -> List[Dict[Text, Any]]:
url = "https://www.hybrid-analysis.com/api/v2/search/hash"
with ssl_verification(verify=verify_ssl):
headers = {
... | Python | nomic_cornstack_python_v1 |
function play_again
begin
print string Press Y to play again and any key to finish
return starts with lower input string y
end function | def play_again():
print("Press Y to play again and any key to finish")
return input().lower().startswith("y") | Python | nomic_cornstack_python_v1 |
string Sort the words in a given sentence alphabetically
function sort_words_alphabetically sentence
begin
comment Split sentence into words
set words_list = split sentence
comment Sort the words
sort words_list
comment Join the words
return join string words_list
end function
if __name__ == string __main__
begin
prin... | """
Sort the words in a given sentence alphabetically
"""
def sort_words_alphabetically(sentence):
# Split sentence into words
words_list = sentence.split()
# Sort the words
words_list.sort()
# Join the words
return ' '.join(words_list)
if __name__ == '__main__':
print(sort_words_alphabe... | Python | flytech_python_25k |
function __init__ self square_coords identifier move_cost reward
begin
set coords = square_coords
set identifier = string identifier
set reward = reward
set move_cost = move_cost
end function | def __init__(self, square_coords, identifier, move_cost, reward):
self.coords = square_coords
self.identifier = str(identifier)
self.reward = reward
self.move_cost = move_cost | Python | nomic_cornstack_python_v1 |
import sqlite3
from db import db
class CarModel extends Model
begin
set __tablename__ = string cars
set id = call Column Integer primary_key=true
set make = call Column call String 80
set model = call Column call String 80
set color = call Column call String 80
set doors = call Column call String 80
set top_speed = cal... | import sqlite3
from db import db
class CarModel(db.Model):
__tablename__ = 'cars'
id = db.Column(db.Integer, primary_key=True)
make = db.Column(db.String(80))
model = db.Column(db.String(80))
color = db.Column(db.String(80))
doors = db.Column(db.String(80))
top_speed = db.Column(db.String(... | Python | zaydzuhri_stack_edu_python |
from util.tree.tokenize import tokenize
from util.tree.reader import reader
from util.tree.node import Node
from util.tree.list import List
function node_tree_from_sequence sequence
begin
string transforms a bracketed notation parse into a regular tree from
set list_tree = call list_tree_from_sequence sequence
return c... | from util.tree.tokenize import tokenize
from util.tree.reader import reader
from util.tree.node import Node
from util.tree.list import List
def node_tree_from_sequence(sequence):
''' transforms a bracketed notation parse into a regular tree from '''
list_tree = list_tree_from_sequence(sequence)
return unp... | Python | zaydzuhri_stack_edu_python |
import pymongo
import pprint
import json
import numpy as np
comment Connect to the mongoDB
set pp = call PrettyPrinter indent=4
set client = call MongoClient string mongodb://user1:dva2020!@35.227.61.30/outdoor
set db = client at string outdoor
comment Extract our 2 collections
set hp_collection = db at string hikingpr... | import pymongo
import pprint
import json
import numpy as np
# Connect to the mongoDB
pp = pprint.PrettyPrinter(indent=4)
client = pymongo.MongoClient("mongodb://user1:dva2020!@35.227.61.30/outdoor")
db = client['outdoor']
# Extract our 2 collections
hp_collection = db['hikingproject']
at_collection = db... | Python | zaydzuhri_stack_edu_python |
comment example 3
comment 2*x**2+6*x-20
set a = 2
set b = 6
set c = - 20
set delta = b ^ 2 - 4 * a * c
set roots1 = - b - delta ^ 0.5 / 2 * a
set roots2 = - b + delta ^ 0.5 / 2 * a
print string roots1: roots1
print string roots2: roots2 | # example 3
# 2*x**2+6*x-20
a = 2
b = 6
c = -20
delta = b ** 2 - 4 * a * c
roots1 = (-b - delta ** 0.5) / (2 * a)
roots2 = (-b + delta ** 0.5) / (2 * a)
print ("roots1:", roots1)
print ("roots2:", roots2)
| Python | zaydzuhri_stack_edu_python |
function get_variable_for_api_name self api_name param_instance=none
begin
if not is instance api_name str
begin
raise call SDKException DATA_TYPE_ERROR string KEY: api_name EXPECTED TYPE: str none none
end
if param_instance is not none and not is instance param_instance ParameterMap
begin
raise call SDKException DATA_... | def get_variable_for_api_name(self, api_name, param_instance=None):
if not isinstance(api_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: api_name EXPECTED TYPE: str', None, None)
if param_instance is not None and not isinstance(param_instance, ParameterMap):
raise SDKException(Constants.D... | Python | nomic_cornstack_python_v1 |
import os
import argparse
import csv
import overpy
try
begin
set parser = call ArgumentParser
call add_argument string -wdir type=str default=string /home/miguel/Documents/projects/Wildfire/wfire/src/simulation help=string working dir
call add_argument string lat1 type=float help=string latitude1 for HGT file
call add_... | import os
import argparse
import csv
import overpy
try:
parser = argparse.ArgumentParser()
parser.add_argument('-wdir', type=str, default=r'/home/miguel/Documents/projects/Wildfire/wfire/src/simulation', help="working dir")
parser.add_argument('lat1', type=float, help="latitude1 for HGT file")
par... | Python | zaydzuhri_stack_edu_python |
comment This is where we will manipulate the data
comment We will put the result of this into the model
comment This will go in a pickle (.pkl) file that goes in the data directory
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import sentlex
import sentlex.sentanalysis
from textblob import TextBl... | # This is where we will manipulate the data
# We will put the result of this into the model
# This will go in a pickle (.pkl) file that goes in the data directory
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import sentlex
import sentlex.sentanalysis
from textblob import TextBlob, Word
from skl... | Python | zaydzuhri_stack_edu_python |
function test_search_config tmp_path
begin
set root_yaml = tmp_path / string root.yaml
with open root_yaml string w as f
begin
write f string foobar
end
set chosen_path = call search_config root_yaml
assert chosen_path == root_yaml
end function | def test_search_config(tmp_path):
root_yaml = tmp_path / "root.yaml"
with open(root_yaml, "w") as f:
f.write("foobar")
chosen_path = search_config(root_yaml)
assert chosen_path == root_yaml | Python | nomic_cornstack_python_v1 |
function _get_rows_from_query self query data
begin
set to_return = list
set results = execute call cursor query data
for result in results
begin
append to_return result
end
return to_return
end function | def _get_rows_from_query(self, query, data):
to_return = []
results = self.db_conn.cursor().execute(query, data)
for result in results:
to_return.append(result)
return to_return | Python | nomic_cornstack_python_v1 |
function plot_all_stratified self percent=true filter_f=none prepend=string filename_pre=string
begin
comment TODO: fix bug, positions on chart are out of order
if filter_f != none
begin
set result_df = call stratify_and_filter_results filter_f
end
else
begin
set result_df = stratified_results
end
comment consider add... | def plot_all_stratified(self, percent=True, filter_f=None, prepend="", filename_pre=""):
# TODO: fix bug, positions on chart are out of order
if filter_f != None:
result_df = self.stratify_and_filter_results(filter_f)
else:
result_df = self.stratified_results
# consider additionally using a 3d plot ... | Python | nomic_cornstack_python_v1 |
function isPallindrome x
begin
if integer string x at slice : : - 1 is x
begin
return true
end
return false
end function
function isPositive x
begin
if x > 0
begin
return true
end
return false
end function
set n = integer input
set numbers = list map int split input
if all list comprehension call isPositive x for x i... | def isPallindrome(x):
if int(str(x)[::-1]) is x:
return True
return False
def isPositive(x):
if x>0:
return True
return False
n = int(input())
numbers = list(map(int, input().split()))
if all([isPositive(x) for x in numbers]):
if any([isPallindrome(x) for x in numbers]):
... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
import os
function download_page url
begin
set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
set r = get requests url headers=headers
set encoding = apparent_encoding
return text
end function
function ... | import requests
from bs4 import BeautifulSoup
import os
def download_page(url):
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
r=requests.get(url,headers=headers)
r.encoding=r.apparent_encoding
return r.text
def get_pic_list1(url,... | Python | zaydzuhri_stack_edu_python |
function append self *args
begin
return call vectorPosition2D_append self *args
end function | def append(self, *args):
return _almathswig.vectorPosition2D_append(self, *args) | Python | nomic_cornstack_python_v1 |
comment /tests/test_auth.py
import unittest
import json
from app import create_app , db
class AuthTestCase extends TestCase
begin
string Test case for the authentication blueprint.
function setUp self
begin
string Set up test variables.
set app = call create_app configure=string testing
comment initialize the test clie... | # /tests/test_auth.py
import unittest
import json
from app import create_app, db
class AuthTestCase(unittest.TestCase):
"""Test case for the authentication blueprint."""
def setUp(self):
"""Set up test variables."""
self.app = create_app(configure="testing")
# initialize the test cli... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
from collections import defaultdict
string nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}}
comment s1
set nested_dict = dict
set nested_dict at string dictA = dict
set nested_dict at string dictB = dict
set nested_dict at string dictA at string key_1 = string v... | #!/usr/bin/python3
from collections import defaultdict
'''
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
'''
## s1
nested_dict = {}
nested_dict['dictA'] = {}
nested_dict['dictB'] = {}
nested_dict['dictA']['key_1'] = 'value_1'
nested_dict['dictB']['key_2'] = 'valu... | Python | zaydzuhri_stack_edu_python |
function clean self
begin
run init_op
print string Clean the running state of graph!
end function | def clean(self):
self.sess.run(self.init_op)
print("Clean the running state of graph!") | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
class eDBMException extends Exception
begin
function __init__ self message
begin
set _message = message
end function
function getMessage self
begin
return string Errore: + _message
end function
function __str__ self
begin
return string Errore: + _message
end function
end class | # -*- coding: utf-8 -*-
class eDBMException(Exception):
def __init__(self, message):
self._message = message
def getMessage(self):
return "Errore: " + self._message
def __str__(self):
return "Errore: " + self._message | Python | zaydzuhri_stack_edu_python |
function get_LA_initial_states self
begin
call __sendByte__ TIMING
call __sendByte__ GET_INITIAL_DIGITAL_STATES
set initial = call __getInt__
set A = call __getInt__ - initial / 2
set B = call __getInt__ - initial / 2 - MAX_SAMPLES / 4
set C = call __getInt__ - initial / 2 - 2 * MAX_SAMPLES / 4
set D = call __getInt__ ... | def get_LA_initial_states(self):
self.H.__sendByte__(CP.TIMING)
self.H.__sendByte__(CP.GET_INITIAL_DIGITAL_STATES)
initial = self.H.__getInt__()
A = (self.H.__getInt__() - initial) / 2
B = (self.H.__getInt__() - initial) / 2 - self.MAX_SAMPLES / 4
C = (self.H.__getInt__()... | Python | nomic_cornstack_python_v1 |
function to_rdkit_mol self
begin
assert all generator expression idx is not none for atom in self
set rd_mol = call EditableMol call Mol
for atom in self
begin
set rd_atom = call Atom symbol
call SetAtomMapNum idx
call AddAtom rd_atom
end
for atom1 in self
begin
for tuple atom2 connection in items connections
begin
com... | def to_rdkit_mol(self):
assert all(atom.idx is not None for atom in self)
rd_mol = Chem.rdchem.EditableMol(Chem.rdchem.Mol())
for atom in self:
rd_atom = Chem.rdchem.Atom(atom.symbol)
rd_atom.SetAtomMapNum(atom.idx)
rd_mol.AddAtom(rd_atom)
for atom1 ... | Python | nomic_cornstack_python_v1 |
import socket
import _thread
import sys
import os
comment loop to mannage connected socket input
function on_new_client clientsocket addr
begin
while true
begin
set msg = call recv 1024
set cmd = decode msg encoding=string utf-8
print cmd
call system cmd
end
close clientsocket
end function
comment created and bind sock... | import socket
import _thread
import sys
import os
#loop to mannage connected socket input
def on_new_client(clientsocket,addr):
while True:
msg=clientsocket.recv(1024)
cmd = msg.decode(encoding='utf-8')
print(cmd)
os.system(cmd)
clientsocket.close()
#created and bind socket
s =... | Python | zaydzuhri_stack_edu_python |
function build_command self
begin
return get pulumi self string build_command
end function | def build_command(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "build_command") | Python | nomic_cornstack_python_v1 |
comment import
from flask import Flask , render_template , request , session , flash , redirect , url_for , g
import sqlite3
from functools import wraps
import os
set key = call urandom 24
comment configuration
set DATABASE = string blog.db
set USERNAME = string admin
set PASSWORD = string admin
set SECRET_KEY = key
se... | #import
from flask import Flask, render_template, request,session,\
flash,redirect,url_for,g
import sqlite3
from functools import wraps
import os
key=os.urandom(24)
#configuration
DATABASE='blog.db'
USERNAME='admin'
PASSWORD='admin'
SECRET_KEY=key
app=Flask(__name__)
# pulls in app configuration by looking for UPPERCAS... | Python | zaydzuhri_stack_edu_python |
function rotate self count=1 center=none
begin
set center = center or call Vec2D 0 0
set result = self
for i in range count % 8
begin
set result = call rotate_once center
end
return result
end function | def rotate(self, count=1, center=None):
center = center or Vec2D(0, 0)
result = self
for i in range(count % 8):
result = result.rotate_once(center)
return result | Python | nomic_cornstack_python_v1 |
import json
function query_ticker_term ticker
begin
string Tries to get unique stock ticker to query news articles.
comment Use ticker data to load all fortune 500 this is a dictionary with key as symbol and value as name of company
with open string ./data/fortune500/fortune500s_n.json string r as json_file
begin
set d... | import json
def query_ticker_term(ticker):
"""
Tries to get unique stock ticker to query news articles.
"""
# Use ticker data to load all fortune 500 this is a dictionary with key as symbol and value as name of company
with open('./data/fortune500/fortune500s_n.json', 'r') as json_file:
... | Python | zaydzuhri_stack_edu_python |
function testsvm_step1 self models_name sample_name output_name
begin
set args = call get_file_args models_name
set args = args + call get_commonlib
set h_args = call mapreduce_core sample_name=sample_name output_name=output_name exe_file=exe_testsvm1 is_cat=true args=args
return h_args
end function | def testsvm_step1(self, models_name, sample_name, output_name):
args = self.get_file_args(models_name)
args += self.get_commonlib()
h_args = self.mapreduce_core(sample_name=sample_name,
output_name=output_name,
exe_file=s... | Python | nomic_cornstack_python_v1 |
function init_scene scene_db history_db name
begin
from src.praxxis.sqlite import sqlite_scene
call init_scene scene_db name
call update_current_scene history_db name
return tuple scene_db name
end function | def init_scene(scene_db, history_db, name):
from src.praxxis.sqlite import sqlite_scene
sqlite_scene.init_scene(scene_db, name)
sqlite_scene.update_current_scene(history_db, name)
return (scene_db, name) | Python | nomic_cornstack_python_v1 |
function get_even_numbers lst
begin
set even_numbers = list
for num in lst
begin
if num % 2 == 0
begin
append even_numbers num
end
else
if num < 0 and absolute num % 2 == 0
begin
append even_numbers num
end
end
return even_numbers
end function | def get_even_numbers(lst):
even_numbers = []
for num in lst:
if num % 2 == 0:
even_numbers.append(num)
elif num < 0 and abs(num) % 2 == 0:
even_numbers.append(num)
return even_numbers
| Python | greatdarklord_python_dataset |
string 给定一个 n × n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 示例 1: 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] 示例 2: 给定 matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], 原地旋转输入矩阵,使其变为: [ [15,13, 2, 5], [14, 3, 4, 1], ... | """给定一个 n × n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2,... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: H_Hoshigi
function main
begin
set tuple N K = map int split input
set x_lsit = list map int split input
set INF = power 10 9
set min_time = INF
for i in range N - K + 1
begin
set x_l = x_lsit at i
set x_r = x_lsit at i + K - 1
set this_time = integer
if x_l <= - 1
begin
if ... | # -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""
def main():
N, K = map(int, input().split())
x_lsit = list(map(int, input().split()))
INF = pow(10, 9)
min_time = INF
for i in range(N-K+1):
x_l = x_lsit[i]
x_r = x_lsit[i+K-1]
this_time = int()
if x_l <= -1:
... | Python | zaydzuhri_stack_edu_python |
function toggleLongTouchPoint self
begin
string Toggles the long touch point operation.
if not isLongTouchingPoint
begin
set msg = string Long touching point
call toast msg background=GREEN
set msg
set isLongTouchingPoint = true
comment FIXME: There should be 2 methods DIP & PX
set coordinatesUnit = PX
end
else
begin
c... | def toggleLongTouchPoint(self):
'''
Toggles the long touch point operation.
'''
if not self.isLongTouchingPoint:
msg = 'Long touching point'
self.toast(msg, background=Color.GREEN)
self.statusBar.set(msg)
self.isLongTouchingPoint = True
... | Python | jtatman_500k |
from typing import List
from import strategy
from utils.util_functions import get_shortest_path , get_path_action_seq , get_nearest_tile , get_reachable_tiles , move_results_in_ouchie , manhattan_distance , convert_entities_to_coords , player_has_control , get_articulation_points
from utils.constants import ACTIONS
cl... | from typing import List
from . import strategy
from ..utils.util_functions import get_shortest_path, get_path_action_seq, get_nearest_tile, get_reachable_tiles, \
move_results_in_ouchie, manhattan_distance, convert_entities_to_coords, player_has_control, get_articulation_points
from ..utils.constants import ACTIONS... | Python | zaydzuhri_stack_edu_python |
from database.database import create_table_database , query_database
from entities.studio import Studio
function create_studios_table
begin
set query = string CREATE TABLE IF NOT EXISTS studios ( studioId INTEGER PRIMARY KEY AUTOINCREMENT, studioName TEXT)
call create_table_database query
end function
comment funkcija ... | from database.database import create_table_database, query_database
from entities.studio import Studio
def create_studios_table():
query = """CREATE TABLE IF NOT EXISTS studios (
studioId INTEGER PRIMARY KEY AUTOINCREMENT,
studioName TEXT)"""
create_table_databa... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Class for identifying documents to publish.
from __future__ import absolute_import , division , print_function , unicode_literals
import csv
import logging
import os
import sys
from publishable_doc import Doc
import util
set logger = call getLogger __name__
call addHandler call Null... | # -*- coding: utf-8 -*-
"""
Class for identifying documents to publish.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
import logging
import os
import sys
from publishable_doc import Doc
import util
logger = logging.getLogger(__name__)
logger.addHandler(logging.Nul... | Python | zaydzuhri_stack_edu_python |
comment play_vibrato_interpolation.py
comment Reads a specified wave file (mono) and plays it with a vibrato effect.
comment (Sinusoidally time-varying delay)
comment Uses linear interpolation
import numpy as np
function my_vibrato_func myInput
begin
set LEN = length myInput
comment Vibrato parameters
set f0 = 2
commen... | # play_vibrato_interpolation.py
# Reads a specified wave file (mono) and plays it with a vibrato effect.
# (Sinusoidally time-varying delay)
# Uses linear interpolation
import numpy as np
def my_vibrato_func(myInput):
LEN = len(myInput)
# Vibrato parameters
f0 = 2
W = 0.05 # W = 0 for no effect
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
string FileName: dp_solution.py Description: Author: Barry Chow Date: 2020/10/20 9:34 PM Version: 0.1
class Solution extends object
begin
function minCostClimbingStairs self cost
begin
string 1.定义状态: dp[i]表示到第i层,最小的花费 2.定义状态转移方程 dp[i]= min(dp[i-1],dp[i-2])+cost[... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
FileName: dp_solution.py
Description:
Author: Barry Chow
Date: 2020/10/20 9:34 PM
Version: 0.1
"""
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
1.定义状态:
dp[i]表示到第i层,最小的花费
2.定义状态转移方程
dp[i]= min(dp[i-1],d... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function summaryRanges self nums
begin
if not nums
begin
return list
end
set res = list
set length = length nums
set prev = none
for i in range length
begin
if prev == none
begin
set prev = nums at i
end
else
if nums at i - 1 != nums at i - 1
begin
if prev == nums at i - 1
begin
append res string... | class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
if not nums:
return []
res = []
length = len(nums)
prev = None
for i in range(length):
if prev == None:
prev = nums[i]
elif nums[i - 1] != nums[... | Python | zaydzuhri_stack_edu_python |
function find_serial_numbers cls
begin
return list comprehension serial_number for d in find core idVendor=id_vendor idProduct=id_product find_all=true
end function | def find_serial_numbers(cls):
return [d.serial_number for d in usb.core.find(
idVendor=cls.id_vendor, idProduct=cls.id_product, find_all=True)] | Python | nomic_cornstack_python_v1 |
function addLinearPointConstr self constr path=false
begin
assert is instance constr linearPointConstr
if path
begin
append linPathConstr constr
end
else
begin
append linPointConstr constr
end
end function | def addLinearPointConstr(self, constr, path=False):
assert isinstance(constr, linearPointConstr)
if path:
self.linPathConstr.append(constr)
else:
self.linPointConstr.append(constr) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string ************************************************************************** * Cross_A_Crater (e-Yantra 2016) * ================================ * This software is intended to teach image processing concepts * * MODULE: Task2 * Filename: imgLib.py * Version: 1.5.0 * Date: November 21,... | # -*- coding: utf-8 -*-
"""
**************************************************************************
* Cross_A_Crater (e-Yantra 2016)
* ================================
* This software is intended to teach image processing concepts
*
* MODULE: Task2
* Filename: imgLib.py
* Versio... | Python | zaydzuhri_stack_edu_python |
string The purpose of a spectrum object is to maintain the calculated values for a given spectrum. History: 6/25/2018: Class created
import numpy as np
class Spectrum
begin
function __init__ self waves name
begin
set waves = waves
set name = name
set isSolved = false
set values = list 0 0 0
set grpsize = 8
set peaks = ... | '''
The purpose of a spectrum object is to maintain the calculated values for a given spectrum.
History:
6/25/2018: Class created
'''
import numpy as np
class Spectrum:
def __init__(self, waves, name):
self.waves = waves
self.name = name
self.isSolved = False
self.values = [0,0,0]
self.grpsize = 8
se... | Python | zaydzuhri_stack_edu_python |
string Find a peak element Given an array of integers. Find a peak element in it. An array element is peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor. Following corner cases give better idea about the problem. 1) If input array is sorted in strictly increasing or... | """
Find a peak element
Given an array of integers. Find a peak element in it.
An array element is peak if it is NOT smaller than its neighbors.
For corner elements, we need to consider only one neighbor.
Following corner cases give better idea about the problem.
1) If input array is sorted in strictly increasing ... | Python | zaydzuhri_stack_edu_python |
function create_covariance_matrix cls coordinates
begin
set number_of_conformations = shape at 0
set number_of_atoms = shape at 1
set coordinates_per_conformation = number_of_atoms * 3
set covariance_matrix = zeros tuple coordinates_per_conformation coordinates_per_conformation
set coordinates = reshape coordinates tup... | def create_covariance_matrix(cls, coordinates):
number_of_conformations = coordinates.shape[0]
number_of_atoms = coordinates.shape[1]
coordinates_per_conformation = number_of_atoms * 3
covariance_matrix = numpy.zeros((coordinates_per_conformation, coordinates_per_conformation))
... | Python | nomic_cornstack_python_v1 |
function sortColors self nums
begin
set n = length nums
if n == 1
begin
return
end
set tuple zeroRightBoundary twoLeftBoundary = tuple 0 n - 1
while zeroRightBoundary < n - 1 and nums at zeroRightBoundary == 0
begin
set zeroRightBoundary = zeroRightBoundary + 1
end
while twoLeftBoundary > 0 and nums at twoLeftBoundary ... | def sortColors(self, nums: List[int]) -> None:
n = len(nums)
if n == 1:
return
zeroRightBoundary, twoLeftBoundary = 0, n-1
while zeroRightBoundary < n-1 and nums[zeroRightBoundary] == 0:
zeroRightBoundary += 1
while twoLeftBoundary > 0 and nums[twoLeftBoun... | Python | nomic_cornstack_python_v1 |
function all self target=none include_global=true
begin
string Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True``). For example:: >>> aliases.all(target='my_a... | def all(self, target=None, include_global=True):
"""
Get a dictionary of all aliases and their options.
:param target: Include aliases for this specific field, model or app
(optional).
:param include_global: Include all non target-specific aliases
(default ``True... | Python | jtatman_500k |
function test_Goal_creation self
begin
set test_goal = call create_Goal
assert true is instance test_goal Goal
end function | def test_Goal_creation(self):
test_goal = self.create_Goal()
self.assertTrue(isinstance(test_goal, Goal)) | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
string @author: weiyang_tang @contact: weiyang_tang@126.com @file: data_input.py @time: 2019-02-22 10:17 @desc: 读取脸部图片,并对图片进行预处理
comment -*- coding: utf-8 -*-
import os
import numpy as np
import cv2
set IMAGE_SIZE = 64
function resize_with_pad image height=IMAGE_SIZE width=IMAGE_SIZE
begin
funct... | # encoding: utf-8
'''
@author: weiyang_tang
@contact: weiyang_tang@126.com
@file: data_input.py
@time: 2019-02-22 10:17
@desc: 读取脸部图片,并对图片进行预处理
'''
# -*- coding: utf-8 -*-
import os
import numpy as np
import cv2
IMAGE_SIZE = 64
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):
def get_padding_si... | 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.