code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Gabriel Daniels
comment PSID: 1856516
comment import modules
import csv
from operator import itemgetter
from collections import defaultdict
comment import class date from module datetime
from datetime import datetime
comment set up dictionaries and lists to be used later
set item_id = dict
set item_type = dict... | # Gabriel Daniels
# PSID: 1856516
# import modules
import csv
from operator import itemgetter
from collections import defaultdict
# import class date from module datetime
from datetime import datetime
# set up dictionaries and lists to be used later
item_id = {}
item_type = {}
damaged = {}
manufacturers =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding:utf-8
import random
from c36 import SRP_client , i2s
import hashlib
import hmac
import socket
import os
if __name__ == string __main__
begin
comment 定义大素数
set NISTprime = 49999
end | #!/usr/bin/env python
#coding:utf-8
import random
from c36 import SRP_client,i2s
import hashlib
import hmac
import socket
import os
if __name__ == "__main__":
NISTprime = 0xc34f #定义大素数
| Python | zaydzuhri_stack_edu_python |
function test_link_to_admin_when_logged_in self
begin
call create_user string test string dudarev+test@gmail.com string test
call login username=string test password=string test
set response = get client reverse string index
assert true string (admin) in content
end function | def test_link_to_admin_when_logged_in(self):
User.objects.create_user('test', 'dudarev+test@gmail.com', 'test')
self.client.login(username='test', password='test')
response = self.client.get(reverse('index'))
self.assertTrue('(admin)' in response.content) | Python | nomic_cornstack_python_v1 |
function mean_log_prob_approx self y=none name=string mean_log_prob_approx
begin
with call _name_and_control_scope name
begin
return call approx_expected_log_prob_sigmoid loc scale y MONAHAN_MIX_PROB at num_probit_terms_approx MONAHAN_INVERSE_SCALE at num_probit_terms_approx
end
end function | def mean_log_prob_approx(self, y=None, name='mean_log_prob_approx'):
with self._name_and_control_scope(name):
return approx_expected_log_prob_sigmoid(
self.loc, self.scale, y,
MONAHAN_MIX_PROB[self.num_probit_terms_approx],
MONAHAN_INVERSE_SCALE[self.num_probit_terms_approx]) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import os
comment data source: https://dane.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/miesieczne/synop/
set dataset_folder_name = string csv
set filenames = list directory dataset_folder_name
set data = list
comment t is average month temperature, destination column
set colnames... | import pandas as pd
import os
# data source: https://dane.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/miesieczne/synop/
dataset_folder_name = "csv"
filenames = os.listdir(dataset_folder_name)
data = []
# t is average month temperature, destination column
colnames = ["station_code", "station_name", "... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from matplotlib import pyplot as plt
comment create the 5x5 mean filter
set meanFilter = ones tuple 5 5 / 25
comment create a 5x5 guassian filter
set x = call getGaussianKernel 5 1
set gaussian = x * T
comment create a Laplacian filter
set laplacian = array list list 0 1 0 list 1 - 4 1 lis... | import cv2
import numpy as np
from matplotlib import pyplot as plt
# create the 5x5 mean filter
meanFilter = np.ones((5,5))/25
# create a 5x5 guassian filter
x = cv2.getGaussianKernel(5,1)
gaussian = x*x.T
# create a Laplacian filter
laplacian=np.array([[0, 1, 0],
[1,-4, 1],
... | Python | zaydzuhri_stack_edu_python |
function post_cov self
begin
return call invwishart df=nun_ scale=Sn_
end function | def post_cov(self):
return stats.invwishart(df=self.nun_, scale=self.Sn_) | Python | nomic_cornstack_python_v1 |
if type_fabric == string Linen
begin
set price_shirt = size_m * 15 + 10
end
else
if type_fabric == string Cotton
begin
set price_shirt = size_m * 12 + 10
end
else
if type_fabric == string Denim
begin
set price_shirt = size_m * 20 + 10
end
else
if type_fabric == string Twill
begin
set price_shirt = size_m * 16 + 10
end
... | if type_fabric == "Linen":
price_shirt = size_m * 15 + 10
elif type_fabric == "Cotton":
price_shirt = size_m * 12 + 10
elif type_fabric == "Denim":
price_shirt = size_m * 20 + 10
elif type_fabric == "Twill":
price_shirt = size_m * 16 + 10
elif type_fabric == "Flannel":
price_shirt = size_m * 11 + 10... | Python | zaydzuhri_stack_edu_python |
function normalise_correlation image_tile_dict transformed_array template normed_tolerance=1
begin
string Calculates the normalisation coefficients of potential match positions Then normalises the correlation at these positions, and returns them if they do indeed constitute a match
set template_norm = norm template
set... | def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""Calculates the normalisation coefficients of potential match positions
Then normalises the correlation at these positions, and returns them
if they do indeed constitute a match
"""
template_norm = n... | Python | jtatman_500k |
function generate_pops target_reg exclude_regs=list count=1 allow_dups=true
begin
set random_regs = list
for _ in range 0 count - 1
begin
set random_reg = call get_random_register exclude_regs=exclude_regs
append random_regs random_reg
end
set pops = string
for reg in random_regs
begin
set pops = pops + string pop {... | def generate_pops(target_reg, exclude_regs=[], count=1, allow_dups=True):
random_regs = []
for _ in range(0, count-1):
random_reg = get_random_register(exclude_regs=exclude_regs)
random_regs.append(random_reg)
pops = ''
for reg in random_regs:
pops += f'pop {reg}; '
pop... | Python | nomic_cornstack_python_v1 |
import sys
set input = readline
set N = integer input
set result = list comprehension 0 for _ in range 10001
for _ in range N
begin
set n = integer input
set result at n = result at n + 1
end
for tuple idx n in enumerate result
begin
if n != 0
begin
for m in range n
begin
print idx
end
end
end | import sys
input = sys.stdin.readline
N = int(input())
result = [0 for _ in range(10001)]
for _ in range(N):
n = int(input())
result[n] += 1
for idx, n in enumerate(result):
if n != 0:
for m in range(n):
print(idx) | Python | zaydzuhri_stack_edu_python |
import requests
from urllib import parse
import json
set baseurl = string https://fanyi.baidu.com/sug
set c1 = input string 请输入一个单词:
comment 存放模拟form的数据一定是dict格式
set data = dict string kw c1
comment 需要使用parse模块对data进行编码
comment data = parse.urlencode(data)
comment print(type(data))
comment data = data.encode('utf-8')
c... | import requests
from urllib import parse
import json
baseurl = "https://fanyi.baidu.com/sug"
c1 = input("请输入一个单词:")
#存放模拟form的数据一定是dict格式
data = {"kw": c1}
#需要使用parse模块对data进行编码
# data = parse.urlencode(data)
# print(type(data))
# data = data.encode('utf-8')
# print(type(data))
#我们需要构造一个请求头,请求头应该至... | Python | zaydzuhri_stack_edu_python |
function update self
begin
if n_users == 0
begin
set n_users_min = 0
return
end
sort self
set min_point = user_points at - 1
set max_point = user_points at 0
set same_count = 0
for i in user_points
begin
if i == min_point
begin
set same_count = same_count + 1
end
end
set n_users_min = same_count
end function | def update(self):
if self.n_users == 0:
self.n_users_min = 0;
return;
self.sort();
self.min_point = self.user_points[-1];
self.max_point = self.user_points[0];
same_count = 0
for i in self.user_points:
if i =... | Python | nomic_cornstack_python_v1 |
function merge user default
begin
if is instance user dict and is instance default dict
begin
for tuple kk vv in items default
begin
if kk not in user
begin
set user at kk = vv
end
else
begin
set user at kk = merge user at kk vv
end
end
end
return user
end function | def merge(user, default):
if isinstance(user, dict) and isinstance(default, dict):
for kk, vv in default.items():
if kk not in user:
user[kk] = vv
else:
user[kk] = merge(user[kk], vv)
return user | Python | nomic_cornstack_python_v1 |
function newton_convergence_plot f_vals
begin
set fig = figure
set ax = call add_subplot 1 1 1
plot f_vals color=string blue lw=2
call set_yscale string log
show
end function | def newton_convergence_plot(f_vals):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(f_vals, color='blue', lw=2)
ax.set_yscale('log')
pylab.show() | Python | nomic_cornstack_python_v1 |
function display_image window_name image
begin
call namedWindow window_name
image show window_name image
call waitKey 0
end function | def display_image(window_name, image):
cv2.namedWindow(window_name)
cv2.imshow(window_name, image)
cv2.waitKey(0) | Python | nomic_cornstack_python_v1 |
function limite_do_palete qtde_de_cxs
begin
global largura comprimento
set comprimento = comprimento + 2
set k = 32
set largura = largura + 2 * qtde_de_cxs - comprimento
return k
end function
set largura = 92
set comprimento = 100
set qtde_de_cxs = 3
call limite_do_palete qtde_de_cxs
print largura
set teste = call limi... | def limite_do_palete(qtde_de_cxs):
global largura, comprimento
comprimento = comprimento + 2
k = 32
largura = largura + \
2 * qtde_de_cxs - comprimento
return k
largura = 92
comprimento = 100
qtde_de_cxs = 3
limite_do_palete(qtde_de_cxs)
print(largura)
teste = limite_do_palete(qtde... | Python | zaydzuhri_stack_edu_python |
function predict self inputPath inputWords pathLens CUDA
begin
set inv_dic = call get_inv tag_to_ix
with no grad
begin
set all_predictions = list
set tuple out _ = call self inputPath inputWords pathLens CUDA
set prediction = softmax out dim=1
set tuple _ maxIndices = max prediction 1
set all_predictions = list compre... | def predict(self,inputPath,inputWords,pathLens,CUDA):
inv_dic = get_inv(self.tag_to_ix)
with torch.no_grad():
all_predictions = []
out,_ = self(inputPath,inputWords,pathLens,CUDA)
prediction = F.softmax(out, dim=1)
_,maxIndices = torch.max(pr... | Python | nomic_cornstack_python_v1 |
from pyspark import SparkConf , SparkContext , SQLContext
import pyspark.sql.functions as F
from pyspark.sql.types import ArrayType , IntegerType
import os
import sys
from pyspark.sql.window import Window
set conf = set string spark.sql.shuffle.partitions string 8
set sc = call SparkContext master=string local appName=... | from pyspark import SparkConf, SparkContext, SQLContext
import pyspark.sql.functions as F
from pyspark.sql.types import ArrayType, IntegerType
import os
import sys
from pyspark.sql.window import Window
conf = SparkConf().set("spark.driver.host", "127.0.0.1").set("spark.sql.crossJoin.enabled", "true") \
.set("... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf8 -*-
class MatrixEditor extends object
begin
string Creates, edits and saves a simple ASCII matrix
function __init__ self width height
begin
string Initializes a matrix with width and height, filling it with 0s :param width: positive integer for matrix width :param heigh... | #!/usr/bin/python
# -*- coding: utf8 -*-
class MatrixEditor(object):
"""
Creates, edits and saves a simple ASCII matrix
"""
def __init__(self, width: int, height: int):
"""
Initializes a matrix with width and height, filling it with 0s
:param width: positive integer for matrix ... | Python | zaydzuhri_stack_edu_python |
function load_transactions self address update=true verbose=false **kwargs
begin
if apikey is none
begin
set update = false
end
if verbose
begin
print string load_transactions address
end
set fn = join path cache_dir address + string .json
set startblock = none
set transactions = list
if exists path fn
begin
with open... | def load_transactions(self, address, update=True, verbose=False, **kwargs):
if self.apikey is None:
update = False
if verbose:
print('load_transactions', address)
fn = os.path.join(self.cache_dir, address + '.json')
startblock = None
transactions = []
... | Python | nomic_cornstack_python_v1 |
function remove_duplicate_rows rows
begin
set item_ids = list
set new_rows = list
for row in rows
begin
set row = deep copy row
set item_id = row at string Stock & Site
if item_id not in item_ids
begin
append item_ids item_id
append new_rows row
end
end
return new_rows
end function | def remove_duplicate_rows(rows):
item_ids = []
new_rows = []
for row in rows:
row = copy.deepcopy(row)
item_id = row["Stock & Site"]
if item_id not in item_ids:
item_ids.append(item_id)
new_rows.append(row)
return new_rows | Python | nomic_cornstack_python_v1 |
function get_http_authentication private_key private_key_id
begin
string Get HTTP signature authentication for a request.
set key = call exportKey
return call HTTPSignatureHeaderAuth headers=list string (request-target) string user-agent string host string date algorithm=string rsa-sha256 key=key key_id=private_key_id
... | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
"""
Get HTTP signature authentication for a request.
"""
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorit... | Python | jtatman_500k |
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import joblib
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble im... | from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import joblib
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.en... | Python | zaydzuhri_stack_edu_python |
function user_stats df
begin
print string Calculating User Stats...
set start_time = time
comment Display counts of user types
print string Counts of User types is: value counts df at string User Type
comment Display counts of gender with exception for Washington
while string Gender not in df
begin
print string No gend... | def user_stats(df):
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
print('Counts of User types is:\n',df['User Type'].value_counts())
# Display counts of gender with exception for Washington
while 'Gender' not in df:
print('No gender dat... | Python | nomic_cornstack_python_v1 |
function _message self json schema
begin
try
begin
set response = post _url json=json verify=cert_path auth=call Auth serial secret headers=_headers
call raise_for_status
call schema json response
end
except tuple ConnectionError HTTPError as ex
begin
raise call NeatoRobotException string Unable to communicate with rob... | def _message(self, json: dict, schema: Schema):
try:
response = requests.post(
self._url,
json=json,
verify=self._vendor.cert_path,
auth=Auth(self.serial, self.secret),
headers=self._headers,
)
r... | Python | nomic_cornstack_python_v1 |
import webbrowser
open string https://www.ebay.com/b/Electronics/bn_7000259124 | import webbrowser
webbrowser.open('https://www.ebay.com/b/Electronics/bn_7000259124')
| Python | flytech_python_25k |
comment @lc app=leetcode.cn id=13 lang=python3
comment [13] 罗马数字转整数
comment 题解
comment 从左到右扫描字符串,不光观察当前字符,还要观察下一个字符。当字符是 I,而下一个字符是 V 或 X 时,两个字符组成 IV 或 IX,对 X 和 C 同理。
comment 提交结果
comment 3999/3999 cases passed (52 ms)
comment Your runtime beats 75.72 % of python3 submissions
comment Your memory usage beats 57.36 % of p... | #
# @lc app=leetcode.cn id=13 lang=python3
#
# [13] 罗马数字转整数
#
# 题解
# 从左到右扫描字符串,不光观察当前字符,还要观察下一个字符。当字符是 I,而下一个字符是 V 或 X 时,两个字符组成 IV 或 IX,对 X 和 C 同理。
#
# 提交结果
# 3999/3999 cases passed (52 ms)
# Your runtime beats 75.72 % of python3 submissions
# Your memory usage beats 57.36 % of python3 submissions (13.2 MB)
# @lc code... | Python | zaydzuhri_stack_edu_python |
comment Nicholas M. Rathmann, NBI, UCPH, 2020.
comment Sponsered by Villum Fonden as part of the project "IceFlow".
import sys
import pandas
import matplotlib.pyplot as plt
comment commandline argument #1
set fname = argv at 1
set df = read csv fname sep=string ,
set tuple f tuple tuple ax1 ax2 ax3 tuple ax4 ax5 ax6 = ... | # Nicholas M. Rathmann, NBI, UCPH, 2020.
# Sponsered by Villum Fonden as part of the project "IceFlow".
import sys
import pandas
import matplotlib.pyplot as plt
fname = sys.argv[1] # commandline argument #1
df = pandas.read_csv(fname, sep=',')
f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(12,7)... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import serial
import time
comment init serial, open arduino to check the port that the arduino is using
set ser = call Serial string /dev/ttyACM1
comment let the arduino rest
sleep 1.5
comment write stuff to it!
write ser string boom
close ser | #!/usr/bin/python
import sys
import serial
import time
# init serial, open arduino to check the port that the arduino is using
ser = serial.Serial('/dev/ttyACM1')
# let the arduino rest
time.sleep(1.5)
# write stuff to it!
ser.write('boom')
ser.close()
| Python | zaydzuhri_stack_edu_python |
function getAllSiblings name
begin
set siblings_list = list
if ParentA == none
begin
print siblings_list
end
else
if ParentB == none
begin
print siblings_list
end
end function | def getAllSiblings(name):
siblings_list = []
if (name.ParentA == None):
print(siblings_list)
elif (name.ParentB == None):
print(siblings_list) | Python | zaydzuhri_stack_edu_python |
function _create_user session
begin
set session at string login = true
set session at string id = string uuid 4
set session at string nickname = string Meme + string random integer 10000 99999
set session at string theme = string light
end function | def _create_user(session: SessionData) -> None:
session["login"] = True
session["id"] = str(uuid4())
session["nickname"] = "Meme" + str(randint(10000, 99999))
session["theme"] = "light" | Python | nomic_cornstack_python_v1 |
function move self *args
begin
if length args == 3
begin
set __pos at 0 = __pos at 0 + args at 0
set __pos at 1 = __pos at 1 + args at 1
set __pos at 2 = __pos at 2 + args at 2
pass
end
else
if __name__ == string list
begin
set __pos = list comprehension sum values for values in zip *[self.__pos] + [args[0]]
end
else
i... | def move(self, *args):
if len(args) == 3:
self.__pos[0] = self.__pos[0] + args[0]
self.__pos[1] = self.__pos[1] + args[1]
self.__pos[2] = self.__pos[2] + args[2]
pass
elif (type(args[0]).__name__) == 'list':
self.__pos = [sum(values) for values in zip( *([self.__pos] + [args[0]]) )]
elif len(args)... | Python | nomic_cornstack_python_v1 |
function create_third_section self nb
begin
set right = call ParagraphStyle name=string right alignment=TA_RIGHT
set left = call ParagraphStyle name=string left alignment=TA_LEFT
set colonnes = 5
set lignes = 30
set table = list comprehension list string * colonnes for _ in range lignes
set table at 0 at 3 = call Para... | def create_third_section(self, nb):
right = ParagraphStyle(name="right", alignment=TA_RIGHT)
left = ParagraphStyle(name="left", alignment=TA_LEFT)
colonnes = 5
lignes = 30
table = [[''] * colonnes for _ in range(lignes)]
table[0][3] = Paragraph("<b>Power Estimation</b>... | Python | nomic_cornstack_python_v1 |
import nltk , spacy , time
from yelpapi import YelpAPI
import secret
set en_nlp = load spacy string en
set nlp = load spacy string en_core_web_sm
set yelp_api = call YelpAPI yelp_key
function run_chatbot
begin
set user_response = input string CRAVEBOT: Hi. I'm Cravebot. <3 What are you craving today?
set food = orth_
s... | import nltk, spacy, time
from yelpapi import YelpAPI
import secret
en_nlp = spacy.load('en')
nlp = spacy.load('en_core_web_sm')
yelp_api = YelpAPI(secret.yelp_key)
def run_chatbot():
user_response = input("CRAVEBOT: Hi. I'm Cravebot. <3 What are you craving today? \n")
food = process_food(user_response).orth_... | Python | zaydzuhri_stack_edu_python |
for _ in range tests
begin
set line = input
set values = list comprehension integer v for v in split line string
sort values
set tuple x y = values
set s = 0
for i in range x + 1 y
begin
if i % 2 != 0
begin
set s = s + i
end
end
print s
end | for _ in range(tests):
line = input()
values = [int(v) for v in line.split(' ')]
values.sort()
x, y = values
s = 0
for i in range(x+1, y):
if (i % 2) != 0:
s += i
print(s) | Python | zaydzuhri_stack_edu_python |
function match2 img1 img2 coordinates1 coordinates2 PATCH_SIZE
begin
set possible_matches = call DataFrame columns=list string feature1 string feature2 string diff
comment iteration through all the possible pairs of features from img1 and img2
for tuple feature1 feature2 in product coordinates1 coordinates2
begin
set p... | def match2(img1, img2, coordinates1, coordinates2, PATCH_SIZE):
possible_matches = pd.DataFrame(columns=['feature1', 'feature2', 'diff'])
# iteration through all the possible pairs of features from img1 and img2
for (feature1, feature2) in product(coordinates1, coordinates2):
patch1 = make_patch(f... | Python | nomic_cornstack_python_v1 |
import pandas as pd
set x_base = 4.8
set z_base = 1.2
set step = 1.2
set room = 0.4
set x_border = x_base - step / 2
set z_border = z_base - step / 2
set df = read csv string ../data/data_1_separated.csv
set df at string player0_position_x = as type df at string player0_position_x - x_border / step int
set df at string... | import pandas as pd
x_base = 4.8
z_base = 1.2
step = 1.2
room = 0.4
x_border = x_base-step/2
z_border = z_base-step/2
df = pd.read_csv('../data/data_1_separated.csv')
df['player0_position_x'] = (
(df['player0_position_x']-x_border)/step).astype(int)
df['player0_position_z'] = (
(df['player0_position_z']-z_bo... | Python | zaydzuhri_stack_edu_python |
string Base plugin class for pluggable scoring.
from abc import abstractmethod , ABCMeta
function load_plugin path plugin_class
begin
string Instantiate a plugin object from a Python file. :param path: File path to plugin python file. :param plugin_class: Full class path of plugin. :return: Plugin object.
import os
imp... | """
Base plugin class for pluggable scoring.
"""
from abc import abstractmethod, ABCMeta
def load_plugin(path, plugin_class):
"""
Instantiate a plugin object from a Python file.
:param path: File path to plugin python file.
:param plugin_class: Full class path of plugin.
:return: Plugin object.
... | Python | zaydzuhri_stack_edu_python |
comment $NON-NLS-1$
function runPreprocess self
begin
if preprocessed
begin
return true
end
set preprocessed = true
return call _runProcess preprocessHandlers
end function | def runPreprocess(self): #$NON-NLS-1$
if self.preprocessed:
return True
self.preprocessed = True
return self._runProcess(self.preprocessHandlers) | Python | nomic_cornstack_python_v1 |
function bounding_box self side
begin
comment Compute the bounding box based on the normal vector to the plane
set nhat = call _get_normal
set ll = array list - inf - inf - inf
set ur = array list inf inf inf
comment If the plane is axis aligned, find the proper bounding box
if any call isclose absolute nhat 1.0 rtol=0... | def bounding_box(self, side):
# Compute the bounding box based on the normal vector to the plane
nhat = self._get_normal()
ll = np.array([-np.inf, -np.inf, -np.inf])
ur = np.array([np.inf, np.inf, np.inf])
# If the plane is axis aligned, find the proper bounding box
if np... | Python | nomic_cornstack_python_v1 |
import os
import pandas as pd
import datetime as dt
from datetime import datetime
import numpy as np
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
import yfinance as yf
from statsmodels.tsa.stattools import adfuller
from Main.DriverObject.Trading.Strategy import PairConstants
class Stra... | import os
import pandas as pd
import datetime as dt
from datetime import datetime
import numpy as np
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
import yfinance as yf
from statsmodels.tsa.stattools import adfuller
from Main.DriverObject.Trading.Strategy import PairConstants
class ... | Python | zaydzuhri_stack_edu_python |
function test90
begin
try
begin
set p = call get_processors
assert false msg string This should have raised about no args
end
except RuntimeError
begin
pass
end
end function | def test90():
try:
p = get_processors()
assert False, "This should have raised about no args"
except RuntimeError:
pass | Python | nomic_cornstack_python_v1 |
function draw_chimera_yield G **kwargs
begin
try
begin
assert graph at string family == string chimera
set m = graph at string rows
set n = graph at string columns
set t = graph at string tile
set coordinates = graph at string labels == string coordinate
end
except any
begin
raise call ValueError string Target chimera ... | def draw_chimera_yield(G, **kwargs):
try:
assert(G.graph["family"] == "chimera")
m = G.graph["rows"]
n = G.graph["columns"]
t = G.graph["tile"]
coordinates = G.graph["labels"] == "coordinate"
except:
raise ValueError("Target chimera graph needs to have columns, ro... | Python | nomic_cornstack_python_v1 |
function csr_has_sorted_indices *args
begin
return call csr_has_sorted_indices *args
end function | def csr_has_sorted_indices(*args):
return _csr.csr_has_sorted_indices(*args) | Python | nomic_cornstack_python_v1 |
function sort_brackets_adj self start end match_type bracket_id
begin
if touch_right is false and end == center
begin
comment Check for adjacent opening or closing bracket on left side
set entry = call BracketEntry start end bracket_id
set touch_right = true
if match_type == BH_SEARCH_OPEN
begin
append left at match_ty... | def sort_brackets_adj(self, start, end, match_type, bracket_id):
if (
self.touch_right is False and
end == (self.center)
):
# Check for adjacent opening or closing bracket on left side
entry = BracketEntry(start, end, bracket_id)
self.touch_ri... | Python | nomic_cornstack_python_v1 |
import PyPDF2 , os
set pdfReader = call PdfFileReader open string encrypted.pdf string rb
isEncrypted
true
set my_textfile = open base name path string dictionary.txt string r
set decr = false
for line in my_textfile
begin
set decr = call decrypt line
print line
if decr == true
begin
print line
call getPage 0
end
end
c... | import PyPDF2, os
pdfReader = PyPDF2.PdfFileReader(open('encrypted.pdf', 'rb'))
pdfReader.isEncrypted
True
my_textfile = open(os.path.basename('dictionary.txt'), 'r')
decr = False
for line in my_textfile:
decr = pdfReader.decrypt(line)
print (line)
if decr == True:
print (line)
pdfReader.g... | Python | zaydzuhri_stack_edu_python |
string SQL Data Tool
import sqlite3
import os
from colorama import Fore , Back , init
comment noinspection PyUnusedLocal
class KJVSQL extends object
begin
string KJVSQL class
function __init__ self
begin
string
comment self.settings = os.path.expanduser( "~\\Documents\\Discord Logs\\SETTINGS" )
set settings = string {... | """
SQL Data Tool
"""
import sqlite3
import os
from colorama import Fore, Back, init
# noinspection PyUnusedLocal
class KJVSQL( object ):
"""
KJVSQL class
"""
def __init__ ( self ):
"""
"""
# self.settings = os.path.expanduser( "~\\Documents\\Discord Logs\\SETTINGS" )
self.settings = f"{os.getcwd( )}\\Disc... | Python | zaydzuhri_stack_edu_python |
set shares = integer input string How many people you want to share your money with?>>
set money = 1000 / shares
print money | shares = int(input("How many people you want to share your money with?>>"))
money = 1000/shares
print(money) | Python | zaydzuhri_stack_edu_python |
function execute_plan self
begin
yield from call generate_delete_configurations include_for_deletion
end function | def execute_plan(self):
yield from self.generate_delete_configurations(self.include_for_deletion) | Python | nomic_cornstack_python_v1 |
import random
function stdDev X
begin
set mean = decimal sum X / length X
set tot = 0.0
for x in X
begin
set tot = tot + x - mean ^ 2
end
return tot / length X ^ 0.5
end function
function throwNeedles numNeedls
begin
set inCircle = 0
for Needles in call xrange 1 numNeedls + 1
begin
set x = random
set y = random
if x * ... | import random
def stdDev(X):
mean=float(sum(X))/len(X)
tot=0.0
for x in X:
tot+=(x-mean)**2
return (tot/len(X))**0.5
def throwNeedles(numNeedls):
inCircle=0
for Needles in xrange(1,numNeedls+1):
x=random.random()
y=random.random()
if (x*x+y*y)**0.5<=1.0:
... | Python | zaydzuhri_stack_edu_python |
for x in ans
begin
set gop = gop * x
end
print gop % m | for x in ans:
gop *= x
print(gop%m)
| Python | zaydzuhri_stack_edu_python |
import threading
from queue import Queue
class CrawlThread extends Thread
begin
function __init__ self threadName
begin
comment 继承父类属性的同时,并且拓展父类的属性
call __init__
set threadName = threadName
pass
end function
function run self
begin
pass
end function
end class
class ParseThread extends Thread
begin
pass
end class
functi... | import threading
from queue import Queue
class CrawlThread(threading.Thread):
def __init__(self,threadName):
# 继承父类属性的同时,并且拓展父类的属性
super().__init__()
self.threadName=threadName
pass
def run(self):
pass
class ParseThread(threading.Thread):
pass
def main():
page... | Python | zaydzuhri_stack_edu_python |
function _help
begin
string Display both SQLAlchemy and Python help statements
set statement = string %s%s % tuple shelp phelp % join string , keys cntx_
end function | def _help():
""" Display both SQLAlchemy and Python help statements """
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys())) | Python | jtatman_500k |
comment Highly Divisible Triangular Number
comment The sequence of triangle numbers is generated by adding the natural numbers.
comment So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
comment The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
comment Let us list the factors of th... | # Highly Divisible Triangular Number
#
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numb... | Python | zaydzuhri_stack_edu_python |
import sys
function solve n m strings
begin
pass
end function
set lines = read lines stdin
set tuple n m = split lines at 0
set strings = list *map(str.strip, lines[1:])
call solve n m strings | import sys
def solve(n,m,strings):
pass
lines=sys.stdin.readlines()
n,m=lines[0].split()
strings=[*map(str.strip,lines[1:])]
solve(n,m,strings) | Python | zaydzuhri_stack_edu_python |
function dequeue self
begin
return pop items
end function | def dequeue(self):
return self.items.pop() | Python | nomic_cornstack_python_v1 |
function load_array file
begin
set array = list
with open file string r as ints
begin
for line in ints
begin
set t = split strip line
for x in t
begin
append array integer x
end
end
end
return array
end function
function merge_sort array1 array2
begin
set tuple i j D Z = tuple 0 0 list 0
set tuple B C = tuple array1 ... | def load_array(file):
array = []
with open(file,'r') as ints:
for line in ints:
t = line.strip().split()
for x in t:
array.append(int(x))
return array
def merge_sort(array1,array2):
i,j,D,Z = 0,0,[],0
B,C = array1,a... | Python | zaydzuhri_stack_edu_python |
function materials self
begin
return _materials
end function | def materials(self):
return self._materials | Python | nomic_cornstack_python_v1 |
from table import Table
from issue_status import IssueStatus
from member import Member
from book import Book
class ReturnStatus extends Table
begin
set _table_name = string ReturnStatus
set _table_pk = string return_id
function __init__ self data
begin
assert length data == 5 msg string in { _table_name } : expected 5 ... | from .table import Table
from .issue_status import IssueStatus
from .member import Member
from .book import Book
class ReturnStatus(Table):
_table_name = 'ReturnStatus'
_table_pk = 'return_id'
def __init__(self, data: list):
assert len(data) == 5, f'in {self._table_name}: expected 5 data, got {le... | Python | zaydzuhri_stack_edu_python |
function create_bulk cls name interfaces=none primary_mgt=none backup_mgt=none log_server_ref=none domain_server_address=none location_ref=none default_nat=false enable_antivirus=false enable_gti=false sidewinder_proxy_enabled=false enable_ospf=false ospf_profile=none comment=none snmp=none **kw
begin
set physical_inte... | def create_bulk(cls, name, interfaces=None,
primary_mgt=None, backup_mgt=None,
log_server_ref=None,
domain_server_address=None,
location_ref=None, default_nat=False,
enable_antivirus=False, enable_gti=False,
... | Python | nomic_cornstack_python_v1 |
import base64
import json
import urllib.request
set tweet = string Paste hier de minifiede Tweet! | import base64
import json
import urllib.request
tweet = r'''Paste hier de minifiede Tweet!'''
| Python | zaydzuhri_stack_edu_python |
string Created by ysBach 2017-12-21
from matplotlib import pyplot as plt
import matplotlib as mpl
import goodnotes4_template.core as gc
comment =============================================================================
comment Parameters
comment =======================================================================... | """
Created by ysBach
2017-12-21
"""
from matplotlib import pyplot as plt
import matplotlib as mpl
import goodnotes4_template.core as gc
# =============================================================================
# Parameters
# =============================================================================
OUTPUT ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment this Lambda Deregisters AMI and deletes Snapshots (optional)
import boto3
import pprint
set delete_snap = true
set regionSource = string eu-west-1
set client = call client string ec2 region_name=regionSource
set counter = 0
set filters = list dict string Name string tag:AmiStage2Ve... | #!/usr/bin/env python3
# this Lambda Deregisters AMI and deletes Snapshots (optional)
import boto3
import pprint
delete_snap = True
regionSource = 'eu-west-1'
client = boto3.client('ec2', region_name=regionSource)
counter = 0
filters=[
{'Name': 'tag:AmiStage2Version', 'Values': ['2']},
{'Name': 'tag:... | Python | zaydzuhri_stack_edu_python |
function T N A
begin
set t = 1
for i in range N
begin
if A at i % 2 == 1
begin
set t = 0
end
end
return t
end function
function W b
begin
return b / 2
end function
set N = integer input
set A = list map int split input
set count = 0
set t = t dist N A
while t == 1
begin
set A = list map W A
set count = count + 1
set t ... | def T(N,A):
t = 1
for i in range(N):
if A[i]%2 == 1:
t = 0
return t
def W(b):
return b/2
N = int(input())
A = list(map(int,input().split()))
count = 0
t = T(N,A)
while t == 1:
A = list(map(W,A))
count += 1
t = T(N,A)
print(count)
| Python | zaydzuhri_stack_edu_python |
comment Dates
import datetime
set x = now
set y = today
print string la fecha es: { x }
print y | ###Dates
import datetime
x = datetime.datetime.now()
y = datetime.datetime.today()
print(f"la fecha es: {x}")
print(y) | Python | zaydzuhri_stack_edu_python |
function testJunkAfterAll self
begin
set rec = string v=spf1 ip4:213.5.39.110 -all MS=83859DAEBD1978F9A7A67D3
set domain = string avd.dk
set parsed_record = call parse_spf_record rec domain
assert equal length parsed_record at string warnings 1
end function | def testJunkAfterAll(self):
rec = "v=spf1 ip4:213.5.39.110 -all MS=83859DAEBD1978F9A7A67D3"
domain = "avd.dk"
parsed_record = checkdmarc.parse_spf_record(rec, domain)
self.assertEqual(len(parsed_record["warnings"]), 1) | Python | nomic_cornstack_python_v1 |
function GetNext self item
begin
set i = item
comment First see if there are any children.
set children = call GetChildren
if length children > 0
begin
return children at 0
end
else
begin
comment Try a sibling of this or ancestor instead
set p = item
set toFind = none
while p and not toFind
begin
set toFind = call GetN... | def GetNext(self, item):
i = item
# First see if there are any children.
children = i.GetChildren()
if len(children) > 0:
return children[0]
else:
# Try a sibling of this or ancestor instead
p = item
toFind = None
... | Python | nomic_cornstack_python_v1 |
comment !/bin/python
comment coding='gbk
from socket import *
import json
class Comm
begin
function __init__ self host port bufsize
begin
set mHost = host
set mPort = port
set mBufsize = bufsize
set mTcpClientSock = none
end function
function conn_to_master self
begin
set ADDR = tuple mHost mPort
set mTcpClientSock = c... | #!/bin/python
#coding='gbk
from socket import *
import json
class Comm:
def __init__(self,host,port,bufsize):
self.mHost = host
self.mPort = port
self.mBufsize = bufsize
self.mTcpClientSock = None
def conn_to_master(self):
ADDR = (self.mHost, self.mPort)
self.... | Python | zaydzuhri_stack_edu_python |
function make_expr_mapping maps default_color=tuple 0 0 0
begin
comment find exact matches and expressions
set exacts = dict
set exps = list
for tuple key val in maps
begin
if string * not in key
begin
set exacts at key = val
end
else
begin
append exps tuple key val
end
end
comment create mapping function
function ma... | def make_expr_mapping(maps, default_color=(0, 0, 0)):
# find exact matches and expressions
exacts = {}
exps = []
for key, val in maps:
if "*" not in key:
exacts[key] = val
else:
exps.append((key, val))
# create mapping function
def mapping(key):
... | Python | nomic_cornstack_python_v1 |
function run
begin
run
call clean_temp_directories
end function | def run():
init_runner.run()
clean_temp_directories() | Python | nomic_cornstack_python_v1 |
class Question extends object
begin
function __init__ self questionID questionText ans1 ans2 ans3 ans4 rightAns
begin
set questionID = questionID
set questionText = questionText
set ans1 = ans1
set ans2 = ans2
set ans3 = ans3
set ans4 = ans4
set rightAns = rightAns
end function
function get_questionID self
begin
return... | class Question(object):
def __init__(self, questionID, questionText, ans1, ans2, ans3, ans4, rightAns):
self.questionID = questionID
self.questionText = questionText
self.ans1 = ans1
self.ans2 = ans2
self.ans3 = ans3
self.ans4 = ans4
self.rightAns = rightAns
... | Python | zaydzuhri_stack_edu_python |
function send_cmd_callback self evt
begin
call send_cmd
end function | def send_cmd_callback(self, evt):
self.send_cmd() | Python | nomic_cornstack_python_v1 |
function timeseries_json site_id variable_id value date
begin
return dict KEY_SITE_ID site_id ; KEY_VARIABLE_ID variable_id ; KEY_VALUE value ; KEY_DATE date ; KEY_DST_TIMEZONE tzname at 1 ; KEY_NON_DST_TIMEZONE tzname at 0
end function | def timeseries_json(site_id, variable_id, value, date):
return {
KEY_SITE_ID: site_id,
KEY_VARIABLE_ID: variable_id,
KEY_VALUE: value,
KEY_DATE: date,
KEY_DST_TIMEZONE: tzname[1],
KEY_NON_DST_TIMEZONE: tzname[0]
} | Python | nomic_cornstack_python_v1 |
function __init__ self parent
begin
set gwDict = dict
comment new tls data incomming flag.
set tlsFlag = false
set terminate = false
comment tcp latency from host computer to google
set latency = 0.0001
set client = call InfluxCli ipAddr=tuple string localhost 8086 dbInfo=tuple string root string root string gatewayDB... | def __init__(self, parent):
self.gwDict = {}
self.tlsFlag = False # new tls data incomming flag.
self.terminate = False
self.latency = 0.0001 # tcp latency from host computer to google
self.client = InfluxCli(
ipAddr=('localhost', 8086), dbInfo=('root', 'root', '... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
print string --------- Task One ---------
set my_tuple = tuple 2 123.4567 10000 12345.67
print format string file_{:03d}: {:.2f}, {:.2e}, {:.2e} *my_tuple
print string --------- Task Two ---------
print string file_ { my_tuple at 0 } : { my_tuple at 1 } , { my_tuple at 2 } , { my_tuple at ... | #!/usr/bin/env python3
print("\n--------- Task One ---------")
my_tuple = (2, 123.4567, 10000, 12345.67)
print("file_{:03d}: {:.2f}, {:.2e}, {:.2e}".format(*my_tuple))
print("\n--------- Task Two ---------")
print(f"file_{my_tuple[0]:03d}: {my_tuple[1]:.2f}, {my_tuple[2]:.2e}, "
f"{my_tuple[3]:.2e}")
p... | Python | zaydzuhri_stack_edu_python |
from pprint import pprint
from collections import deque
from hashlib import md5
class CustomFile extends file
begin
function __eq__ self other
begin
return hex digest md5 read self == hex digest md5 read other
end function
function __lshift__ self other
begin
set temp = list
set count = 1
while count <= other
begin
ap... | from pprint import pprint
from collections import deque
from hashlib import md5
class CustomFile(file):
def __eq__(self, other):
return \
md5(self.read()).hexdigest() == \
md5(other.read()).hexdigest()
def __lshift__(self, other):
temp = []
count = 1
wh... | Python | zaydzuhri_stack_edu_python |
class Grid
begin
function __init__ self
begin
set cubes = dict
end function
function register self cube
begin
if parent != self
begin
set parent = self
end
set cubes = cubes ? dict position cube
return cube
end function
function register_from_file self filepath corner_coord=none
begin
with open filepath string r as f
... | class Grid():
def __init__(self):
self.cubes = {}
def register(self, cube):
if cube.parent != self:
cube.parent = self
self.cubes |= {cube.position: cube}
return cube
def register_from_file(self, filepath, corner_coord=None):
with open(filepath, "r") as ... | Python | zaydzuhri_stack_edu_python |
function items self
begin
string return all the app_names and their values as tuples
set sql = string SELECT app_name, next_run, first_run, last_run, last_success, depends_on, error_count, last_error FROM crontabber
set columns = tuple string app_name string next_run string first_run string last_run string last_success... | def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
first_run,
last_run,
last_success,
depends_on,
error_count,
... | Python | jtatman_500k |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Apr 12 11:24:42 2017 @author: SteveJSmith1
class Solution extends object
begin
function trailingZeroes self n
begin
string Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time c... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 12 11:24:42 2017
@author: SteveJSmith1
"""
class Solution(object):
def trailingZeroes(self, n):
"""
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time comple... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
string https://projecteuler.net/problem=67 https://www.hackerrank.com/contests/projecteuler/challenges/euler067 https://projecteuler.net/problem=18 https://www.hackerrank.com/contests/projecteuler/challenges/euler018 tag_knapsack, tag_dynamic
import sys
import time
set TRIANGLE_SIMPLE = string 3 7... | #!/bin/python3
'''
https://projecteuler.net/problem=67
https://www.hackerrank.com/contests/projecteuler/challenges/euler067
https://projecteuler.net/problem=18
https://www.hackerrank.com/contests/projecteuler/challenges/euler018
tag_knapsack, tag_dynamic
'''
import sys
import time
TRI... | Python | zaydzuhri_stack_edu_python |
function getSN self conditions
begin
while true
begin
set sns = list
for _ in range SN_REDUNDANCY
begin
if not sns
begin
set sn_in = input string Enter a SN:
end
else
begin
set sn_in = input string Repeat the SN:
end
if sn_in in list string q string quit string end
begin
return
end
if not all generator expression cond... | def getSN(self, conditions: List[Function[[int], bool]]) -> Optional[int]:
while True:
sns = []
for _ in range(SN_REDUNDANCY):
if not sns:
sn_in = input('Enter a SN: ')
else:
sn_in = input('Repeat the SN: ')
... | Python | nomic_cornstack_python_v1 |
comment 037-3.py
set n = 144
print n ^ 0.5 | #037-3.py
n = 144
print(n**0.5)
| Python | zaydzuhri_stack_edu_python |
function gnss_data self
begin
return _gnss_data
end function | def gnss_data(self) -> List[TripGnssData]:
return self._gnss_data | Python | nomic_cornstack_python_v1 |
async function _missing_storage_hashes self address_hash_nibbles storage_root starting_main_root
begin
if storage_root == BLANK_NODE_HASH
begin
comment Nothing to do if the storage has an empty root
return
end
set storage_tracker = call _get_storage_tracker address_hash_nibbles
while is_running
begin
set storage_iterat... | async def _missing_storage_hashes(
self,
address_hash_nibbles: Nibbles,
storage_root: Hash32,
starting_main_root: Hash32) -> AsyncIterator[TrackedRequest]:
if storage_root == BLANK_NODE_HASH:
# Nothing to do if the storage has an empty root
... | Python | nomic_cornstack_python_v1 |
import socket
set TIMEOUT = 5
function get_ipv4
begin
try
begin
with call socket AF_INET SOCK_DGRAM as s
begin
call settimeout TIMEOUT
call connect tuple string 8.8.8.8 80
return call getsockname at 0
end
end
except Exception
begin
return none
end
end function
function get_ipv6
begin
try
begin
with call socket AF_INET6... | import socket
TIMEOUT = 5
def get_ipv4() -> str:
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(TIMEOUT)
s.connect(('8.8.8.8', 80))
return s.getsockname()[0]
except Exception:
return None
def get_ipv6() -> str:
try:
... | Python | zaydzuhri_stack_edu_python |
function delete
begin
set post_id = get args string id
set connection = call connect string blog.sqlite
if not post_id
begin
return string <h1>Ошибка. Вы не ввели номер поста "id"</>
end
set cursor = call cursor
execute cursor string DELETE FROM posts WHERE Id = ? post_id
commit connection
close connection
return call ... | def delete():
post_id = request.args.get('id')
connection = sqlite3.connect('blog.sqlite')
if not post_id:
return '<h1>Ошибка. Вы не ввели номер поста "id"</>'
cursor = connection.cursor()
cursor.execute('DELETE FROM posts WHERE Id = ?', post_id)
connection.commit()
connection.close(... | Python | nomic_cornstack_python_v1 |
function get_case_and_institute adapter case_id institute
begin
if institute
begin
return tuple case_id institute
end
set split_case = split case_id string -
set institute_id = none
if length split_case > 1
begin
set institute_id = split_case at 0
set institute_obj = call institute institute_id
if institute_obj
begin
s... | def get_case_and_institute(
adapter: MongoAdapter, case_id: str, institute: Optional[str]
) -> (str, str):
if institute:
return case_id, institute
split_case = case_id.split("-")
institute_id = None
if len(split_case) > 1:
institute_id = split_case[0]
institute_obj = adapter... | Python | nomic_cornstack_python_v1 |
function test_motion_wheels_back self
begin
call set_rpm - VESC_RPM_SLOW
call start_moving
call wait_for_stop
end function | def test_motion_wheels_back(self):
self.vesc.set_rpm(-config.VESC_RPM_SLOW)
self.vesc.start_moving()
self.vesc.wait_for_stop() | Python | nomic_cornstack_python_v1 |
function disconnect_lowest_ecc G num_remove
begin
set num_removed = list
set spectral_gap = list
set g = copy G
set vs = random choice list call nodes num_remove replace=false
for tuple i v in enumerate vs
begin
set neighbors = list call neighbors v
if length neighbors == 0
begin
continue
end
set ecc = array list com... | def disconnect_lowest_ecc(G, num_remove):
num_removed = []
spectral_gap = []
g = G.copy()
vs = np.random.choice(list(g.nodes()), num_remove, replace=False)
for i, v in enumerate(vs):
neighbors = list(g.neighbors(v))
if len(neighbors) == 0:
continue
ecc = np.array... | Python | nomic_cornstack_python_v1 |
function get_size self location context=none
begin
set loc = store_location
comment if there is a pool specific in the location, use it; otherwise
comment we fall back to the default pool specified in the config
set target_pool = pool or pool
with call get_connection conffile=conf_file rados_id=user as conn
begin
with ... | def get_size(self, location, context=None):
loc = location.store_location
# if there is a pool specific in the location, use it; otherwise
# we fall back to the default pool specified in the config
target_pool = loc.pool or self.pool
with self.get_connection(conffile=self.conf_fi... | Python | nomic_cornstack_python_v1 |
import random
set array = list 1 2 3 4 5 6
comment shuffle list in-place using a random permutation
shuffle random array | import random
array = [1, 2, 3, 4, 5, 6]
random.shuffle(array) # shuffle list in-place using a random permutation
| Python | flytech_python_25k |
import socket
import numpy as np
import time
comment Standard loopback interface address (localhost)
set HOST = string 192.168.56.1
comment Port to listen on (non-privileged ports are > 1023)
set PORT = 65432
set buffer_size = 1024
function minas n
begin
if n == 10
begin
print string Se colocaron 10 minas
set x = rando... | import socket
import numpy as np
import time
HOST = "192.168.56.1" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
buffer_size = 1024
def minas(n):
if n == 10:
print("Se colocaron 10 minas")
x = np.random.randint(1... | Python | zaydzuhri_stack_edu_python |
comment /usr/bin/env python3
string
from application import Application
import json
comment Absolut file path
import os
comment For checking if we have internet connectivity
import socket
import time
class StartContoller extends object
begin
function __init__ self applicationsJSON
begin
set timeZero = time
set applica... | # /usr/bin/env python3
"""
"""
from application import Application
import json
import os # Absolut file path
import socket # For checking if we have internet connectivity
import time
class StartContoller(object):
def __init__(self, applicationsJSON):
self.timeZero = time.time()
self.applications = [Applica... | Python | zaydzuhri_stack_edu_python |
function showNameCarefully self email first_name last_name
begin
if first_name and last_name
begin
return first_name + string + last_name
end
set name = none
if first_name
begin
set name = first_name
end
else
if last_name
begin
set name = last_name
end
if match email
begin
set tuple first_half second_half = split emai... | def showNameCarefully(self, email, first_name, last_name):
if first_name and last_name:
return first_name + ' ' + last_name
name = None
if first_name:
name = first_name
elif last_name:
name = last_name
if COMMON_EMAIL_DOMA... | Python | nomic_cornstack_python_v1 |
function test_valid_distribution_info_keys self
begin
set valid_distrib_obj = dict string distribution_type string cpu ; string worker_cost true ; string platform_cost true
set ocp_data at string distribution_info = valid_distrib_obj
assert equal ocp_data at string distribution_info valid_distrib_obj
with call tenant_c... | def test_valid_distribution_info_keys(self):
valid_distrib_obj = {"distribution_type": "cpu", "worker_cost": True, "platform_cost": True}
self.ocp_data["distribution_info"] = valid_distrib_obj
self.assertEqual(self.ocp_data["distribution_info"], valid_distrib_obj)
with tenant_context(se... | Python | nomic_cornstack_python_v1 |
function load_config parser args cfgparser=none
begin
if cfgparser is none
begin
set cfgparser = call SafeConfigParser
end
set full_config = call _default_cmd_line_options parser args
set cfg_values = call load_config_from_config_file cfgparser section keys variables args + SECRET_KEYS
set cmd_line_cfg_values = call _n... | def load_config(parser, args, cfgparser=None):
if cfgparser is None:
cfgparser = SafeConfigParser()
full_config = _default_cmd_line_options(parser, args)
cfg_values = load_config_from_config_file(cfgparser, args.section,
vars(args).keys()+ SECRET_KEYS)
... | Python | nomic_cornstack_python_v1 |
function comp_from_ics x_init modes
begin
set a = x_init @ modes at tuple slice : : 0
set b = x_init @ modes at tuple slice : : 1
return tuple a b
end function | def comp_from_ics(x_init, modes):
a = x_init @ modes[:,0]
b = x_init @ modes[:,1]
return a,b | Python | nomic_cornstack_python_v1 |
function on_activation self battle entity
begin
pass
end function | def on_activation(self, battle: Battle, entity: StattedEntity):
pass | Python | nomic_cornstack_python_v1 |
function normalize_rir rir
begin
comment busco el valor maximo
set index_max = argument maximum absolute rir
comment Normalizo
set rir = rir / rir at index_max
comment Elimino el delay
comment rir = rir[index_max:]
return rir
end function | def normalize_rir(rir):
#busco el valor maximo
index_max = np.argmax(abs(rir))
#Normalizo
rir = rir / rir[index_max]
#Elimino el delay
#rir = rir[index_max:]
return rir | 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.