code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function calculate_err a b pop1 pheno1 pop2 pheno2 err_corr err_df
begin
comment If in lower triangle, do not compute; symmetric matrix
if a > b
begin
return err_corr at tuple b a
end
else
if a == b
begin
return 1
end
else
begin
set err_df = drop missing err_df
set tuple err_beta1 err_beta2 = call get_betas err_df pop1... | def calculate_err(a, b, pop1, pheno1, pop2, pheno2, err_corr, err_df):
# If in lower triangle, do not compute; symmetric matrix
if a > b:
return err_corr[b, a]
elif a == b:
return 1
else:
err_df = err_df.dropna()
err_beta1, err_beta2 = get_betas(err_df, pop1, pheno1, pop... | Python | nomic_cornstack_python_v1 |
function test_scm_isolation_one_node
begin
set om = om
set scm = scm
set dns = datanodes
set client = client
set oz_client = call get_client
call run_freon 1 1 1 10240
set first_set = list om dns at 0 dns at 1 dns at 2 client
set second_set = list om scm dns at 1 dns at 2 client
call partition_network first_set second_... | def test_scm_isolation_one_node():
om = cluster.om
scm = cluster.scm
dns = cluster.datanodes
client = cluster.client
oz_client = cluster.get_client()
oz_client.run_freon(1, 1, 1, 10240)
first_set = [om, dns[0], dns[1], dns[2], client]
second_set = [om, scm, dns[1], dns[2], client]
... | Python | nomic_cornstack_python_v1 |
function root_node self
begin
return _root_node
end function | def root_node(self):
return self._root_node | Python | nomic_cornstack_python_v1 |
function Gaussian_sampling mu=1 beta=1 size=none rng=call RandomState 100
begin
if not call isscalar mu
begin
set size = shape
if call isscalar beta
begin
set beta = repeat beta size at 0
set shape = tuple size 1
end
set X = copy np mu
comment for i in range(size[0]):
comment for j in range(size[1]):
comment X[i,j]=rng... | def Gaussian_sampling(mu=1,beta=1,size=None,rng=np.random.RandomState(100)):
if (not np.isscalar(mu)):
size=mu.shape
if np.isscalar(beta):
beta=np.repeat(beta,size[0])
beta.shape=(beta.size,1)
X=np.copy(mu)
#for i in range(size[0]):
# for j in ... | Python | nomic_cornstack_python_v1 |
function create self request *args **kwargs
begin
comment Deserialize and validate the data from the user.
set serializer = call get_serializer data=data
call is_valid raise_exception=true
comment Execute the document and annotation creation
call perform_create serializer
comment Get the headers and return a response
s... | def create(self, request, *args, **kwargs):
# Deserialize and validate the data from the user.
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
# Execute the document and annotation creation
self.perform_create(serializer)
# ... | Python | nomic_cornstack_python_v1 |
function insert self table values
begin
execute connect insert_disc at table values
commit connect
end function | def insert(self,table,values):
self.connect.execute(self.insert_disc[table],values)
self.connect.commit() | Python | nomic_cornstack_python_v1 |
import glob
import sys
from preprocessing import preprocessing
class classifier
begin
function __init__ self
begin
set dictionary = dict
end function
function readAndTokenize self file_list listindex
begin
for file in file_list
begin
set fp = open file string r
set word_list = call preprocessing read fp
for w in word_... | import glob
import sys
from preprocessing import preprocessing
class classifier:
def __init__(self):
self.dictionary={}
def readAndTokenize(self,file_list,listindex):
for file in file_list:
fp=open(file,"r")
word_list=preprocessing(fp.read())
f... | Python | zaydzuhri_stack_edu_python |
comment bot.py
import os
import numpy as np
import discord
import unidecode
import json
from collections import OrderedDict
from affinite import love_compute
import dwarf_factory
from discord.ext import commands
from collections import defaultdict
set TOKEN = call getenv string DISCORD_TOKEN
set GUILD = string ThePurpl... | # bot.py
import os
import numpy as np
import discord
import unidecode
import json
from collections import OrderedDict
from affinite import love_compute
import dwarf_factory
from discord.ext import commands
from collections import defaultdict
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = 'ThePurpleWaleWithBluePschitPchitO... | Python | zaydzuhri_stack_edu_python |
function hann_sinc_high_pass x N fs fc
begin
return x - call hann_sinc_low_pass x N fs fc
end function | def hann_sinc_high_pass(x: Tensor, N: int, fs: int, fc: float) -> Tensor:
return x - hann_sinc_low_pass(x, N, fs, fc) | Python | nomic_cornstack_python_v1 |
function plot_densplot self plot=string kde glm=false test=false summary=string sum figsize=tuple 8 8 font=none save=none saveformat=string pdf
begin
if not exp_result
begin
raise call NameError string No results yet retrieved
end
if string experiment in query
begin
set title = query at string experiment
end
else
begin... | def plot_densplot(self, plot='kde', glm=False, test=False, summary='sum', figsize=(8, 8), font=None, save=None,
saveformat='pdf'):
if not self.exp_result:
raise NameError("No results yet retrieved")
if 'experiment' in self.query:
title = self.query['experime... | Python | nomic_cornstack_python_v1 |
function async_recognize self sample language_code=none max_alternatives=none profanity_filter=none speech_context=none
begin
set data = call _build_request_data sample language_code max_alternatives profanity_filter speech_context
set api_response = call api_request method=string POST path=string speech:asyncrecognize... | def async_recognize(self, sample, language_code=None,
max_alternatives=None, profanity_filter=None,
speech_context=None):
data = _build_request_data(sample, language_code, max_alternatives,
profanity_filter, speech_context)
... | Python | nomic_cornstack_python_v1 |
comment import turtle
comment x=turtle.Screen()
comment t=turtle.pen()
comment turtle.width(10)
comment turtle.goto(100,100)
comment turtle.goto(200,0)
comment turtle.goto(140,-108)
comment turtle.goto(0,-250)
comment turtle.goto(-140,-108)
comment turtle.goto(-200,0)
comment turtle.goto(-100,100)
comment turtle.goto(0... | # import turtle
# x=turtle.Screen()
# t=turtle.pen()
# turtle.width(10)
# turtle.goto(100,100)
# turtle.goto(200,0)
# turtle.goto(140,-108)
# turtle.goto(0,-250)
# turtle.goto(-140,-108)
# turtle.goto(-200,0)
# turtle.goto(-100,100)
# turtle.goto(0,0)
#
# # while i >= 0:
# # while j >= -100:
# # i -= 0.015
... | Python | zaydzuhri_stack_edu_python |
function query_api term location
begin
for cnt in range 20
begin
set data = list
set response = search API_KEY term location cnt * 50
set businesses = get response string businesses
if not businesses
begin
print format string No businesses for {0} in {1} found. term location
return
end
for i in range length businesses... | def query_api(term, location):
for cnt in range(20):
data=[]
response = search(API_KEY, term, location,cnt*50)
businesses = response.get('businesses')
if not businesses:
print(u'No businesses for {0} in {1} found.'.format(term, location))
return
for... | Python | nomic_cornstack_python_v1 |
import requests
import logging
class RotateProxy extends object
begin
comment 代理ip集合
set proxy_list = list
decorator classmethod
function init cls
begin
set ip_proxy = IP_PROXY_CONFIG
set proxy_url = format ip_proxy at string URL num=ip_proxy at string FETCH_NUM
set response = get requests proxy_url
set json_data = js... | import requests
import logging
class RotateProxy(object):
#代理ip集合
proxy_list=[]
@classmethod
def init(cls):
cls.ip_proxy = settings.IP_PROXY_CONFIG
cls.proxy_url = cls.ip_proxy['URL'].format(num=cls.ip_proxy['FETCH_NUM'])
response = requests.get(cls.proxy_url)
jso... | Python | zaydzuhri_stack_edu_python |
function batch_gen self
begin
return call training_inputs eval_data=false batch_size=batch_size request=request ingest_config=ingest_config data_types=tuple string fingerprints label_type
end function | def batch_gen(self):
return training_inputs(eval_data=False, batch_size=self.train_config.batch_size,
request=self.request, ingest_config=self.ingest_config,
data_types=('fingerprints', self.model_config.label_type)) | Python | nomic_cornstack_python_v1 |
class ToPurchase
begin
function __init__ self
begin
set item_name = string none
set item_price = 0
set item_quantity = 0
end function
function print_item_cost self
begin
print item_name item_quantity string @ %s%.0f % tuple string $ item_price string = %s%.0f % tuple string $ call added_total
print item_name item_quant... | class ToPurchase:
def __init__(self):
self.item_name = 'none'
self.item_price = 0
self.item_quantity = 0
def print_item_cost(self):
print(items1.item_name, items1.item_quantity, '@ %s%.0f' % ('$', items1.item_price), '= %s%.0f' % ('$', items1.added_total()))
... | Python | zaydzuhri_stack_edu_python |
import gitlab
import logging
class GitLabHelper
begin
function __init__ self host token
begin
set host = host
set token = token
set __log = call getLogger __name__
debug string Making a connection to GitLab at + host
set gitlab = call Gitlab host token=token
end function
function get_groups self
begin
return call getgr... | import gitlab
import logging
class GitLabHelper():
def __init__(self, host, token):
self.host = host
self.token = token
self.__log = logging.getLogger(__name__)
self.__log.debug("Making a connection to GitLab at " + host)
self.gitlab = gitlab.Gitlab(host, token=token)
d... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy.optimize import line_search
comment list of energies
set x = list 1 25 100 1300
function objective p
begin
return x at p
end function
function gradient p
begin
if not p == 0
begin
set low_x = x at p - 1
set current_x = x at p
set grad = call gradient list current_x low_x
end
else
begin
set... | import numpy as np
from scipy.optimize import line_search
x = [1,25,100,1300] # list of energies
def objective(p):
return x[p]
def gradient(p):
if not p==0:
low_x = x[p-1]
current_x = x[p]
grad = np.gradient([current_x,low_x])
else:
grad = [0.2, 0.2]
retu... | Python | zaydzuhri_stack_edu_python |
string Iterates through data folder appends each csv removes duplicates writes new CSV to base of data
comment IMPORT STATEMENTS
import json
import os
import time
import sys
from datetime import date , timedelta
import pandas as pd
set today = today
set yesterday = today + time delta days=- 1
comment GET TARGET DIR
set... | """
Iterates through data folder
appends each csv
removes duplicates
writes new CSV to base of data
"""
# IMPORT STATEMENTS
import json
import os
import time
import sys
from datetime import date, timedelta
import pandas as pd
today = date.today()
yesterday = date.today() + timedelta(days=-1)
# GET TARGET DIR
dir =... | Python | zaydzuhri_stack_edu_python |
function thesaurus *args
begin
set dictionary = dict
for name in args
begin
set first_letter = name at 0
set default dictionary first_letter list
append dictionary at first_letter name
end
return dictionary
end function
print call thesaurus string Иван string Мария string Петр string Илья | def thesaurus(*args):
dictionary = {}
for name in args:
first_letter = name[0]
dictionary.setdefault(first_letter, [])
dictionary[first_letter].append(name)
return dictionary
print(thesaurus("Иван", "Мария", "Петр", "Илья"))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Get relevant history from the Safari history database based on the given query and build Alfred items based on the results. Usage: safari.py PROFILE QUERY safari.py (-h | --help) safari.py --version The path to the Safari user profile to get the history database from is given in PROF... | #!/usr/bin/env python
"""
Get relevant history from the Safari history database based on the given query and build
Alfred items based on the results.
Usage:
safari.py PROFILE QUERY
safari.py (-h | --help)
safari.py --version
The path to the Safari user profile to get the history database from is given in... | Python | zaydzuhri_stack_edu_python |
function isPreposition node
begin
comment TODO: efficiency
return is instance node PrepNode
end function | def isPreposition(node):
#TODO: efficiency
return isinstance(node,PrepNode) | Python | nomic_cornstack_python_v1 |
set l = decimal input string Insira a largura da parede em metros:
set h = decimal input string Insira a altura da parede em metros:
set a = l * h
print format string Sua parede tem a dimensão de {}x{} e sua área é de {}m². l h a
set tinta = a / 2
print format string Para pintar sua parede você precisará de {}l de tint... | l = float(input('Insira a largura da parede em metros:'))
h = float(input('Insira a altura da parede em metros:'))
a = l * h
print('Sua parede tem a dimensão de {}x{} e sua área é de {}m².'.format(l, h, a))
tinta = a / 2
print('Para pintar sua parede você precisará de {}l de tinta.'.format(tinta))
| Python | zaydzuhri_stack_edu_python |
function format_column p_df column no_of_prod idx_col
begin
set p_df at column = as type p_df at column int + 1
set p_df at column = where p_df at column <= no_of_prod as type p_df at column str string CL + as type p_df at idx_col at p_df at column - no_of_prod - 1 str
set p_df at column = map lambda x -> call rsplit s... | def format_column(p_df, column, no_of_prod, idx_col):
p_df[column] = p_df[column].astype(int) + 1
p_df[column] = np.where(p_df[column] <= no_of_prod,
p_df[column].astype(str),
"CL" + p_df[idx_col][p_df[column]-no_of_prod-1].astype(str)
... | Python | nomic_cornstack_python_v1 |
function xavier_uniform weight_shape
begin
if length weight_shape == 4
begin
set tuple fW fH fC num_fitls = weight_shape
return uniform - square root 6 / fW * fH * fC + num_fitls square root 6 / fW * fH * fC + num_fitls weight_shape
end
set tuple num_input num_output = weight_shape
return uniform - square root 6 / num_... | def xavier_uniform(weight_shape):
if len(weight_shape) == 4:
fW, fH, fC, num_fitls = weight_shape
return np.random.uniform(-np.sqrt(6 / (fW*fH*fC + num_fitls)), np.sqrt(6 / (fW*fH*fC + num_fitls)), weight_shape)
num_input, num_output = weight_shape
return np.random.uniform(-np.sqrt(6 / (num_... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function numRookCaptures self board
begin
string :type board: List[List[str]] :rtype: int
set res = 0
set rowid = 0
set colid = 0
set found = 0
for i in range 8
begin
for j in range 8
begin
if board at i at j == string R
begin
set rowid = i
set colid = j
set found = 1
break
end
end
i... | class Solution(object):
def numRookCaptures(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
res = 0
rowid = colid = 0
found = 0
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
... | Python | zaydzuhri_stack_edu_python |
function traverse_extract_fetch config wukey stop_after_extraction=false
begin
string Given a config and a `wukey=cbor.dumps((folder_name,subfolder_name))`, traverse the folders to generate queries, issue them to Google, fetch the results, and ingest them.
call setup_namespace dict string openquery tuple str
try
begin
... | def traverse_extract_fetch(config, wukey, stop_after_extraction=False):
'''Given a config and a
`wukey=cbor.dumps((folder_name,subfolder_name))`, traverse the
folders to generate queries, issue them to Google, fetch the
results, and ingest them.
'''
config.kvlclient.setup_namespace({'openquery... | Python | jtatman_500k |
function test_remove_feature
begin
set mock = call MagicMock
with dictionary __salt__ dict string cmd.run_all mock
begin
call remove_feature string test
call assert_called_once_with list bin_dism string /Quiet string /Online string /Disable-Feature string /FeatureName:test string /NoRestart
end
end function | def test_remove_feature():
mock = MagicMock()
with patch.dict(dism.__salt__, {"cmd.run_all": mock}):
dism.remove_feature("test")
mock.assert_called_once_with(
[
dism.bin_dism,
"/Quiet",
"/Online",
"/Disable-Feature",
... | Python | nomic_cornstack_python_v1 |
function test_Model_1D
begin
class MyModel extends Model
begin
function __init__ self
begin
set weight = call Parameter list 5 1 name=string Weight
set bias = call Parameter list 1 1 name=string Bias
set std = call ScaleParameter list 1 1 name=string Std
end function
function __call__ self x
begin
return call Normal x ... | def test_Model_1D():
class MyModel(Model):
def __init__(self):
self.weight = Parameter([5, 1], name='Weight')
self.bias = Parameter([1, 1], name='Bias')
self.std = ScaleParameter([1, 1], name='Std')
def __call__(self, x):
return Normal(x@self.weight... | Python | nomic_cornstack_python_v1 |
comment 2. Write a Python program to append a new item to the end of the array.
comment 3. Write a Python program to reverse the order of the items in the array.
from array import *
set num_array = array string i list 1 2 3
set new_nums = 4
append num_array new_nums | #2. Write a Python program to append a new item to the end of the array.
#3. Write a Python program to reverse the order of the items in the array.
from array import *
num_array = array("i", [1, 2, 3])
new_nums = 4
num_array.append(new_nums)
| Python | zaydzuhri_stack_edu_python |
from Tkinter import *
import tkMessageBox
from questions import *
set top = call Tk
call geometry string 1366x728
set i = 0
set photo = call PhotoImage file=string dolphins.gif
set q = call Label top image=photo
set photo = photo
set name_label = call Label top text=string Your name: anchor=CENTER height=3 pady=2 font=... | from Tkinter import *
import tkMessageBox
from questions import *
top = Tk()
top.geometry('1366x728')
i = 0
photo = PhotoImage(file="dolphins.gif")
q = Label(top, image = photo)
q.photo = photo
name_label = Label(top, text="Your name: ", anchor = CENTER, height = 3, pady = 2, font = 'Helvetica -30 bold')... | Python | zaydzuhri_stack_edu_python |
from Tkinter import Tk , Button , Label , Text , Entry , Radiobutton , mainloop
from PIL import Image , ImageTk
class Gui
begin
set Button = Button
set Label = Label
set Text = Text
set Entry = Entry
set Radiobutton = Radiobutton
function __init__ self
begin
set root = call Tk
set height = none
set width = none
end fun... | from Tkinter import Tk, Button, Label, Text, Entry, Radiobutton, mainloop
from PIL import Image, ImageTk
class Gui:
Button = Button
Label = Label
Text = Text
Entry = Entry
Radiobutton = Radiobutton
def __init__(self):
self.root = Tk()
self.height = None
self.width = ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import os
function sigmoid x
begin
return 1 / 1 + exp - x
end function
function relu x
begin
return call maximum 0 x
end function
function tanh x
begin
return exp x - exp - x / exp x + exp - x
end function
set x = array range - 6 6 0.1
figure figsize=tuple 4 4
plot x s... | import numpy as np
import matplotlib.pyplot as plt
import os
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def relu(x):
return np.maximum(0, x)
def tanh(x):
return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))
x = np.arange(-6, 6, .1)
plt.figure(figsize=(4,4))
plt.plot(x, sigmoid(x), linestyle=... | Python | zaydzuhri_stack_edu_python |
from math import pow , pi
set raio : float
set area : float
set raio = decimal input string Digite o valor do raio do circulo:
set area = pi * power raio 2
comment print(pi)
print string AREA = { area } | from math import pow, pi
raio : float; area: float
raio = float(input('Digite o valor do raio do circulo: '))
area = pi * pow(raio, 2)
#print(pi)
print(f'AREA = {area:.3f}') | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.decomposition import PCA
set lojas_df = read csv string data/lojas_enc.csv
set encrypted_5_zipcode = call to_numeric encrypted_5_zipcode errors=string coerce
set subset = dr... | import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.decomposition import PCA
lojas_df = pd.read_csv("data/lojas_enc.csv")
lojas_df.encrypted_5_zipcode = pd.to_numeric(lojas_df.encrypted_5_zipcode, errors='coerce')
subset = l... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Diogo Pinheiro Function that given a phylogentic tree and the original distance matrix, calculates and returns the phylogenetic distance matrix.
function least_squares_calc tree orig_mat names
begin
import numpy as np
from Bio.Phylo.TreeConstruction import DistanceTreeConst... | # -*- coding: utf-8 -*-
"""
@author: Diogo Pinheiro
Function that given a phylogentic tree and the original distance matrix, calculates and returns the phylogenetic distance matrix.
"""
def least_squares_calc(tree,orig_mat,names):
import numpy as np
from Bio.Phylo.TreeConstruction import DistanceTreeCons... | Python | zaydzuhri_stack_edu_python |
from openpyxl import load_workbook
import os
import pandas as pd
set filename = string C:\Users\Ephraim.Sun\Desktop\proj3\final.xlsx
comment wb = load_workbook(filename=filename)
comment ws = wb.active
set df_excel = call read_excel filename index_col=0
comment print(len(df_excel.columns))
string Clean Up col names
for... | from openpyxl import load_workbook
import os
import pandas as pd
filename = r'C:\Users\Ephraim.Sun\Desktop\proj3\final.xlsx'
# wb = load_workbook(filename=filename)
# ws = wb.active
df_excel = pd.read_excel(filename, index_col=0)
# print(len(df_excel.columns))
'''Clean Up col names'''
for col in df_excel.columns:
... | Python | zaydzuhri_stack_edu_python |
for tc in range 1 T + 1
begin
comment 2 ≤ N ≤ 1,000,000
set N = integer input
set arr = list map int split input
end | for tc in range(1, T+1):
N = int(input()) # 2 ≤ N ≤ 1,000,000
arr = list(map(int, input().split()))
| Python | zaydzuhri_stack_edu_python |
string 快速排序
comment 进行一次分区操作,并找出基准值的位置
function partion array begin end
begin
set pivot_index = begin
set pivot = array at pivot_index
set left = pivot_index + 1
set right = end - 1
while true
begin
comment 左边寻找大于基准值 pivot 的那个值
while left <= right and array at left < pivot
begin
set left = left + 1
end
comment 右边寻找小于基准... | """
快速排序
"""
# 进行一次分区操作,并找出基准值的位置
def partion(array, begin, end):
pivot_index = begin
pivot = array[pivot_index]
left = pivot_index + 1
right = end - 1
while True:
# 左边寻找大于基准值 pivot 的那个值
while left <= right and array[left] < pivot:
left += 1
# 右边寻找小于基准值 pivot 的... | Python | zaydzuhri_stack_edu_python |
comment IMPORT LIBS-----
import cv2
import numpy as np
import pyautogui
import pytesseract
from PIL import Image
import time
from ocr import ImageTextReader
comment from tkinter import *
comment import tkinter as tk
set IR = call ImageTextReader
comment SETTINGS-----
comment This means the OCR will search true->char by... | # IMPORT LIBS-----
import cv2
import numpy as np
import pyautogui
import pytesseract
from PIL import Image
import time
from ocr import ImageTextReader
# from tkinter import *
# import tkinter as tk
IR = ImageTextReader()
# SETTINGS-----
# This means the OCR will search true->char by char, false->word by word
CHARACTER_... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2019/3/12 0012 0:42
comment @Author : Administrator
comment @Comment : 多线程,线程池水示例
import time
import threading
comment 新线程执行的代码: | # -*- coding: utf-8 -*-
# @Time : 2019/3/12 0012 0:42
# @Author : Administrator
# @Comment : 多线程,线程池水示例
import time
import threading
# 新线程执行的代码: | Python | zaydzuhri_stack_edu_python |
import pandas as pd
function sentiments
begin
set data = call read_excel string user_reviews.xlsx
set sentiment = call tolist
set Apps = call tolist
set apps = set
for app in Apps
begin
add apps app
end
set track1 = dict
set track2 = dict
set strr = list
for i in apps
begin
set start_index = index Apps i
set length ... | import pandas as pd
def sentiments():
data=pd.read_excel('user_reviews.xlsx')
sentiment=data["Sentiment"].tolist()
Apps=data["App"].tolist()
apps=set()
for app in Apps:
apps.add(app)
track1={}
track2={}
strr=[]
for i in apps:
start_index= Apps.index(i)... | Python | zaydzuhri_stack_edu_python |
string array: [5, 1, 22, 25, 6, -1, 8, 10] seq : [1, 6, -1, 10]
function isValidSubsequence array sequence
begin
comment Write your code here.
set seq_idx = 0
set count = 0
for i in range length array
begin
if seq_idx < length sequence and array at i == sequence at seq_idx
begin
set count = count + 1
set seq_idx = seq_... | '''
array: [5, 1, 22, 25, 6, -1, 8, 10]
seq : [1, 6, -1, 10]
'''
def isValidSubsequence(array, sequence):
# Write your code here.
seq_idx = 0
count =0
for i in range(len(array)):
if seq_idx < len(sequence) and array[i] == sequence[seq_idx]:
count +=1
seq_idx += 1
re... | Python | zaydzuhri_stack_edu_python |
from turtle import Turtle
set tuple WIDTH HEIGHT = tuple 590 590
class Border extends Turtle
begin
function __init__ self
begin
call __init__
set min_x = - WIDTH / 2
set max_x = WIDTH / 2
set min_y = - HEIGHT / 2
set max_y = HEIGHT / 2
call penup
call hideturtle
call goto x=min_x y=min_y
call pendown
call color string ... | from turtle import Turtle
WIDTH, HEIGHT = 590, 590
class Border(Turtle):
def __init__(self):
super(Border, self).__init__()
self.min_x = -WIDTH / 2
self.max_x = WIDTH / 2
self.min_y = -HEIGHT / 2
self.max_y = HEIGHT / 2
self.penup()
self.hidetu... | Python | zaydzuhri_stack_edu_python |
comment Copyright (c) 2020, salesforce.com, inc.
comment All rights reserved.
comment SPDX-License-Identifier: BSD-3-Clause
comment For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import time
function throttle wait_time
begin
string Decorator that will thrott... | # Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import time
def throttle(wait_time):
"""
Decorator that will throttle a function so tha... | Python | zaydzuhri_stack_edu_python |
class C
begin
function __init__ self x
begin
set x = x
end function
function __eq__ self other
begin
print string equals operator
return x == x
end function
end class
set c1 = call C 10
set c2 = list call C 11 * 10
set c2 at 9 = call C 10
print c1 in c2 | class C:
def __init__(self, x):
self.x = x
def __eq__(self, other):
print("equals operator")
return self.x == other.x
c1 = C(10)
c2 = [C(11)] * 10
c2[9] = C(10)
print(c1 in c2) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy.io as sio
import scipy.signal
from PIL import Image
import numpy as ny
function photo_split im
begin
set im = im at tuple slice 0 : 20 : slice : :
set im = call wiener im
set im = im > 255 * 0.4
set s1 = im at tuple slice : : slice 4 : 17 :
set s2 = im at tuple slice : : slice... | import numpy as np
import scipy.io as sio
import scipy.signal
from PIL import Image
import numpy as ny
def photo_split(im):
im = im[0:20, :]
im = scipy.signal.wiener(im)
im = im > (255 * 0.4)
s1 = im[:, 4:17]
s2 = im[:, 17:30]
s3 = im[:, 30:43]
s4 = im[:, 43:56]
s1 = np.tr... | Python | zaydzuhri_stack_edu_python |
from requests import get , post
import json
import os
import re
function rest_api_parameters in_args prefix=string out_dict=none
begin
string Transform dictionary/array structure to a flat dictionary, with key names defining the structure. Example usage: >>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]}... | from requests import get, post
import json
import os
import re
def rest_api_parameters(in_args, prefix='', out_dict=None):
"""Transform dictionary/array structure to a flat dictionary, with key names
defining the structure.
Example usage:
>>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]... | Python | zaydzuhri_stack_edu_python |
function gamma_humic_acid_to_coag ConcAl ConcNatOrgMat NatOrgMat coag
begin
string Return the fraction of the coagulant that is coated with humic acid. :param ConcAl: Concentration of alumninum in solution :type ConcAl: float :param ConcNatOrgMat: Concentration of natural organic matter in solution :type ConcNatOrgMat:... | def gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag):
"""Return the fraction of the coagulant that is coated with humic acid.
:param ConcAl: Concentration of alumninum in solution
:type ConcAl: float
:param ConcNatOrgMat: Concentration of natural organic matter in solution
:type Con... | Python | jtatman_500k |
function set_inactive self
begin
if active is false
begin
return
end
set active = false
save
update question_set active=false
end function | def set_inactive(self):
if self.active is False:
return
self.active = False
self.save()
self.question_set.update(active=False) | Python | nomic_cornstack_python_v1 |
import telebot
from telebot import types
import config
import markups as m
set bot = call TeleBot token
decorator call message_handler commands=list string start string help
function any_msg message
begin
set markup = call ReplyKeyboardMarkup
call row string 📗Статьи string ⭐️Избранное string 📰 Лента
call row string �... | import telebot
from telebot import types
import config
import markups as m
bot = telebot.TeleBot(config.token)
@bot.message_handler(commands=['start', 'help'])
def any_msg(message):
markup = types.ReplyKeyboardMarkup()
markup.row('📗Статьи', '⭐️Избранное', '📰 Лента')
markup.row('🔔Популярное', '💰Подпис... | Python | zaydzuhri_stack_edu_python |
string Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate nu... | '''
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate numbe... | Python | zaydzuhri_stack_edu_python |
import math
set radius = decimal input string Enter the radius of the circle in cm :
set area = pi * radius * radius
print string Area of circle is area string square cm | import math
radius = float(input("Enter the radius of the circle in cm : "))
area = math.pi * radius * radius
print('Area of circle is ', area, ' square cm') | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
string hmm1.py is two slow: delta_lambda = 15 ,x=8 more zhan 30k times 1. with scale 2. be modified References: 1. 统计学习方法 2. 数学之美 3. http://www.tuicool.com/articles/3iENzaV Pivot: 1. alpha,beta,gamma,xi are all for Baum_Welch 2. delta,psi are for viterbi 3. Baum_Welch for traning, viterbi for predi... | # coding:utf-8
"""
hmm1.py is two slow: delta_lambda = 15 ,x=8 more zhan 30k times
1. with scale
2. be modified
References:
1. 统计学习方法
2. 数学之美
3. http://www.tuicool.com/articles/3iENzaV
Pivot:
1. alpha,beta,gamma,xi are all for Baum_Welch
2. delta,psi are for viterbi
3. Baum_Welch for traning, viterbi for predict
Id... | Python | zaydzuhri_stack_edu_python |
function tags self
begin
return get pulumi self string tags
end function | def tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "tags") | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
string --- Advent of Code Day 16: Ticket Translation ---
from typing import List , Dict , Tuple
import re
set FILENAME = string day_16.txt
set RE_FIELD = string ^([a-z ]+): (\d+-\d+) or (\d+-\d+)$
function parse_input inp
begin
set tuple fields my_ticket nearby = inp
set field_ranges = di... | #! /usr/bin/env python3
"""--- Advent of Code Day 16: Ticket Translation ---"""
from typing import List, Dict, Tuple
import re
FILENAME = "day_16.txt"
RE_FIELD = r"^([a-z ]+): (\d+-\d+) or (\d+-\d+)$"
def parse_input(inp: List[str]) -> List[str]:
fields, my_ticket, nearby = inp
field_ranges = {}
for li... | Python | zaydzuhri_stack_edu_python |
set outer_dict = dict
comment Function to validate the values for keys and lists
function validate_input key_name list_values
begin
comment Check if key is a string and not already present in the dictionary
if not is instance key_name str or key_name in outer_dict
begin
raise call ValueError string Invalid key name or... | outer_dict = {}
# Function to validate the values for keys and lists
def validate_input(key_name, list_values):
# Check if key is a string and not already present in the dictionary
if not isinstance(key_name, str) or key_name in outer_dict:
raise ValueError("Invalid key name or key already exists.")
... | Python | jtatman_500k |
import time
import random
from N_Crepes import *
from N_Puzzle import *
from Utilidades import *
string Metodo para inicializar la busqueda nos valdra para compartir variables y no tener que meterlas en la ram en cada recursion
function inicializaBusquedaHaz anchHaz tamMem tipoProblema estadoInicial
begin
string "Prepa... | import time
import random
from N_Crepes import *
from N_Puzzle import *
from Utilidades import *
"""Metodo para inicializar la busqueda nos valdra para compartir variables y no tener que meterlas en la ram en cada recursion"""
def inicializaBusquedaHaz(anchHaz, tamMem, tipoProblema, estadoInicial):
""""Preparamos ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import os
import re
from bs4 import BeautifulSoup
from urllib.request import urlopen
from app import convert_csv_to_gpd
function lstFiles rootPath ext
begin
string retrieve file path + names based on extension
set file_list = list
set root = rootPath
for tuple path subdirs files in walk root
begin
... | import pandas as pd
import os
import re
from bs4 import BeautifulSoup
from urllib.request import urlopen
from app import convert_csv_to_gpd
def lstFiles(rootPath, ext):
'''
retrieve file path + names based on extension
'''
file_list = []
root = rootPath
for path, subdirs, files in os.walk(root):
for ... | Python | zaydzuhri_stack_edu_python |
function update_syntax self start end=none
begin
comment if no lang set
if not _lang_def
begin
return
end
call _log_debug string Update syntax from %i % call get_offset
comment if not end defined
if not end
begin
set end = call get_end_iter
end
comment We do not use recursion -> long files exceed rec-limit!
set finishe... | def update_syntax(self, start, end=None):
# if no lang set
if not self._lang_def: return
_log_debug("Update syntax from %i"%start.get_offset())
# if not end defined
if not end: end = self.get_end_iter()
# We do not use recursion -> l... | Python | nomic_cornstack_python_v1 |
comment 函数:
comment 1、作用
comment 2、使用的步骤
comment 3、参数的作用
comment 4、返回值作用
comment 5、说明文档
comment 6、函数嵌套
comment 一、函数的作用
comment 需求:用户到ATM机取钱
string 1、输入密码后显示"选择功能"界面 2、查询余额后显示"选择功能"界面 3、取出2000后显示"选择功能"界面
comment 函数就是将一段具有独立功能的代码块整合到一个整体并命名,在需要的位置调用这个名称即可完成对应的需求
comment 函数在开发过程中,可以高效的实现代码重用
string 2.1 定义函数 def 函数名(参数): 代... | # 函数:
# 1、作用
# 2、使用的步骤
# 3、参数的作用
# 4、返回值作用
# 5、说明文档
# 6、函数嵌套
# 一、函数的作用
# 需求:用户到ATM机取钱
"""
1、输入密码后显示"选择功能"界面
2、查询余额后显示"选择功能"界面
3、取出2000后显示"选择功能"界面
"""
# 函数就是将一段具有独立功能的代码块整合到一个整体并命名,在需要的位置调用这个名称即可完成对应的需求
# 函数在开发过程中,可以高效的实现代码重用
"""
2.1 定义函数
def 函数名(参数):
代码1
代码2
2.2 调用函数
函数名(参数)
注意:
1、不同的需求,参数可有可无
2、在Py... | Python | zaydzuhri_stack_edu_python |
string Read files generated by Annovar and write out a CSV file with variant transcript effects. Input: One or more variant_function and exonic_variant_function files generated by Annovar. Output: CSV file Created on Apr 14, 2022 @author: pleyte
import argparse
import logging.config
from edu.ohsu.compbio.annovar import... | '''
Read files generated by Annovar and write out a CSV file with variant transcript effects.
Input: One or more variant_function and exonic_variant_function files generated by Annovar.
Output: CSV file
Created on Apr 14, 2022
@author: pleyte
'''
import argparse
import logging.config
from edu.ohsu.compbio.annovar... | Python | zaydzuhri_stack_edu_python |
function process_caption post_node
begin
set processed_caption = dict string text string
if string edge_media_to_caption in post_node and post_node at string edge_media_to_caption and post_node at string edge_media_to_caption at string edges
begin
set processed_caption at string text = post_node at string edge_media_t... | def process_caption(post_node):
processed_caption = {
'text': ''
}
if 'edge_media_to_caption' in post_node and post_node['edge_media_to_caption'] and post_node['edge_media_to_caption']['edges']:
processed_caption['text'] = post_node['edge_media_to_caption']['edges'][0]['node']['text']
proc... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Script that takes in an argument and displays all values in the states table of hbtn_0e_0_usa where name matches the argument
from sys import argv
import MySQLdb
if __name__ == string __main__
begin
comment Open database connection
set db = call connect host=string localhost port=3306 u... | #!/usr/bin/python3
""" Script that takes in an argument and displays all values in the states
table of hbtn_0e_0_usa where name matches the argument """
from sys import argv
import MySQLdb
if __name__ == "__main__":
# Open database connection
db = MySQLdb.connect(
host="localhost",
port=3306,... | Python | zaydzuhri_stack_edu_python |
import sys
set n = integer read line stdin
set tmp = list 5
for i in range 1 n
begin
append tmp 3 * i + 1 + 1
end
comment print(tmp)
print sum tmp % 45678 | import sys
n=int(sys.stdin.readline())
tmp=[5]
for i in range(1,n):
tmp.append(3*(i+1)+1)
#print(tmp)
print( sum(tmp)%45678) | Python | zaydzuhri_stack_edu_python |
function sub_count self
begin
return length split s_pks string ,
end function | def sub_count(self):
return len(self.s_pks.split(',')) | Python | nomic_cornstack_python_v1 |
import torch.nn as nn
class F1_Loss extends Module
begin
function __init__ self epsilon=1e-07
begin
call __init__
set epsilon = epsilon
end function
function forward self output target
begin
set probas = sigmoid output
set TP = sum dim=1
set precision = TP / sum dim=1 + epsilon
set recall = TP / sum dim=1 + epsilon
set... | import torch.nn as nn
class F1_Loss(nn.Module):
def __init__(self, epsilon=1e-7):
super(F1_Loss, self).__init__()
self.epsilon = epsilon
def forward(self, output, target):
probas = nn.Sigmoid()(output)
TP = (probas * target).sum(dim=1)
precision = TP / (probas.sum(dim=1... | Python | zaydzuhri_stack_edu_python |
comment import addl for mongo, pandas, mongocredentials
from pymongo import MongoClient
import pandas as pd
from creds import *
set MONGO_CONNECTION_STRING = MONGO_URI
set MONGO_DB_NAME = DB_NAME
set MONGO_COLLECTION_NAME = COLLECTION_NAME
function get_data_from_mongo uri db collection
begin
set charactersList = list
... | #import addl for mongo, pandas, mongocredentials
from pymongo import MongoClient
import pandas as pd
from creds import *
MONGO_CONNECTION_STRING = MONGO_URI
MONGO_DB_NAME = DB_NAME
MONGO_COLLECTION_NAME = COLLECTION_NAME
def get_data_from_mongo(uri, db, collection):
charactersList = []
client = MongoClient(ur... | Python | zaydzuhri_stack_edu_python |
import argparse
from utils.argparse import ArgParser
set arg_parser = call ArgParser description=string Convert Mulcross DAT file to CSV format formatter_class=RawDescriptionHelpFormatter epilog=string Example: mulcross2csv.py MULCROSS.DAT output/mulcross.csv
call add_argument string file type=str help=string path to t... | import argparse
from utils.argparse import ArgParser
arg_parser = ArgParser(
description='''Convert Mulcross DAT file to CSV format''',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''Example:
mulcross2csv.py MULCROSS.DAT output/mulcross.csv''')
arg_parser.add_argument('file', type=str, he... | Python | zaydzuhri_stack_edu_python |
function getdelta self
begin
call initializehelmholtz
set abar = 13.714285714285715
set zbar = abar / 2.0
set data at string delta = zeros length data at string rho
for i in range length data at string rho
begin
set tuple adgradred hydrograd my_nu my_alpha data at string delta at i my_gamma1 my_cp my_cph my_c_s failtri... | def getdelta(self):
myhmag.initializehelmholtz()
abar = 13.714285714285715
zbar = abar/2.0
self.data["delta"] = np.zeros(len(self.data["rho"]))
for i in range(len(self.data["rho"])):
adgradred,hydrograd,my_nu,my_alpha,self.data["delta"][i],my_gamma1,my_cp,my_cph,my_c_s,failtrig = myhmag.gethelmgrads(self.d... | Python | nomic_cornstack_python_v1 |
function _send_device_command self requested_state requested_data
begin
if requested_state
begin
if requested_data is not none
begin
set _brightness = integer requested_data
end
dim _tellcore_device _brightness
end
else
begin
call turn_off
end
end function | def _send_device_command(self, requested_state, requested_data):
if requested_state:
if requested_data is not None:
self._brightness = int(requested_data)
self._tellcore_device.dim(self._brightness)
else:
self._tellcore_device.turn_off() | Python | nomic_cornstack_python_v1 |
for i in range min length O length E
begin
print O at i E at i sep=string end=string
end
if length O > length E
begin
print O at - 1
end | for i in range(min(len(O),len(E))):
print(O[i],E[i],sep="",end="")
if len(O) > len(E):
print(O[-1]) | Python | zaydzuhri_stack_edu_python |
function get_bounding_box prediction
begin
set x1 = prediction at string x_min
set x2 = prediction at string x_max
set y1 = prediction at string y_min
set y2 = prediction at string y_max
return list x1 y1 x2 y2
end function | def get_bounding_box(prediction):
x1 = prediction['x_min']
x2 = prediction['x_max']
y1 = prediction['y_min']
y2 = prediction['y_max']
return [x1, y1, x2, y2] | Python | nomic_cornstack_python_v1 |
function matrix_addition matrix1 matrix2
begin
comment Check if matrices have the same size
if length matrix1 != length matrix2 or length matrix1 at 0 != length matrix2 at 0
begin
return string Matrices must have the same size
end
comment Check if matrices are valid
if not call is_valid_matrix matrix1 or not call is_va... | def matrix_addition(matrix1, matrix2):
# Check if matrices have the same size
if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):
return "Matrices must have the same size"
# Check if matrices are valid
if not is_valid_matrix(matrix1) or not is_valid_matrix(matrix2):
r... | Python | jtatman_500k |
string Logistic Regression model Caveat: this was coded to see how you can build a simple model in PyTorch. It's a pretty bad model for the proposed problem. Adapted from https://hsaghir.github.io/data_science/pytorch_starter/ May 2018
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.op... | """
Logistic Regression model
Caveat: this was coded to see how you can build a simple model in PyTorch.
It's a pretty bad model for the proposed problem.
Adapted from https://hsaghir.github.io/data_science/pytorch_starter/
May 2018
"""
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch... | Python | zaydzuhri_stack_edu_python |
from math import pi , acos , cos , sin
while 1
begin
set tuple *S = map float split input
if all generator expression e == - 1 for e in S
begin
break
end
set tuple a b c d = map lambda x -> pi * x / 180.0 S
set x = 6378.1 * call acos sin a * sin c + cos a * cos c * cos b - d
print round x
end | from math import pi, acos, cos, sin
while 1:
*S, = map(float, input().split())
if all(e == -1 for e in S):
break
a, b, c, d = map(lambda x: pi * x / 180., S)
x = 6378.1 * acos(sin(a)*sin(c) + cos(a)*cos(c)*cos(b-d))
print(round(x))
| Python | jtatman_500k |
function connect dbn **keywords
begin
if dbn == string postgres
begin
try
begin
import psycopg2 as db
end
except ImportError
begin
try
begin
import psycopg as db
end
except ImportError
begin
import pgdb as db
end
end
set keywords at string password = keywords at string pw
del keywords at string pw
set keywords at strin... | def connect(dbn, **keywords):
if dbn == "postgres":
try:
import psycopg2 as db
except ImportError:
try:
import psycopg as db
except ImportError:
import pgdb as db
keywords['password'] = keywords['pw']
del keywords['p... | Python | nomic_cornstack_python_v1 |
import os
import shutil
from cryptography.fernet import Fernet
comment Read the encryption key from the 'key' file
with open string key string rb as key_file
begin
set encryption_key = read key_file
end
comment Remove the 'key' file
comment os.remove('key')
comment Create an instance of the encryption cipher
set cipher... | import os
import shutil
from cryptography.fernet import Fernet
# Read the encryption key from the 'key' file
with open('key', 'rb') as key_file:
encryption_key = key_file.read()
# Remove the 'key' file
# os.remove('key')
# Create an instance of the encryption cipher
cipher = Fernet(encryption_key)
# Get the cur... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import math
import operator
import time
set infinity = 999999
set FRIEND = 1
set ENEMY = - 1
set EMPTY = 0
class HardCodeSearch
begin
string NOTE: in this module, all things based on canonical board, and use coordinate (column, row)
function __init__ self game player
begin
comment Player will always ... | import numpy as np
import math
import operator
import time
infinity = 999999
FRIEND = 1
ENEMY = -1
EMPTY = 0
class HardCodeSearch():
"""
NOTE:
in this module, all things based on canonical board,
and use coordinate (column, row)
"""
def __init__(self, game, player):
#Player will alwa... | Python | zaydzuhri_stack_edu_python |
function GenerateStaticFrames self
begin
return none
end function | def GenerateStaticFrames(self):
return None | Python | nomic_cornstack_python_v1 |
from itertools import permutations
set n = input
set l = list permutations string n length n
set l = list set l
set l = sorted l
for i in range 0 length l
begin
for j in range 0 length n
begin
print l at i at j end=string
end
print string
end | from itertools import permutations
n=(input())
l=list(permutations(str(n),len(n)))
l=list(set(l))
l=sorted(l)
for i in range(0,len(l)):
for j in range(0,len(n)): print(l[i][j],end="")
print("\r")
| Python | zaydzuhri_stack_edu_python |
for i in range n
begin
if absolute integer s at i - integer s1 at i > 5
begin
set c = c + 10 - absolute integer s at i - integer s1 at i
end
else
begin
set c = c + absolute integer s at i - integer s1 at i
end
end
print c | for i in range(n):
if abs(int(s[i])-int(s1[i]))>5:
c+=10-abs(int(s[i])-int(s1[i]))
else:
c+=abs(int(s[i])-int(s1[i]))
print(c)
| Python | jtatman_500k |
function estimate_job self
begin
comment GET /jobs/{job_id}/estimate
pass
end function | def estimate_job(self):
# GET /jobs/{job_id}/estimate
pass | Python | nomic_cornstack_python_v1 |
function post_activities
begin
pass
end function | def post_activities():
pass | Python | nomic_cornstack_python_v1 |
function set_mode self mode
begin
if mode == string train
begin
set hidden = call _make_hidden batch_size
end
else
if mode == string generate
begin
set hidden = call _make_hidden 1
end
end function | def set_mode(self, mode):
if mode == 'train':
self.hidden = self._make_hidden(self.batch_size)
elif mode == 'generate':
self.hidden = self._make_hidden(1) | Python | nomic_cornstack_python_v1 |
function merge line
begin
set line = call adjust_line line
for _item in range length line - 1
begin
if line at _item == line at _item + 1
begin
set line at _item = line at _item * 2
set line at _item + 1 = 0
set line = call adjust_line line
end
else
if line at _item + 1 == 0
begin
break
end
end
return line
end function | def merge(line):
line = adjust_line(line)
for _item in range(len(line) - 1):
if line[_item] == line[_item + 1]:
line[_item] *= 2
line[_item + 1] = 0
line = adjust_line(line)
elif line[_item + 1] == 0:
break
return line | Python | nomic_cornstack_python_v1 |
function compute_pred_boxes deltas anchors mean=0.0 std=0.2
begin
comment first dimension is the batch size
set width = anchors at tuple slice : : slice : : 2 - anchors at tuple slice : : slice : : 0
set height = anchors at tuple slice : : slice : : 3 - anchors at tuple slice : : slice : : 1
set... | def compute_pred_boxes(deltas, anchors, mean=0.0, std=0.2):
#first dimension is the batch size
width = anchors[:, :, 2] - anchors[:, :, 0]
height = anchors[:, :, 3] - anchors[:, :, 1]
x1 = anchors[:, :, 0] + (deltas[:, :, 0] * std[0] + mean[0]) * width
y1 = anchors[:, :, 1] + (deltas[:, :, 1] * st... | Python | nomic_cornstack_python_v1 |
function filter2d input_img filter
begin
comment M is height, N is width
set tuple M N = shape
comment m is height, n is width
set tuple n m = tuple length filter length filter at 0
comment size of neighborhood
set tuple a b = tuple m / 2 n / 2
comment get transpose of the 1-d filter
if is instance filter ndarray
begin... | def filter2d(input_img, filter):
M, N = input_img.shape # M is height, N is width
n, m = len(filter), len(filter[0]) # m is height, n is width
a, b = m / 2, n / 2 # size of neighborhood
# get transpose of the 1-d filter
if isinstance(filter, np.ndarray):
wt = filter.ravel()
else:
... | Python | nomic_cornstack_python_v1 |
function ngram_types cls
begin
return list comprehension t for t in ModelType if metatype is ngram
end function | def ngram_types(cls):
return [t for t in LinguisticDistributionalModel.ModelType if t.metatype is LinguisticDistributionalModel.MetaType.ngram] | Python | nomic_cornstack_python_v1 |
function forbidden e
begin
return tuple call render_template string errors/403.html 500
end function | def forbidden(e):
return render_template('errors/403.html'), 500 | Python | nomic_cornstack_python_v1 |
import openpyxl
set wb = call load_workbook string example.xlsx data_only=true
set sheet2 = call get_active_sheet
set sheet = call get_sheet_names | import openpyxl
wb = openpyxl.load_workbook('example.xlsx',data_only=True)
sheet2 = wb.get_active_sheet()
sheet = wb.get_sheet_names() | Python | zaydzuhri_stack_edu_python |
function get_access_control_max_age self
begin
return access_control_max_age
end function | def get_access_control_max_age(self):
return self.access_control_max_age | Python | nomic_cornstack_python_v1 |
import os , sys
from json import dumps , load
from os.path import join , getsize
set dirs_dict = dict
set ROOT_PATH = argv at 1
function sizeFmt num
begin
for x in list string Bytes string KB string MB string GB string TB
begin
if num < 1024.0
begin
return string %3.1f %s % tuple num x
end
set num = num / 1024.0
end
e... | import os, sys
from json import dumps, load
from os.path import join, getsize
dirs_dict = {}
ROOT_PATH = sys.argv[1]
def sizeFmt(num):
for x in ['Bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
#for root, dirs, files in os.walk(ROOT_PATH,... | Python | zaydzuhri_stack_edu_python |
function filter_vario_params self data_id=none name=none
begin
comment build the base query
set query = query session VarioParams
comment apply filter
if data_id is not none
begin
set query = filter data_id == data_id
end
if name is not none
begin
set name = replace name string * string %
if string % not in name
begin
... | def filter_vario_params(self, data_id=None, name=None) -> List[VarioParams]:
# build the base query
query = self.session.query(VarioParams)
# apply filter
if data_id is not None:
query = query.filter(VarioParams.data_id == data_id)
if name is not None:
... | Python | nomic_cornstack_python_v1 |
function check_crc self message_from_sensor check_value_from_sensor
begin
comment Pad with 8 bits because we have to add in the check value
set remainder = message_from_sensor ? 8
comment Add on the check value
set remainder = remainder ? check_value_from_sensor
set divsor = SHIFTED_DIVISOR
comment Operate on only 16 p... | def check_crc(self,message_from_sensor, check_value_from_sensor):
remainder = message_from_sensor << 8 #Pad with 8 bits because we have to add in the check value
remainder |= check_value_from_sensor #Add on the check value
divsor = SHIFTED_DIVISOR
for i in range(0, 16): #Operate on onl... | Python | nomic_cornstack_python_v1 |
function update_record self status payload_id
begin
set conn = call create_connection
set cur = call cursor
set query = string UPDATE `payload` SET `downloaded` = ?, `downloaded_at` = strftime('%Y-%m-%d %H:%M:%S','now') WHERE `id` = ?
set execute = execute cur query tuple status payload_id
commit conn
close cur
return ... | def update_record(self, status, payload_id):
conn = Db.create_connection()
cur = conn.cursor()
query = "UPDATE `payload` SET `downloaded` = ?, `downloaded_at` = \
strftime('%Y-%m-%d %H:%M:%S','now') WHERE `id` = ?"
execute = cur.execute(query, (status, payload_id,))
... | Python | nomic_cornstack_python_v1 |
comment Fizz Buzz
function fizzBuzz self n
begin
return list comprehension string Fizz * not i % 3 + string Buzz * not i % 5 or string i for i in range 1 n + 1
end function
function fizzBuzz self n
begin
string :type n: int :rtype: List[str]
set result = list
for i in range 1 n + 1
begin
if i % 5 == 0 and i % 3 == 0
b... | ## Fizz Buzz
def fizzBuzz(self, n):
return ['Fizz'* (not i % 3) + 'Buzz'*(not i % 5) or str(i) for i in range(1, n+1)]
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result=[]
for i in range(1, n+1):
if i % 5==0 and i % 3 ==0:
result.append(str("FizzBuzz")... | Python | zaydzuhri_stack_edu_python |
comment Description
comment Given a undirected graph, a node and a target, return the nearest node to given node which value of it is target, return NULL if you can't find.
comment There is a mapping store the nodes' values in the given parameters.
comment Notice
comment It's guaranteed there is only one available solu... | # Description
# Given a undirected graph, a node and a target, return the nearest node to given node which value of it is target, return NULL if you can't find.
#
# There is a mapping store the nodes' values in the given parameters.
#
# Notice
# It's guaranteed there is only one available solution
#
#
# Example
# 2----... | Python | zaydzuhri_stack_edu_python |
function calculate_cut_coords_by_zoom coord metatile_zoom cfg_tile_sizes max_zoom
begin
string Returns a map of nominal zoom to the list of cut coordinates at that nominal zoom. Note that max_zoom should be the maximum coordinate zoom, not nominal zoom.
set tile_sizes_by_zoom = call calculate_sizes_by_zoom coord metati... | def calculate_cut_coords_by_zoom(
coord, metatile_zoom, cfg_tile_sizes, max_zoom):
"""
Returns a map of nominal zoom to the list of cut coordinates at that
nominal zoom.
Note that max_zoom should be the maximum coordinate zoom, not nominal
zoom.
"""
tile_sizes_by_zoom = calculate_s... | Python | jtatman_500k |
function _filtered_tb
begin
return string %s % join string generator expression strip line for line in call format_stack if string ag__.converted_call in line and not string _filtered_tb in line
end function | def _filtered_tb():
return "\n%s" % ("\n".join(line.strip() for line in traceback.format_stack()
if ("ag__.converted_call" in line) and not ("_filtered_tb" in line))) | 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.