code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Feb 23 13:08:56 2019 @author: harman
string ADD MORE PREPROCESSING AS NECESSARY
import numpy as np
import random
import keras
import cv2
comment returns the samples and the labels in two numpy arrays
comment combine part of the mouse data... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 23 13:08:56 2019
@author: harman
"""
'''
ADD MORE PREPROCESSING AS NECESSARY
'''
import numpy as np
import random
import keras
import cv2
#returns the samples and the labels in two numpy arrays
#combine part of the mouse dataset with the frui... | Python | zaydzuhri_stack_edu_python |
function upload_to_database table files_dir filename func
begin
set host = environ at string MYSQL_HOST
set schema = environ at string MYSQL_SCHEMA
set user = environ at string MYSQL_USER
set password = environ at string MYSQL_PASSWORD
set connection_string = string mysql+mysqldb:// { user } : { password } @ { host } /... | def upload_to_database(table, files_dir, filename, func):
host = os.environ['MYSQL_HOST']
schema = os.environ['MYSQL_SCHEMA']
user = os.environ['MYSQL_USER']
password = os.environ['MYSQL_PASSWORD']
connection_string = f"mysql+mysqldb://{user}:{password}@{host}/{schema}"
my_conn = create_engine... | Python | nomic_cornstack_python_v1 |
function ViewTranslateminusy self
begin
return call InvokeTypes 65627 LCID 1 tuple 24 0 tuple
end function | def ViewTranslateminusy(self):
return self._oleobj_.InvokeTypes(65627, LCID, 1, (24, 0), (),) | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
import matplotlib.pyplot as plt
from google.colab import files
set simlen = 10000
set count = 0.0
set theoretical = 0.85556
for i in range simlen
begin
set value = random integer 10 99
if value % 7 != 0
begin
set count = count + 1
end
end
set simulated = count / simlen
print string Fina... | import numpy as np
import random
import matplotlib.pyplot as plt
from google.colab import files
simlen = 10000
count = 0.0
theoretical = 0.85556
for i in range(simlen):
value = random.randint(10, 99)
if(value % 7 != 0):
count = count + 1
simulated = count/simlen
print("Final answer (simluated): " ... | Python | zaydzuhri_stack_edu_python |
import unittest
from employee import Employee
class TestEmployee extends TestCase
begin
string Tests for the class Employee
function setUp self
begin
string Create base employee.
set employee = call Employee string Nelson string Ripoll 50000
end function
function test_give_default_raise self
begin
string Give raise usi... | import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Tests for the class Employee"""
def setUp(self):
"""Create base employee."""
self.employee = Employee("Nelson", "Ripoll", 50000)
def test_give_default_raise(self):
"""Give raise using default a... | Python | zaydzuhri_stack_edu_python |
function reshape self X y
begin
set X = reshape X tuple shape at 0 integer shape at 1 / l_subseq n_row n_col n_feature
set y = reshape y tuple shape at 0 n_col 1
return tuple X y
end function | def reshape(self, X: np.ndarray, y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
X = X.reshape((X.shape[0], int(X.shape[1]/self.l_subseq),
self.n_row, self.n_col, self.n_feature
))
y = y.reshape((y.shape[0], self.n_col, 1))
return X, y | Python | nomic_cornstack_python_v1 |
class Solution
begin
comment @param A : integer
comment @return a list of list of strings
function solveNQueens self n
begin
set output = list
function dfs row queens diags
begin
if row == n
begin
append output list comprehension string . * x + string Q + string . * n - x - 1 for x in queens
return
end
for col in rang... | class Solution:
# @param A : integer
# @return a list of list of strings
def solveNQueens(self, n):
output = []
def dfs(row, queens, diags):
if row == n:
output.append(['.'*x + 'Q' + '.'*(n-x-1) for x in queens])
return
for col in range... | Python | zaydzuhri_stack_edu_python |
function generate_data self length size
begin
return list comprehension join string generator expression random choice ascii_letters + digits for _ in range length for _ in range size
end function | def generate_data(self, length, size):
return [''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) for _ in range(size)] | Python | nomic_cornstack_python_v1 |
function _input_flux_type self pool_to
begin
set sv = state_vector at pool_to
comment we compute the derivative of the appropriate row of the input vector w.r.t. all the state variables
comment (This is a row of the jacobian)
set u_i = call Matrix list external_inputs at pool_to
set s_v = call Matrix state_vector
set J... | def _input_flux_type(self, pool_to):
sv = self.state_vector[pool_to]
# we compute the derivative of the appropriate row of the input vector w.r.t. all the state variables
# (This is a row of the jacobian)
u_i=Matrix([self.external_inputs[pool_to]])
s_v=Matrix(self.state_vector)... | Python | nomic_cornstack_python_v1 |
function load_img img_filename
begin
set img = call TiffFile img_filename
set img_mat = as type call get_tiff_array at 0 float32 at tuple newaxis slice : :
return img_mat
end function | def load_img(img_filename):
img = libtiff.TiffFile(img_filename)
img_mat = img.get_tiff_array()[0].astype(np.float32)[np.newaxis, :]
return img_mat | Python | nomic_cornstack_python_v1 |
function normalize_observation observation tree_depth observation_radius=0
begin
if observation is none
begin
return zeros 11 * sum generator expression call power 4 i for i in range tree_depth + 1 dtype=float32
end
set tuple data distance agent_data = call split_tree_into_feature_groups observation tree_depth
set data... | def normalize_observation(
observation: Node, tree_depth: int, observation_radius: int = 0
) -> np.ndarray:
if observation is None:
return np.zeros(
11 * sum(np.power(4, i) for i in range(tree_depth + 1)), dtype=np.float32
)
data, distance, agent_data = split_tree_into_feature_gr... | Python | nomic_cornstack_python_v1 |
function ComBat_preproc_ff_covariates train_df test_dfs covariates
begin
comment train
for cov in covariates
begin
set train_df = call forward_filling train_df cov
end
comment tests
set filled_test_dfs = list
for test_df in test_dfs
begin
for cov in covariates
begin
set test_df = call forward_filling test_df cov
end
a... | def ComBat_preproc_ff_covariates(train_df, test_dfs, covariates):
# train
for cov in covariates:
train_df = forward_filling(train_df, cov)
# tests
filled_test_dfs = []
for test_df in test_dfs:
for cov in covariates:
test_df = forward_filling(test_df, cov)
filled_t... | Python | nomic_cornstack_python_v1 |
function get_matcher self
begin
from translate.search import match
comment FIXME: should we cache this?
set matcher = call matcher self max_candidates=1 max_length=FUZZY_MATCH_MAX_LENGTH min_similarity=FUZZY_MATCH_MIN_SIMILARITY usefuzzy=true
call extendtm filter state=OBSOLETE
set addpercentage = false
return matcher
... | def get_matcher(self):
from translate.search import match
#FIXME: should we cache this?
matcher = match.matcher(
self,
max_candidates=1,
max_length=settings.FUZZY_MATCH_MAX_LENGTH,
min_similarity=settings.FUZZY_MATCH_MIN_SIMILARITY,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Nov 20 18:20:22 2019 @author: dbosami2
import pandas as pd
set data = read csv string airquality.csv
set data_melt = call melt data id_vars=list string Month string Day var_name=string measurement value_name=string reading
comment print(data_melt)
set data_pivot = cal... | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 18:20:22 2019
@author: dbosami2
"""
import pandas as pd
data=pd.read_csv('airquality.csv')
data_melt=pd.melt(data, id_vars=['Month','Day'],var_name='measurement', value_name='reading')
#print(data_melt)
data_pivot=data_melt.pivot_table(index=['Month','Day'], colum... | Python | zaydzuhri_stack_edu_python |
function list_loaded_applications self to_dictionary=false **filters
begin
return call _list_loaded_applications connection=connection to_dictionary=to_dictionary keyword filters
end function | def list_loaded_applications(self, to_dictionary: bool = False,
**filters) -> Union[List["Application"], List[dict]]:
return Application._list_loaded_applications(
connection=self.connection,
to_dictionary=to_dictionary,
**filters,
) | Python | nomic_cornstack_python_v1 |
string Invert Values Level: 8 kyu Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] You can assume that all values are integers.
function inver... | '''
Invert Values
Level: 8 kyu
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
You can assume that all values are integers.
'''
def invert(... | Python | zaydzuhri_stack_edu_python |
function test_send_individual_email_error mocker raise_for_status mock_post mocked_json
begin
set return_value = call Mock spec=Response status_code=HTTP_400_BAD_REQUEST json=mocked_json
set response = call send_individual_email subject=string email subject body=string email body recipient=string a@example.com raise_fo... | def test_send_individual_email_error(mocker, raise_for_status, mock_post, mocked_json):
mock_post.return_value = mocker.Mock(
spec=Response, status_code=HTTP_400_BAD_REQUEST, json=mocked_json
)
response = MailgunClient.send_individual_email(
subject="email subject",
body="email body... | Python | nomic_cornstack_python_v1 |
from typing import List
from collections import Counter
string https://www.cnblogs.com/grandyang/p/4606822.html Moore Voting Time: O(n) Space: O(1)
class Solution
begin
function majorityElement self nums
begin
string Use Moore Voting, so space: O(1)
set tuple res1 cnt1 res2 cnt2 = tuple - 1 0 - 1 0
comment 1. Find firs... | from typing import List
from collections import Counter
'''
https://www.cnblogs.com/grandyang/p/4606822.html
Moore Voting
Time: O(n)
Space: O(1)
'''
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
"Use Moore Voting, so space: O(1)"
res1, cnt1, res2, cnt2 = -1, 0, -1, 0
... | Python | zaydzuhri_stack_edu_python |
function shellExecErrorCode cmd
begin
return call cmd shell=true
end function | def shellExecErrorCode(cmd):
return subprocess.call(cmd, shell=True) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function plusOne self digits
begin
string :type digits: List[int] :rtype: List[int]
set outList = list
set length = length digits
if digits at - 1 != 9
begin
set digits at - 1 = digits at - 1 + 1
return digits
end
set carryOver = true
append outList 0
for i in call xrange 1 length
b... | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
outList = []
length = len(digits)
if digits[-1] != 9:
digits[-1] += 1
return digits
carryOver = True
outList.append(0)
... | Python | zaydzuhri_stack_edu_python |
function get_default_config self
begin
set config = call get_default_config
update config dict string enabled string True ; string devices string PhysicalDrive[0-9]+$ + string |md[0-9]+$ + string |sd[a-z]+[0-9]*$ + string |x?vd[a-z]+[0-9]*$ + string |disk[0-9]+$ + string |dm\-[0-9]+$ ; string fs_types join string , SUP... | def get_default_config(self):
config = super(DiskHealthCollector, self).get_default_config()
config.update({
'enabled': 'True',
'devices': ('PhysicalDrive[0-9]+$'
+ '|md[0-9]+$'
+ '|sd[a-z]+[0-9]*$'
+ '|... | Python | nomic_cornstack_python_v1 |
function version_guids
begin
return call text alphabet=hexdigits min_size=24 max_size=24
end function | def version_guids():
return strategies.text(alphabet=string.hexdigits, min_size=24, max_size=24) | Python | nomic_cornstack_python_v1 |
function obtain_access_token self token verifier
begin
set oauth_request = call from_consumer_and_token consumer token=token http_url=access_token_url verifier=verifier
call sign_request signature_method_hmac_sha1 consumer token
set token = call fetch_access_token oauth_request
return token
end function | def obtain_access_token(self, token, verifier):
self.oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
token=token,
http_url=self.client.access_token_url,
verifier=v... | Python | nomic_cornstack_python_v1 |
comment 一个班级有一个花名册,存在列表里面
comment while 控制循环
comment 语法:
comment while 条件表达式: # 逻辑 成员 比较 孔书记 布尔值
comment 代码块
comment 执行规律:首先判断while 后面的条件表达式是否成立
comment 如果True 那就执行代码块,执行完毕后,继续判断--->如果True 那就执行代码块...
comment 否则 不进入内部 执行代码块
comment a=1
comment while a<=10:
comment print("现在是输入的第{0}次".format(a))
comment a+=1
comment sum=... | # 一个班级有一个花名册,存在列表里面
# while 控制循环
# 语法:
# while 条件表达式: # 逻辑 成员 比较 孔书记 布尔值
# 代码块
#
# 执行规律:首先判断while 后面的条件表达式是否成立
# 如果True 那就执行代码块,执行完毕后,继续判断--->如果True 那就执行代码块...
# 否则 不进入内部 执行代码块
# a=1
# while a<=10:
# print("现在是输入的第{0}次".format(a))
# a+=1
# sum=0 # 求和初始值
# # a=1 # 循环的起始值
i=1
sum=0
while i<=10:... | Python | zaydzuhri_stack_edu_python |
function constructFromFenString self fenString
begin
set bitboards = call BitBoardsFromFenString fenString
set fenPieces = call groups
set turnString = fenPieces at 8
set castleString = fenPieces at 9
if turnString == string b
begin
set turn = BLACK
end
else
begin
set turn = WHITE
end
set enpassantString = fenPieces at... | def constructFromFenString(self, fenString):
self.bitboards = BitBoardsFromFenString(fenString)
fenPieces = re.match(FENParseString, fenString).groups()
turnString = fenPieces[8]
castleString = fenPieces[9]
if turnString == "b":
self.turn = Turn.BLACK
else:
... | Python | nomic_cornstack_python_v1 |
function get_layer_arns bosslet_config layer_dirs
begin
set client = call client string lambda
set layers = list
for layer_dir in layer_dirs
begin
set layer_config = call load_lambda_config layer_dir
set layer_name = replace layer_config at string name + string . + INTERNAL_DOMAIN string . string -
set resp = call lis... | def get_layer_arns(bosslet_config, layer_dirs):
client = bosslet_config.session.client('lambda')
layers = []
for layer_dir in layer_dirs:
layer_config = load_lambda_config(layer_dir)
layer_name = (layer_config['name'] + '.' + bosslet_config.INTERNAL_DOMAIN).replace('.', '-')
resp =... | Python | nomic_cornstack_python_v1 |
function bland_altman_plot result reference save=false dest_path=get current directory + string / filename=string bland_altman_plot.png
begin
print string Checking that result and reference are 1D and that they have the same length
if length shape == 1 and length shape == 1
begin
if length result == length reference
be... | def bland_altman_plot(result, reference, save = False, dest_path = os.getcwd() + '/', filename = 'bland_altman_plot.png'):
print('\nChecking that result and reference are 1D and that they have the same length\n')
if (len(result.shape) == 1) and (len(reference.shape) == 1):
if len(resu... | Python | nomic_cornstack_python_v1 |
function get_total_lane_volume self
begin
if type _total_lane_volume != int
begin
write _logger string Error! total_lane_volume must be of type int
end
else
if _total_lane_volume == none
begin
write _logger string Error! total_lane_volume contains no value
end
else
begin
try
begin
return _total_lane_volume
end
except E... | def get_total_lane_volume(self):
if(type(self._total_lane_volume) != int):
self._logger.write("Error! total_lane_volume must be of type int")
elif(self._total_lane_volume == None):
self._logger.write("Error! total_lane_volume contains no value")
else:
try:
... | Python | nomic_cornstack_python_v1 |
import pyecharts
from pyecharts.charts import Bar
comment print(pyecharts.__version__)
set bar = bar
call add_xaxis list string 衬衫 string 羊毛衫 string 裤子 string 袜子
call add_yaxis string 商家 list 5 20 45 32
call render | import pyecharts
from pyecharts.charts import Bar
# print(pyecharts.__version__)
bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "裤子", "袜子"])
bar.add_yaxis("商家", [5, 20, 45, 32])
bar.render() | Python | zaydzuhri_stack_edu_python |
function configure_logger verbosity
begin
set logging_parameters = VERBOSITY_LOGGING_PARAMETERS at verbosity
comment create logger and set level
set logger = call getLogger name
call setLevel level
comment create console handler and set level
set handler = call StreamHandler
call setLevel level
comment create formatter... | def configure_logger(verbosity):
logging_parameters = VERBOSITY_LOGGING_PARAMETERS[verbosity]
# create logger and set level
logger = logging.getLogger(logging_parameters.name)
logger.setLevel(logging_parameters.level)
# create console handler and set level
handler = logging.StreamHandler()
... | Python | nomic_cornstack_python_v1 |
from pandas import *
from bs4 import BeautifulSoup
set desc = list
set job_requirement = list
set data_frame = read csv string wuzzuf.csv encoding=string ISO-8859-1
for tuple index row in call iterrows
begin
set soup = call BeautifulSoup row at string description string lxml
set soup2 = call BeautifulSoup row at stri... | from pandas import *
from bs4 import BeautifulSoup
desc = []
job_requirement = []
data_frame = pandas.read_csv("wuzzuf.csv",encoding="ISO-8859-1")
for index, row in data_frame.iterrows():
soup = BeautifulSoup(row['description'],"lxml")
soup2 = BeautifulSoup(row['job_requirements'], "lxml")
... | Python | zaydzuhri_stack_edu_python |
function find_longest_ride arr
begin
set max_duration = 0
for i in range length arr
begin
for j in range i + 1 length arr
begin
set duration = arr at j - arr at i
if duration > max_duration
begin
set max_duration = duration
end
end
end
return max_duration
end function
comment Main Program
set arr = list 9.0 9.4 9.5 11.... | def find_longest_ride(arr):
max_duration = 0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
duration = arr[j] - arr[i]
if duration > max_duration:
max_duration = duration
return max_duration
# Main Program
arr = [9.00, 9.40, 9.50, 11.00, 15.00]
resu... | Python | iamtarun_python_18k_alpaca |
function express_route_gateway_bypass self
begin
return get pulumi self string express_route_gateway_bypass
end function | def express_route_gateway_bypass(self) -> Optional[bool]:
return pulumi.get(self, "express_route_gateway_bypass") | Python | nomic_cornstack_python_v1 |
import turtle
import random
function random_function screen
begin
set lists = list string mobile string panda
set num = random integer 0 1
set func = lists at num
if func == string mobile
begin
call registering_Ans func
call mobile screen
end
else
if func == string panda
begin
call registering_Ans func
call panda scree... | import turtle
import random
def random_function(screen):
lists=['mobile','panda']
num = random.randint(0,1)
func = lists[num]
if func == 'mobile' :
registering_Ans(func)
mobile(screen)
elif func == 'panda' :
registering_Ans(func)
panda(screen)
... | Python | zaydzuhri_stack_edu_python |
function round_date date
begin
assert is instance date Time
if second or microsecond
begin
return date - time delta seconds=second microseconds=microsecond
end
return date
end function | def round_date(date):
assert(isinstance(date, Time))
if date.second or date.microsecond:
return date - datetime.timedelta(seconds=date.second,
microseconds=date.microsecond)
return date | Python | nomic_cornstack_python_v1 |
import multiprocessing
function download q
begin
comment data=[1,2,3,4,5,6,7]
for i in range 1000
begin
put i
end
end function
function analysis q
begin
for i in range 1000
begin
pass
end
while true
begin
set a = get q
print a
if call empty
begin
break
end
end
end function
function main
begin
set q = queue 1000
set p1 ... | import multiprocessing
def download(q):
# data=[1,2,3,4,5,6,7]
for i in range(1000):
q.put(i)
def analysis(q):
for i in range(1000):
pass
while True:
a = q.get()
print(a)
if q.empty():
break
def main():
q = multiprocessing.Queue(1000)
p1 ... | Python | zaydzuhri_stack_edu_python |
from lxml import html
import requests
from bs4 import BeautifulSoup
import pandas as pd
set movie_urls = read open string \Users\Ashley Rodondi\Documents\Spring 2018\MBA 696 MSBA Capstone Project\Capstone Project Final\movieLinks.txt string r
with open string \Users\Ashley Rodondi\Documents\Spring 2018\MBA 696 MSBA Cap... | from lxml import html
import requests
from bs4 import BeautifulSoup
import pandas as pd
movie_urls = open("\\Users\\Ashley Rodondi\\Documents\\Spring 2018\\MBA 696 MSBA Capstone Project\\Capstone Project Final\\movieLinks.txt", "r").read()
with open("\\Users\\Ashley Rodondi\\Documents\\Spring 2018\\MBA 696 MSB... | Python | zaydzuhri_stack_edu_python |
import os
function clear
begin
return call system string clear
end function
function enu input_array
begin
set count = 0
for entry in input_array
begin
print count entry
set count = count + 1
end
end function
function enuT input_class enable_debug=true
begin
string given a class, list all entries within dir(<class>) th... | import os
def clear():
return os.system('clear')
def enu(input_array):
count = 0
for entry in input_array:
print(count, entry)
count += 1
def enuT(input_class, enable_debug = True):
''' given a class, list all entries within dir(<class>) then tell me if its a method or att... | Python | zaydzuhri_stack_edu_python |
function deallocateFlag self pluginName flag
begin
pass
end function | def deallocateFlag(self, pluginName, flag):
pass | Python | nomic_cornstack_python_v1 |
import pytest
from voting import voter
decorator fixture
function turtle_voter
begin
return call Voter list string turtle string tiger string monkey
end function
function test_voter_first_choice_is_best_choice turtle_voter
begin
assert top_choice == string turtle
end function
function test_convert_to_string turtle_vote... | import pytest
from voting import voter
@pytest.fixture
def turtle_voter():
return voter.Voter(["turtle", "tiger", "monkey"])
def test_voter_first_choice_is_best_choice(turtle_voter):
assert turtle_voter.top_choice == "turtle"
def test_convert_to_string(turtle_voter):
assert str(turtle_voter) == "turt... | Python | zaydzuhri_stack_edu_python |
function get_network self project_id name=none network_id=none
begin
set query = dict
if project_id is not none and network_id is none
begin
set query at string tenant_id = project_id
end
if name is not none
begin
set query at string name = name
end
else
if network_id is not none
begin
set query at string id = network... | def get_network(self, project_id, name=None, network_id=None):
query = {}
if project_id is not None and network_id is None:
query["tenant_id"] = project_id
if name is not None:
query["name"] = name
elif network_id is not None:
query["id"] = network_id... | Python | nomic_cornstack_python_v1 |
import chess
import chess.pgn
import tkinter as tk
from PIL import Image , ImageTk
import time
import os
from datetime import datetime , date
import threading
from tkinter.filedialog import asksaveasfile
import globals
function PGN_init
begin
set game = call Game
end function
function addPGN
begin
set folder_name = str... | import chess
import chess.pgn
import tkinter as tk
from PIL import Image, ImageTk
import time
import os
from datetime import datetime,date
import threading
from tkinter.filedialog import asksaveasfile
import globals
def PGN_init():
globals.game = chess.pgn.Game()
def addPGN():
folder_name = 'Ga... | Python | zaydzuhri_stack_edu_python |
function test_fetchParserTextSection self
begin
set p = call _FetchParser
call parseString b'BODY[TEXT]'
assert equal length result 1
assert is instance result at 0 Body
assert equal peek false
assert is instance text Text
assert equal bytes result at 0 b'BODY[TEXT]'
end function | def test_fetchParserTextSection(self):
p = imap4._FetchParser()
p.parseString(b"BODY[TEXT]")
self.assertEqual(len(p.result), 1)
self.assertIsInstance(p.result[0], p.Body)
self.assertEqual(p.result[0].peek, False)
self.assertIsInstance(p.result[0].text, p.Text)
sel... | Python | nomic_cornstack_python_v1 |
function post_routing_instance_create self resource_dict
begin
pass
end function | def post_routing_instance_create(self, resource_dict):
pass | Python | nomic_cornstack_python_v1 |
function broadcast_index args to_shape index_from=none axis=0 ignore_sr_names=none **kwargs
begin
from vectorbt import settings
if ignore_sr_names is none
begin
set ignore_sr_names = broadcasting at string ignore_sr_names
end
set index_str = if expression axis == 1 then string columns else string index
set to_shape_2d ... | def broadcast_index(args, to_shape, index_from=None, axis=0, ignore_sr_names=None, **kwargs):
from vectorbt import settings
if ignore_sr_names is None:
ignore_sr_names = settings.broadcasting['ignore_sr_names']
index_str = 'columns' if axis == 1 else 'index'
to_shape_2d = (to_shape[0], 1) if le... | Python | nomic_cornstack_python_v1 |
function to_json self
begin
return dict string script decode base64 encode script string utf-8 ; string parameters list map lambda index -> dict string name parameter_names at index ; string type call PascalCase range length parameter_list ; string deployed deployed
end function | def to_json(self) -> dict:
return {
'script': base64.b64encode(self.script).decode('utf-8'),
'parameters': list(map(lambda index: {'name': self.parameter_names[index],
'type': self.parameter_list[index].PascalCase()
... | Python | nomic_cornstack_python_v1 |
function test_serialize_read_only self
begin
set dt = now
set serializer = call serializer_class dict string dt dt
assert data == dict string dt string format time dt DRF_DT_FORMAT
end function | def test_serialize_read_only(self):
dt = timezone.now()
serializer = self.serializer_class({'dt': dt})
assert serializer.data == {'dt': dt.strftime(DRF_DT_FORMAT)} | Python | nomic_cornstack_python_v1 |
function search cls expression page per_page
begin
set tuple ids total = call query_index __tablename__ expression page per_page
if not total
begin
return tuple filter by query id=0 0
end
set when = list comprehension tuple ids at i i for i in range length ids
return tuple call order_by call case when value=id total
en... | def search(cls, expression: str, page: int, per_page: int) -> Tuple[BaseQuery, int]:
ids, total = query_index(cls.__tablename__, expression, page, per_page)
if not total:
return cls.query.filter_by(id=0), 0
when = [(ids[i], i) for i in range(len(ids))]
return cls.query.filter... | Python | nomic_cornstack_python_v1 |
function text_init self text
begin
set t = split string text string
if max_text_size != 1
begin
set t = list comprehension call wrap i win_size_x - 1 for i in t
end
else
begin
set t = list t
end
set text = list
for line in t
begin
comment This retains any empty lines
if line
begin
extend text line
end
else
begin
appen... | def text_init(self, text):
t = str(text).split('\n')
if self.max_text_size != 1:
t = [wrap(i, self.win_size_x - 1) for i in t]
else:
t = [t]
self.text = []
for line in t:
# This retains any empty lines
if line:
self.... | Python | nomic_cornstack_python_v1 |
function IsInPostcondition self
begin
set callResult = call _Call string IsInPostcondition
if callResult is none
begin
return none
end
return callResult
end function | def IsInPostcondition(self):
callResult = self._Call("IsInPostcondition", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function update_pLvlNextFunc self
begin
set pLvlNextFunc = list
for t in range T_cycle
begin
append pLvlNextFunc call LinearInterp array list 0.0 1.0 array list 0.0 PermGroFac at t
end
set pLvlNextFunc = pLvlNextFunc
call add_to_time_vary string pLvlNextFunc
end function | def update_pLvlNextFunc(self):
pLvlNextFunc = []
for t in range(self.T_cycle):
pLvlNextFunc.append(
LinearInterp(np.array([0.0, 1.0]), np.array([0.0, self.PermGroFac[t]]))
)
self.pLvlNextFunc = pLvlNextFunc
self.add_to_time_vary("pLvlNextFunc") | Python | nomic_cornstack_python_v1 |
from modules import *
function choose_accounts aws_env_list
begin
set account_names = list
set account_numbers = list
set my_account_name = string
set my_account_number = string
print YELLOW
set all_accounts_question = input string Loop through all accounts (one/some/all):
if lower all_accounts_question == string o... | from modules import *
def choose_accounts(aws_env_list):
account_names = []
account_numbers = []
my_account_name = ''
my_account_number = ''
print(Fore.YELLOW)
all_accounts_question = input("Loop through all accounts (one/some/all): ")
if all_accounts_question.lower() == 'one':
my_a... | Python | zaydzuhri_stack_edu_python |
import datetime
import json
from collections import defaultdict , OrderedDict
import os
import redis
set tuple START ADD_ADDRESS IS_PHOTO_NEEDED ADD_PHOTO IS_LOCATION_NEEDED ADD_LOCATION END = range 7
set USER_STATE = default dictionary lambda -> START
set USER_DATA = dict
class Connector
begin
function get_user_data... | import datetime
import json
from collections import defaultdict, OrderedDict
import os
import redis
START, ADD_ADDRESS, IS_PHOTO_NEEDED, ADD_PHOTO, IS_LOCATION_NEEDED, ADD_LOCATION, END = range(7)
USER_STATE = defaultdict(lambda: START)
USER_DATA = {}
class Connector:
def get_user_data(self, chat_id):
r... | Python | zaydzuhri_stack_edu_python |
import logicchecker as lg
import math
import cv2
comment List contains the spatial range for unicycles
set uni_range = list 0.33312159941979147 0.6528219512240684
comment List of global range for bicycles
set w1_w2_range = list 0.4545536661228686 0.6335231719118755
set w1_s_range = list 0.19592735476362458 0.6765103385... | import logicchecker as lg
import math
import cv2
uni_range = [0.33312159941979147, 0.6528219512240684] # List contains the spatial range for unicycles
# List of global range for bicycles
w1_w2_range = [0.4545536661228686, 0.6335231719118755]
w1_s_range = [0.19592735476362458, 0.6765103385064127]
w2_s_range = [0.28824... | Python | zaydzuhri_stack_edu_python |
comment https://www.codewars.com/kata/52efefcbcdf57161d4000091/solutions/python
function count s
begin
set dct = dict
if s == string
begin
return dict
end
return dictionary comprehension letter : count s letter for letter in s
end function | # https://www.codewars.com/kata/52efefcbcdf57161d4000091/solutions/python
def count(s):
dct = {}
if s == '':
return {}
return {letter: s.count(letter) for letter in s} | Python | zaydzuhri_stack_edu_python |
comment Exercício 2.2
comment Dada uma sequência de números inteiros diferentes de zero, terminada por
comment um zero, calcular a sua soma. Por exemplo, para a sequência:
comment 12 17 4 -6 8 0
comment o seu programa deve escrever o número 35.
comment link: https://panda.ime.usp.br/aulasPython/static/aulasPython/aula0... | # Exercício 2.2
# Dada uma sequência de números inteiros diferentes de zero, terminada por
# um zero, calcular a sua soma. Por exemplo, para a sequência:
# 12 17 4 -6 8 0
# o seu programa deve escrever o número 35.
# link: https://panda.ime.usp.br/aulasPython/static/aulasPython/aula02.html
def main():
nu... | Python | zaydzuhri_stack_edu_python |
string 58. Write a python program to find the sum of the first n positive integers.
set n = integer input string Input a number:
set sumNumbers = n * n + 1 / 2
print sumNumbers | """
58. Write a python program to find the sum of the first n positive integers.
"""
n = int(input("Input a number: "))
sumNumbers = (n * (n + 1)) / 2
print(sumNumbers)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment from Emp import Employee,BankAccount
comment from Emp.Emp1 import BankAccount
comment from Emp.Emp1 import *
comment print Employee.message
comment print dir (BankAccount)
comment emp1 = Employee("employee1",5000)
comment print dir(emp1)
comment print "Employee count is: ", emp1._Employ... | #!/usr/bin/python
#from Emp import Employee,BankAccount
#from Emp.Emp1 import BankAccount
# from Emp.Emp1 import *
# print Employee.message
# print dir (BankAccount)
# emp1 = Employee("employee1",5000)
# print dir(emp1)
# print "Employee count is: ", emp1._Employee__empCount
# print "Employee name is: ", emp1._name
... | Python | zaydzuhri_stack_edu_python |
function run_ace_zero scenario=none graph=false critics=false noxcombat=false xcombat_path=none
begin
comment Load scenario from path if provided
if is instance scenario basestring
begin
set scenario = call load_scenario scenario
end
comment Run the simulation
set ace_zero = call MultiAgentSimulation scenario
run
comme... | def run_ace_zero(scenario=None, graph=False, critics=False, noxcombat=False,
xcombat_path=None):
# Load scenario from path if provided
if isinstance(scenario, basestring):
scenario = load_scenario(scenario)
# Run the simulation
ace_zero = simulation.MultiAgentSimulation(scenari... | Python | nomic_cornstack_python_v1 |
function register_campaign campaign
begin
set campaigns at name = campaign
end function | def register_campaign(campaign: ba.Campaign) -> None:
_ba.app.campaigns[campaign.name] = campaign | Python | nomic_cornstack_python_v1 |
import time
set LINK = string http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/
function test_find_add_button browser
begin
get browser LINK
set add_button = call find_element_by_css_selector string .btn-add-to-basket
assert call is_displayed msg string Button is unavailable
sleep 5
end function | import time
LINK = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
def test_find_add_button(browser):
browser.get(LINK)
add_button = browser.find_element_by_css_selector('.btn-add-to-basket')
assert add_button.is_displayed(), "Button is unavailable"
time.sleep(5)
| Python | zaydzuhri_stack_edu_python |
function is_disabled self
begin
return _tag == string disabled
end function | def is_disabled(self):
return self._tag == 'disabled' | Python | nomic_cornstack_python_v1 |
comment author Dominik Capkovic
comment contact: domcapkovic@gmail.com; https://www.linkedin.com/in/dominik-čapkovič-b0ab8575/
comment GitHub: https://github.com/kilimetr
import numpy as np
function calc_gas_flooding pars yvec
begin
set uL = pars at 0
set g = pars at 1
set epsilon = pars at 2
set a = pars at 3
set rhoL... | # author Dominik Capkovic
# contact: domcapkovic@gmail.com; https://www.linkedin.com/in/dominik-čapkovič-b0ab8575/
# GitHub: https://github.com/kilimetr
import numpy as np
def calc_gas_flooding(pars,yvec):
uL = pars[0]
g = pars[1]
epsilon = pars[2]
a = pars[3]
rhoL = pars[4]
rhoV = par... | Python | zaydzuhri_stack_edu_python |
from pyspark import SparkContext , SparkConf
from pyspark.sql import SparkSession , Row
function main
begin
set lines = call textFile string file:///root/workspace/spark_SQL/people.txt
call foreach print
set rdd1 = filter lambda line -> length strip line > 0
call foreach print
set rdd2 = map lambda x -> split x string ... | from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession, Row
def main():
lines = sc.textFile("file:///root/workspace/spark_SQL/people.txt")
lines.foreach(print)
rdd1 = lines.filter(lambda line:len(line.strip())>0)
rdd1.foreach(print)
rdd2 = rdd1.map(lambda x:x.s... | Python | zaydzuhri_stack_edu_python |
function test_updating_project_name_updates_interaction es_with_signals
begin
set interaction = call InvestmentProjectInteractionFactory
set new_project_name = string helios
set name = new_project_name
save
call refresh
set result = get es_with_signals index=call get_write_index id=pk
assert result at string _source at... | def test_updating_project_name_updates_interaction(es_with_signals):
interaction = InvestmentProjectInteractionFactory()
new_project_name = 'helios'
interaction.investment_project.name = new_project_name
interaction.investment_project.save()
es_with_signals.indices.refresh()
result = es_with_si... | Python | nomic_cornstack_python_v1 |
function delete name tenant_name client logger
begin
call explicit_tenant_name_message tenant_name logger
set graceful_msg = format string Requested site with name `{0}` was not found name
with call handle_client_error 404 graceful_msg logger
begin
info format string Deleting site `{0}`... name
delete name
info string ... | def delete(name, tenant_name, client, logger):
utils.explicit_tenant_name_message(tenant_name, logger)
graceful_msg = 'Requested site with name `{0}` was not found'.format(name)
with handle_client_error(404, graceful_msg, logger):
logger.info('Deleting site `{0}`...'.format(name))
client.sit... | Python | nomic_cornstack_python_v1 |
function decompress compressed
begin
set DS = string
from io import StringIO
comment Build the dictionary.
set dict_size = 256
set dictionary = dictionary generator expression tuple i character i for i in range dict_size
set result = call StringIO
set w = character pop compressed 0
write result w
for k in compressed
b... | def decompress(compressed):
DS=""
from io import StringIO
# Build the dictionary.
dict_size = 256
dictionary = dict((i, chr(i)) for i in range(dict_size))
result = StringIO()
w = chr(compressed.pop(0))
result.write(w)
for k in compressed:
if k in dictionary:... | Python | nomic_cornstack_python_v1 |
function find_squares start end
begin
set squares = list
set current = start
while current <= end
begin
if current % 3 == 0 and current % 5 == 0
begin
set square = current * current
append squares square
print square
end
set current = current + 1
end
return squares
end function | def find_squares(start, end):
squares = []
current = start
while current <= end:
if current % 3 == 0 and current % 5 == 0:
square = current * current
squares.append(square)
print(square)
current += 1
return squares
| Python | jtatman_500k |
import datetime
function printTimeStamp name
begin
print string Автор програми: + name
print string Час компіляції: + string now
end function
call printTimeStamp string Наживотов Олександр
class Ship
begin
function __init__ self length width name
begin
set length = length
set width = width
set name = name
end function
... | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
printTimeStamp('Наживотов Олександр')
class Ship():
def __init__(self, length, width, name):
self.length = length
self.width = width
... | Python | zaydzuhri_stack_edu_python |
function testEmptyDict self
begin
call check_well_formed dict
end function | def testEmptyDict(self):
check_well_formed({}) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import matplotlib.pyplot as plt
import os
import math
from sklearn.metrics import accuracy_score , mean_squared_error , mean_absolute_error
comment for ignoring warnings on console
set environ at string TF_CPP_MIN_LOG_LEVEL = string 3
import tensorflow as tf
function main
begin
print string inside m... | import pandas as pd
import matplotlib.pyplot as plt
import os
import math
from sklearn.metrics import accuracy_score, mean_squared_error,mean_absolute_error
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # for ignoring warnings on console
import tensorflow as tf
def main():
print("inside main ")
# print("l-1")
def... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Jul 20 10:47:39 2016 @author: ben
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
string # Thermal Constants (Van der Veen 2013 - from Yen CRREL 1981) spy = 31556926. #Seconds per year rhoi = 917. #Bulk density of ice (kg/m3) Kice =... | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 20 10:47:39 2016
@author: ben
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
"""
# Thermal Constants (Van der Veen 2013 - from Yen CRREL 1981)
spy = 31556926. #Seconds per year
rhoi = 917. #Bulk density... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment Copyright (C) 2020 Doguhan Sariturk
comment This program is free software: you can redistribute it and/or modify
comment it under the terms of the GNU General Public License as published by
comment the Free Software Foundation, either version 3 of the ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Doguhan Sariturk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | Python | zaydzuhri_stack_edu_python |
async function put self key value
begin
set _data at string key = value
await save
end function | async def put(self, key: Any, value: Any):
self._data[str(key)] = value
await self.save() | Python | nomic_cornstack_python_v1 |
function matrix_exp_jordan_form A t
begin
set tuple N M = shape
if N != M
begin
raise call ValueError string Needed square matrix but got shape (%s, %s) % tuple N M
end
else
if call has t
begin
raise call ValueError string Matrix A should not depend on t
end
function jordan_chains A
begin
string Chains from Jordan norm... | def matrix_exp_jordan_form(A, t):
N, M = A.shape
if N != M:
raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
elif A.has(t):
raise ValueError('Matrix A should not depend on t')
def jordan_chains(A):
'''Chains from Jordan normal form analogous to M.eigenve... | Python | nomic_cornstack_python_v1 |
function sing self
begin
if _energy < _sing_cost
begin
return
end
set _energy = _energy - _sing_cost
call simulate
end function | def sing(self):
if self._energy < self._sing_cost:
return
self._energy = self._energy - self._sing_cost
self._env.simulate() | Python | nomic_cornstack_python_v1 |
from random import sample
function common_herbs n=5
begin
set common_herbs_list = list string Ginger string Ginseng string Turmeric string Astragalus string Cinnamon
return random sample common_herbs_list n
end function
function common_conditions n=4
begin
set common_conditions_list = list string Headache string Sleep ... | from random import sample
def common_herbs(n=5):
common_herbs_list = [
'Ginger', 'Ginseng', 'Turmeric', 'Astragalus', 'Cinnamon'
]
return sample(common_herbs_list, n)
def common_conditions(n=4):
common_conditions_list = [
'Headache', 'Sleep Problem', 'Stomach Ache', 'Weight Loss'
... | Python | zaydzuhri_stack_edu_python |
function generate self low_res norm_in=false un_norm_out=false exogenous_data=none
begin
set msg = format string exogenous_data is of a bad type {}! type exogenous_data
assert is instance exogenous_data tuple list tuple msg msg
set msg = format string exogenous_data is of a bad length {}! length exogenous_data
assert l... | def generate(self, low_res, norm_in=False, un_norm_out=False,
exogenous_data=None):
msg = ('exogenous_data is of a bad type {}!'
.format(type(exogenous_data)))
assert isinstance(exogenous_data, (list, tuple)), msg
msg = ('exogenous_data is of a bad length {}!'
... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import requests
import csv
import re
import os
from lxml import html
comment from selenium import webdriver
class budgetProd
begin
function __init__ self url
begin
comment self.levelOne = levelOne
comment self.LevelTwo = LevelTwo
set url = url
end functio... | from bs4 import BeautifulSoup
from urllib.request import urlopen
import requests
import csv
import re
import os
from lxml import html
# from selenium import webdriver
class budgetProd():
def __init__(self, url):
# self.levelOne = levelOne
# self.LevelTwo = LevelTwo
self.url = url
... | Python | zaydzuhri_stack_edu_python |
function distribute_keys
begin
call local string ssh-copy-id -i ~/.ssh/id_rsa.pub %s@%s % tuple user host
end function | def distribute_keys():
local("ssh-copy-id -i ~/.ssh/id_rsa.pub %s@%s" % (env.user, env.host)) | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems swagger_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
from django.test import TestCase
from django.urls import resolve
from views import home_page
from django.http import HttpRequest
comment Create your tests here.
class HomePageTest extends TestCase
begin
function test_root_url_resolves_to_home_page self
begin
set found = call resolve string /lists/
assert equal func hom... | from django.test import TestCase
from django.urls import resolve
from .views import home_page
from django.http import HttpRequest
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page(self):
found = resolve('/lists/')
self.assertEqual(found.func, home_page)... | Python | zaydzuhri_stack_edu_python |
string Name : Subashree Setno: 3 Question_no:6
function fn wl fr_l
begin
set count = 0
for i in fr_l
begin
if i in wl
begin
break
end
else
begin
set count = count + 1
print string count of words without forbidden: + string count
break
end
end
if count > 0
begin
print string true
end
if count == 0
begin
print string fal... | '''
Name : Subashree
Setno: 3
Question_no:6
'''
def fn(wl,fr_l):
count=0
for i in fr_l:
if i in wl:
break
else:
count+=1
print("count of words without forbidden:" +str(count))
break
if(count>0):
print("true")
if(count==0):
... | Python | zaydzuhri_stack_edu_python |
function qteRunHook self hookName msgObj=none
begin
string Trigger the hook named ``hookName`` and pass on ``msgObj``. This will call all slots associated with ``hookName`` but without calling the event loop in between. Therefore, if one slots changes the state of the GUI, every subsequent slot may have difficulties de... | def qteRunHook(self, hookName: str, msgObj: QtmacsMessage=None):
"""
Trigger the hook named ``hookName`` and pass on ``msgObj``.
This will call all slots associated with ``hookName`` but
without calling the event loop in between. Therefore, if
one slots changes the state of the ... | Python | jtatman_500k |
set x = 10
set y = 5
print x - y | x = 10
y = 5
print(x-y) | Python | zaydzuhri_stack_edu_python |
from enum import Enum
class LotAction extends Enum
begin
set Buy = 1
set Sell = 2
set Unknown = 3
end class
class StockLot
begin
function __init__ self date_of_action action_type ticker quantity price_per_stock
begin
set date_of_action = date_of_action
if action_type == string Buy
begin
set action_type = Buy
end
else
i... | from enum import Enum
class LotAction(Enum):
Buy = 1
Sell = 2
Unknown = 3
class StockLot:
def __init__(self, date_of_action, action_type, ticker, quantity, price_per_stock):
self.date_of_action = date_of_action
if action_type == "Buy":
self.action_type = LotAction.Buy
... | Python | zaydzuhri_stack_edu_python |
function magic_index_brute arr
begin
if arr
begin
for tuple idx n in enumerate arr
begin
if idx == n
begin
print idx n
return idx
end
end
end
return - 1
end function
print call magic_index_brute list - 20 0 1 2 3 4 5 7 20 | def magic_index_brute(arr):
if arr:
for idx, n in enumerate(arr):
if idx == n:
print(idx,n)
return idx
return -1
print(magic_index_brute([-20,0,1,2,3,4,5,7,20])) | Python | zaydzuhri_stack_edu_python |
function get_most_complex_bites N=10 stats=stats
begin
with open stats newline=string as csvfile
begin
set reader = reader csvfile delimiter=string ;
comment throw header
call __next__
set lines = list reader
end
sort lines key=lambda x -> if expression x at 1 != string None then decimal x at 1 else - 1 reverse=true
re... | def get_most_complex_bites(N=10, stats=stats):
with open(stats, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
reader.__next__() # throw header
lines = list(reader)
lines.sort(key=lambda x:float(x[1]) if x[1] != "None" else -1, reverse=True)
return [x[0]... | Python | nomic_cornstack_python_v1 |
function shape tensor
begin
string Get shape of variable. Return type is tuple.
set temp_s = call get_shape
return tuple list comprehension value for i in range 0 length temp_s
end function | def shape(tensor):
'''
Get shape of variable.
Return type is tuple.
'''
temp_s = tensor.get_shape()
return tuple([temp_s[i].value for i in range(0, len(temp_s))]) | Python | jtatman_500k |
function _argsort seq
begin
comment http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted range length seq key=__getitem__
end function | def _argsort(seq):
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__) | Python | nomic_cornstack_python_v1 |
import nodosd
import listasimple
import os
from random import choice
from subprocess import check_output
from ArbolAvl import ArbolAvl
from activo import activo
class listad1
begin
function __init__ self
begin
set cl = none
set cdir = none
end function
function agregar self usuario contra nombrec empresa dep
begin
set ... | import nodosd
import listasimple
import os
from random import choice
from subprocess import check_output
from ArbolAvl import ArbolAvl
from activo import activo
class listad1:
def __init__(self):
self.cl =None
self.cdir = None
def agregar (self,usuario,contra,nombrec,empresa,dep):
nombre = dep
tipo = empre... | Python | zaydzuhri_stack_edu_python |
import sys
import csv
set filename = string examples/csv/monty_python.csv
if length argv == 2
begin
set filename = argv at 1
end
set people = list
with open filename as fh
begin
set reader = dict reader fh
for line in reader
begin
append people line
end
end
print people at 1 at string fname | import sys
import csv
filename = 'examples/csv/monty_python.csv'
if len(sys.argv) == 2:
filename = sys.argv[1]
people = []
with open(filename) as fh:
reader = csv.DictReader(fh)
for line in reader:
people.append(line)
print(people[1]['fname'])
| Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
from math import sqrt
comment nicer notation to make it easier to read.
set tuple a b = tuple x y
return integer square root a ^ 2 + b ^ 2
end function | def __len__(self):
from math import sqrt
#nicer notation to make it easier to read.
a, b = self.x, self.y
return int(sqrt(a**2 + b**2)) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Aug 6 12:14:14 2021 @author: Prince
comment Nesting
set shaxslar = list
for n in range 4
begin
set shaxs = dict string ism-sharifi none ; string tug'ilgan joyi none ; string tugilgan yili none ; string umri none
append shaxslar shaxs
end
set n = 1
for shaxs in shaxsl... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 6 12:14:14 2021
@author: Prince
"""
#Nesting
shaxslar = []
for n in range(4) :
shaxs = {"ism-sharifi" : None ,
"tug'ilgan joyi" : None ,
"tugilgan yili" : None ,
"umri" : None
}
shaxslar.ap... | Python | zaydzuhri_stack_edu_python |
import pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score , accuracy_score
set FILE = string ../data/results.csv
set MODEL_FILENAME = string model.sav
set data = read csv FILE
set X = drop data columns=... | import pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, accuracy_score
FILE = "../data/results.csv"
MODEL_FILENAME = 'model.sav'
data = pd.read_csv(FILE)
X = data.drop(columns=['date', 'bidopen', ... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import configparser
from gevent import os
comment import os
function get_conf title key
begin
string 获取可变配置,读取config.ini下的数据 :param title: :param key: :return:
set config = call RawConfigParser
set path = directory name path directory name path absolute path path __file__
read config path + string ... | # coding=utf-8
import configparser
from gevent import os
# import os
def get_conf(title: str, key: str) -> object:
'''
获取可变配置,读取config.ini下的数据
:param title:
:param key:
:return:
'''
config = configparser.RawConfigParser()
path = os.path.dirname(os.path.dirname(os.path.... | Python | zaydzuhri_stack_edu_python |
import math
comment Return factorial of n
function fact n
begin
if n == 1 or n == 0
begin
return 1
end
else
begin
return n * call fact n - 1
end
end function
comment Return list of all proper divisors of n
function getDivisors n
begin
set divisors = list
for i in range 1 integer ceil n / 2 + 1
begin
if n % i == 0
begi... | import math
# Return factorial of n
def fact(n):
if n==1 or n==0:
return 1
else:
return n * fact(n-1)
# Return list of all proper divisors of n
def getDivisors(n):
divisors = []
for i in range(1,int(math.ceil(n/2))+1):
if n%i==0:
divisors.append(i)
return di... | Python | zaydzuhri_stack_edu_python |
comment -------------------------------------------------------------------------------
comment coding: utf-8
comment Created: 16/12/2015
import sys
set io = stdin
set op = dict string + lambda x y -> x + y ; string - lambda x y -> x - y ; string / lambda x y -> x / y ; string * lambda x y -> x * y
while true
begin
set... | #-------------------------------------------------------------------------------
# coding: utf-8
# Created: 16/12/2015
import sys
io = sys.stdin
op = { "+" : lambda x, y: x + y,
"-": lambda x,y: x - y,
"/": lambda x,y: x/y,
"*": lambda x,y: x*y }
while True:
a, op_, b = io.readline(... | Python | zaydzuhri_stack_edu_python |
function find_max centroids
begin
set max_sim = 0.0
set max_i = 0
set max_j = 0
set length = length centroids
for i in call xrange 0 length
begin
for j in call xrange i + 1 length
begin
set curr_sim = call similarity centroids at i centroids at j
if curr_sim > max_sim
begin
set max_sim = curr_sim
set max_i = i
set max_... | def find_max(centroids):
max_sim = 0.0
max_i = 0
max_j = 0
length = len(centroids)
for i in xrange(0, length):
for j in xrange(i + 1, length):
curr_sim = similarity(centroids[i], centroids[j])
if curr_sim > max_sim:
max_sim = curr_sim
... | Python | nomic_cornstack_python_v1 |
function isClean n grid rows cols
begin
for i in range n
begin
for j in range n
begin
set idx = i * n + j
if grid at idx != 1
begin
set isValid = false
for row_v in rows at i
begin
if grid at idx - row_v in cols at j
begin
set isValid = true
break
end
end
if not isValid
begin
print string No
return
end
end
end
end
prin... | def isClean(n, grid, rows, cols):
for i in range(n):
for j in range(n):
idx = i*n+j
if grid[idx] != 1:
isValid = False
for row_v in rows[i]:
if grid[idx]-row_v in cols[j]:
isValid = True
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.