code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment coding=utf-8
import discord
import random
set client = call Client
decorator event
async function on_ready
begin
print string Logged in as
print name
print id
print string ------
end function
decorator event
async function on_message message
begin
if bot
begin
return
end
if content == string ルール
begin
set rulel... | # coding=utf-8
import discord
import random
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.author.bot:
return
if message.content=="ル... | Python | zaydzuhri_stack_edu_python |
function assert_equals expected received
begin
if expected != received
begin
set stack = call extract_stack
set frame = stack at - 2
end
end function | def assert_equals(expected,received):
if (expected != received):
stack = traceback.extract_stack()
frame = stack[-2] | Python | nomic_cornstack_python_v1 |
function set_names self text base ruby
begin
if language == chinese_code
begin
if not ruby
begin
raise call ValueError string Nothing to download
end
set base_name = format string {0}_{1} base ruby
set display_text = format string {1} ({0}) base ruby
end
else
begin
if not text
begin
raise call ValueError string Nothing... | def set_names(self, text, base, ruby):
if self.language == self.chinese_code:
if not ruby:
raise ValueError('Nothing to download')
self.base_name = u"{0}_{1}".format(base, ruby)
self.display_text = u"{1} ({0})".format(base, ruby)
else:
if n... | Python | nomic_cornstack_python_v1 |
comment This program allows customers to order simple breakfasts.
comment It also validates user inputs.
import time
comment Print Introduction
function intro
begin
call print_pause string Hello! I am Bob, the Breakfast Bot.
call print_pause string Today we have two breakfasts available.
call print_pause string The fir... | # This program allows customers to order simple breakfasts.
# It also validates user inputs.
import time
# Print Introduction
def intro():
print_pause("Hello! I am Bob, the Breakfast Bot.\n")
print_pause("Today we have two breakfasts available.\n")
print_pause("The first is waffles with strawberries and w... | Python | zaydzuhri_stack_edu_python |
function urls product
begin
return list string http://report
end function | def urls(product):
return ["http://report"] | Python | nomic_cornstack_python_v1 |
comment show file lines
import sys
import os
if length argv != 2
begin
print string the argument is wrong
end
else
begin
set filename = argv at 1
if not exists path filename
begin
print string the file:%s is not exists. % filename
end
else
begin
set f = open filename string r
print string the file:%s has %d lines % tup... | # show file lines
import sys
import os
if len(sys.argv) != 2:
print("the argument is wrong")
else:
filename = sys.argv[1]
if not os.path.exists(filename):
print("the file:%s is not exists." % (filename))
else:
f = open(filename, "r")
print("the file:%s has %d lines" % (filename... | Python | zaydzuhri_stack_edu_python |
function buildCube self x_center y_center z_center step cote
begin
set fig = figure
set ax = call add_subplot 111 projection=string 3d
for i in range - cote / 2 cote / 2 step
begin
for j in range - cote / 2 cote / 2 step
begin
for k in range - cote / 2 cote / 2 step
begin
append z_cube_vector k + z_center
append y_cube... | def buildCube(self, x_center, y_center, z_center, step, cote):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(-cote/2, cote/2, step):
for j in range(-cote/2, cote/2, step):
for k in range(-cote / 2, cote / 2, step):
se... | Python | nomic_cornstack_python_v1 |
function label_training_data
begin
set training_images = list
for i in call tqdm list directory training_data
begin
set path = join path training_data i
set image_file = call imread path IMREAD_GRAYSCALE
set image_file = call resize image_file tuple 64 64
append training_images list array image_file call one_hot_label... | def label_training_data():
training_images = []
for i in tqdm(os.listdir(training_data)):
path = os.path.join(training_data, i)
image_file = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
image_file = cv2.resize(image_file, (64,64))
training_images.append([np.array(image_file),
Label(i).one_hot_label()])
random.... | Python | nomic_cornstack_python_v1 |
string drives the process
import sys
import os
import glob
from CodeWriter import CodeWriter
if __name__ == string __main__
begin
set user_input = argv at 1
set counter = 0
if is directory path user_input
begin
change directory user_input
set final_file = list
set to_init = true
for file in glob glob string *.vm
begin... | """drives the process"""
import sys
import os
import glob
from CodeWriter import CodeWriter
if __name__ == '__main__':
user_input = sys.argv[1]
counter = 0
if os.path.isdir(user_input):
os.chdir(user_input)
final_file = []
to_init = True
for file in glob.glob("*.vm"):
... | Python | zaydzuhri_stack_edu_python |
function findframe startdir camera grating filename
begin
set grating = sub string \/ string _ grating
set gdir = camera + grating
if is file path join path startdir filename
begin
return startdir
end
else
begin
comment now the grating directory
if is file path join path startdir gdir filename
begin
return join path st... | def findframe(startdir,camera,grating,filename):
grating = re.sub("\/","_",grating)
gdir = camera + grating
if os.path.isfile(os.path.join(startdir,filename)):
return(startdir)
else:
# now the grating directory
if os.path.isfile(os.path.join(startdir,gdir,filename)):
... | Python | nomic_cornstack_python_v1 |
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
set gedata = read csv string /Users/moritatarou/Dropbox/01_study/02_YagaiLab/2020/intro/python/14Zn1Gejc.csv delimiter=string ,
set nogedata = read csv string /Users/moritatarou/Dropbox/01_study/02_YagaiLab/2020/intro/pyth... | import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
gedata = pd.read_csv('/Users/moritatarou/Dropbox/01_study/02_YagaiLab/2020/intro/python/14Zn1Gejc.csv', delimiter=',')
nogedata = pd.read_csv('/Users/moritatarou/Dropbox/01_study/02_YagaiLab/2020/intro/python/15Znjc.csv',... | Python | zaydzuhri_stack_edu_python |
function test_no_section_by_section self
begin
set notice = dict string document_number string 111-22 ; string fr_volume 22 ; string cfr_part string 100 ; string publication_date string 2010-10-10
set s = call SectionBySection none notices=list notice
assert equal none process call Node label=list string 100 string 22
... | def test_no_section_by_section(self):
notice = {
"document_number": "111-22",
"fr_volume": 22,
"cfr_part": "100",
"publication_date": "2010-10-10"
}
s = SectionBySection(None, notices=[notice])
self.assertEqual(None, s.process(Node(label=['... | Python | nomic_cornstack_python_v1 |
function run_checks df
begin
comment Find flowpath column
set fpcol = list comprehension x for x in columns if starts with x string fp at 0
set gordcol = list comprehension x for x in columns if starts with x string gord at 0
set fplencol = list comprehension x for x in columns if starts with x string fpLen at 0
set gd... | def run_checks(df):
# Find flowpath column
fpcol = [x for x in df.columns if x.startswith("fp")][0]
gordcol = [x for x in df.columns if x.startswith("gord")][0]
fplencol = [x for x in df.columns if x.startswith("fpLen")][0]
gdf = df.groupby(fpcol).agg([np.min, np.max])
# collapse multiindex
... | Python | nomic_cornstack_python_v1 |
function test_vfy_paircode_functionality_wrong_paircode flask_app db session
begin
set pair_code = string Y9DwX2OM
set imei = string 928019923475048
call complete_db_insertion session db 512 string 923046831111 512 string F-3 string OPPO string U7a2eTazbh string 3G,4G pair_code 512 imei
set url = format string {api}?pa... | def test_vfy_paircode_functionality_wrong_paircode(flask_app, db, session):
pair_code = 'Y9DwX2OM'
imei = '928019923475048'
complete_db_insertion(session, db, 512, '923046831111', 512, 'F-3', 'OPPO', 'U7a2eTazbh', '3G,4G',
pair_code, 512, imei)
url = '{api}?pair_code=A1B2C3D4&i... | Python | nomic_cornstack_python_v1 |
if lower ty_pe == string K
begin
set converted = weight / 0.45
print string Weight in Lbs: + string converted
end
else
begin
set converted_ = weight * 0.45
print string Weight in K: + string converted_
end | if ty_pe.lower() == 'K':
converted = weight / 0.45
print('Weight in Lbs: ' + str(converted))
else:
converted_ = weight * 0.45
print('Weight in K: ' + str(converted_))
| Python | zaydzuhri_stack_edu_python |
from levelstone4 import Contacto , Agenda
function menu
begin
print string ----MENU-----
print string 1-agregar Contacto
print string 2-Buscar Contacto
print string 3-Modificar
print string 4-Mostrar
print string 5-salir
return input string opcion:
end function
function agregar agenda
begin
print string -----HOLA VAMOS... | from levelstone4 import Contacto, Agenda
def menu():
print('----MENU-----')
print('1-agregar Contacto')
print('2-Buscar Contacto')
print('3-Modificar')
print('4-Mostrar')
print('5-salir')
return input("opcion: \t")
def agregar(agenda):
print("-----HOLA VAMOS A CARGAR CONTACTOS----")
nombre = input("Ingrese e... | Python | zaydzuhri_stack_edu_python |
function civic_eid74_proposition
begin
return dict string id string proposition:Vyzbpg-s6mw27yJfYBFxGyQeuEJacP4l ; string type string diagnostic_proposition ; string predicate string is_diagnostic_inclusion_criterion_for ; string subject string ga4gh:VA.GweduWrfxV58YnSvUBfHPGOA-KCH_iIl ; string object_qualifier string ... | def civic_eid74_proposition():
return {
"id": "proposition:Vyzbpg-s6mw27yJfYBFxGyQeuEJacP4l",
"type": "diagnostic_proposition",
"predicate": "is_diagnostic_inclusion_criterion_for",
"subject": "ga4gh:VA.GweduWrfxV58YnSvUBfHPGOA-KCH_iIl",
"object_qualifier": "ncit:C3879"
} | Python | nomic_cornstack_python_v1 |
class Memoize
begin
function __init__ self fn
begin
set fn = fn
set memo = dict
end function
function __call__ self *args
begin
if args not in memo
begin
set memo at args = call fn *args
end
return memo at args
end function
end class
decorator Memoize
function lcs strA strB
begin
if length strA == 0 or length strB == ... | class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if args not in self.memo:
self.memo[args] = self.fn(*args)
return self.memo[args]
@Memoize
def lcs(strA, strB):
if len(strA) == 0 or len(strB) == 0:
return 0
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string ---------------------------------------------------- after specifying a splitting field and a compare field, splits data into HI and LO by the splitting field, then compares the compare field between T and F separately for HI and then for LO. provides t-test, MW U test, and Cohen's ... | #!/usr/bin/env python3
"""----------------------------------------------------
after specifying a splitting field and a compare field,
splits data into HI and LO by the splitting field,
then compares the compare field between T and F separately for HI and then for LO.
provides t-test, MW U test, and Cohen's d
Does a ... | Python | zaydzuhri_stack_edu_python |
import logging
import sys
import Queue
import json
import urllib2
import urllib
import threading
import hashlib
append path string ..
from config import CONFIG
from common import my_request
class Finger extends object
begin
function __init__ self domain
begin
set data = list
set domain = string http:// + domain
set Q ... | import logging
import sys
import Queue
import json
import urllib2
import urllib
import threading
import hashlib
sys.path.append("..")
from config import CONFIG
from common import my_request
class Finger(object):
def __init__(self, domain):
self.data = []
self.domain = "http://" + domain
self.Q = Queue.Queue()... | Python | zaydzuhri_stack_edu_python |
import numpy as np
function minesweeper matrix
begin
set linha = call shape matrix at 0
set coluna = call shape matrix at 1
set big = zeros tuple linha + 2 coluna + 2
set m = zeros tuple linha coluna
set matrix = array matrix
set big at tuple slice 1 : call shape big at 0 - 1 : slice 1 : call shape big at 1 - 1 : = m... | import numpy as np
def minesweeper(matrix):
linha = np.shape(matrix)[0]
coluna = np.shape(matrix)[1]
big = np.zeros((linha+2,coluna+2))
m =np.zeros((linha,coluna))
matrix = np.array(matrix)
big[1:np.shape(big)[0]-1, 1:np.shape(big)[1]-1]=matrix
for i in range(0,linha):
... | Python | zaydzuhri_stack_edu_python |
function getUserInfo user_id
begin
set user = call one
return user
end function | def getUserInfo(user_id):
user = session.query(User).filter_by(id=user_id).one()
return user | Python | nomic_cornstack_python_v1 |
function memoization func
begin
set cache = dict
function wrapper *args
begin
set value = get cache args
if not value
begin
set value = call func *args
set cache at args = value
end
return value
end function
return wrapper
end function
class Solution extends object
begin
decorator memoization
comment Write your code h... | def memoization(func):
cache = {}
def wrapper(*args):
value = cache.get(args)
if not value:
value = func(*args)
cache[args] = value
return value
return wrapper
class Solution(object):
# Write your code here.
@memoization
def fib(self, n):
... | Python | zaydzuhri_stack_edu_python |
function reason self
begin
return get pulumi self string reason
end function | def reason(self) -> Optional[str]:
return pulumi.get(self, "reason") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
set __author__ = string zhangchengliang
set n = integer input
set arr = list map int split input
set arrSet = set arr
set sum = 0
for i in arrSet
begin
if count arr i > 2
begin
set sum = sum + 2
continue
end
set sum = sum + count arr i
end
print sum | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zhangchengliang'
n = int(input())
arr = list(map(int, input().split()))
arrSet = set(arr)
sum = 0
for i in arrSet:
if(arr.count(i) > 2):
sum += 2
continue
sum += arr.count(i)
print(sum) | Python | zaydzuhri_stack_edu_python |
function initialize self
begin
if real
begin
call connect self
end
else
begin
comment Connect python client to VREP
call connect
call connect self
end
end function | def initialize(self):
if self.real:
self.agent.connect(self)
else:
self.connect() # Connect python client to VREP
self.agent.connect(self) | Python | nomic_cornstack_python_v1 |
function add_to_playlist self playlist_name video_id
begin
print string add_to_playlist needs implementation
end function | def add_to_playlist(self, playlist_name, video_id):
print("add_to_playlist needs implementation") | Python | nomic_cornstack_python_v1 |
function get_rmnist_idx n labels test=false
begin
set indices = default dictionary list
for tuple i label in enumerate labels
begin
if length indices at label < n
begin
append indices at label i
end
end
set filename = if expression test is false then string ./RMNIST/indexes/rmnist + string n + string _train else string... | def get_rmnist_idx(n, labels, test=False):
indices = defaultdict(list)
for i, label in enumerate(labels):
if len(indices[label]) < n:
indices[label].append(i)
filename = "./RMNIST/indexes/rmnist" + str(n) + "_train" if test is False else "./RMNIST/indexes/rmnist" + str(
n) + "_te... | Python | nomic_cornstack_python_v1 |
function realistic_send self data flags=0
begin
comment print("Sending data: {}".format(data))
call settimeout 0.25
try
begin
set received = call recv 1
end
except timeout
begin
call settimeout none
return call send data flags
end
if length received == 0
begin
raise call BluetoothError string (104, 'Connection reset by... | def realistic_send(self, data: bytes, flags: int = 0) -> int:
# print("Sending data: {}".format(data))
self.sock.settimeout(0.25)
try:
received = self.sock.recv(1)
except socket.timeout:
self.sock.settimeout(None)
return self.sock.send(data, flags)
... | Python | nomic_cornstack_python_v1 |
function get resource_name id opts=none auto_delete_on_idle=none client_scoped_subscription=none client_scoped_subscription_enabled=none dead_lettering_on_filter_evaluation_error=none dead_lettering_on_message_expiration=none default_message_ttl=none enable_batched_operations=none forward_dead_lettered_messages_to=none... | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
auto_delete_on_idle: Optional[pulumi.Input[str]] = None,
client_scoped_subscription: Optional[pulumi.Input[pulumi.InputType['SubscriptionClientScopedSubscriptionArgs']]] = No... | Python | nomic_cornstack_python_v1 |
function __msu_ptr s_type
begin
set msu = call MScriptUtil
if s_type == string int or s_type == string short
begin
call createFromInt 0
if s_type == string int
begin
return call asIntPtr
end
else
begin
return call asShortPtr
end
end
else
if s_type == string double
begin
call createFromDouble 0.0
if s_type == string dou... | def __msu_ptr(s_type):
msu = OpenMaya.MScriptUtil()
if s_type == "int" or s_type == "short":
msu.createFromInt(0)
if s_type == "int":
return msu.asIntPtr()
else:
return msu.asShortPtr()
elif s_type == "double":
msu.createFromDouble(0.0)
if s_... | Python | nomic_cornstack_python_v1 |
function label self t
begin
if labels is none
begin
return none
end
set prev_label = none
for l in labels
begin
if time > t
begin
break
end
set prev_label = l
end
if prev_label is none
begin
return none
end
return name
end function | def label(self, t):
if self.labels is None:
return None
prev_label = None
for l in self.labels:
if l.time > t:
break
prev_label = l
if prev_label is None:
return None
return prev_label.name | Python | nomic_cornstack_python_v1 |
from get_option_chain import get_option_chain
from ib_insync import IB , Stock
import pandas as pd
from typing import List
function calc_option_contract_profit asks strikes multipliers rights future_price
begin
set right_is_call = apply rights lambda right -> if expression right == string C or right == string CALL then... | from get_option_chain import get_option_chain
from ib_insync import IB, Stock
import pandas as pd
from typing import List
def calc_option_contract_profit(
asks: List[float],
strikes: List[float],
multipliers: List[int],
rights: List[str],
future_price: float,
) -> List[float]:
right_is_call = r... | Python | zaydzuhri_stack_edu_python |
for i in range 5
begin
comment print(start + step*i, end="bb")
set result = result + string start + step * i + 1
end
print result | for i in range(5):
# print(start + step*i, end="bb")
result += str(start + step * i + 1)
print(result)
| Python | zaydzuhri_stack_edu_python |
import os
import socket
import sys
import datetime
import datetime as DT
function createMysqlDump
begin
set databaseName = argv at 3
set databaseUserName = argv at 1
set databasePassword = argv at 2
set backupTime = string format time datetime now string %Y%m%d%H%M%S
set outputFileName = databaseName + backupTime + str... | import os
import socket
import sys
import datetime
import datetime as DT
def createMysqlDump():
databaseName = sys.argv[3]
databaseUserName = sys.argv[1]
databasePassword = sys.argv[2]
backupTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S')
outputFileName = databaseName + b... | Python | zaydzuhri_stack_edu_python |
function _gen_garbled_AND_gate self labels0 labels1 labels2
begin
set tuple key0_0 key0_1 = labels0
set tuple key1_0 key1_1 = labels1
set tuple key2_0 key2_1 = labels2
set G = list
append G call garble_label key0_0 key1_0 key2_0
append G call garble_label key0_0 key1_1 key2_0
append G call garble_label key0_1 key1_0 k... | def _gen_garbled_AND_gate(self, labels0, labels1, labels2):
key0_0, key0_1 = labels0
key1_0, key1_1 = labels1
key2_0, key2_1 = labels2
G = []
G.append(garble_label(key0_0, key1_0, key2_0))
G.append(garble_label(key0_0, key1_1, key2_0))
G.append(ga... | Python | nomic_cornstack_python_v1 |
function running self running
begin
if running is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `running`, must not be `None`
end
set _running = running
end function | def running(self, running: float):
if running is None:
raise ValueError("Invalid value for `running`, must not be `None`") # noqa: E501
self._running = running | Python | nomic_cornstack_python_v1 |
from guizero import App , Drawing , Text , PushButton
from random import choice
from time import sleep
from format_num import format_num
set f = open string areas.txt
set data = split read f string
close f
set areas = dict
for line in data
begin
set areas at split line string : at 0 = integer replace split line string... | from guizero import App, Drawing, Text, PushButton
from random import choice
from time import sleep
from format_num import format_num
f = open('areas.txt')
data = f.read().split('\n')
f.close()
areas = {}
for line in data:
areas[line.split(': ')[0]] = int(line.split(': ')[1].replace(',', ''))
def button_pressed... | Python | zaydzuhri_stack_edu_python |
import cv2
function image_otsu img
begin
set img = call imread img 0
set tuple ret thr = call threshold img 0 255 THRESH_OTSU
return thr
end function
function image_resize img size
begin
set resized_image = call resize img tuple size at 0 size at 1
return resized_image
end function
function save_image save_path img
beg... | import cv2
def image_otsu(img):
img = cv2.imread(img, 0)
ret, thr = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)
return thr
def image_resize(img, size):
resized_image = cv2.resize(img, (size[0], size[1]))
return resized_image
def save_image(save_path, img):
cv2.imwrite(save_path, img)
# t... | Python | zaydzuhri_stack_edu_python |
function is_anagram str1 str2
begin
comment Check if both strings are empty or have length less than 2
if length str1 < 2 or length str2 < 2
begin
return false
end
comment Convert both strings to lowercase
set str1 = lower str1
set str2 = lower str2
comment Check if both strings contain at least one vowel and one conso... | def is_anagram(str1, str2):
# Check if both strings are empty or have length less than 2
if len(str1) < 2 or len(str2) < 2:
return False
# Convert both strings to lowercase
str1 = str1.lower()
str2 = str2.lower()
# Check if both strings contain at least one vowel and one conson... | Python | jtatman_500k |
function send_password_reset_email
begin
call send_password_reset_email username=call post_get string username email_addr=call post_get string email_address
return string Please check your mailbox.
end function | def send_password_reset_email():
aaa.send_password_reset_email(
username=post_get('username'),
email_addr=post_get('email_address')
)
return 'Please check your mailbox.' | Python | nomic_cornstack_python_v1 |
comment reliably restored by inspect
function handler_block obj handler_id
begin
pass
end function | def handler_block(obj, handler_id): # reliably restored by inspect
pass | Python | nomic_cornstack_python_v1 |
comment source: https://medium.com/@falconives/day-91-gensim-for-text-summarization-12aeb6485326
import requests
from gensim.summarization import summarize , keywords
set text = text
print string Summary:
print call summarize text ratio=0.01
print string Keywords:
print call keywords text ratio=0.01
comment Result
comm... | # source: https://medium.com/@falconives/day-91-gensim-for-text-summarization-12aeb6485326
import requests
from gensim.summarization import summarize, keywords
text = requests.get('http://rare-technologies.com/the_matrix_synopsis.txt').text
print("Summary:")
print(summarize(text, ratio=0.01))
print("\nKeywords:")
pr... | Python | zaydzuhri_stack_edu_python |
function downloadCSV data
begin
if data
begin
comment Generate csv from data
call generateCSV data
return get current directory + string /log.csv
end
else
begin
return false
end
end function | def downloadCSV(data):
if data:
# Generate csv from data
generateCSV(data)
return os.getcwd() + '/log.csv'
else:
return False | Python | nomic_cornstack_python_v1 |
function analyze_sorting_performance arr
begin
comment Bubble Sort
function bubble_sort arr
begin
set comparisons = 0
set swaps = 0
set n = length arr
for i in range n
begin
for j in range 0 n - i - 1
begin
set comparisons = comparisons + 1
if arr at j > arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at... | def analyze_sorting_performance(arr):
# Bubble Sort
def bubble_sort(arr):
comparisons = 0
swaps = 0
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
comparisons += 1
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = ... | Python | jtatman_500k |
function __eq__ self other
begin
return call isvariadic other and set variadic_type == set variadic_type
end function | def __eq__(self, other):
return isvariadic(other) and set(self.variadic_type) == set(other.variadic_type) | Python | nomic_cornstack_python_v1 |
function first self
begin
if call is_empty
begin
raise exception string Deque is empty
end
return _element
end function | def first(self):
if self.is_empty():
raise Exception('Deque is empty')
return self._header._next._element | Python | nomic_cornstack_python_v1 |
function test_optional_none_to_int self
begin
set optional_value = call optional
assert false is_set
set optional_value = call set_value 5
assert true is instance optional_value int
assert equal optional_value + 5 10
assert true is_set
assert false is_default
end function | def test_optional_none_to_int(self):
optional_value = optional.optional()
self.assertFalse(optional_value.is_set)
optional_value = optional_value.set_value(5)
self.assertTrue(isinstance(optional_value, int))
self.assertEqual(optional_value + 5, 10)
self.assertTrue(optiona... | Python | nomic_cornstack_python_v1 |
import sys
set index = 0
comment 0 read preamble
comment 1 read packet number H
comment 2 read packet number M
comment 3 read packet number L
comment 4 read throttle value H
comment 5 read throttle value L
comment 6 read output PWM H
comment 7 read output PWM L
comment 8 read output RPM H
comment 9 read output RPM L
se... | import sys
index=0
#0 read preamble
#1 read packet number H
#2 read packet number M
#3 read packet number L
#4 read throttle value H
#5 read throttle value L
#6 read output PWM H
#7 read output PWM L
#8 read output RPM H
#9 read output RPM L
f = open(sys.argv[1], "rb")
last_pn=0
byte = 1
try:
while True:
byte = [... | Python | zaydzuhri_stack_edu_python |
function addition a b
begin
return a + b
end function
function test_numbers_3_4
begin
assert call addition 2 3 == 5
assert call addition 5 6 == 11
assert call addition 9 0 == 9
end function | def addition(a, b):
return a + b
def test_numbers_3_4():
assert addition(2,3) == 5
assert addition(5,6) == 11
assert addition (9,0) == 9
| Python | zaydzuhri_stack_edu_python |
function armStrong num
begin
comment num = int(input("Enter a number : ")) #123456
set num_copy = num
set num_of_digits = 0
comment 1
while num_copy
begin
comment num_of_digits = 6
set num_of_digits = num_of_digits + 1
comment 0
set num_copy = num_copy // 10
end
comment print(f"Total num of digits in {num} are {num_of_... | def armStrong(num):
#num = int(input("Enter a number : ")) #123456
num_copy = num
num_of_digits = 0
while num_copy : #1
num_of_digits += 1 #num_of_digits = 6
num_copy = num_copy // 10 #0
#print(f"Total num of digits in {num} are {num_of_digits}")
num_copy = num... | Python | nomic_cornstack_python_v1 |
function wait_for_confirmation self txid
begin
set last_round = get call status string last-round
set txinfo = call pending_transaction_info txid
while not get txinfo string confirmed-round and get txinfo string confirmed-round > 0
begin
print string Waiting for confirmation
set last_round = last_round + 1
call status_... | def wait_for_confirmation(self, txid):
last_round = self.algod_client.status().get('last-round')
txinfo = self.algod_client.pending_transaction_info(txid)
while not (txinfo.get('confirmed-round') and txinfo.get('confirmed-round') > 0):
print("Waiting for confirmation")
la... | Python | nomic_cornstack_python_v1 |
for i in list range length palavra2
begin
set contador = 0
for j in list range length palavra1
begin
if palavra1 at j == palavra2 at i
begin
if contador > 0
begin
print string end=string
end
print j end=string
set contador = contador + 1
end
end
set x = length palavra2 - 1
if contador == 0
begin
print - 1
end
else
beg... | for i in list(range(len(palavra2))):
contador = 0
for j in list(range(len(palavra1))):
if palavra1[j] == palavra2[i]:
if contador > 0:
print(" ", end = "")
print(j, end = "")
contador += 1
x = (len(palavra2)-1)
if contador == 0:
print(... | Python | zaydzuhri_stack_edu_python |
function eval_infix_product expr
begin
set ans = call eval_infix_exponent expr
set oper = call peek
while call peek in string */%
begin
call __next__
set other = call eval_infix_exponent expr
if oper == string *
begin
set ans = ans * other
end
else
if oper == string /
begin
set ans = ans / other
end
set oper = call pee... | def eval_infix_product(expr):
ans = eval_infix_exponent(expr)
oper = expr.peek()
while expr.peek() in "*/%":
expr.__next__()
other = eval_infix_exponent(expr)
if oper == '*':
ans *= other
elif oper == '/':
ans /= other
oper = expr.peek()
return ans | Python | nomic_cornstack_python_v1 |
comment Function space
function ica_correction raw picks
begin
comment ## Function "ica_correction" will correct artifacts in eeg data
comment (eg. blink) using ICA and return an ICA array under "my-ica.fif"
comment Will also plot ICA components
from mne.preprocessing import ICA
from mne.preprocessing import create_eog... | #### Function space
def ica_correction(raw, picks):
# ## Function "ica_correction" will correct artifacts in eeg data
# (eg. blink) using ICA and return an ICA array under "my-ica.fif"
## Will also plot ICA components
from mne.preprocessing import ICA
from mne.preprocessing import create_... | Python | zaydzuhri_stack_edu_python |
function run self verbose=false
begin
set verbose = verbose
if data is none
begin
set tuple model_run lce lce_run = call build_model
end
else
begin
set tuple model_run lce lce_run = data
end
set tuple ts_data results = call build_esn model_run
return tuple model_run tuple lce lce_run ts_data results
end function | def run(self, verbose=False):
self.verbose = verbose
if self.data is None:
model_run, lce, lce_run = self.build_model()
else:
model_run, lce, lce_run = self.data
ts_data, results = self.build_esn(model_run)
return model_run, (lce, lce_run), ts_data, result... | Python | nomic_cornstack_python_v1 |
function _remove_unencrypted_cell_sections encryptor_dict col_dict
begin
set source_locations = set
set target_locations = set
for tuple cell_string encryptor in items encryptor_dict
begin
update source_locations cell_sections
add target_locations cell_string
end
for sec in source_locations - target_locations
begin
set... | def _remove_unencrypted_cell_sections(encryptor_dict, col_dict):
source_locations = set()
target_locations = set()
for (cell_string, encryptor) in encryptor_dict.items():
source_locations.update(encryptor.cell_sections)
target_locations.add(cell_string)
f... | Python | nomic_cornstack_python_v1 |
function make_tent product_id
begin
set best_use_id = integer get form string bestuse
set sleep = integer get form string sleep
set seasoncat = integer get form string seasoncat
set weight = integer get form string weight
comment Deal with optional values.
try
begin
set width = integer get form string width
end
except ... | def make_tent(product_id):
best_use_id = int(request.form.get("bestuse"))
sleep = int(request.form.get("sleep"))
seasoncat = int(request.form.get("seasoncat"))
weight = int(request.form.get("weight"))
# Deal with optional values.
try:
width = int(request.form.get("width"))
except V... | Python | nomic_cornstack_python_v1 |
function get_cpu
begin
comment running processes
with open string /proc/loadavg string r as f
begin
comment e.g. 52.10 52.07 52.04 53/2016 54847 -> 53-1 = 52
set used = max integer split split read f at 3 string / at 0 - 1 0
end
with open string /proc/cpuinfo string r as f
begin
set total = 0
for l in read lines f
begi... | def get_cpu():
#running processes
with open('/proc/loadavg','r') as f:
#e.g. 52.10 52.07 52.04 53/2016 54847 -> 53-1 = 52
used = max(int(f.read().split()[3].split('/')[0]) - 1, 0)
with open('/proc/cpuinfo','r') as f:
total = 0
for l in f.readlines():
if l.startswith('processor'):
total += 1
return ... | Python | nomic_cornstack_python_v1 |
function post self description file_path type_map
begin
debug string Sending request to the schema matcher server to post a dataset.
set uri = _uri
try
begin
set f = dict string file open file_path string rb
set data = dict string description string description ; string typeMap type_map
set r = post uri data=data files... | def post(self, description, file_path, type_map):
logging.debug('Sending request to the schema matcher server to post a dataset.')
uri = self._uri
try:
f = {"file": open(file_path, "rb")}
data = {
"description": str(description),
"typeMa... | Python | nomic_cornstack_python_v1 |
function as_array self minimum_address=none padding=none separator=string ,
begin
string Format the binary file as a string values separated by given separator `separator`. This function can be used to generate array initialization code for C and other languages. `minimum_address` is the start address of the resulting ... | def as_array(self, minimum_address=None, padding=None, separator=', '):
"""Format the binary file as a string values separated by given
separator `separator`. This function can be used to generate
array initialization code for C and other languages.
`minimum_address` is the start addres... | Python | jtatman_500k |
function deleteFile self CorpNum MgtKeyType MgtKey FileID UserID=none
begin
string 첨부파일 삭제 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 UserID : 팝빌 회원아이디 return 처리결과. consist of code and message raise PopbillException
if MgtKeyType not in __MgtKeyTypes
begin
raise call... | def deleteFile(self, CorpNum, MgtKeyType, MgtKey, FileID, UserID=None):
""" 첨부파일 삭제
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
처리결... | Python | jtatman_500k |
function model_performance predictions test_labels
begin
set errors = absolute predictions - test_labels
comment mean absolute percentage error (MAPE)
set mape = 100 * errors / test_labels + EPSILON
set accuracy = 100 - mean np mape
print string Mean Absolute Error : round mean np errors 2
print string Model Accuracy :... | def model_performance(predictions, test_labels):
errors = abs(predictions - test_labels)
# mean absolute percentage error (MAPE)
mape = 100 * (errors / (test_labels + EPSILON))
accuracy = 100 - np.mean(mape)
print("Mean Absolute Error : ", round(np.mean(errors), 2))
print("Model Accuracy ... | Python | nomic_cornstack_python_v1 |
import os
import json
import cv2
import numpy as np
import argparse
import math
from glob import glob
from typing import List , Tuple
from tqdm import tqdm
from multiprocessing import Pool
import logging
class VideoReader
begin
function __init__ self file_name args
begin
comment path to viedeo file or camera id
set fil... | import os
import json
import cv2
import numpy as np
import argparse
import math
from glob import glob
from typing import List, Tuple
from tqdm import tqdm
from multiprocessing import Pool
import logging
class VideoReader:
def __init__(self, file_name, args):
self.file_name = file_name # pa... | Python | zaydzuhri_stack_edu_python |
from getpass import getpass
print string Hello to the world of CODE!
set n = input string Username:
set x = call getpass string Password:
if n == string KhauTu
begin
if x == string Tahy
begin
print string successfully login!
end
else
begin
print string Wrong password!
end
end
else
begin
print string Username not valid!... | from getpass import getpass
print("Hello to the world of CODE!")
n = input("Username: ")
x = getpass("Password: ")
if n == "KhauTu":
if x == "Tahy":
print("successfully login!")
else:
print("Wrong password!")
else:
print("Username not valid!")
| Python | zaydzuhri_stack_edu_python |
comment ! /var/cfengine/bin/python
for i in range 5
begin
print string I ranked + string i
end
print string Well done | #! /var/cfengine/bin/python
for i in range(5):
print("I ranked " + str(i))
print("Well done")
| Python | zaydzuhri_stack_edu_python |
function drawcube_old
begin
set allpoints = list zip CUBE_POINTS CUBE_COLORS
call glBegin GL_QUADS
for face in CUBE_QUAD_VERTS
begin
for vert in face
begin
set tuple pos color = allpoints at vert
call glColor3fv color
call glVertex3fv pos
end
end
call glEnd
call glColor3f 1.0 1.0 1.0
call glBegin GL_LINES
for line in C... | def drawcube_old():
allpoints = list(zip(CUBE_POINTS, CUBE_COLORS))
GL.glBegin(GL.GL_QUADS)
for face in CUBE_QUAD_VERTS:
for vert in face:
pos, color = allpoints[vert]
GL.glColor3fv(color)
GL.glVertex3fv(pos)
GL.glEnd()
GL.glColor3f(1.0, 1.0, 1.0)
GL... | Python | nomic_cornstack_python_v1 |
function pan self y_dist x_dist
begin
call pan_to max 0 _viewport_y + y_dist max 0 _viewport_x + x_dist
end function | def pan(self,y_dist,x_dist):
self.pan_to(max(0,self._viewport_y + y_dist),
max(0,self._viewport_x + x_dist)) | Python | nomic_cornstack_python_v1 |
function extract_values self possible_solution use_defaults=false
begin
set defaults = if expression use_defaults then _vardefaults else dict
set values = list _template
for tuple i var in enumerate _vars
begin
set values at i = get possible_solution var get defaults var call NilObject
end
return values
end function | def extract_values(self, possible_solution, use_defaults=False):
defaults = self._vardefaults if use_defaults else {}
values = list(self._template)
for i, var in enumerate(self._vars):
values[i] = possible_solution.get(var, defaults.get(var, NilObject()))
return values | Python | nomic_cornstack_python_v1 |
function _checkPermission self module
begin
set permission = list
for p in path
begin
set path = join path p module at 0
if is directory path path
begin
if not call access path R_OK ? X_OK
begin
append permission true
end
else
if length module > 1 and any generator expression call access join path path init F_OK for i... | def _checkPermission(self, module):
permission = []
for p in sys.path:
path = os.path.join(p, module[0])
if os.path.isdir(path):
if not os.access(path, os.R_OK | os.X_OK):
permission.append(True)
elif (len(module) > 1... | Python | nomic_cornstack_python_v1 |
function single_time_stream self stream_time=120 do_plot=false fmin=5 fmax=50
begin
call take_ts stream_time=stream_time
if do_plot
begin
call plot_ts
end
call get_median_bias_wl fmin=fmin fmax=fmax
if verbose
begin
print string wl_median { wl_median }
end
end function | def single_time_stream(self, stream_time=120, do_plot=False, fmin=5, fmax=50):
self.time_stream_data.take_ts(stream_time=stream_time)
if do_plot:
self.time_stream_data.plot_ts()
self.time_stream_data.get_median_bias_wl(fmin=fmin, fmax=fmax)
if self.verbose:
print(... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- encoding: utf-8 -*-
comment HTTP Passive cookie implementation: https://web.archive.org/web/20150603012044/https://support.f5.com/kb/en-us/products/big-ip_ltm/manuals/product/ltm_configuration_guide_10_0_0/ltm_persist_profiles.html
comment https://support.f5.com/csp/article/K83... | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# HTTP Passive cookie implementation: https://web.archive.org/web/20150603012044/https://support.f5.com/kb/en-us/products/big-ip_ltm/manuals/product/ltm_configuration_guide_10_0_0/ltm_persist_profiles.html
# https://support.f5.com/csp/article/K83419154
# Source: http:/... | Python | zaydzuhri_stack_edu_python |
function instruction_SBC self opcode m register
begin
string Subtracts the contents of memory location M and the borrow (in the C (carry) bit) from the contents of the designated 8-bit register, and places the result in that register. The C bit represents a borrow and is set to the inverse of the resulting binary carry... | def instruction_SBC(self, opcode, m, register):
"""
Subtracts the contents of memory location M and the borrow (in the C
(carry) bit) from the contents of the designated 8-bit register, and
places the result in that register. The C bit represents a borrow and is
set to the invers... | Python | jtatman_500k |
function get_note_shared self
begin
if not call is_note_shared
begin
raise call AttributeError string tag 'note_shared' not set
end
return _value
end function | def get_note_shared(self):
if not self.is_note_shared():
raise AttributeError("tag 'note_shared' not set")
return self._value | Python | nomic_cornstack_python_v1 |
function write_uint32 self val timeout=0
begin
write self call pack string !I val timeout
end function | def write_uint32(self, val, timeout = 0):
self.write(struct.pack("!I", val), timeout) | Python | nomic_cornstack_python_v1 |
set dictionary = dict string key1 1 ; string key2 3 ; string key3 2
set sorted_dict = dictionary comprehension key : value for tuple key value in sorted items dictionary key=lambda item -> item at 1 | dictionary = {'key1':1, 'key2': 3, 'key3': 2}
sorted_dict = {key: value for key, value in sorted(dictionary.items(), key=lambda item: item[1])} | Python | iamtarun_python_18k_alpaca |
function link self obj
begin
return call get_absolute_url
end function | def link(self, obj):
return obj.get_absolute_url() | Python | nomic_cornstack_python_v1 |
import xml.etree.ElementTree as ET
function extract_book_details xml_str book_id
begin
comment Parse the XML string
set root = call fromstring xml_str
comment Iterate over the book elements
for book in iterate string book
begin
if attrib at string id == book_id
begin
comment Check if the book is available for borrowing... | import xml.etree.ElementTree as ET
def extract_book_details(xml_str, book_id):
# Parse the XML string
root = ET.fromstring(xml_str)
# Iterate over the book elements
for book in root.iter('book'):
if book.attrib['id'] == book_id:
# Check if the book is available for borrowing
... | Python | greatdarklord_python_dataset |
comment !/usr/bin/python
import urllib
import time
import color_markup_string as cms
from isAGirl import *
set myfile = open string log string a
set data = open string data string a | #!/usr/bin/python
import urllib
import time
import color_markup_string as cms
from isAGirl import *
myfile = open("log","a")
data = open("data","a")
| Python | zaydzuhri_stack_edu_python |
function obtain_labeled_data i_type=TRAIN i_person=ALL_PERSONS i_degrees=ALL_DEGREES i_orientation=ALL_ORIENTATIONS i_color=GRAYSCALE
begin
set current_df = call _filter_df i_type i_person i_degrees i_orientation i_color
if i_color == RGB
begin
set images = call to_numpy
set labels = call to_numpy
return tuple images l... | def obtain_labeled_data(i_type=DataType.TRAIN, i_person=Label.ALL_PERSONS, i_degrees=Angle.ALL_DEGREES, i_orientation=Orientation.ALL_ORIENTATIONS, i_color=Color.GRAYSCALE):
current_df = ImageAccess._filter_df(i_type, i_person, i_degrees, i_orientation, i_color)
if i_color == Color.RGB:
im... | Python | nomic_cornstack_python_v1 |
async function main
begin
set parser = call ArgumentParser description=string Generate network IoCs for files matching a VTI query.
call add_argument string --apikey required=true help=string your VirusTotal API key
call add_argument string --query required=true help=string VT Intelligence search query
call add_argumen... | async def main():
parser = argparse.ArgumentParser(
description="Generate network IoCs for files matching a VTI query."
)
parser.add_argument("--apikey", required=True, help="your VirusTotal API key")
parser.add_argument(
"--query", required=True, help="VT Intelligence search query"
)
parser.add... | Python | nomic_cornstack_python_v1 |
function label self
begin
return _label
end function | def label(self):
return self._label | Python | nomic_cornstack_python_v1 |
function validate_batch_size_for_multi_gpu batch_size
begin
from tensorflow.python.client import device_lib
set local_device_protos = call list_local_devices
set num_gpus = sum list comprehension 1 for d in local_device_protos if device_type == string GPU
if not num_gpus
begin
raise call ValueError string Multi-GPU mod... | def validate_batch_size_for_multi_gpu(batch_size):
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
num_gpus = sum([1 for d in local_device_protos if d.device_type == 'GPU'])
if not num_gpus:
raise ValueError('Multi-GPU mode was specified, but no GPUs '
... | Python | nomic_cornstack_python_v1 |
comment encoding = utf-8
string 通过一段时间的波动率对操作价格进行加权,如果波动较大,应该加大操作价格
import math
import tushare as ts
import pandas as pd
from Auto_Report.Auto_Email.Email_SendPdf import dumpPickle
from SDK.DBOpt import genDbConn
from SDK.MyTimeOPT import add_date_str , get_current_date_str
from SendMsgByQQ.QQGUI import send_qq
functio... | # encoding = utf-8
"""
通过一段时间的波动率对操作价格进行加权,如果波动较大,应该加大操作价格
"""
import math
import tushare as ts
import pandas as pd
from Auto_Report.Auto_Email.Email_SendPdf import dumpPickle
from SDK.DBOpt import genDbConn
from SDK.MyTimeOPT import add_date_str, get_current_date_str
from SendMsgByQQ.QQGUI import send_qq
def calW... | Python | zaydzuhri_stack_edu_python |
import sys
import numpy as np
import matplotlib.pyplot as plt
import operator
comment requires file to be in SLiM's sample data format - 'outputSample' or 'outputFull'
comment input: filename, popSize (sample size of file), genome Size, number of windows
class Mutation
begin
function __init__ self kind position num
beg... | import sys
import numpy as np
import matplotlib.pyplot as plt
import operator
# requires file to be in SLiM's sample data format - 'outputSample' or 'outputFull'
#input: filename, popSize (sample size of file), genome Size, number of windows
class Mutation:
def __init__(self, kind, position, num):
self.typ... | Python | zaydzuhri_stack_edu_python |
function test_from_healpix_int self
begin
seed 12345
set nside_coverage = 32
set nside_map = 128
set full_map = zeros call nside_to_npixel nside_map dtype=int32 + min
set full_map at slice 0 : 5000 : = poisson size=5000
set sparse_map = call HealSparseMap healpix_map=full_map nside_coverage=nside_coverage sentinel=min... | def test_from_healpix_int(self):
np.random.seed(12345)
nside_coverage = 32
nside_map = 128
full_map = np.zeros(hpg.nside_to_npixel(nside_map), dtype=np.int32) + np.iinfo(np.int32).min
full_map[0: 5000] = np.random.poisson(size=5000)
sparse_map = healsparse.HealSparseMa... | Python | nomic_cornstack_python_v1 |
comment Contest: Codeforces Round #797 (Div. 3)
comment https://codeforces.com/contest/1690/problem/B
comment B. Array Decrements # Solved
set t = integer input
for blahblah in range t
begin
set n = integer input
set a = list comprehension integer x for x in split input
set b = list comprehension integer x for x in spl... | # Contest: Codeforces Round #797 (Div. 3)
# https://codeforces.com/contest/1690/problem/B
# B. Array Decrements # Solved
t = int(input())
for blahblah in range(t):
n = int(input())
a =[int(x) for x in input().split()]
b =[int(x) for x in input().split()]
c = set()
temp_zero = -1
flag = ... | Python | zaydzuhri_stack_edu_python |
class GlossaryError extends Exception
begin
string Base error for everything that can go wrong in Glossary operations.
function __init__ self message
begin
call __init__ message
end function
end class | class GlossaryError(Exception):
"""Base error for everything that can go wrong in Glossary operations."""
def __init__(self, message):
super(Exception, self).__init__(message)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import os
from statsmodels.tsa.stattools import adfuller
set path = get current directory
set data = read csv path + string /close.csv
set data at string Date = call to_datetime data at string Date
set index data string Date inplace=true
set tickers = list values
set data = data /... | import pandas as pd
import numpy as np
import os
from statsmodels.tsa.stattools import adfuller
path = os.getcwd()
data = pd.read_csv(path + '/close.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace = True)
tickers = list(data.columns.values)
data = data/data.iloc[0]
result_dict = {}
t... | Python | zaydzuhri_stack_edu_python |
function display_global
begin
set variable_1 = variable_1 + 1
print variable_1
end function
set variable_1 = 2
call display_global | def display_global ():
variable_1 = variable_1 + 1
print (variable_1)
variable_1 = 2
display_global ()
| Python | zaydzuhri_stack_edu_python |
function __init__ self units norm activation
begin
call __init__
set dense = dense units
set functions = list dense
if norm is not none
begin
if norm == string batch
begin
append functions batch normalization
end
else
if norm == string instance
begin
raise call NotImplementedError string Instance norm requires tensorfl... | def __init__(self, units, norm, activation):
super().__init__()
dense = tf.keras.layers.Dense(units)
self.functions = [dense]
if norm is not None:
if norm == "batch":
self.functions.append(tf.keras.layers.BatchNormalization())
elif norm == "instanc... | Python | nomic_cornstack_python_v1 |
async function test_config_entry_not_ready mock_request hass mock_config_entry
begin
call add_to_hass hass
await call async_setup entry_id
await call async_block_till_done
assert call_count == 1
assert state is SETUP_RETRY
end function | async def test_config_entry_not_ready(
mock_request: MagicMock, hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_request.call_count ... | Python | nomic_cornstack_python_v1 |
for tuple name number in items phonebook
begin
print string Phone number of %s is %d % tuple name number
end
pop phonebook string Jill
print phonebook | for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
phonebook.pop("Jill")
print(phonebook)
| Python | zaydzuhri_stack_edu_python |
comment Those coordinates are collected manually
comment key - name of the station
comment value - latitude, longitude pair
set SUBWAY_DATA = dict string Площадь Победы tuple 53.908273 27.574682 ; string Каменная Горка tuple 53.906645 27.439102 ; string Кунцевщина tuple 53.907354 27.454018 ; string Спортивная tuple 53.... | # Those coordinates are collected manually
# key - name of the station
# value - latitude, longitude pair
SUBWAY_DATA = {
"Площадь Победы": (53.908273, 27.574682),
"Каменная Горка": (53.906645, 27.439102),
"Кунцевщина": (53.907354, 27.454018),
"Спортивная": (53.909800, 27.480059),
"Пушкинская": (53... | Python | zaydzuhri_stack_edu_python |
function parse_single_token self token
begin
if starts with token string "
begin
return strip token string "
end
if starts with token string :
begin
return token
end
if token == string T
begin
return true
end
else
if token == string NIL
begin
return none
end
try
begin
return integer token
end
except ValueError
begin
pa... | def parse_single_token(self, token):
if token.startswith('"'):
return token.strip('"')
if token.startswith(':'):
return token
if token == 'T':
return True
elif token == 'NIL':
return None
try:
return int(token)
... | Python | nomic_cornstack_python_v1 |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
set screen = call Screen
setup screen width=600 height=400
call tracer 0
set player = call Player
set car = call CarManager
set score = Scoreboard
call turt
call outline
call listen
set g... | import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=400)
screen.tracer(0)
player = Player()
car = CarManager()
score = Scoreboard
player.turt()
player.outline()
screen.listen()
game_is... | Python | zaydzuhri_stack_edu_python |
function request_url url list_iter=true verbose=false
begin
set req = url open url
if verbose
begin
print call getcode call geturl
end
if call getcode == 200
begin
return req
end
else
comment or req.getcode() == 503 or req.getcode() == 504:
if call getcode == 429
begin
call request_url url list_iter=list_iter verbose=v... | def request_url(url, list_iter=True, verbose=False):
req = urllib2.urlopen(url)
if verbose:
print(req.getcode(), req.geturl())
if req.getcode() == 200:
return req
elif req.getcode() == 429: # or req.getcode() == 503 or req.getcode() == 504:
request_url(url, list_iter=list_iter,... | Python | nomic_cornstack_python_v1 |
comment Nesse exemplo o erro acontece por que a entrada de dados no python
comment são consideradas como strings, então para resolver vc precisa converter
comment o numero para um valor int() inteiro | #Nesse exemplo o erro acontece por que a entrada de dados no python
#são consideradas como strings, então para resolver vc precisa converter
#o numero para um valor int() inteiro
| Python | zaydzuhri_stack_edu_python |
from textblob import TextBlob
function sentiment_analysis text
begin
set blob = call TextBlob text
for sentence in sentences
begin
print string Sentence: { sentence }
print string Polarity: { polarity }
print string Subjectivity: { subjectivity }
end
end function
comment Example usage:
set text = string I love this lib... | from textblob import TextBlob
def sentiment_analysis(text):
blob = TextBlob(text)
for sentence in blob.sentences:
print(f'Sentence: {sentence}')
print(f'Polarity: {sentence.sentiment.polarity}')
print(f'Subjectivity: {sentence.sentiment.subjectivity}')
# Example usage:
text = 'I love t... | Python | flytech_python_25k |
function _retrieve_easypost_stripe_api_key
begin
set requestor = call Requestor
set tuple public_key _ = call request method=GET url=string /partners/stripe_public_key
return get public_key string public_key string
end function | def _retrieve_easypost_stripe_api_key() -> str:
requestor = Requestor()
public_key, _ = requestor.request(
method=RequestMethod.GET,
url="/partners/stripe_public_key",
)
return public_key.get("public_key", "") | 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.