code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function service self
begin
return get pulumi self string service
end function | def service(self) -> pulumi.Input[str]:
return pulumi.get(self, "service") | Python | nomic_cornstack_python_v1 |
function is_correct_password salt pw_hash password
begin
return call compare_digest pw_hash call pbkdf2_hmac string sha256 encode password salt 100000
end function | def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool:
return hmac.compare_digest(
pw_hash,
hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
) | Python | nomic_cornstack_python_v1 |
import random
import simpy
import numpy as np
import scipy
from matplotlib import pyplot as plt
from scipy.stats import bernoulli , shapiro
import seaborn as sns
function MMn_queuing NEW_CUSTOMERS INTERVAL_CUSTOMERS SERVER
begin
set MMn_wait = list
function source env number interval counter
begin
string Source genera... | import random
import simpy
import numpy as np
import scipy
from matplotlib import pyplot as plt
from scipy.stats import bernoulli , shapiro
import seaborn as sns
def MMn_queuing(NEW_CUSTOMERS,INTERVAL_CUSTOMERS,SERVER):
MMn_wait = []
def source(env, number, interval, counter):
"""Source generates cus... | Python | zaydzuhri_stack_edu_python |
function parse_equality self
begin
set l_expression = call parse_comparison
while call check_type EQUAL_TO or call check_type NOT_EQUAL_TO
begin
set token = call consume
set op = to_operator_type at value
set r_expression = call parse_comparison
set l_expression = call BinaryOperator l_expression op r_expression line c... | def parse_equality(self):
l_expression = self.parse_comparison()
while self.check_type(TokenType.EQUAL_TO) or self.check_type(TokenType.NOT_EQUAL_TO):
token = self.consume()
op = to_operator_type[token.value]
r_expression = self.parse_comparison()
l_expre... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
from req_ import req
from re import search
from data.mysql import *
import urllib.parse
function getConf body config
begin
set badChar = list string ' string "
set escape = list string ' string " string %20
set err_ = string
set char_ = string
comment Détection basée sur les messages d'erreurs (S... | #coding:utf-8
from req_ import req
from re import search
from data.mysql import *
import urllib.parse
def getConf(body, config):
badChar = [
'\'',
'"'
]
escape = [
'\'',
'"',
'%20'
]
err_ = ''
char_ = ''
# Détection basée sur les messages d'erreurs (STRING context only)
# On regarde quel ca... | Python | zaydzuhri_stack_edu_python |
function plotGraph self y1 y2 title=string Y1 and Y2 xLabel=string X yLabel=string Y yOneLegend=string Y1 yTwoLegend=string Y2 name=none
begin
comment Clear the canvas
call clf
comment Plot data
plot y1 color=string black label=yOneLegend
plot y2 color=string magenta label=yTwoLegend
x label xLabel
y label yLabel
title... | def plotGraph(self, y1, y2, title="Y1 and Y2", xLabel="X", yLabel="Y", yOneLegend="Y1", yTwoLegend="Y2", name=None):
# Clear the canvas
plt.clf()
# Plot data
plt.plot(y1, color="black", label=yOneLegend)
plt.plot(y2, color="magenta", label=yTwoLegend)
plt.xlabel(xLabel)... | Python | nomic_cornstack_python_v1 |
function filter_results source results aggressive=false
begin
set non_docstring_string_line_numbers = call multiline_string_lines source include_docstrings=false
set all_string_line_numbers = call multiline_string_lines source include_docstrings=true
set split_source = list none + call splitlines
for r in results
begin... | def filter_results(source, results, aggressive=False):
non_docstring_string_line_numbers = multiline_string_lines(
source, include_docstrings=False)
all_string_line_numbers = multiline_string_lines(
source, include_docstrings=True)
split_source = [None] + source.splitlines()
fo... | Python | nomic_cornstack_python_v1 |
function getWordScore word n
begin
set score = 0
for letter in word
begin
set score = score + SCRABBLE_LETTER_VALUES at letter
end
set score = score * length word
if length word == n
begin
set score = score + 50
end
return score
end function | def getWordScore(word, n):
score = 0
for letter in word:
score += SCRABBLE_LETTER_VALUES[letter]
score *= len(word)
if len(word) == n:
score += 50
return score | Python | nomic_cornstack_python_v1 |
import turtle
import time
set pen1 = call Turtle
set paper = call Screen
set colorList = list string blue string red string yellow
comment addcolorList = ["green"]
set colorList = colorList + list string green string black string pink + list string blue string red string yellow
comment colorList = colorList[1:5]
commen... | import turtle
import time
pen1 = turtle.Turtle()
paper = turtle.Screen()
colorList = ["blue","red","yellow"]
#addcolorList = ["green"]
colorList = colorList +["green","black","pink"] + ["blue","red","yellow"]
#colorList = colorList[1:5]
#print(colorList)
#a =int(input("Enter the Sides "))
a= 4
j = 360/a
t1 = time.... | Python | zaydzuhri_stack_edu_python |
comment import cv2
comment import numpy as np
comment # img = cv2.imread("lena.jpg")
comment # blank = np.zeros((512,512,3), np.uint8)
comment # cv2.imshow("blank",blank)
comment # cv2.waitKey(0)
comment events = [i for i in dir(cv2) if 'EVENT' in i]
comment print(events)
comment drawing = False
comment mode =True
comm... | # import cv2
# import numpy as np
# # img = cv2.imread("lena.jpg")
# # blank = np.zeros((512,512,3), np.uint8)
# # cv2.imshow("blank",blank)
# # cv2.waitKey(0)
#
# events = [i for i in dir(cv2) if 'EVENT' in i]
# print(events)
# drawing = False
# mode =True
# ix , iy = 1,1
#
# # mouse callback function
#... | Python | zaydzuhri_stack_edu_python |
import turtle
from turtle import *
import shapes
from shapes import *
call shape string turtle
call speed 10
call o
call penup
call forward 100
call pendown
call h
call done | import turtle
from turtle import *
import shapes
from shapes import *
shape('turtle')
speed(10)
o()
penup()
forward(100)
pendown()
h()
done()
| Python | zaydzuhri_stack_edu_python |
comment general graph class
class Graph
begin
function __init__ self nodes=list
begin
set nodes = nodes
end function
end class
class Node
begin
function __init__ self name children=list
begin
set name = name
set children = children
end function
end class | # general graph class
class Graph:
def __init__(self, nodes = []):
self.nodes = nodes
class Node:
def __init__(self, name, children = []):
self.name = name
self.children = children | Python | zaydzuhri_stack_edu_python |
comment Jung Kim
comment CS-21
comment Project #2 - Basic grade book
comment creates the grade book as an empty list
function gradebook
begin
set roster = list
return roster
end function
comment a function to add students to the roster created in gradebook()
function add_student roster
begin
comment local confirm feat... | #Jung Kim
#CS-21
#Project #2 - Basic grade book
def gradebook(): #creates the grade book as an empty list
roster = []
return roster
def add_student(roster): #a function to add students to the roster created in gradebook()
user_confirm, confirm = confirming() #local confirm feature to increase efficiency
... | Python | zaydzuhri_stack_edu_python |
import pytest
from cards import Card , Rank , Suit
import screen
from art import suits
set ace_of_club = list string .------. string |A __ | string | ( ) | string |(_ _)| string | /__\ | string `------´
set ten_of_club = list string .------. string |10__ | string | ( ) | string |(_ _)| string | /__\ | string `------´
s... | import pytest
from cards import Card, Rank, Suit
import screen
from art import suits
ace_of_club = [
".------.",
"|A __ |",
"| ( ) |",
"|(_ _)|",
"| /__\\ |",
"`------´",
]
ten_of_club = [
".------.",
"|10__ |",
"| ( ) |",
"|(_ _)|",
"| /__\\ |",
"`------´",
... | Python | zaydzuhri_stack_edu_python |
function test_delete_file_with_name self
begin
call delete_file filename
set file = call get_file filename
assert file is none
end function | def test_delete_file_with_name(self):
files.delete_file(self.filename)
file = files.get_file(self.filename)
assert file is None | Python | nomic_cornstack_python_v1 |
function __init__ self maxlen=none
begin
comment nonpublic list instance
set _data = list
set maxlen = maxlen
end function | def __init__(self, maxlen = None):
self._data = [] #nonpublic list instance
self.maxlen = maxlen | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import os
import sys
import subprocess
import string
comment print 'sys.argv[0]', sys.argv[0] #Contains name of the script as it appears in the command line
comment returns a directory path portion
set pathname = directory name path argv at 0
comment print 'path = ', pathname
comment returns th... | #!/usr/bin/python
import os
import sys
import subprocess
import string
#print 'sys.argv[0]', sys.argv[0] #Contains name of the script as it appears in the command line
pathname = os.path.dirname(sys.argv[0]) #returns a directory path portion
#print 'path = ', pathname
dirpath = os.path.abspath(pathname) #returns the ... | Python | zaydzuhri_stack_edu_python |
import re
comment ? indicates, the pattern can apear 0 or 1 time in an expression
set batRegEx = compile string Bat(wo)*man
set mo = search string The adventures of Batman
print call group
set mo = search string The adventures of Batwoman
print call group
set mo = search string The adventures of Batwowowowoman
print ca... | import re
# ? indicates, the pattern can apear 0 or 1 time in an expression
batRegEx = re.compile(r'Bat(wo)*man')
mo = batRegEx.search('The adventures of Batman')
print(mo.group())
mo = batRegEx.search('The adventures of Batwoman')
print(mo.group())
mo = batRegEx.search('The adventures of Batwowowowoman')
print(mo.gro... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function calculateMinimumHP self dungeon
begin
set M = length dungeon
set N = length dungeon at 0
set dp = list 0 * N
set dp at 0 = list dungeon at 0 at 0 dungeon at 0 at 0
for i in range M
begin
for j in range N
begin
set m = - 999999999
if i == 0 and j == 0
begin
continue
end
if i == 0
begin
set ... | class Solution:
def calculateMinimumHP(self, dungeon) -> int:
M = len(dungeon)
N = len(dungeon[0])
dp = [0] * N
dp[0] = [dungeon[0][0],dungeon[0][0]]
for i in range(M):
for j in range(N):
m = -999999999
if i == 0 and j == 0:
... | Python | zaydzuhri_stack_edu_python |
function test_account_modification_empty flask_server create_account
begin
import copy
import requests
set data = create_account
set inputs = tuple dict string new_name string foo2 ; string new_password string bar2 ; string new_code string
for input_ in inputs
begin
set data_tmp = copy copy data
set data_tmp = dict no... | def test_account_modification_empty(flask_server, create_account):
import copy
import requests
data = create_account
inputs = (
{'new_name': 'foo2', 'new_password': 'bar2', 'new_code': ''},
)
for input_ in inputs:
data_tmp = copy.copy(data)
data_tmp = {**data_tmp, **inpu... | Python | nomic_cornstack_python_v1 |
function testBlockingReadWrite self
begin
set write_data = call GetRandomIntegers 2048
set read_data = list
comment Writer waits for 0.05s and writes.
sleep 0.05
assert true call writeBlocking write_data 2048 1000000 string Writer should write successfully.
comment Reader reads.
set read_success = call readBlocking re... | def testBlockingReadWrite(self):
write_data = self.GetRandomIntegers(2048)
read_data = []
# Writer waits for 0.05s and writes.
time.sleep(0.05)
asserts.assertTrue(
self._queue2_writer.writeBlocking(write_data, 2048, 1000000),
"Writer should write successf... | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data
begin
set data = data
set prev = none
set next = none
end function
end class
class DoublyLinkedList
begin
function __init__ self
begin
set head = none
set tail = none
end function
function insert_at_beginning self data
begin
set new_node = call Node data
if head is none
begi... | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_beginning(self, data):
new_node = Node(data)
if self.head is None:
... | Python | greatdarklord_python_dataset |
function fizzBuzz num
begin
comment Check if the input is an integer
if not is instance num int
begin
return string Invalid input
end
comment Check if the number is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0
begin
return string FizzBuzz
end
comment Check if the number is divisible by 3
if num % 3 == 0
b... | def fizzBuzz(num):
# Check if the input is an integer
if not isinstance(num, int):
return "Invalid input"
# Check if the number is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0:
return "FizzBuzz"
# Check if the number is divisible by 3
if num % 3 == 0:
retu... | Python | greatdarklord_python_dataset |
function step_impl_the_msg_to_is_set_to_respondent_as_string_not_array context
begin
set message_data at string msg_to = respondent_id
end function | def step_impl_the_msg_to_is_set_to_respondent_as_string_not_array(context):
context.bdd_helper.message_data["msg_to"] = context.bdd_helper.respondent_id | Python | nomic_cornstack_python_v1 |
with open string input.txt string r as f
begin
set a = read lines f
end
set ok = true
with open string output.txt string w as f1
begin
for i in range 1 length a
begin
if a at i < a at i - 1
begin
set ok = false
end
end
if ok
begin
print string YES
write f1 string YES
end
else
begin
print string NO
write f1 string NO
en... | with open('input.txt','r') as f:
a = f.readlines()
ok = True
with open('output.txt','w') as f1:
for i in range(1,len(a)):
if a[i] < a[i-1]:
ok = False
if ok:
print("YES")
f1.write("YES")
else:
print("NO")
f1.write("NO")
for i in range(len(a)):
... | Python | zaydzuhri_stack_edu_python |
comment Taking user inputs and initializing variables
set starting_salary = decimal input string Enter the starting salary:
set total_cost = 1000000
set semi_annual_raise = 0.07
set portion_down_payment = total_cost * 0.25
set r = 0.04
set number_of_months = 36
set current_savings = 0.0
set current_savings_low_income =... | #Taking user inputs and initializing variables
starting_salary=float(input("Enter the starting salary: "))
total_cost=1000000
semi_annual_raise=0.07
portion_down_payment=total_cost*0.25
r=0.04
number_of_months=36
current_savings=0.0
current_savings_low_income=0.0
left=steps=0
right=10000
mid=(left+right)/2
... | Python | zaydzuhri_stack_edu_python |
function second_largest lst
begin
set sorted_list = sorted lst
return sorted_list at - 2
end function
set result = call second_largest lst
print result | def second_largest(lst):
sorted_list = sorted(lst)
return sorted_list[-2]
result = second_largest(lst)
print(result) | Python | jtatman_500k |
function get_histogram self
begin
set values_array = array values
for bin0 in range size
begin
set bin_inf0 = bins at 0 at bin0
try
begin
set bin_sup0 = bins at 0 at bin0 + 1
end
except IndexError
begin
set bin_sup0 = vmax at 0
end
set values = values_array at values_array at tuple slice : : 0 >= bin_inf0 * values_a... | def get_histogram(self):
values_array = np.array(self.values)
for bin0 in range(self.bins[0].size):
bin_inf0 = self.bins[0][bin0]
try: bin_sup0 = self.bins[0][bin0 + 1]
except IndexError: bin_sup0 = self.vmax[0]
values = values_array[
(val... | Python | nomic_cornstack_python_v1 |
import time
function timer func
begin
function wrapper s
begin
set start_time = time
set str_len = call func s
set end_time = time
print string func name: { __name__ } , total cost: { round end_time - start_time * 1000 * 1000 2 } ns
return str_len
end function
return wrapper
end function | import time
def timer(func):
def wrapper(s):
start_time = time.time()
str_len = func(s)
end_time = time.time()
print(f"func name: {func.__name__}, total cost: {round((end_time - start_time) * 1000 * 1000, 2)} ns")
return str_len
return wrapper
| Python | zaydzuhri_stack_edu_python |
function compute_2d_reho datat adjacency_matrix
begin
comment a zero for each voxel
set KCC = zeros shape at 0
comment loop through each voxel
for i in range shape at 0
begin
comment the index of 4 neightbouts
set neigbor_index = where adjacency_matrix at tuple i slice : : > 0 at 0
comment stack those indexes with v... | def compute_2d_reho(datat, adjacency_matrix):
KCC = np.zeros(datat.shape[0]) # a zero for each voxel
for i in range(datat.shape[0]): # loop through each voxel
neigbor_index = np.where(adjacency_matrix[i, :] > 0)[0] # the index of 4 neightbouts
nn = np.hstack((neigbor_index, np.array(i))) # ... | Python | nomic_cornstack_python_v1 |
import json
set quesfile = open string questions string w
set ansfile = open string answers string w
with open string SingleOp.json as f2
begin
set dataSingleOp = load json f2
end
close f2
for i in range 0 length dataSingleOp
begin
write quesfile dataSingleOp at i at string sQuestion
write quesfile string
write ansfile... | import json
quesfile = open("questions","w")
ansfile = open("answers", "w")
with open('SingleOp.json') as f2:
dataSingleOp = json.load(f2)
f2.close()
for i in range(0, len(dataSingleOp)):
quesfile.write(dataSingleOp[i]["sQuestion"])
quesfile.write('\n')
ansfile.write(str(dataSingleOp[i]["lSolutions"]... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Apr 30 21:28:31 2019 @author: mflattery
import pandas as pd
function ReadATACCMA f xshift=0 y=0
begin
with open f string r as fi
begin
set l = read line fi
end
set x = decimal split l at - 3
set CleanedData = read csv f skiprows=list 0 names=list string t string hrec ... | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 21:28:31 2019
@author: mflattery
"""
import pandas as pd
def ReadATACCMA(f,xshift=0,y=0):
with open(f,'r') as fi:
l=fi.readline()
x=float(l.split()[-3])
CleanedData=pd.read_csv(f,skiprows=[0],names=['t','hrec','na','ruch','P... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf8 -*-
string Pozwól użytkownikowi wprowadzić dowolną liczbę imion ciągiem (np.jako jeden string rozdzielonych przecinkiem lub białym znakiem). Następnie powitaj każdą osobę na liście.
set imiona = split input string Wprowadź parę imion oddzielając je przecinakmi: string ,
comment funkcja która us... | # -*- coding: utf8 -*-
"""
Pozwól użytkownikowi wprowadzić dowolną liczbę imion ciągiem (np.jako jeden string rozdzielonych przecinkiem lub białym znakiem). Następnie powitaj każdą osobę na liście.
"""
imiona = input("Wprowadź parę imion oddzielając je przecinakmi: ").split(",")
imiona = [x.strip(' ').capitalize() f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed May 8 08:23:48 2019 @author: kardalto
import numpy as np
import matplotlib.pyplot as plt
import opt_utils
set data_star_lum = T
set afterFitting = call lin_LS data_star_lum at 0 data_star_lum at 1
set a = 515.9896349043293
set b = - 0.24207087442733877
set fitLum = li... | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 08:23:48 2019
@author: kardalto
"""
import numpy as np
import matplotlib.pyplot as plt
import opt_utils
data_star_lum = np.genfromtxt('star_luminos.txt').T
afterFitting = opt_utils.lin_LS(data_star_lum[0],data_star_lum[1])
a = 515.9896349043293
b... | Python | zaydzuhri_stack_edu_python |
function dict self arg
begin
if call is_bare_dict type
begin
return varname
end
else
begin
set karg = arg at 0
set name = string k
set varg = arg at 1
set name = string v
return string { { call render karg } : { call render varg } for k, v in { varname } .items()}
end
end function | def dict(self, arg: SeField[Any]) -> str:
if is_bare_dict(arg.type):
return arg.varname
else:
karg = arg[0]
karg.name = "k"
varg = arg[1]
varg.name = "v"
return f"{{{self.render(karg)}: {self.render(varg)} for k, v in {arg.varname}.... | Python | nomic_cornstack_python_v1 |
function _completions_from_starboard starboard
begin
set completions = list 0 0
for day in starboard
begin
if day at 0
begin
set completions at 0 = completions at 0 + 1
end
if day at 1
begin
set completions at 1 = completions at 1 + 1
end
end
return tuple completions
end function | def _completions_from_starboard(starboard: list) -> tuple:
completions = [0, 0]
for day in starboard:
if day[0]:
completions[0] += 1
if day[1]:
completions[1] += 1
return tuple(completions) | Python | nomic_cornstack_python_v1 |
function paragraphs self index=none
begin
string Return a generator of all paragraphs found in the document. If an index is specified, return the n'th paragraph only (starting at 0)
if index is none
begin
return select self Paragraph
end
else
begin
if index < 0
begin
set index = sum generator expression count t Paragra... | def paragraphs(self, index = None):
"""Return a generator of all paragraphs found in the document.
If an index is specified, return the n'th paragraph only (starting at 0)"""
if index is None:
return self.select(Paragraph)
else:
if index < 0:
inde... | Python | jtatman_500k |
comment ~~Wind Chill~~
from math import *
import sys
append path string E:\Projects\Python\Practice_Examples\linuxtopia_python\Class
from loop_functions import cont
set x = true
while x == true
begin
set wind_speed = integer input string What is the wind speed in mph?:
set temp = integer input string What is the temper... | #~~Wind Chill~~
from math import *
import sys
sys.path.append('E:\Projects\Python\Practice_Examples\linuxtopia_python\Class')
from loop_functions import cont
x = True
while x == True:
wind_speed = int(input("What is the wind speed in mph?: "))
temp = int(input("What is the temperature in degrees F?: "))
if wind_... | Python | zaydzuhri_stack_edu_python |
function config seasons seed=1 scramble=true verbose=true dec=0.0
begin
comment store individual llh as lists to prevent pointer over-writing
set llh = list
set multillh = call FastMultiPointSourceLLH seed=seed ncpu=25
comment setup likelihoods
if verbose
begin
print string seasons:
end
for season in call atleast_1d s... | def config(seasons, seed = 1, scramble = True, verbose = True, dec = 0.):
# store individual llh as lists to prevent pointer over-writing
llh = []
multillh = FastMultiPointSourceLLH(seed = seed, ncpu = 25)
# setup likelihoods
if verbose: print("\n seasons:")
for season in np.atleast_1d(seasons):
#sa... | Python | nomic_cornstack_python_v1 |
function bus_ob_public_id self bus_ob_public_id
begin
set _bus_ob_public_id = bus_ob_public_id
end function | def bus_ob_public_id(self, bus_ob_public_id):
self._bus_ob_public_id = bus_ob_public_id | Python | nomic_cornstack_python_v1 |
function log logfile st
begin
with open logfile string a as f
begin
write f st + string
end
print st
end function | def log(logfile, st):
with open(logfile, 'a') as f:
f.write(st + '\n')
print(st) | Python | nomic_cornstack_python_v1 |
from tkinter import *
from datetime import *
import time
set root = call Tk
function close
begin
call destroy
end function
function show
begin
set top = call Toplevel root
call overrideredirect true
call geometry format string {0}x{1}+0+0 call winfo_screenwidth call winfo_screenheight
call configure bg=string black
cal... | from tkinter import *
from datetime import *
import time
root = Tk()
def close():
root.destroy()
def show():
top = Toplevel(root)
top.overrideredirect(True)
top.geometry("{0}x{1}+0+0".format(top.winfo_screenwidth(), top.winfo_screenheight()))
top.configure(bg='black')
Label(top,... | Python | zaydzuhri_stack_edu_python |
function arrange_neighbors self preferred_kind=LAND
begin
set seen = list
set remain = list tuple none self list
if preferred_kind == LAND
begin
set kind_weights = dict LAND 0 ; WATER 2
end
else
if preferred_kind == WATER
begin
set kind_weights = dict WATER 0 ; LAND 2
end
else
begin
raise exception string I don't kno... | def arrange_neighbors(self, preferred_kind=LAND):
seen = []
remain = [(None, self, [])]
if preferred_kind == LAND:
kind_weights = {LAND: 0, WATER: 2}
elif preferred_kind == WATER:
kind_weights = {WATER: 0, LAND: 2}
else:
raise Exceptio... | Python | nomic_cornstack_python_v1 |
class Employee
begin
function __init__ self fname lname
begin
set fname = fname
set lname = lname
end function
comment self.email = f"{fname}.{lname}@abxy.com"
function explain self
begin
return string This employee is { fname } { lname }
end function
decorator property
function email self
begin
if fname == none or lna... | class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}@abxy.com"
def explain(self):
return f"This employee is {self.fname} {self.lname}"
@property
def email(self):
if self.fname==None or self.lnam... | Python | zaydzuhri_stack_edu_python |
function word_symmetry2 msk show=true
begin
set l = list
for r in range shape at 0
begin
set row = msk at tuple r slice : :
set i = where row at 0
if length i > 0
begin
append l max i - min i
end
else
begin
append l 0
end
end
set l = array l
if show
begin
set fig = figure
set ax = call add_subplot 111
plot l
show
e... | def word_symmetry2(msk, show=True):
l = []
for r in range(msk.shape[0]):
row = msk[r, :]
i = np.where(row)[0]
if len(i) > 0:
l.append(max(i) - min(i))
else:
l.append(0)
l = np.array(l)
if show:
fig = plt.figure()
ax = fig.add_subp... | Python | nomic_cornstack_python_v1 |
function get_text_from_file file_path
begin
comment We try to read the file
try
begin
with open file_path string r encoding=string utf-8 as text_file
begin
set file = read text_file
return file
end
end
except any
begin
print string Couldn't open the file : + file_path
end
end function | def get_text_from_file(file_path):
#We try to read the file
try:
with open(file_path, "r", encoding="utf-8") as text_file:
file = text_file.read()
return file
except:
print("Couldn't open the file : "+file_path) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function deepestLeavesSum self root
begin
set db = dict
function traverse root depth=0
begin
if root == none
begin
return
end
if depth not in db
begin
set db at depth = 0
end
set db at depth = db at depth + val
call traverse left depth + 1
call traverse right depth + 1
end function
... | class Solution(object):
def deepestLeavesSum(self, root):
db = {}
def traverse(root, depth=0):
if (root == None):
return
if (depth not in db):
db[depth] = 0
db[depth] += root.val
traverse(root.left, (depth + 1))
... | Python | zaydzuhri_stack_edu_python |
function get_adapt_intent self utterance lang=string en-us
begin
set msg = call Message string intent.service.adapt.get dict string utterance utterance ; string lang lang context=dict string destination string intent_service ; string source string intent_api
set resp = call wait_for_response msg string intent.service.a... | def get_adapt_intent(self, utterance, lang="en-us"):
msg = Message("intent.service.adapt.get",
{"utterance": utterance, "lang": lang},
context={"destination": "intent_service",
"source": "intent_api"})
resp = self.bus.wait_for_r... | Python | nomic_cornstack_python_v1 |
function read_transform self transform_id=string
begin
debug string (%s): Reading Transform: %s % tuple name transform_id
set transform = read resource_registry object_id=transform_id rev_id=string
return transform
end function | def read_transform(self, transform_id=''):
log.debug('(%s): Reading Transform: %s' % (self.name,transform_id))
transform = self.clients.resource_registry.read(object_id=transform_id,rev_id='')
return transform | Python | nomic_cornstack_python_v1 |
function build_relative_path full_path prefix=string / split_on=string /data/
begin
set splits = split full_path split_on
return join path prefix split_on splits at - 1
end function | def build_relative_path(full_path, prefix='/', split_on='/data/'):
splits = full_path.split(split_on)
return os.path.join(prefix, split_on, splits[-1]) | Python | nomic_cornstack_python_v1 |
function conv2d input weight bias=none stride=1 padding=0 dilation=1 groups=1
begin
return call _conv string Conv _pair keyword locals
end function | def conv2d(
input,
weight,
bias=None,
stride=1,
padding=0,
dilation=1,
groups=1,
):
return _conv('Conv', utils._pair, **locals()) | Python | nomic_cornstack_python_v1 |
function vector self
begin
return call get_vector_to endpoints at 1
end function | def vector(self) -> Vector:
return self.endpoints[0].get_vector_to(self.endpoints[1]) | Python | nomic_cornstack_python_v1 |
function is_ace_alert self
begin
if string data.json in path
begin
set ace_data_json_pattern = compile string [a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/data.json$
if search path
begin
return true
end
end
return false
end function | def is_ace_alert(self):
if 'data.json' in self.path:
ace_data_json_pattern = re.compile(r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/data.json$')
if ace_data_json_pattern.search(self.path):
return True
return False | Python | nomic_cornstack_python_v1 |
import math
from functools import reduce
function lcm2 x y
begin
return x * y // call gcd x y
end function
function lcm nums
begin
return reduce lambda x y -> call lcm2 x y nums
end function
set N = integer input
set T = list
for _ in range N
begin
append T integer input
end
print call lcm T | import math
from functools import reduce
def lcm2(x, y):
return (x * y) // math.gcd(x, y)
def lcm(nums):
return reduce(lambda x, y: lcm2(x, y), nums)
N = int(input())
T = []
for _ in range(N):
T.append(int(input()))
print(lcm(T)) | Python | zaydzuhri_stack_edu_python |
function visit_functiondef self node
begin
string check function name, docstring, arguments, redefinition, variable names, max locals
comment init branch and returns counters
append _returns 0
comment check number of arguments
set args = args
set ignored_argument_names = _ignored_argument_names
if args is not none
begi... | def visit_functiondef(self, node):
"""check function name, docstring, arguments, redefinition,
variable names, max locals
"""
# init branch and returns counters
self._returns.append(0)
# check number of arguments
args = node.args.args
ignored_argument_name... | Python | jtatman_500k |
string This python script contains functions that kept showing up in scripts that I had to write, in one way or another. 1. consv_prim_1D(U) Function that converts a 1D Euler Equations conserved variables vector into its corresponding primtive variables vector. Under the assumption that the gas that we are dealing with... | """
This python script contains functions that kept showing up in scripts that I had to write,
in one way or another.
1. consv_prim_1D(U)
Function that converts a 1D Euler Equations conserved variables vector into its
corresponding primtive variables vector.
Under the assumption t... | Python | zaydzuhri_stack_edu_python |
function organization self
begin
return _organization
end function | def organization(self):
return self._organization | Python | nomic_cornstack_python_v1 |
from __future__ import print_function
import sys
from collections import defaultdict , deque
class D extends defaultdict
begin
function __getitem__ self k
begin
try
begin
set v = integer k
return v
end
except any
begin
return call __getitem__ k
end
end function
end class
class Program extends object
begin
function __in... | from __future__ import print_function
import sys
from collections import defaultdict, deque
class D(defaultdict):
def __getitem__(self, k):
try:
v = int(k)
return v
except:
return super(D, self).__getitem__(k)
class Program(object):
def __init__(self, ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment coding: utf-8
function main
begin
set points = list comprehension list map int split input for _ in range integer input
sort points key=lambda x -> tuple x at 1 x at 0
for p in points
begin
print format string {0} {1} p at 0 p at 1
end
end function
if __name__ == string __main__
be... | #!/usr/bin/env python3
# coding: utf-8
def main():
points = [list(map(int, input().split())) for _ in range(int(input()))]
points.sort(key=lambda x: (x[1], x[0]))
for p in points:
print('{0} {1}'.format(p[0], p[1]))
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
function IsContainer self
begin
set callResult = call _Call string IsContainer
if callResult is none
begin
return none
end
return callResult
end function | def IsContainer(self):
callResult = self._Call("IsContainer", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function _step_plot_closure self step_number
begin
if watermark_hint is not none
begin
call plot_image_grid format string watermark_hint_and_mask_{} step_number list call clip watermark_hint 0 1 call clip call torch_to_np mask_net_output 0 1
end
call plot_image_grid format string watermark_clean_{} step_number list cal... | def _step_plot_closure(self, step_number):
if self.watermark_hint is not None:
plot_image_grid("watermark_hint_and_mask_{}".format(step_number),
[np.clip(self.watermark_hint, 0, 1),
np.clip(torch_to_np(self.mask_net_output), 0, 1)])
p... | Python | nomic_cornstack_python_v1 |
comment Question Link: https://www.codewars.com/kata/52f787eb172a8b4ae1000a34
import math
function zeros n
begin
return sum list comprehension n // 5 ^ i for i in range 1 ceil log n + 1 5 if n // 5 ^ i > 0
end function | # Question Link: https://www.codewars.com/kata/52f787eb172a8b4ae1000a34
import math
def zeros(n):
return sum([n//(5**i) for i in range(1,math.ceil(math.log(n+1,5))) if n//(5**i)>0]) | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import pandas as pd
import requests
import time
from dateutil.parser import parse
from manager.tg_manager import TgManager
from manager.db_manager import DbManager
from utils.common import get_current_time
set BASE_URL = string https://cathiesark.com/{etf}/trades
set ARK_ETFS = list string... | from bs4 import BeautifulSoup
import pandas as pd
import requests
import time
from dateutil.parser import parse
from manager.tg_manager import TgManager
from manager.db_manager import DbManager
from utils.common import get_current_time
BASE_URL = 'https://cathiesark.com/{etf}/trades'
ARK_ETFS = ['arkk', 'arkq', 'ark... | Python | zaydzuhri_stack_edu_python |
comment Gabriel Yudi Sanefugi - 160027
comment Wallacy Rychard Sousa Cabral - 155336
import socket
import _thread as thread
import time
comment Porta que o Servidor esta
set PORT = 6000
set ListaLider = dict 1 string 26.139.227.213 ; 2 string 26.139.134.240 ; 3 string 26.130.240.169 ; 4 string 26.139.134.20 ; 5 string ... | # Gabriel Yudi Sanefugi - 160027
# Wallacy Rychard Sousa Cabral - 155336
import socket
import _thread as thread
import time
PORT = 6000 # Porta que o Servidor esta
ListaLider = {
1: "26.139.227.213", # Alexander
2: "26.139.134.240", # Alishow
3: "26.130.240.169", # Giron
4: "26.139.134.20"... | Python | zaydzuhri_stack_edu_python |
function get_observed_data_moments_and_weighting data_file_name
begin
set data_frame_observed = call pre_process_soep_data data_file_name
set moments_obs = call get_moments_obs data_frame_observed
set weighting_matrix = call get_weighting_matrix data_frame_observed num_agents_smm=6000 num_samples=200
with open string R... | def get_observed_data_moments_and_weighting(data_file_name):
data_frame_observed = pre_process_soep_data(data_file_name)
moments_obs = get_moments_obs(data_frame_observed)
weighting_matrix = get_weighting_matrix(
data_frame_observed, num_agents_smm=6000, num_samples=200
)
with open(str(RES... | Python | nomic_cornstack_python_v1 |
function plot_annual_contribution station list_OPtype normalize=false **kwarg
begin
set OPtypes = list comprehension string OP + OP for OP in list_OPtype
set df = call DataFrame columns=list string PM mass + OPtypes
comment mass
set df at string PM mass = sum
comment OP DTT and OP AAv
for OPtype in list_OPtype
begin
se... | def plot_annual_contribution(station, list_OPtype, normalize=False, **kwarg):
OPtypes = ["OP "+OP for OP in list_OPtype]
df = pd.DataFrame(columns=["PM mass"]+OPtypes)
# mass
df["PM mass"] = station.SRC.sum()
# OP DTT and OP AAv
for OPtype in list_OPtype:
df["OP "+OPtype] = (statio... | Python | nomic_cornstack_python_v1 |
function build_min_aggs min_field
begin
set min_body = dict string min_sms_time dict string min dict string field min_field
return min_body
end function | def build_min_aggs(min_field):
min_body = {
"min_sms_time": {"min": {"field": min_field}}
}
return min_body | Python | nomic_cornstack_python_v1 |
import json
import random
import time
from workqueue.queue import QueueTask , FileQueueTask , Queue
class TestQueue
begin
function test_task self tempdir
begin
set payload = string test payload
set priority = 100
set exectime = 1500000000
set timestamp = string 2017-07-14T02:40:00
set task_id = string 5741fd6f-4388-482... | import json
import random
import time
from workqueue.queue import QueueTask, FileQueueTask, Queue
class TestQueue:
def test_task(self, tempdir):
payload = 'test payload'
priority = 100
exectime = 1500000000
timestamp = '2017-07-14T02:40:00'
task_id = '5741fd6f-4388-482b-a... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Feb 19 14:39:46 2021 @author: Anthony
import numpy as np
import copy as cp
import random as rd
function inner_product a r
begin
set scalar_product = sum a * r
set a_norm = sum a ^ 2
return scalar_product / a_norm
end function
function OMP y A s print_stuff=false
begin... | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 14:39:46 2021
@author: Anthony
"""
import numpy as np
import copy as cp
import random as rd
def inner_product(a, r) :
scalar_product = np.sum(a*r)
a_norm = np.sum(a **2)
return scalar_product / a_norm
def OMP(y, A, s, print_stuff=False) :... | Python | zaydzuhri_stack_edu_python |
from turtle import Turtle
set STARTING_POSITION = tuple 0 - 280
set MOVE_DISTANCE = 10
set FINISH_LINE_Y = 280
class Player extends Turtle
begin
function __init__ self
begin
call __init__
call shape string turtle
call penup
call left 90
call go_to_up
end function
function move_up self
begin
call forward MOVE_DISTANCE
e... | from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.penup()
self.left(90)
self.go_to_up()
def move_up(self):
self.forward(MOVE_DI... | Python | zaydzuhri_stack_edu_python |
if num > 0
begin
print string That's a positive number!
end
else
if num < 0
begin
print string That's a negative number!
end
else
begin
print string zero is neither positive nor negative
end
set x = 20
if x > 18
begin
print string You can buy lottery tickets!
if x > 25
begin
print string You can also rent a car!
end
pr... | if num > 0:
print("That's a positive number!")
elif num < 0:
print("That's a negative number!")
else:
print("zero is neither positive nor negative")
x = 20
if x > 18:
print("You can buy lottery tickets!")
if x > 25:
print("You can also rent a car!")
print("And you can get your own credi... | Python | zaydzuhri_stack_edu_python |
function prepare self sample
begin
set request = call PredictRequest
set name = string default
set signature_name = _signature_key
for tuple k v in items sample
begin
set proto = call make_tensor_proto v dtype=get _types k
comment Convert to column-wise format
call CopyFrom proto
end
return request
end function | def prepare(self, sample: Mapping[str, Any]) -> predict_pb2.PredictRequest:
request = predict_pb2.PredictRequest()
request.model_spec.name = 'default'
request.model_spec.signature_name = self._signature_key
for k, v in sample.items():
proto = tf.make_tensor_proto(v, dtype=self._types.get(k))
... | Python | nomic_cornstack_python_v1 |
function load_parameters uuid_map=none mxnet_parameters=none variable_constants=none mxnet_constants=none context=none dtype=none current_params=none
begin
function with_uuid_map item uuid_map
begin
if uuid_map is not none
begin
return uuid_map at item
end
else
begin
return item
end
end function
set ip = call Inference... | def load_parameters(uuid_map=None,
mxnet_parameters=None,
variable_constants=None,
mxnet_constants=None,
context=None, dtype=None,
current_params=None):
def with_uuid_map(item, uuid_map):
... | Python | nomic_cornstack_python_v1 |
function clearCurrentEnv self
begin
set _currentEnv at call get_ident = dict
end function | def clearCurrentEnv(self):
self._currentEnv[thread.get_ident()] = {} | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function ladderLength self beginWord endWord wordList
begin
string :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
if endWord not in wordList
begin
return 0
end
if not wordList
begin
return 0
end
set aplha = string abcdefghijklmnopqrstuvwxyz
set q = list... | class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList:
return 0
if not wordList:
... | Python | zaydzuhri_stack_edu_python |
function __init__ self repository
begin
set __repo = repository
end function | def __init__(self, repository):
self.__repo = repository | Python | nomic_cornstack_python_v1 |
function sapling trans player spell target=none
begin
call _common_cone CONES_PER_SAPLING trans player spell target=target
end function | def sapling(trans, player, spell, target=None):
_common_cone(CONES_PER_SAPLING, trans, player, spell, target=target) | Python | nomic_cornstack_python_v1 |
import numpy as np
set a = call arage 5
print string array a
print string shape shape
set b = array range 8 12
print string array b
print string shape shape
set c = append np a b
print string appended array c | import numpy as np
a=np.arage(5)
print("array ",a)
print("shape ",a.shape)
b=np.arange(8,12)
print("array ",b)
print("shape ",b.shape)
c=np.append(a,b)
print("appended array ",c)
| Python | zaydzuhri_stack_edu_python |
class Gaia
begin
function __init__ self
begin
set flag_life = false
end function
function birth self
begin
set flag_life = true
end function
end class
class JindoDog extends Gaia
begin
function __init__ self
begin
call __init__
set power_bark = 0
end function
function train self
begin
set power_bark = power_bark + 1
en... | class Gaia:
def __init__(self):
self.flag_life = False
def birth(self):
self.flag_life = True
class JindoDog(Gaia):
def __init__(self):
super().__init__()
self.power_bark = 0
def train(self):
self.power_bark += 1
class SokchoBird(Gaia):
... | Python | zaydzuhri_stack_edu_python |
class Twitter
begin
function __init__ self
begin
string Initialize your data structure here. 1.用双端队列初始化推特 2.并初始化最大时间戳,用来标识推特发布的先后顺序 3.用集合初始化推文 4.注意,本class的实例对象为twitter,并非推特使用者
set twitter = default dictionary deque
set followList = default dictionary set
set timestamp = 2 ^ 31
end function
function postTweet self userI... | class Twitter:
def __init__(self):
"""
Initialize your data structure here.
1.用双端队列初始化推特
2.并初始化最大时间戳,用来标识推特发布的先后顺序
3.用集合初始化推文
4.注意,本class的实例对象为twitter,并非推特使用者
"""
self.twitter=collections.defaultdict(collections.deque)
self.follow... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2
comment Red range HSV - Hue Saturation Value
set lower_red = array list 120 30 30
set upper_red = array list 179 255 255
set lower_red2 = array list 0 60 60
set upper_red2 = array list 34 255 255
comment Green range HSV
set lower_green = array list 60 40 40
set upper_green = array list 98 ... | import numpy as np
import cv2
# Red range HSV - Hue Saturation Value
lower_red = np.array([120, 30, 30])
upper_red = np.array([179, 255, 255])
lower_red2 = np.array([0, 60, 60])
upper_red2 = np.array([34, 255, 255])
# Green range HSV
lower_green = np.array([60, 40, 40])
upper_green = np.array([98, 255, 255])
def ve... | Python | zaydzuhri_stack_edu_python |
function reset self
begin
if not configured
begin
set configured = true
call link string critic string >normalize_whitespace
call link string critic-post string >raw_html
end
clear critic_stash
end function | def reset(self):
if not self.configured:
self.configured = True
self.md.preprocessors.link('critic', '>normalize_whitespace')
self.md.postprocessors.link('critic-post', '>raw_html')
self.critic_stash.clear() | Python | nomic_cornstack_python_v1 |
function retrieve_leads self
begin
if leads_df is none
begin
set leads_df = call read_sql_query string SELECT * FROM clean_leads ORDER BY created_on DESC con=call connection
end
return leads_df
end function | def retrieve_leads(self) -> pd.DataFrame:
if self.leads_df is None:
self.leads_df = pd.read_sql_query('SELECT * FROM clean_leads ORDER BY created_on DESC',
con=self.connection())
return self.leads_df | Python | nomic_cornstack_python_v1 |
import sys
import json
import os
from collections import defaultdict
from pathlib import Path
function load_char_set char_set_path
begin
with open char_set_path as f
begin
set char_set = load json f
end
set idx_to_char = dict
for tuple k v in call iteritems
begin
set idx_to_char at integer k = v
end
return tuple idx_t... | import sys
import json
import os
from collections import defaultdict
from pathlib import Path
def load_char_set(char_set_path):
with open(char_set_path) as f:
char_set = json.load(f)
idx_to_char = {}
for k,v in char_set['idx_to_char'].iteritems():
idx_to_char[int(k)] = v
return idx_to... | Python | zaydzuhri_stack_edu_python |
from enum import Enum
class Action extends object
begin
class Operation extends Enum
begin
set BUY = 0
set SELL = 1
end class
function __init__ self symbol op quantity
begin
set symbol = symbol
set op = op
set quantity = quantity
end function
end class | from enum import Enum
class Action(object):
class Operation(Enum):
BUY = 0
SELL = 1
def __init__(self, symbol, op, quantity):
self.symbol = symbol
self.op = op
self.quantity = quantity
| Python | zaydzuhri_stack_edu_python |
function test_put_meal self
begin
with client
begin
set response = call put_meal
set data = loads decode data
assert equal status_code 201
assert in string Meal updated successfully get data string message
end
end function | def test_put_meal(self):
with self.client:
response = self.put_meal()
data = json.loads(response.data.decode())
self.assertEqual(response.status_code, 201)
self.assertIn("Meal updated successfully", data.get('message')) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat May 18 19:35:37 2019 @author: Ruman. Acceso a ForoCoches para buscar insultos.
import spacy
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span
import pandas as pd
import requests
import urllib.request
import time
from b... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 19:35:37 2019
@author: Ruman.
Acceso a ForoCoches para buscar insultos.
"""
import spacy
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span
import pandas as pd
import requests
import urllib.request
import time
from bs4 import ... | Python | zaydzuhri_stack_edu_python |
import json , hmac , hashlib , time , requests , base64
from requests.auth import AuthBase
import pymongo
from pymongo import MongoClient
set uri = string https://*.com
class tradingAuth extends AuthBase
begin
set passphrase = string nopassphrase
function __init__ self api_key secret_key passphrase
begin
set api_key = ... | import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase
import pymongo
from pymongo import MongoClient
uri="https://*.com"
class tradingAuth(AuthBase):
passphrase="nopassphrase"
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_k... | Python | zaydzuhri_stack_edu_python |
function _output_to_keys_predict self
begin
set mean_and_std = set literal string mean string std
return dictionary comprehension k : mean_and_std for k in predictor_output_names
end function | def _output_to_keys_predict(self) -> Dict[str, Set[str]]:
mean_and_std = {"mean", "std"}
return {k: mean_and_std for k in self.predictor_output_names} | Python | nomic_cornstack_python_v1 |
for i in range 1 length myList
begin
set myList2 at i - 1 = myList at i
end
print myList2
append myList2 string new Item
print myList2
pop myList2 2
print myList2 | for i in range(1,len(myList)):
myList2[i-1] = myList[i]
print(myList2)
myList2.append("new Item")
print(myList2)
myList2.pop(2)
print(myList2)
| Python | zaydzuhri_stack_edu_python |
function filter_correlation self x_analyte y_analyte window=none r_threshold=0.9 p_threshold=0.05 filt=true samples=none subset=none
begin
if samples is not none
begin
set subset = call make_subset samples silent=true
end
set samples = call _get_samples subset
set x_analyte = call _analyte_checker x_analyte single=true... | def filter_correlation(self, x_analyte, y_analyte, window=None,
r_threshold=0.9, p_threshold=0.05, filt=True,
samples=None, subset=None):
if samples is not None:
subset = self.make_subset(samples, silent=True)
samples = self._get_samples... | Python | nomic_cornstack_python_v1 |
function get_ignorable_form_fields form_element_entries
begin
comment Get ignorable plugins
set ignorable_plugins = list
for tuple key value in items _registry
begin
if not has_value
begin
append ignorable_plugins key
end
end
comment Get ignorable form fields
set ignorable_form_fields = list
for form_element_entry in... | def get_ignorable_form_fields(form_element_entries):
# Get ignorable plugins
ignorable_plugins = []
for key, value in form_element_plugin_registry._registry.items():
if not value.has_value:
ignorable_plugins.append(key)
# Get ignorable form fields
ignorable_form_fields = []
... | Python | nomic_cornstack_python_v1 |
import urllib2
import re
set nothing = string 56060
comment at 16044 they want to divide by 2
for i in range 400
begin
set filehandle = url open string http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing= + nothing
set temp = read filehandle
set m = search string and the next nothing is (\d.*) temp
end | import urllib2
import re
nothing = '56060'
# at 16044 they want to divide by 2
for i in range(400):
filehandle = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='+nothing)
temp = filehandle.read()
m = re.search('and the next nothing is (\d.*)',temp) | Python | zaydzuhri_stack_edu_python |
from PIL import Image , ImageDraw
import math
import cv2 as cv
import numpy as np
comment 面积计算
function area img
begin
set width = size at 0
set height = size at 1
set S = width * height
return tuple S width height
end function
function karea img
begin
set count = 0
comment 遍历所有长度的点
for i in range 0 width
begin
comment... | from PIL import Image,ImageDraw
import math
import cv2 as cv
import numpy as np
def area(img):#面积计算
width=img.size[0]
height=img.size[1]
S=width*height
return S,width,height
def karea(img):
count=0
for i in range(0,img.width):#遍历所有长度的点
for j in range(0,img.height):#遍历所有宽度的点
data = (img.getpixel((i,j)))#打... | Python | zaydzuhri_stack_edu_python |
function push remote=string origin branch=none
begin
if remote and branch
begin
set command = string git push ' { remote } ' ' { branch } '
end
else
begin
set command = string git push
end
print string Command: { command }
set error = call command shell=true
return error
end function | def push(remote="origin", branch=None):
if remote and branch:
command = f"git push '{remote}' '{branch}'"
else:
command = "git push"
print(f"Command: {command}")
error = call(command, shell=True)
return error | Python | nomic_cornstack_python_v1 |
function putvartype self j_ vartype_
begin
set res = call MSK_XX_putvartype __nativep j_ vartype_
if res != 0
begin
set tuple _ msg = call __getlasterror res
raise error call rescode res msg
end
end function | def putvartype(self,j_,vartype_):
res = __library__.MSK_XX_putvartype(self.__nativep,j_,vartype_)
if res != 0:
_,msg = self.__getlasterror(res)
raise Error(rescode(res),msg) | Python | nomic_cornstack_python_v1 |
import numpy as np
import uncertainties as un
from uncertainties.unumpy import log10 , nominal_values
from scipy.optimize import curve_fit
from fitting import fit_spectrum , guess_p0
import matplotlib.pyplot as plt
from carbspec import dye as dyes
function make_mix_spectra dye
begin
string Returns a mix_spectra functio... | import numpy as np
import uncertainties as un
from uncertainties.unumpy import log10, nominal_values
from scipy.optimize import curve_fit
from .fitting import fit_spectrum, guess_p0
import matplotlib.pyplot as plt
from carbspec import dye as dyes
def make_mix_spectra(dye):
"""
Returns a mix_spectra function i... | Python | zaydzuhri_stack_edu_python |
function integerdigits n
begin
return list comprehension integer i for i in string n
end function | def integerdigits(n):
return [int(i) for i in str(n)] | Python | nomic_cornstack_python_v1 |
function isAnagram str1 str2
begin
if length str1 != length str2
begin
return false
end
comment Sort the strings
set str1_sorted = join string sorted str1
set str2_sorted = join string sorted str2
comment Check if both strings are equal
return str1_sorted == str2_sorted
end function
comment Driver code
set str1 = str... | def isAnagram(str1, str2):
if len(str1) != len(str2):
return False
# Sort the strings
str1_sorted = ''.join(sorted(str1))
str2_sorted = ''.join(sorted(str2))
# Check if both strings are equal
return str1_sorted == str2_sorted
# Driver code
str1 = 'banana'
str2 = 'abanan'
... | Python | jtatman_500k |
function doy2dt year doy
begin
if is instance year tuple int uint or is instance year float
begin
set year = list year
end
if is instance doy tuple int uint or is instance doy float
begin
set doy = list doy
end
if length doy > length year
begin
set year = zeros length doy + year
end
set datearray = list
for i in range... | def doy2dt(year, doy):
if isinstance(year, (int, np.uint)) or isinstance(year, (float)):
year = [year]
if isinstance(doy, (int, np.uint)) or isinstance(doy, (float)):
doy = [doy]
if len(doy) > len(year):
year = np.zeros(len(doy))+year
datearray = []
for i in range(len(doy)):... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.