code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function closelog
begin
global log logfile logfp
set logfile = string
if logfp
begin
close logfp
set logfp = none
end
set log = initlog
end function | def closelog():
global log, logfile, logfp
logfile = ''
if logfp:
logfp.close()
logfp = None
log = initlog | Python | nomic_cornstack_python_v1 |
string This module contains basic unit tests for math operations. Their purpose is to show how to use the pytest framework by example.
comment -------------------------------------------------------------------
comment imports
comment -------------------------------------------------------------------
import pytest
dec... | """
This module contains basic unit tests for math operations.
Their purpose is to show how to use the pytest framework by example.
"""
# -------------------------------------------------------------------
# imports
# -------------------------------------------------------------------
import pytest
# ---------------... | Python | zaydzuhri_stack_edu_python |
function parse_string txt
begin
return string txt at slice 1 : - 1 :
end function | def parse_string(txt):
return str(txt[1:-1]) | Python | nomic_cornstack_python_v1 |
function get_user_subscription_activities user_id exclude_system=none limit=none offset=none subscription_id=none namespace=none x_additional_headers=none **kwargs
begin
if namespace is none
begin
set tuple namespace error = call get_services_namespace
if error
begin
return tuple none error
end
end
set request = call c... | def get_user_subscription_activities(
user_id: str,
exclude_system: Optional[bool] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
subscription_id: Optional[str] = None,
namespace: Optional[str] = None,
x_additional_headers: Optional[Dict[str, str]] = None,
**kwargs
):... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python
function getDict string
begin
set dict = dict
for i in range length string
begin
set count = 0
if call has_key string at i
begin
set count = dict at string at i + 1
end
else
begin
set count = 1
end
set dict at string at i = count
end
return dict
end function
function getCount dict char
begin
... | #! /usr/bin/python
def getDict(string):
dict = {}
for i in range(len(string)):
count = 0
if dict.has_key(string[i]):
count = dict[string[i]] + 1
else:
count = 1
dict[string[i]] = count
return dict
def getCount(dict, char):
if dict.has_key(char):
... | Python | zaydzuhri_stack_edu_python |
function parameters self
begin
return get pulumi self string parameters
end function | def parameters(self) -> Optional[Sequence['outputs.ModuleAssetParameterResponse']]:
return pulumi.get(self, "parameters") | Python | nomic_cornstack_python_v1 |
function _print_test_results classification_model test_points test_response_name plot_file threshold
begin
global MESSAGES
call _verbose_print string _print_test_results
call _verbose_print format string classification_model: {} classification_model
call _verbose_print format string test_points: {} test_points
call _ve... | def _print_test_results(classification_model, test_points, test_response_name, plot_file, threshold):
global MESSAGES
_verbose_print("_print_test_results")
_verbose_print("classification_model: {}".format(classification_model))
_verbose_print("test_points: {}".format(test_points))
_verbose_print("te... | Python | nomic_cornstack_python_v1 |
function sample self M
begin
set ran = random sample M replace=true
return join string index
end function | def sample(self, M):
ran = self.mdl.sample(M, replace=True)
return ' '.join(ran.index) | Python | nomic_cornstack_python_v1 |
function receive self
begin
set count = 0
while fifo
begin
try
begin
set cqitem = pop fifo 0
end
except IndexError
begin
comment multi-consumer race lost
break
end
try
begin
set ret = call func *cqitem.args keyword kwargs
set done = 1
end
except any
begin
if raise_exception ? 1
begin
set exc = call exc_info
end
set don... | def receive(self):
count=0
while self.fifo:
try:
cqitem=self.fifo.pop(0)
except IndexError:
break # multi-consumer race lost
try:
cqitem.ret=cqitem.func(*cqitem.args,**cqitem.kwargs)
cqitem.done=1
... | Python | nomic_cornstack_python_v1 |
function _check_valid_dep self department
begin
if department
begin
for tuple x y in items department
begin
if search string [a-z]{2}[0-9]{5} y and search string ^[a-zA-ZA-Za-zÀ-ÖØ-öø-ÿ ,.'-]+$ x
begin
continue
end
else
begin
raise call ValueError string Department entries are not correct
end
end
end
else
begin
raise c... | def _check_valid_dep(self, department: Dict[str, str]) -> Dict[str, str]:
if department:
for x, y in department.items():
if re.search("[a-z]{2}[0-9]{5}", y) \
and re.search("^[a-zA-ZA-Za-zÀ-ÖØ-öø-ÿ ,.'-]+$", x):
continue
els... | Python | nomic_cornstack_python_v1 |
import argparse
set parser = call ArgumentParser
comment parser.add_argument("echo", help="echo the string entered here")
call add_argument string square help=string display the square of a given number type=int
set args = call parse_args
print square ^ 2 | import argparse
parser = argparse.ArgumentParser()
#parser.add_argument("echo", help="echo the string entered here")
parser.add_argument("square", help="display the square of a given number", type=int)
args = parser.parse_args()
print(args.square**2)
| Python | zaydzuhri_stack_edu_python |
function view_sbo self
begin
string View slackbuild.org
set sbo_url = replace sbo_url string /slackbuilds/ string /repository/
set tuple br1 br2 fix_sp = tuple string string string
if use_colors in list string off string OFF
begin
set br1 = string (
set br2 = string )
set fix_sp = string
end
comment new line at sta... | def view_sbo(self):
"""View slackbuild.org
"""
sbo_url = self.sbo_url.replace("/slackbuilds/", "/repository/")
br1, br2, fix_sp = "", "", " "
if self.meta.use_colors in ["off", "OFF"]:
br1 = "("
br2 = ")"
fix_sp = ""
print("") # new l... | Python | jtatman_500k |
from pyramid.view import view_config
from docrequest import docrequest_pyramid as docrequest
from docrequest import readable_type
decorator call view_config route_name=string decorated_without_definitions renderer=string string
decorator docrequest
function decorated_without_definitions request
begin
string A view deco... | from pyramid.view import view_config
from docrequest import docrequest_pyramid as docrequest
from docrequest import readable_type
@view_config(route_name='decorated_without_definitions', renderer='string')
@docrequest
def decorated_without_definitions(request):
"""
A view decorated with `@docrequest` that do... | Python | zaydzuhri_stack_edu_python |
function detrend_seasonal_median self wl=11 in_place=false verbose=false
begin
comment check data is not None
from pyacs.gts.lib.errors import GtsInputDataNone
try
begin
if data is none
begin
comment raise exception
raise call GtsInputDataNone stack at 0 at 3 __name__ self
end
end
except GtsInputDataNone as error
begin... | def detrend_seasonal_median(self , wl=11, in_place=False, verbose=False):
###############################################################################
###########################################################################
# check data is not None
from pyacs.gts.lib.errors import GtsInputDataNon... | Python | nomic_cornstack_python_v1 |
import pygame
class Speaker
begin
function __init__ self path_mask
begin
call pre_init 44100 - 16 2 512
call init
call _load_sounds path_mask
end function
function play self number
begin
call play
end function
function stop self number
begin
comment self._sounds[number].stop()
pass
end function
function _load_sounds se... | import pygame
class Speaker:
def __init__(self, path_mask):
pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.mixer.init()
self._load_sounds(path_mask)
def play(self, number):
self._sounds[number].play()
def stop(self, number):
# self._sounds[number]... | Python | zaydzuhri_stack_edu_python |
function count_similarity self n
begin
call count_certificates
set tuple common max_size = call largest_common_forest n
return common / max_size
end function | def count_similarity(self, n) -> float:
self.count_certificates()
common, max_size = self.largest_common_forest(n)
return common / max_size | Python | nomic_cornstack_python_v1 |
import numpy as np
import copy
from matplotlib import pyplot as plt
from pandas import DataFrame
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
comment functions
function sigmoid x deriv=false
begin
set sigmoid = 1 / 1 + exp - x
if deriv == false
begin
return sigmoid
end
else
if deriv == true
begin
r... | import numpy as np
import copy
from matplotlib import pyplot as plt
from pandas import DataFrame
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
#functions
def sigmoid(x,deriv=False):
sigmoid = 1 / (1 + np.exp(-x))
if deriv==False:
return sigmoid
elif deriv==True:
... | Python | zaydzuhri_stack_edu_python |
function rmse rating_true rating_pred col_user=DEFAULT_USER_COL col_item=DEFAULT_ITEM_COL col_rating=DEFAULT_RATING_COL col_prediction=DEFAULT_PREDICTION_COL
begin
set tuple y_true y_pred = call merge_rating_true_pred rating_true=rating_true rating_pred=rating_pred col_user=col_user col_item=col_item col_rating=col_rat... | def rmse(
rating_true,
rating_pred,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_prediction=DEFAULT_PREDICTION_COL,
):
y_true, y_pred = merge_rating_true_pred(
rating_true=rating_true,
rating_pred=rating_pred,
col_user=col_u... | Python | nomic_cornstack_python_v1 |
import os
import argparse
from multiprocessing import Process , Pipe
function son_job con2
begin
while true
begin
set line = call recv
set temp = upper line at slice : : - 1
call send temp
end
end function
if __name__ == string __main__
begin
set arg = call ArgumentParser description=string Invertir y pasar a mayuscu... | import os
import argparse
from multiprocessing import Process,Pipe
def son_job(con2):
while True:
line = con2.recv()
temp = line[::-1].upper()
con2.send(temp)
if __name__ == "__main__":
arg = argparse.ArgumentParser(description='Invertir y pasar a mayuscula',
usage='./ej1 -f pasar... | Python | zaydzuhri_stack_edu_python |
function plotBasicHistogram self ax=none bins=20 labels=false
begin
if call ndim data <= 2
begin
return
end
set doshow = false
if ax is none
begin
set doshow = true
set fig = figure
set ax = call add_subplot 111
end
set arr = call getDynamicSpectrum
set abs_max = call amax arr
set abs_min = call amin arr
set step_size ... | def plotBasicHistogram(self, ax = None, bins = 20, labels = False):
if np.ndim(self.data) <= 2:
return
doshow = False
if ax is None:
doshow = True
fig = figure()
ax = fig.add_subplot(111)
arr = self.getDynamicSpectrum()
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import configparser
from tinydb import TinyDB , where
from flask import Flask , render_template , Response , request , json , send_from_directory
from functools import wraps
set app = call Flask __name__
set config = config parser
read config string config.ini
set IMAGE_FOLDER = config at stri... | #!/usr/bin/python3
import configparser
from tinydb import TinyDB, where
from flask import Flask, render_template, Response, request, json, send_from_directory
from functools import wraps
app = Flask(__name__)
config = configparser.ConfigParser()
config.read('config.ini')
IMAGE_FOLDER = config['DEFAULT']["image_fo... | Python | zaydzuhri_stack_edu_python |
function diff self other spin=string a
begin
return call DM_diff self other spin
end function | def diff(self, other, spin="a"):
return DM_diff(self, other, spin) | Python | nomic_cornstack_python_v1 |
function fromDataAndAnalysisPeriod cls data analysisPeriod header=none
begin
return call fromDataAndDatetimes data datetimes header
end function | def fromDataAndAnalysisPeriod(cls, data, analysisPeriod, header=None):
return cls.fromDataAndDatetimes(data, analysisPeriod.datetimes, header) | Python | nomic_cornstack_python_v1 |
class Asc
begin
pass
end class
class Bsc
begin
pass
end class
set a = call Asc
set b = call Bsc
print string type a at slice - 5 : - 2 :
print string type b
print is instance a Asc
print is instance b Asc | class Asc():
pass
class Bsc():
pass
a = Asc()
b = Bsc()
print(str(type(a))[-5:-2])
print(str(type(b)))
print(isinstance(a, Asc))
print(isinstance(b, Asc)) | Python | zaydzuhri_stack_edu_python |
function render_response
begin
set first_name = get form string first_name
set last_name = get form string last_name
set salary = get form string salary
set job = get form string job
comment Create more human-readable strings for possible jobs
if job == string software_engineer
begin
set job = string Software Engineer
... | def render_response():
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
salary = request.form.get("salary")
job = request.form.get("job")
# Create more human-readable strings for possible jobs
if job == "software_engineer":
job = "Software Engineer"... | Python | nomic_cornstack_python_v1 |
function __check_connection self
begin
try
begin
set status = call noop at 0
end
except SMTPServerDisconnected
begin
set status = - 1
info string Disconnected from server, need to reconnect
end
return if expression status == 250 then true else false
end function | def __check_connection(self):
try:
status = self.server.noop()[0]
except SMTPServerDisconnected:
status = -1
self.logger.info('Disconnected from server, need to reconnect')
return True if status == 250 else False | Python | nomic_cornstack_python_v1 |
string Faça um programa completo utilizando classes e métodos que: Possua uma classe chamada bombaCombustível, com no mínimo esses atributos: tipoCombustivel. valorLitro quantidadeCombustivel Possua no mínimo esses métodos: abastecerPorValor( ) – método onde é informado o valor a ser abastecido e mostra a quantidade de... | """
Faça um programa completo utilizando classes e métodos que:
Possua uma classe chamada bombaCombustível, com no mínimo esses atributos:
tipoCombustivel.
valorLitro
quantidadeCombustivel
Possua no mínimo esses métodos:
abastecerPorValor( ) – método onde é informado o v... | Python | zaydzuhri_stack_edu_python |
function postings_batches self postings_batches
begin
set _postings_batches = postings_batches
end function | def postings_batches(self, postings_batches):
self._postings_batches = postings_batches | Python | nomic_cornstack_python_v1 |
function print_stars_grid n
begin
if n % 2 != 0
begin
raise call ValueError string n must be an even number.
end
set stars_per_row = n // 2
for i in range n
begin
set row = list string * * stars_per_row
print join string row
end
end function | def print_stars_grid(n):
if n % 2 != 0:
raise ValueError("n must be an even number.")
stars_per_row = n // 2
for i in range(n):
row = ['*'] * stars_per_row
print(' '.join(row))
| Python | jtatman_500k |
function evalBottomContactDisp length bottomcurve_radius bottomJointAngle
begin
set halfJointAngle = bottomJointAngle / 2
return array tuple 0 - bottomcurve_radius * sin halfJointAngle - bottomcurve_radius * cos halfJointAngle + bottomcurve_radius - length / 2
end function | def evalBottomContactDisp(length: float,
bottomcurve_radius: float,
bottomJointAngle: float):
halfJointAngle = bottomJointAngle/2
return np.array((
0,
-bottomcurve_radius*sin(halfJointAngle),
-bottomcurve_radius*cos(halfJointAngle) + bottom... | Python | nomic_cornstack_python_v1 |
function caesar_password_transform flag
begin
set caesar_list = list
set caesar_list_input = input string please input:
for letter in caesar_list_input
begin
set letter_int = ordinal letter - 64
if 1 <= letter_int <= 26
begin
if flag
begin
set caesar_letter_num = letter_int + 3 % 26
if caesar_letter_num == 0
begin
set... | def caesar_password_transform(flag):
caesar_list = []
caesar_list_input = input("please input:")
for letter in caesar_list_input:
letter_int = ord(letter) - 64
if 1 <= letter_int <= 26:
if flag:
caesar_letter_num = (letter_int + 3) % 26
if caesar_l... | Python | zaydzuhri_stack_edu_python |
function unlink self cr uid ids context=none
begin
set states = read self cr uid ids list string state context=context
set unlink_ids = list
for state in states
begin
if state at string state in tuple string draft string cancel
begin
append unlink_ids state at string id
end
else
begin
raise call except_orm call _ stri... | def unlink(self, cr, uid, ids, context=None):
states = self.read(cr, uid, ids, ['state'], context=context)
unlink_ids = []
for state in states:
if state['state'] in ('draft','cancel'):
unlink_ids.append(state['id'])
else:
raise orm.except_o... | Python | nomic_cornstack_python_v1 |
import os
import sys
function get_warning_count lines
begin
set wcount = 0
for line in lines
begin
if find line string warning >= 0
begin
set wcount = wcount + 1
end
end
comment line = line.lstrip().rstrip()
comment print line.split(":")[4].lstrip()
return wcount
end function
function get_warn_count_by_file log_file
be... | import os
import sys
def get_warning_count(lines):
wcount = 0
for line in lines:
if (line.find("warning") >= 0):
wcount += 1;
#line = line.lstrip().rstrip()
#print line.split(":")[4].lstrip()
return wcount
def get_warn_count_by_file(log_file):
... | Python | zaydzuhri_stack_edu_python |
function helper arr first last
begin
if first < last
begin
set split = call partition arr first last
call helper arr first split - 1
call helper arr split + 1 last
end
end function | def helper(arr, first, last):
if first < last:
split = partition(arr, first, last)
helper(arr, first, split - 1)
helper(arr, split + 1, last) | Python | nomic_cornstack_python_v1 |
function view_project project_id
begin
return call render_template string project/view_project.html project=call first_or_404
end function | def view_project(project_id):
return render_template(
"project/view_project.html",
project=Project.query.filter(Project.id == project_id).first_or_404()
) | Python | nomic_cornstack_python_v1 |
comment loop will be start below
while true
begin
try
begin
comment input for enter deposit amount
set x = input string enter deposit amount
set x = decimal x
break
end
except any
begin
print string invalid input
continue
end
end
while x <= 10000
begin
set z = x * 0.06
set x = x + z
print string year - y string abalanc... | #loop will be start below
while True:
try:
#input for enter deposit amount
x=input('enter deposit amount')
x=float(x)
break
except:
print("invalid input")
continue
while x<=10000:
z=x*0.06
x=x+z
print("year - ",y," abalance in your account - ",x)
y=y+1
print("total year - ",y," balance... | Python | zaydzuhri_stack_edu_python |
function branch request branch_name
begin
set userprofile = filter user=id
set allquery = call order_by string -created_at
set popular_query = call order_by string -views at slice : 5 :
set branch = list string CSE string IT string ECE string ME string CE string EN
set title = branch_name + string Queries
set u = 1
s... | def branch(request, branch_name):
userprofile = UserProfileF.objects.filter(user=request.user.id)
allquery = QueryS.objects.filter(branch=branch_name).order_by('-created_at')
popular_query = QueryS.objects.order_by('-views')[:5]
branch = ['CSE', 'IT', 'ECE', 'ME', 'CE', 'EN']
title = branch_name + '... | Python | nomic_cornstack_python_v1 |
comment noqa: E501
function delete_namespaced_endpoints self name namespace **kwargs
begin
string delete_namespaced_endpoints # noqa: E501 delete Endpoints # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_names... | def delete_namespaced_endpoints(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_endpoints # noqa: E501
delete Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>... | Python | jtatman_500k |
function count_even_greater_than_10 arr
begin
set count = 0
for num in arr
begin
if num > 10 and num % 2 == 0
begin
set count = count + 1
end
end
return count
end function
set arr = list 1 5 7 4 9 17
set result = call count_even_greater_than_10 arr
comment Output: 1
print result | def count_even_greater_than_10(arr):
count = 0
for num in arr:
if num > 10 and num % 2 == 0:
count += 1
return count
arr = [1, 5, 7, 4, 9, 17]
result = count_even_greater_than_10(arr)
print(result) # Output: 1
| Python | jtatman_500k |
import cffi
import targetFunctionScanner
class Builder
begin
set __ffi = call FFI
set __arguments = list
set __targetFunction = string
set __sourceCode = string
set __ftraceFunctions = string int setTrace = -1; int marker = -1; char ftracePath[256] = "/sys/kernel/debug/tracing/tracing_on"; char markerPath[256] = "/s... | import cffi
import targetFunctionScanner
class Builder:
__ffi = cffi.FFI()
__arguments = []
__targetFunction = ''
__sourceCode = ''
__ftraceFunctions = r''' int setTrace = -1;
int marker = -1;
char ... | Python | zaydzuhri_stack_edu_python |
from typing import Dict
class Category
begin
function __init__ self name cat_id
begin
set name = name
set cat_id = cat_id
end function
decorator classmethod
function from_json cls json_data
begin
return call cls name=json_data at string name cat_id=json_data at string id
end function
function __repr__ self
begin
return... | from typing import Dict
class Category:
def __init__(self, name: str, cat_id: int):
self.name = name
self.cat_id = cat_id
@classmethod
def from_json(cls, json_data: Dict):
return cls(
name=json_data['name'],
cat_id=json_data['id']
)
def __repr_... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=redefined-outer-name
function with_rank x rank
begin
return call _cast_tensorshape call with_rank rank type x
end function | def with_rank(x, rank): # pylint: disable=redefined-outer-name
return _cast_tensorshape(tf.TensorShape(x).with_rank(rank), type(x)) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[2]:
comment Importing Required Libraries
import pandas as pd
import warnings
filter warnings string ignore
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection im... | #!/usr/bin/env python
# coding: utf-8
# In[2]:
##Importing Required Libraries
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_tes... | Python | zaydzuhri_stack_edu_python |
function as_selectable self
begin
raise NotImplementedError
end function | def as_selectable(self) -> sqlalchemy.Selectable:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function reset_target_network self
begin
comment Make sure that the targetNetwork is still on the correct device
load state dict targetNetwork state dict qNetwork
end function | def reset_target_network(self):
# Make sure that the targetNetwork is still on the correct device
self.targetNetwork.load_state_dict(self.qNetwork.state_dict()) | Python | nomic_cornstack_python_v1 |
comment 3
function putbarablocktriplet self num_ subi subj subk subl valijkl
begin
if subi is none
begin
raise call TypeError string Invalid type for argument subi
end
if subi is none
begin
set subi_ = none
end
else
begin
try
begin
set subi_ = call memoryview subi
end
except TypeError
begin
try
begin
set _tmparr_subi =... | def putbarablocktriplet(self,num_,subi,subj,subk,subl,valijkl): # 3
if subi is None: raise TypeError("Invalid type for argument subi")
if subi is None:
subi_ = None
else:
try:
subi_ = memoryview(subi)
except TypeError:
try:
_tmparr_subi = array.a... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys
class FileHandler
begin
function __init__ self
begin
pass
end function
end class | # -*- coding: utf-8 -*-
import sys
class FileHandler:
def __init__(self):
pass
| Python | zaydzuhri_stack_edu_python |
set nombre = string Alicia
set edad = 35
print string Me llamo nombre string y tengo edad string años. | nombre = "Alicia"
edad = 35
print("Me llamo", nombre, "y tengo", edad, "años.") | Python | zaydzuhri_stack_edu_python |
import sys
from tdapi import get_price_history
from utils import timestamp_to_iso
if platform == string linux or platform == string linux2
begin
set DATA_PATH = string ../Data/
end
else
if platform == string win32
begin
set DATA_PATH = string ..\Data\
end
decorator timestamp_to_iso
function get_recent_data symbol perio... | import sys
from tdapi import get_price_history
from utils import timestamp_to_iso
if sys.platform == 'linux' or sys.platform == 'linux2':
DATA_PATH = '../Data/'
elif sys.platform == 'win32':
DATA_PATH = '..\\Data\\'
@timestamp_to_iso
def get_recent_data(
symbol,
periodType,
period,
frequencyType,
frequency... | Python | zaydzuhri_stack_edu_python |
from threading import Thread
from queue import Queue
import psycopg2
import time
class QueueRetriever extends Thread
begin
string QueueRetriever need to get solution id from database queue.
function __init__ self db_settings
begin
string Initialisation of QueueRetriever. :param db_settings: setting of database to conne... | from threading import Thread
from queue import Queue
import psycopg2
import time
class QueueRetriever(Thread):
"""
QueueRetriever need to get solution id from database queue.
"""
def __init__(self, db_settings):
"""
Initialisation of QueueRetriever.
:param db_settings: setting of datab... | Python | zaydzuhri_stack_edu_python |
function getEvents request practice_id callgroup_id=none
begin
set callgroup_id = call checkMultiCallGroupId practice_id callgroup_id
if not call canAccessMultiCallGroup user call long callgroup_id practice_id
begin
return call err403 request
end
comment defaults
set fromDateTmp = today - time delta days=15
set toDateT... | def getEvents(request, practice_id, callgroup_id=None):
callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
return err403(request)
fromDateTmp = datetime.date.today() - datetime.timedelta(days=15) # defaults
toDateTmp =... | Python | nomic_cornstack_python_v1 |
function test_environment_marker_extras self data
begin
set reqset = call basic_reqset
set req = call from_editable join packages string LocalEnvironMarker
call add_requirement req
set finder = call PackageFinder list find_links list session=call PipSession
call prepare_files finder
comment This is hacky but does test... | def test_environment_marker_extras(self, data):
reqset = self.basic_reqset()
req = InstallRequirement.from_editable(
data.packages.join("LocalEnvironMarker"))
reqset.add_requirement(req)
finder = PackageFinder([data.find_links], [], session=PipSession())
reqset.prepar... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3.6
set filename = input string Enter file name
try
begin
with open filename as f
begin
print string Opening file { filename }
end
end
except any
begin
print string File { filename } can't by opened
end
try
begin
set line = input string Enter the line number you would like to read
for x in r... | #!/usr/bin/env python3.6
filename = input("Enter file name\n")
try:
with open(filename) as f:
print(f"Opening file {filename}\n")
except:
print(f"File {filename} can't by opened\n")
try:
line = input("Enter the line number you would like to read\n")
for x in range (0, int(line)):
f.re... | Python | zaydzuhri_stack_edu_python |
from __future__ import absolute_import
from layers import AbstractLayer
import numpy as np
class Model extends object
begin
string A simple sequential model. self.sequence stores the order in which ops were added. self.layers stores the layers against names. Forward pass and loss are separate. def:forward will just ret... | from __future__ import absolute_import
from ..layers import AbstractLayer
import numpy as np
class Model(object):
"""
A simple sequential model.
self.sequence stores the order in which ops were added.
self.layers stores the layers against names.
Forward pass and loss are separate.
def:forward ... | Python | zaydzuhri_stack_edu_python |
function signout request
begin
call logout request
return call HttpResponseRedirect string /
end function | def signout(request):
logout(request)
return HttpResponseRedirect('/') | Python | nomic_cornstack_python_v1 |
function with_patch
begin
print format string --- In {}.with_patch(): __name__
set a = call Test
with patch string module_a.method_a new=method_b as patched
begin
print format string Applying patch, {}.method_a == {} __name__ patched
call do_stuff
end
print format string Reverting patch, {}.method_a == {} __name__ meth... | def with_patch():
print("--- In {}.with_patch():".format(__name__))
a = Test()
with patch("module_a.method_a", new=method_b) as patched:
print("Applying patch, {}.method_a == {}".format(__name__,
patched))
a.do_stuff()
print("Rever... | Python | nomic_cornstack_python_v1 |
function save_uptime machine_config num_seconds idle_time data_log_date
begin
set uptime = call Uptime stats_machine_config=machine_config date=data_log_date number_of_seconds=num_seconds idle_time=idle_time
save
end function | def save_uptime(machine_config, num_seconds, idle_time, data_log_date):
uptime = Uptime(
stats_machine_config=machine_config,
date=data_log_date,
number_of_seconds=num_seconds,
idle_time=idle_time)
uptime.save() | Python | nomic_cornstack_python_v1 |
string Comentario Multi Linea
comment Python usa sangría para indicar un bloque de código.
if 5 > 2
begin
print string Cinco es mayor que Dos
end
comment El numero de espacios depende del programador, pero debe ser al menos una
if 5 > 2
begin
print string Hola mundo
end
comment Tiene que usar la misma cantidad espacios... | '''
Comentario
Multi
Linea
'''
#Python usa sangría para indicar un bloque de código.
if 5>2:
print('Cinco es mayor que Dos')
#El numero de espacios depende del programador, pero debe ser al menos una
if 5>2:
print('Hola mundo')
#Tiene que usar la misma cantidad espacios en el mismo bloque ... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from string import ascii_uppercase
from pathlib import Path
set PATH = string ../c... | from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from string import ascii_uppercase
from pathlib import Path
PATH="../chromedriver... | Python | zaydzuhri_stack_edu_python |
import pymysql
import pandas as pd
comment 读取数据 我这里是把 xlsx 文件放在了 python 文件的同一级目录下
set df = call read_excel string test.xlsx
set datas = values
comment print(datas)
comment 连接数据库
set db = call connect host=string xxxxx port=3306 user=string root passwd=string **** database=string xrhTest charset=string utf8
comment 获取游标... | import pymysql
import pandas as pd
# 读取数据 我这里是把 xlsx 文件放在了 python 文件的同一级目录下
df = pd.read_excel('test.xlsx')
datas=df.values
# print(datas)
#连接数据库
db = pymysql.connect(host = 'xxxxx',port = 3306,user = 'root',passwd = '****',database = 'xrhTest',charset = 'utf8')
#获取游标
cursor = db.cursor()
rowSum = 0
#数据操作
for data ... | Python | zaydzuhri_stack_edu_python |
function test_inspect_profile host
begin
set cmd = string inspec supermarket info + dev_sec_profile + string --chef-license=accept-silent
set inspec_command = run cmd
assert rc == 0
end function | def test_inspect_profile(host):
cmd = "inspec supermarket info " \
+ dev_sec_profile \
+ " --chef-license=accept-silent"
inspec_command = host.run(cmd)
assert inspec_command.rc == 0 | Python | nomic_cornstack_python_v1 |
import re
function remove_vowels text
begin
set pattern = compile string [aeiouAEIOU]
return sub pattern string text
end function
set text = string Hello, World!
set result = call remove_vowels text
comment Output: "Hll, Wrld!"
print result | import re
def remove_vowels(text):
pattern = re.compile('[aeiouAEIOU]')
return re.sub(pattern, '', text)
text = "Hello, World!"
result = remove_vowels(text)
print(result) # Output: "Hll, Wrld!"
| Python | jtatman_500k |
function __eq__ self other
begin
if not is instance other RuntimeHostProfile
begin
return false
end
return call to_dict == call to_dict
end function | def __eq__(self, other):
if not isinstance(other, RuntimeHostProfile):
return False
return self.to_dict() == other.to_dict() | Python | nomic_cornstack_python_v1 |
import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as pd
from configs.config import colors
set df = read csv string data\mpg.csv
comment print(df.head())
set horsepower_mpg = list scatter go x=df at string horsepower y=df at string mpg text=df at string name mode=string markers marker=dictionary ... | import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as pd
from configs.config import colors
df = pd.read_csv(r'data\mpg.csv')
# print(df.head())
horsepower_mpg = [go.Scatter(x=df['horsepower'],
y=df['mpg'],
text=df['name'],
mode='marker... | Python | zaydzuhri_stack_edu_python |
function test_no_json self
begin
set curr_path = directory name path __file__
set zip_path = join path curr_path ZIP_FOLDER NO_JSON
set select_problem = call SelectProblem zipfile=zip_path
set dml_problem = call DMLProblem zipfile=zip_path
set function_problem = call FunctionProblem zipfile=zip_path
set proc_problem = ... | def test_no_json(self):
curr_path = os.path.dirname(__file__)
zip_path = os.path.join(curr_path, self.ZIP_FOLDER, self.NO_JSON)
select_problem = SelectProblem(zipfile=zip_path)
dml_problem = DMLProblem(zipfile=zip_path)
function_problem = FunctionProblem(zipfile=zip_path)
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Apr 27 00:04:44 2020 @author: anshu
comment josephus problem
from Circular_linkedlist import Circular_llist as self
class josephus extends self
begin
call __init__ self
function jremove self node
begin
if head == node
begin
set cur = head
while next != head
begin
set ... | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 00:04:44 2020
@author: anshu
"""
#josephus problem
from Circular_linkedlist import Circular_llist as self
class josephus(self):
self. __init__(self)
def jremove(self,node):
if self.head==node:
cur=self.head
whi... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
from collections import defaultdict
import operator
set NUMBERS = list string ZERO string ONE string TWO string THREE string FOUR string FIVE string SIX string SEVEN string EIGHT string NINE
function toto n
begin
set l = default dictionary int
for c in n
begin
set l at c = l at c... | #!/usr/bin/env python
import sys
from collections import defaultdict
import operator
NUMBERS = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
def toto(n):
l = defaultdict(int)
for c in n:
l[c] += 1
return l
MAPPED_NUMBERS = [dict(toto(n)) for n in NUMBERS]
LETT... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set str1 = input string enter a string
set replaced_char = input string enter the character you want to replace
set replacement_char = input string enter char eith younwant to replace
comment first appearence of replaced char
set f_occur = find str1 replaced_char
set str2 = str1 at slice ... | # -*- coding: utf-8 -*-
str1=input("enter a string")
replaced_char=input("enter the character you want to replace")
replacement_char=input("enter char eith younwant to replace")
#first appearence of replaced char
f_occur=str1.find(replaced_char)
str2=str1[:f_occur+1]
str3=str1[f_occur+1:].replace(replaced_char, repla... | Python | zaydzuhri_stack_edu_python |
function makeStar r
begin
set h1 = 0
set h2 = 0.224514
set h3 = 0.363271
set h4 = 0.587785
set h5 = 0.951057
set v1 = - 1
set v2 = - 0.309017
set v3 = 0.118034
set v4 = 0.381966
set v5 = 0.809017
set st = call createShape
call beginShape
call fill 255 255 255
call noStroke
call vertex h1 * r v1 * r
call vertex h2 * r v... | def makeStar(r):
h1 = 0
h2 = .224514
h3 = .363271
h4 = .587785
h5 = .951057
v1 = -1
v2 = -.309017
v3 = .118034
v4 = .381966
v5 = .809017
st = createShape()
st.beginShape()
st.fill(255,255,255)
st.noStroke()
st.vertex(h1*r, v1*r)
st.vertex(h2*r, v2*r)
s... | Python | nomic_cornstack_python_v1 |
import os
import sys
comment Add parent dir to PYTHONPATH
set src_path = directory name path directory name path absolute path path __file__ + string /src
append path src_path
import unittest
import youtube_watch_page
set print_dbg = false
class TestYoutubeWatchPage extends TestCase
begin
function test_gets_data_having... | import os
import sys
# Add parent dir to PYTHONPATH
src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/src"
sys.path.append(src_path)
import unittest
import youtube_watch_page
print_dbg = False
class TestYoutubeWatchPage(unittest.TestCase):
def test_gets_data_having_closed_captions(self)... | Python | zaydzuhri_stack_edu_python |
function subscriber_email_addresses self
begin
return get pulumi self string subscriber_email_addresses
end function | def subscriber_email_addresses(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "subscriber_email_addresses") | Python | nomic_cornstack_python_v1 |
function fc x num_in num_out name relu=true
begin
with call variable_scope name as scope
begin
comment Create tf variables for the weights and biases
string weights = tf.get_variable('weights', shape=[num_in, num_out], trainable=True) biases = tf.get_variable('biases', [num_out], trainable=True)
set weights = call weig... | def fc(x, num_in, num_out, name, relu=True):
with tf.variable_scope(name) as scope:
# Create tf variables for the weights and biases
'''
weights = tf.get_variable('weights', shape=[num_in, num_out],
trainable=True)
biases = tf.get_variable('biases', ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn import tree
set data = read csv string customer_data.csv
set feature_names = list string Age string Gender string Occupation string Type string City string Member since string Months on Site
set target_names = list string No string Yes
set X = values
set y = values
comment Create decisi... | import pandas as pd
from sklearn import tree
data = pd.read_csv('customer_data.csv')
feature_names = ['Age','Gender','Occupation','Type','City','Member since','Months on Site']
target_names = ['No','Yes']
X = data[feature_names].values
y = data['Purchase'].values
# Create decision tree classifier
clf = tree.De... | Python | iamtarun_python_18k_alpaca |
comment ! python3
comment Multiclipboard - Saves and loads pieces of text to the clipboard.
comment Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
comment py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
comment py.exe mcb.pyw list - Loads all keywords to clipboard.
comment py.exe mcb.pyw dele... | #! python3
# Multiclipboard - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
# py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
# py.exe mcb.pyw list - Loads all keywords to clipboard.
# py.exe mcb.pyw del... | Python | zaydzuhri_stack_edu_python |
function full_b_init shape name=none
begin
set values = call normal loc=0 scale=0.02 size=shape
return call variable values name=name
end function | def full_b_init(shape, name=None):
values = rng.normal(loc=0, scale=2e-2, size=shape)
return K.variable(values, name=name) | Python | nomic_cornstack_python_v1 |
function process_batch self batch
begin
comment extend with current batch
call _extend batch
comment unpack and compute bounds
set length = length obs
set c = c
comment normally we cannot compute samples for the last c elements, but
comment in the terminal case, we halluciante values where necessary
set end = if expres... | def process_batch(self, batch):
# extend with current batch
self._extend(batch)
# unpack and compute bounds
length = len(self.obs)
c = self.c
# normally we cannot compute samples for the last c elements, but
# in the terminal case, we halluciante values where ne... | Python | nomic_cornstack_python_v1 |
function __init__ self lr=0.1 shuffle=true deterministic=none activationFunction=lambda activation -> if expression activation > 0 then 1 else 0 printIt=false
begin
set lr = lr
set shuffle = shuffle
set epochs = deterministic
set activationFunction = activationFunction
set printIt = printIt
set trainTrace = call Percep... | def __init__(self, lr=.1, shuffle=True, deterministic=None, activationFunction = lambda activation: 1 if activation > 0 else 0, printIt=False):
self.lr = lr
self.shuffle = shuffle
self.epochs = deterministic
self.activationFunction = activationFunction
self.printIt = printIt
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
set N = 1000
set D = 2
set R_inner = 5
set R_outer = 10
set R1 = randn N / 2 + R_inner
set theta = 2 * pi * random N / 2
set X_inner = T
set R2 = randn N / 2 + R_outer
set theta = 2 * pi * random N / 2
set X_outer = T
set X = concatenate list X_inner X_outer
set T = ar... | import numpy as np
import matplotlib.pyplot as plt
N = 1000
D = 2
R_inner = 5
R_outer = 10
R1 = np.random.randn(N/2) + R_inner
theta = 2*np.pi*np.random.random(N/2)
X_inner = np.concatenate([[R1*np.cos(theta)],[R1*np.sin(theta)]]).T
R2 = np.random.randn(N/2) + R_outer
theta = 2*np.pi*np.random.random(N/2)
X_outer =... | Python | zaydzuhri_stack_edu_python |
comment Strings in python are surrounded by either single or double quotation marks.
set name = string Kevin
set age = 32
comment Concatenate
comment print('Hello my name is '+ name + ' and I am '+ str(age))
comment String Formatting
comment Arguments by Position
comment print('My name is {name} and I am {age} years ol... | # Strings in python are surrounded by either single or double quotation marks.
name = 'Kevin'
age = 32
# Concatenate
# print('Hello my name is '+ name + ' and I am '+ str(age))
# String Formatting
# Arguments by Position
# print('My name is {name} and I am {age} years old.'.format(name=name, age=age))
# print('My n... | Python | zaydzuhri_stack_edu_python |
from day_01.numbers import add_two_numbers
set name = string martin
print string hello { name } here
print call add_two_numbers 2.44 4.89
call help add_two_numbers | from day_01.numbers import add_two_numbers
name = "martin"
print(f"hello {name} here")
print(add_two_numbers(2.44, 4.89))
help(add_two_numbers) | Python | zaydzuhri_stack_edu_python |
function get_spot_info self loc
begin
return spots at loc at 0 at loc at 1
end function | def get_spot_info(self, loc):
return self.spots[loc[0]][loc[1]] | Python | nomic_cornstack_python_v1 |
function write_state value
begin
call write_message call StateMessage value=value
end function | def write_state(value):
write_message(StateMessage(value=value)) | Python | nomic_cornstack_python_v1 |
function run_post_apply self migrations force=false
begin
for m in post_apply
begin
call apply_one m mark=false force=force
end
end function | def run_post_apply(self, migrations, force=False):
for m in migrations.post_apply:
self.apply_one(m, mark=False, force=force) | Python | nomic_cornstack_python_v1 |
function __init__ self request_id api seq client server status start end annotation meta
begin
set request_id = request_id
set api = api
set seq = seq
set client = client
set server = server
set status = status
set start = start
set end = end
set annotation = annotation
set meta = meta
end function | def __init__(self, request_id, api, seq, client, server, status, start,
end, annotation, meta):
self.request_id = request_id
self.api = api
self.seq = seq
self.client = client
self.server = server
self.status = status
self.start = start
se... | Python | nomic_cornstack_python_v1 |
function device_palm_rejection self device_palm_rejection=none
begin
return call _send_msg params=device_palm_rejection
end function | def device_palm_rejection(self, device_palm_rejection=None):
return self._send_msg(params=device_palm_rejection) | Python | nomic_cornstack_python_v1 |
function format_json_date value
begin
string Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
if not value
begin
return none
end
comment %f will include 6 microsecond digits
set micro_precision = string format time call astimezone UTC JSON_DATETIME_FORMAT
comment only kee... | def format_json_date(value):
"""
Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
"""
if not value:
return None
# %f will include 6 microsecond digits
micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT)
# only ... | Python | jtatman_500k |
comment importing necessary libraries
import pandas as pd
import collections
import numpy as np
import time
set start = time
class HiddenMarkovModel extends object
begin
comment class init function, transitions, emissions, list of sentences all assigned here.
function __init__ self train_folderpath test_folderpath
begi... | #importing necessary libraries
import pandas as pd
import collections
import numpy as np
import time
start = time.time()
class HiddenMarkovModel(object):
#class init function, transitions, emissions, list of sentences all assigned here.
def __init__(self, train_folderpath, test_folderpath):
self.... | Python | zaydzuhri_stack_edu_python |
comment cwc
import random
function display roll tempscore player count h c
begin
set trow = string * * * * * * * * * * * * * * * * * * * * * * * * *
if player == - 1
begin
set t = string *
set playerName = string HUMAN
end
else
begin
set t = string *
set playerName = string COMPUTER
end
comment print(t+"roll count h c"... | #cwc
import random
def display(roll,tempscore,player,count,h,c):
trow = "* * * * * * * * * * * * * * * * * * * * * * * * *"
if(player == -1):
t="*\t"
playerName = "HUMAN"
else:
t= "*\t\t\t"
playerName = "COMPUTER"
#print(t+"roll count h c")
print(trow)
print(t+... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment 整数の入力
set tuple a b = map int split input
if a * b % 2 == 0
begin
set ans = string Even
end
else
begin
set ans = string Odd
end
print ans | # -*- coding: utf-8 -*-
# 整数の入力
a, b = map(int, input().split())
if a*b % 2 == 0:
ans = "Even"
else:
ans = "Odd"
print(ans) | Python | zaydzuhri_stack_edu_python |
function typesafe self other
begin
if block == block or __class__ == __class__
begin
return false
end
else
if type_ == ANY or type_ == ANY
begin
comment Anything is possible with ANY
return true
end
else
begin
return type_ == type_
end
end function | def typesafe(self, other: 'Pin') -> bool:
if self.block == other.block or self.__class__ == other.__class__:
return False
elif self.type_ == Type.ANY or other.type_ == Type.ANY:
return True # Anything is possible with ANY
else:
return self.type_ == other.type... | Python | nomic_cornstack_python_v1 |
function compress_string string
begin
set compressed = list
set count = 1
for i in range 1 length string
begin
if string at i == string at i - 1
begin
set count = count + 1
end
else
begin
append compressed tuple string at i - 1 count
set count = 1
end
end
append compressed tuple string at - 1 count
return compressed
e... | def compress_string(string):
compressed = []
count = 1
for i in range(1, len(string)):
if string[i] == string[i-1]:
count += 1
else:
compressed.append((string[i-1], count))
count = 1
compressed.append((string[-1], count))
return compresse... | Python | jtatman_500k |
comment write a program that emulates the strip() method,
comment it strips all multiple white spaces either sides of words in a string
comment and replaces that string so it only has one white space in between each separate word.
set s = input string Input a phrase to strip:
set output = string
set i = 0
while i < le... | # write a program that emulates the strip() method,
# it strips all multiple white spaces either sides of words in a string
# and replaces that string so it only has one white space in between each separate word.
s = input("Input a phrase to strip: ")
output = ""
i = 0
while i < len(s):
while i < len(s) and s[i... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
comment The above encoding declaration is required and the file must be saved as UTF-8
from entities.organization import Organization
class OrganizationService extends object
begin
function __init__ self requester
begin
set __requester = requester
end function... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
from ..entities.organization import Organization
class OrganizationService(object):
def __init__(self, requester):
self.__requester = requester
def getOrganizations(self):
... | Python | zaydzuhri_stack_edu_python |
string Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None
from collections import defaultdict
class Solution
begin
string @param: root: the root of binary tree @return: collect and remove all leaves
function findLeaves self root
begin
if not root
begin
ret... | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import defaultdict
class Solution:
"""
@param: root: the root of binary tree
@return: collect and remove all leaves
"""
def findLeaves(sel... | Python | zaydzuhri_stack_edu_python |
function makeLegacyData
begin
with open string C:/Users/NeilS/Desktop/FantasyBoyzUSA/info/newLegacy.json string r as file
begin
set legacy = load json file
end
set regWinsBig = list
set leaderBig = list
set bigGamesBig = list
set regPointsBig = list
set postWinsBig = list
set champsBig = list
set standingBig = li... | def makeLegacyData():
with open('C:/Users/NeilS/Desktop/FantasyBoyzUSA/info/newLegacy.json','r') as file:
legacy = json.load(file)
regWinsBig = []
leaderBig = []
bigGamesBig = []
regPointsBig = []
postWinsBig = []
champsBig = []
standingBig = []
teamList = []
for team in legacy: teamList.append(team)
year... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
comment 本题为考试多行输入输出规范示例,无需提交,不计分。
comment 1
comment 5
comment S###.
comment ...#.
comment E#.##
comment .#..#
comment .####
import sys
if __name__ == string __main__
begin
set next = list list 0 1 list 0 - 1 list 1 0 list - 1 0
set T = integer strip read line stdin
for i in range T
begin
set n = in... | #coding=utf-8
# 本题为考试多行输入输出规范示例,无需提交,不计分。
# 1
# 5
# S###.
# ...#.
# E#.##
# .#..#
# .####
import sys
if __name__ == "__main__":
next=[[0,1],[0,-1],[1,0],[-1,0]]
T = int(sys.stdin.readline().strip())
for i in range(T):
n = int(sys.stdin.readline().strip())
matrix = [[0]*n for i in range(... | Python | zaydzuhri_stack_edu_python |
function on_forever
begin
call show_number call temperature
if call temperature >= 25 and call temperature <= 34
begin
call show_number call temperature
call show_icon HAPPY
call pause 500
end
else
begin
call show_number call temperature
call show_icon SAD
call pause 500
end
end function
call forever on_forever | def on_forever():
basic.show_number(input.temperature())
if input.temperature() >= 25 and input.temperature() <= 34:
basic.show_number(input.temperature())
basic.show_icon(IconNames.HAPPY)
basic.pause(500)
else:
basic.show_number(input.temperature())
basic.show_icon(I... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string parses info from api
import json
import requests
if __name__ == string __main__
begin
set USER_ID = string
set USERNAME = string
set TASK_COMPLETED_STATUS = string
set TASK_TITLE = string
set r = get requests string https://jsonplaceholder.typicode.com/users
set a = get requests str... | #!/usr/bin/python3
"""parses info from api"""
import json
import requests
if __name__ == "__main__":
USER_ID = ""
USERNAME = ""
TASK_COMPLETED_STATUS = ""
TASK_TITLE = ''
r = requests.get('https://jsonplaceholder.typicode.com/users')
a = requests.get('https://jsonplaceholder.typicode.com/todos'... | Python | zaydzuhri_stack_edu_python |
comment 이제 multiprocessing 대신 concurrent.futures 를 임포트하자.
comment import multiprocessing
import concurrent.futures
import time
comment do_something()의 수정
function do_something seconds
begin
print string Sleeping { seconds } second(s)...
sleep seconds
comment print('Done Sleeping...')
return string Done Sleeping...
end ... | # 이제 multiprocessing 대신 concurrent.futures 를 임포트하자.
# import multiprocessing
import concurrent.futures
import time
## do_something()의 수정
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
# print('Done Sleeping...')
return 'Done Sleeping...'
if __nam... | Python | zaydzuhri_stack_edu_python |
function do_author_listing parser token
begin
set contents = call split_contents
if length contents not in list 5 7
begin
raise call TemplateSyntaxError string %r tag requires 4 or 6 arguments. % contents at 0
end
else
if length contents == 5
begin
set tuple tag obj_var count fill var_name = contents
return call Author... | def do_author_listing(parser, token):
contents = token.split_contents()
if len(contents) not in [5, 7]:
raise template.TemplateSyntaxError('%r tag requires 4 or 6 arguments.' % contents[0])
elif len(contents) == 5:
tag, obj_var, count, fill, var_name = contents
return AuthorL... | 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.