code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function steer self
begin
call rt 10
end function | def steer(self):
self.rt(10) | Python | nomic_cornstack_python_v1 |
comment A Priority Queue is a Queue(anyList, compareTo)
comment where Anylist is one of:
comment None, or
comment Pair(value, anyList)
class PriorityQueue
begin
function __init__ self list comes_before
begin
set list = list
set comes_before = comes_before
end function
function __eq__ self other
begin
return type other ... | # A Priority Queue is a Queue(anyList, compareTo)
# where Anylist is one of:
# None, or
# Pair(value, anyList)
class PriorityQueue:
def __init__(self, list, comes_before):
self.list = list
self.comes_before = comes_before
def __eq__(self, other):
return (type(other) == Priorit... | Python | zaydzuhri_stack_edu_python |
function update_input_states
begin
for input_type in values _actions
begin
for actions in values input_type
begin
for action in actions
begin
call update_state
end
end
end
end function | def update_input_states():
for input_type in _actions.values():
for actions in input_type.values():
for action in actions:
action.update_state() | Python | nomic_cornstack_python_v1 |
import pygame
set RAPID_SPEED = 15
class LibraryPyGame
begin
function __init__ self
begin
set rapid = true
end function
function isPlaying self
begin
if not call get_busy
begin
return false
end
if rapid and call get_pos > 1000 * RAPID_SPEED
begin
return false
end
return true
end function
function play self trackName
be... | import pygame
RAPID_SPEED=15
class LibraryPyGame:
def __init__(self):
self.rapid=True
def isPlaying(self):
if not pygame.mixer.music.get_busy():
return False
if self.rapid and pygame.mixer.music.get_pos()> 1000*RAPID_SPEED:
return False
return True
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Mar 4 22:06:43 2021. @author: richa
class QuoteModel
begin
string Class for building quote objects.
function __init__ self body author
begin
set body = body
set author = author
end function
function __repr__ self
begin
string Print the body and author of quote.
return... | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 22:06:43 2021.
@author: richa
"""
class QuoteModel():
"""Class for building quote objects."""
def __init__(self, body, author):
self.body = body
self.author = author
def __repr__(self):
"""Print the body and autho... | Python | zaydzuhri_stack_edu_python |
function get_inner_velo radius outer_speed
begin
set inner_velo = outer_speed * square root radius ^ 2 - 0.31 * radius + 0.1013 / radius + 0.2
set inner_cen_velo = outer_speed * radius - 2 / radius + 0.2
return tuple inner_velo inner_cen_velo
end function | def get_inner_velo(radius: float, outer_speed: float) -> tuple:
inner_velo = outer_speed * (
math.sqrt(radius ** 2 - 0.31 * radius + 0.1013) / (radius + 0.2)
)
inner_cen_velo = outer_speed * ((radius - 2) / (radius + 0.2))
return (inner_velo, inner_cen_velo) | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set module_params = call get_unity_management_host_parameters
update module_params call get_unity_filesystem_parameters
set mutually_exclusive = list list string filesystem_name string filesystem_id list string pool_name string pool_id list string nas_server_name string nas_server_id list s... | def __init__(self):
self.module_params = utils.get_unity_management_host_parameters()
self.module_params.update(get_unity_filesystem_parameters())
mutually_exclusive = [['filesystem_name', 'filesystem_id'],
['pool_name', 'pool_id'],
['... | Python | nomic_cornstack_python_v1 |
string Author: Wen Wei Zheng Course: SSW 540 Assignment: P6 - Slicing and Dicing Files
set run = string 1
while run == string 1
begin
set count = 0
set SPAM_Total = 0
try
begin
set filename = input string What file would you like to open?
set fhand = open filename
end
except any
begin
print string File + filename + str... | """
Author: Wen Wei Zheng
Course: SSW 540
Assignment: P6 - Slicing and Dicing Files
"""
run = "1"
while run == "1":
count=0
SPAM_Total=0
try:
filename = input("What file would you like to open? ")
fhand = open(filename)
except:
print("File " +filename+ " was not f... | Python | zaydzuhri_stack_edu_python |
import random
set chances = 0
set number = random integer 1 10
print string Number guess name
print string Guess a number between 1 and 9
while chances < 5
begin
set chances = chances + 1
set guess = integer input string Enter your guess :-
if guess < number
begin
print string Your guess was too low
end
else
if guess >... | import random
chances = 0
number = random.randint(1,10)
print("Number guess name")
print("Guess a number between 1 and 9")
while chances < 5:
chances = chances+1
guess = int(input("Enter your guess :- "))
if guess < number:
print("Your guess was too low")
elif guess > number:
print("... | Python | zaydzuhri_stack_edu_python |
function get_temporal self
begin
call unimpl_base_class
end function | def get_temporal(self):
self.unimpl_base_class() | Python | nomic_cornstack_python_v1 |
function file_engine_node_count self
begin
return get pulumi self string file_engine_node_count
end function | def file_engine_node_count(self) -> int:
return pulumi.get(self, "file_engine_node_count") | Python | nomic_cornstack_python_v1 |
function is_declined self
begin
return call get_data string state == STATE_DECLINED
end function | def is_declined(self):
return self.get_data("state") == self.STATE_DECLINED | Python | nomic_cornstack_python_v1 |
set name = input string Please input your name:
set age = input string Please iput your age:
print string My name is name string . I'm age string years old. | name = input ("Please input your name: ")
age = input ("Please iput your age: ")
print ("My name is ",name, ". I'm ",age," years old.") | Python | zaydzuhri_stack_edu_python |
function __init__ self candidate
begin
set candidate = join string candidate
call __make_alphabetical
end function | def __init__(self, candidate: Union[str, List[str]]):
self.candidate = ''.join(candidate)
self.__make_alphabetical() | Python | nomic_cornstack_python_v1 |
for i in range m
begin
set tuple w1 w2 = split input
set d at w1 = if expression length w2 < length w1 then w2 else w1
end
print join string list comprehension d at s for s in split input | for i in range(m):
w1, w2 = input().split()
d[w1] = w2 if len(w2) < len(w1) else w1
print(" ".join([d[s] for s in input().split()])) | Python | zaydzuhri_stack_edu_python |
comment 17
set n = integer input
set ori = split input string
set num = list comprehension integer item for item in ori
set dup = list
for item in num
begin
if item not in dup
begin
append dup item
end
end
sort dup
if length dup > 3
begin
print - 1
end
else
if length dup == 3
begin
if dup at 2 - dup at 1 != dup at 1 -... | #17
n = int(input())
ori = input().split(" ")
num =[int(item) for item in ori]
dup = []
for item in num:
if item not in dup:
dup.append(item)
dup.sort()
if(len(dup)>3):
print(-1)
elif len(dup)==3:
if dup[2]-dup[1] != dup[1]-dup[0]:
print(-1)
else:
print(dup[1]-dup[0])
elif len(du... | Python | zaydzuhri_stack_edu_python |
function test_from_json nested_example
begin
set json_str = to json nested_example
set reconstructed = call from_json json_str
assert reconstructed == nested_example
end function | def test_from_json(nested_example):
json_str = nested_example.to_json()
reconstructed = js.from_json(json_str)
assert reconstructed == nested_example | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_intarray_intarray_intarray_floatnum_595 self
begin
comment This version is expected to pass.
call fma floatarrayx floatarrayy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma intarrayx intarrayy intarrayz floatnumout
end
end function | def test_fma_invalid_param_intarray_intarray_intarray_floatnum_595(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.intarrayx, self.intarrayy, se... | Python | nomic_cornstack_python_v1 |
import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
seed 42
set random_x = random integer 1 101 100
set random_y = random integer 1 101 100
comment between 1 to 100 it gives us 100 integers
comment Now we'll plot the graph
set data = list scatter go x=random_x y=random_y mode=string markers m... | import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
np.random.seed(42)
random_x = np.random.randint(1,101,100)
random_y = np.random.randint(1,101,100)
# between 1 to 100 it gives us 100 integers
# Now we'll plot the graph
data=[go.Scatter(x=random_x,
y=random_y,
... | Python | zaydzuhri_stack_edu_python |
function name self
begin
return string ingredient_quantity_form
end function | def name(self) -> Text:
return "ingredient_quantity_form" | Python | nomic_cornstack_python_v1 |
set a = integer input string Pls enter a number
set sum = 0
while a > 0
begin
set sum = sum * 10 + a % 10
set a = a // 10
end
print sum | a=int(input('Pls enter a number'))
sum=0
while(a>0):
sum=sum*10+(a%10)
a=a//10
print(sum)
| Python | zaydzuhri_stack_edu_python |
function draw_mask_on_video model cap output_file
begin
set out = none
while call isOpened
begin
print string Reading input image
set tuple ret frame = read cap
print string Drawing masks on frames
set result = call process_image model frame
set img = call draw_mask_on_image result frame
if out is none
begin
set height... | def draw_mask_on_video(model, cap, output_file):
out = None
while(cap.isOpened()):
print("Reading input image")
ret, frame = cap.read()
print("Drawing masks on frames")
result = process_image(model, frame)
img = draw_mask_on_image(result, frame)
if out is None:
height = img.shape[0]
width = img.s... | Python | nomic_cornstack_python_v1 |
string Create a program that reads the length and width of a farmer’s field from the user in feet. Display the area of the field in acres. Hint: There are 43,560 square feet in an acre. x acres = (ancho en pies * largo en pies) / 43560 pies cuadrados
comment pies cuadrados
set ACRE = 43560
print string ===== Calcular l... | """
Create a program that reads the length and width of a farmer’s field from the user in
feet. Display the area of the field in acres.
Hint: There are 43,560 square feet in an acre.
x acres = (ancho en pies * largo en pies) / 43560 pies cuadrados
"""
ACRE = 43560 #pies cuadrados
print('===== Calcular la superficie ... | Python | zaydzuhri_stack_edu_python |
function test_service_rotating_parameters accelize_drm conf_json cred_json async_handler
begin
set driver = pytest_fpga_driver at 0
set async_cb = call create
set log_type = 2
set verbosity = 2
set rotating_size = 1024
set rotating_num = 5
set msg = string This is a message
comment Test from config file
set log_path = ... | def test_service_rotating_parameters(accelize_drm, conf_json, cred_json, async_handler):
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
log_type = 2
verbosity = 2
rotating_size = 1024
rotating_num = 5
msg = 'This is a message'
# Test from config file
... | Python | nomic_cornstack_python_v1 |
function date_to_version tag
begin
if match string \d\d\d\d\d\d\d\d tag
begin
set year = integer tag at slice 2 : 4 : - 20
set month = integer tag at slice 4 : 6 :
set day = integer tag at slice 6 : 8 :
return string { year } . { month } . { day }
end
return tag
end function | def date_to_version(tag):
if re.match(r"\d\d\d\d\d\d\d\d", tag):
year = int(tag[2:4]) - 20
month = int(tag[4:6])
day = int(tag[6:8])
return f"{year}.{month}.{day}"
return tag | Python | nomic_cornstack_python_v1 |
function doc_tests_cov_vs
begin
set tcmd = cmdd + covr + string -vs
call _run_tests tcmd mods dirs
end function | def doc_tests_cov_vs():
tcmd = cmdd+covr+' -vs '
_run_tests(tcmd, mods, dirs) | Python | nomic_cornstack_python_v1 |
comment from multiprocessing import Process, Queue
comment def task1(q):
comment print("我是子进程1")
comment q.put(111) # 3、我把一个东西放入了队列
comment if __name__ == '__main__':
comment q = Queue() # 1、创建一个队列
comment p = Process(target=task1, args=(q,))
comment p.start() # 2、开始了一个进程
comment p.join() # 这里这一步并不需要,因为get()如果没有东西会阻塞,直... | # from multiprocessing import Process, Queue
#
#
# def task1(q):
# print("我是子进程1")
# q.put(111) # 3、我把一个东西放入了队列
#
#
# if __name__ == '__main__':
# q = Queue() # 1、创建一个队列
# p = Process(target=task1, args=(q,))
# p.start() # 2、开始了一个进程
# p.join() # 这里这一步并不需要,因为get()如果没有东西会阻塞,直到有东西
# print(q... | Python | zaydzuhri_stack_edu_python |
function _getAttrMap self
begin
if not get attribute self string attrMap
begin
set attrMap = dict
for tuple key value in attrs
begin
set attrMap at key = value
end
end
return attrMap
end function | def _getAttrMap(self):
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap | Python | nomic_cornstack_python_v1 |
function setUp self
begin
setup call super
set opts = options
if get environ string TEST_ENABLE_HEADLESS none
begin
set headless = true
end
set drv = call Firefox options=opts
call set_window_size 1920 1080
call get_nav_to_ui drv
end function | def setUp(self):
super().setUp()
self.opts = webdriver.firefox.options.Options()
if environ.get("TEST_ENABLE_HEADLESS", None):
self.opts.headless = True
self.drv = webdriver.Firefox(options=self.opts)
self.drv.set_window_size(1920, 1080)
get_nav_to_ui(self.drv... | Python | nomic_cornstack_python_v1 |
function my_map1 func input_list
begin
comment 0. 빈 리스트를 만들고
comment 1. 인자로 받은 리스트를 돌면서
comment 2. 인자로 받은 함수를 각각의 요소에 적용한 값을 빈 리스트에 넣어서
comment 3. 빈 리스트를 리턴한다.
set new_list = list
for il in input_list
begin
append new_list call func il
end
return new_list
end function
function my_map2 func input_list
begin
return list... | def my_map1(func, input_list):
# 0. 빈 리스트를 만들고
# 1. 인자로 받은 리스트를 돌면서
# 2. 인자로 받은 함수를 각각의 요소에 적용한 값을 빈 리스트에 넣어서
# 3. 빈 리스트를 리턴한다.
new_list = []
for il in input_list:
new_list.append(func(il))
return new_list
def my_map2(func, input_list):
return [func(i) for i in input_list]... | Python | zaydzuhri_stack_edu_python |
import socket
from Crypto.Cipher import DES , AES , PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.Util.Padding import pad , unpad
import hashlib
import hmac
import time
from Crypto.Random import get_random_bytes
comment network configuration... | import socket
from Crypto.Cipher import DES, AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.Util.Padding import pad, unpad
import hashlib
import hmac
import time
from Crypto.Random import get_random_bytes
# network configura... | Python | zaydzuhri_stack_edu_python |
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import os
function data_import file_name
begin
comment input -> the name of the data file
comment output -> an edge list
set edge_list = list
with open file_name string r as f
begin
for e in read lines f
begin
set e = replace replace e string st... | import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import os
def data_import(file_name):
# input -> the name of the data file
# output -> an edge list
edge_list = []
with open(file_name,"r") as f:
for e in f.readlines():
e = e.replace(" ",",").replace("\n",""... | Python | zaydzuhri_stack_edu_python |
import argparse
import math
import glob
import os
import sys
import re
import numpy as np
import pandas as pd
from utilities.common import rbind_all
set parser = call ArgumentParser description=string Read set results and choose winners.
call add_argument string --raw type=str required=true help=string Path to raw gene... | import argparse
import math
import glob
import os
import sys
import re
import numpy as np
import pandas as pd
from utilities.common import rbind_all
parser = argparse.ArgumentParser(
description='Read set results and choose winners.')
parser.add_argument('--raw', type=str, required=True,
he... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
function graficoPreco ae nome
begin
comment Create "Y High" and "Y Low" values as 5% devs from mean
set tuple high low = tuple mean np ygrid * 1.05 mean np ygrid * 0.95
set tuple iy_high iy_low = generator expression... | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
def graficoPreco(ae, nome):
# Create "Y High" and "Y Low" values as 5% devs from mean
high, low = np.mean(ae.ygrid) * 1.05, np.mean(ae.ygrid) * .95
iy_high, iy_low = (np.searchsorted(ae.ygrid, x) for x i... | Python | zaydzuhri_stack_edu_python |
comment Jordan Walker CSC110 this code does the same thing as lab but instteead of putting # on the left its on the right
set code = string input string Enter bar string:
print string +---------+
set i = 0
while i < length code
begin
print string | + string * 9 - integer code at i + string # * integer code at i + stri... | # Jordan Walker CSC110 this code does the same thing as lab but instteead of putting # on the left its on the right
code = str(input("Enter bar string:\n"))
print("+---------+")
i = 0
while i<len(code):
print("|"+ " " * (9-int(code[i])) + "#" * int(code[i]) + "|")
i = i +1
print("+---------+")
| Python | zaydzuhri_stack_edu_python |
comment Convolutional Neural Network
comment 1. Building the CNN
comment Importing the Keras libraries packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ... | # Convolutional Neural Network
# 1. Building the CNN
# Importing the Keras libraries packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenera... | Python | zaydzuhri_stack_edu_python |
function __init__ self time=string center=string
begin
comment collection name to contain documents for the result
set name = string tat_results
if not type time is datetime
begin
set time = replace now hour=23 minute=59 second=59 microsecond=999
end
set lookup_time = time
comment not using it now
comment ptime = DC_D... | def __init__(self, time="", center=""):
# collection name to contain documents for the result
name = 'tat_results'
if not type(time) is datetime.datetime:
time = datetime.datetime.now().replace(
hour=23, minute=59, second=59, microsecond=999)
self.lookup_time ... | Python | nomic_cornstack_python_v1 |
function sort_sorted_lists a b
begin
comment Using merge sort
set merged_list = list
comment While there are still numbers in either a or b
while length a > 0 or length b > 0
begin
comment If a is an empty list, pop the first number of b
if a == list
begin
append merged_list pop b 0
end
else
comment If b is an empty ... | def sort_sorted_lists(a, b):
# Using merge sort
merged_list = []
# While there are still numbers in either a or b
while len(a) > 0 or len(b) > 0:
# If a is an empty list, pop the first number of b
if a == []:
merged_list.append(b.pop(0))
# If b is an empty list, p... | Python | nomic_cornstack_python_v1 |
import cv2
import imutils
set img = call imread string ../image/squirrel.jpg
set resizeImg = call resize img width=260
call imwrite string resizedImage.jpg resizeImg
image show string squirrel.jpg img
image show string resizedImage resizeImg | import cv2
import imutils
img = cv2.imread("../image/squirrel.jpg")
resizeImg = imutils.resize(img, width=260)
cv2.imwrite("resizedImage.jpg",resizeImg)
cv2.imshow("squirrel.jpg",img)
cv2.imshow("resizedImage",resizeImg)
| Python | zaydzuhri_stack_edu_python |
import mlrose
import numpy as np
from sklearn import metrics
from helpers import algos , data_helper , plot_helper , model_helper
function rhc X y lr title filename schedule=none max_iters=1000
begin
set nn = nn X y hidden_nodes=list 4 activation=string relu algorithm=string random_hill_climb max_iters=max_iters learni... | import mlrose
import numpy as np
from sklearn import metrics
from helpers import algos, data_helper, plot_helper, model_helper
def rhc(X, y, lr, title, filename, schedule=None, max_iters=1000):
nn = algos.NN(
X, y,
hidden_nodes = [4],
activation = 'relu',
algorithm = 'random_hill_... | Python | zaydzuhri_stack_edu_python |
function expand_schema engine=none
begin
call _validate_upgrade_order EXPAND_BRANCH engine=engine
call _db_sync EXPAND_BRANCH engine=engine
end function | def expand_schema(engine=None):
_validate_upgrade_order(EXPAND_BRANCH, engine=engine)
_db_sync(EXPAND_BRANCH, engine=engine) | Python | nomic_cornstack_python_v1 |
import mysql.connector
from mysql.connector.cursor import SQL_COMMENT
class dbConnection
begin
function __init__ self host user password database
begin
set host = host
set user = user
set password = password
set database = database
set conn = none
set cursor = none
end function
function getConn self
begin
try
begin
set... | import mysql.connector
from mysql.connector.cursor import SQL_COMMENT
class dbConnection():
def __init__(self,host,user,password,database):
self.host = host
self.user = user
self.password = password
self.database = database
self.conn = None
self.cursor = None
... | Python | zaydzuhri_stack_edu_python |
function server_memory self
begin
return TotalSystemMemoryGiB * 1024
end function | def server_memory(self):
return self.raw.MemorySummary.TotalSystemMemoryGiB * 1024 | Python | nomic_cornstack_python_v1 |
from math import pi
from math import sqrt
class Shape
begin
string A class to represent geometry shape with x-coordinate and y-coordinate
comment x: x coordinate, y: y coordinate
function __init__ self x y
begin
set x = x
set y = y
end function
decorator property
function x self
begin
string Read-only property, can't s... | from math import pi
from math import sqrt
class Shape:
"""A class to represent geometry shape with x-coordinate and y-coordinate"""
def __init__(self, x: float, y:float) -> None: #x: x coordinate, y: y coordinate
self.x = x
self.y = y
@property
def x(self)-> float:
"""Read-only... | Python | zaydzuhri_stack_edu_python |
import mysql.connector
import configparser
function admin_login password
begin
if password == string a
begin
set status = string Success
set message = string
end
else
if password == string
begin
set status = string Failed
set message = string パスワードを入力してください。
end
else
begin
set status = string Failed
set message = str... | import mysql.connector
import configparser
def admin_login(password):
if password == 'a':
status = 'Success'
message = ''
elif password == '':
status = 'Failed'
message = 'パスワードを入力してください。'
else:
status = 'Failed'
message = 'パスワードが正しくありません。'
return status,... | Python | zaydzuhri_stack_edu_python |
function is_team_folder_change_status self
begin
return _tag == string team_folder_change_status
end function | def is_team_folder_change_status(self):
return self._tag == 'team_folder_change_status' | Python | nomic_cornstack_python_v1 |
comment boxwocorners
for i in range 0 4
begin
call penup
call forward 20
call pendown
call forward 60
call penup
call forward 20
call right 90
end | # boxwocorners
for i in range(0,4):
t.penup()
t.forward(20)
t.pendown()
t.forward(60)
t.penup()
t.forward(20)
t.right(90) | Python | zaydzuhri_stack_edu_python |
comment Given data
set lst = list list 2 3 4 7 8 10 list 2 9 15 7 list 3 4 7 list list 4 20 10 2
comment Flattening the list and removing duplicate elements
set flattened_list = list set list comprehension num for sublist in lst for num in sublist
comment Finding the product of the elements which fulfill the criterion... | # Given data
lst = [[2, 3, 4, 7, 8, 10], [2, 9, 15, 7], [3, 4, 7], [], [4, 20, 10, 2]]
# Flattening the list and removing duplicate elements
flattened_list = list(set([num for sublist in lst for num in sublist]))
# Finding the product of the elements which fulfill the criterion
product = 1
for num in filtered_list:
... | Python | flytech_python_25k |
from get_data import *
set start = 0
set stop = 10000
set step = 100
comment def cycle_light(x, y):
comment for i in range(start, stop, step):
comment i = float(i)
comment cct, lumens = get_data(i)
comment light_control.cct(x, y, int(cct),int(lumens))
comment def sun():
comment row = 0
comment lights = light_control.ge... | from get_data import *
start = 0
stop = 10000
step = 100
# def cycle_light(x, y):
# for i in range(start, stop, step):
# i = float(i)
# cct, lumens = get_data(i)
# light_control.cct(x, y, int(cct),int(lumens))
# def sun():
# row = 0
# lights = light_control.get_lights()
# lights.sort()
# ... | Python | zaydzuhri_stack_edu_python |
import os
import random
import time
import sys
from termcolor import colored , cprint
from ast import literal_eval
set game_time = 0
set health = 6
set high_score_list = list
function load_list
begin
string Loading highscore list
global high_score_list
set score_file = open string score.txt string r
set high_score_lis... | import os
import random
import time
import sys
from termcolor import colored, cprint
from ast import literal_eval
game_time = 0
health = 6
high_score_list = []
def load_list():
"""Loading highscore list"""
global high_score_list
score_file = open('score.txt', 'r')
high_score_list = [list(literal_ev... | Python | zaydzuhri_stack_edu_python |
import socket
from socket import *
import os
import sys
import struct
import time
import select
set ICMP_ECHO_REQUEST = 8
function checksum string
begin
set csum = 0
set countTo = length string // 2 * 2
set count = 0
while count < countTo
begin
set thisVal = string at count + 1 * 256 + string at count
set csum = csum +... | import socket
from socket import *
import os
import sys
import struct
import time
import select
ICMP_ECHO_REQUEST = 8
def checksum(string):
csum = 0
countTo = (len(string) // 2) * 2
count = 0
while count < countTo:
thisVal = string[count + 1] * 256 + string[count]
csum = csum + thisVa... | Python | zaydzuhri_stack_edu_python |
function swap_plan self subscription_id body
begin
return execute call response call convertor create
end function | def swap_plan(self,
subscription_id,
body):
return super().new_api_call_builder.request(
RequestBuilder().server('default')
.path('/v2/subscriptions/{subscription_id}/swap-plan')
.http_method(HttpMethodEnum.POST)
.template_para... | Python | nomic_cornstack_python_v1 |
function test_owner_deletion nick email
begin
comment binds the app to the current context
with call clean_app_test_client config_name=string testing as client
begin
with call dummy_user nick=nick email=email as user
begin
comment generating a owner from hypothesis data via marshmallow
set owner_loaded = load owner_sch... | def test_owner_deletion(nick, email):
# binds the app to the current context
with clean_app_test_client(config_name="testing") as client:
with dummy_user(nick=nick, email=email) as user:
# generating a owner from hypothesis data via marshmallow
owner_loaded = owner_schema.load... | Python | nomic_cornstack_python_v1 |
import time
from Tkinter import *
from GibbotModel import *
from InputFrame import *
from GibbotFrame import *
from Controllers import *
set CONTROLLERS = dict string 1. Null nullController ; string 2. Spong Combined spongCombined ; string 2. Spong Swing Up spongSwingUpController ; string 3. Spong Balance spongBalanceC... | import time
from Tkinter import *
from GibbotModel import *
from InputFrame import *
from GibbotFrame import *
from Controllers import *
CONTROLLERS = {
"1. Null": nullController,
"2. Spong Combined": spongCombined,
"2. Spong Swing Up": spongSwingUpController,
"3. Spong Balance": spongBalanceControlle... | Python | zaydzuhri_stack_edu_python |
from Test_17_get_formatted_name import get_formatted_name
print string Enter 'q' at any time to quit.
while true
begin
set first_name = input string Please give me a first name:
if first_name == string q
begin
print string Good bye
break
end
set last_name = input string Please give me a last name:
if last_name == strin... | from Test_17_get_formatted_name import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
first_name = input("\nPlease give me a first name: ")
if first_name == 'q':
print('Good bye')
break
last_name = input("\nPlease give me a last name: ")
if last_name == 'q':
... | Python | zaydzuhri_stack_edu_python |
function most_recognized strings
begin
set max_string = string
set max_count = 0
for string in strings
begin
set count = length split string
if count > max_count
begin
set max_string = string
set max_count = count
end
end
return max_string
end function
set strings = list string Hello string Hi string Greeting
set most... | def most_recognized(strings):
max_string = ""
max_count = 0
for string in strings:
count = len(string.split())
if count > max_count:
max_string = string
max_count = count
return max_string
strings = ["Hello", "Hi", "Greeting"]
most_recognized_word = most_recogni... | Python | jtatman_500k |
function update_languages
begin
with open string languages.txt string r as f
begin
set languages = read lines f
end
with open string ui\snippet_dlg.glade string r as f
begin
set dlg = read lines f
end
set data_start = index dlg string <data>
set data_end = index dlg string </data>
del dlg at slice data_start + 1 : data... | def update_languages():
with open('languages.txt', 'r') as f:
languages = f.readlines()
with open('ui\snippet_dlg.glade', 'r') as f:
dlg = f.readlines()
data_start = dlg.index(' <data>\n')
data_end = dlg.index(' </data>\n')
del dlg[data_start + 1:data_end]
index = data_start + 1
for language in la... | Python | nomic_cornstack_python_v1 |
function flatten self arr
begin
if length shape == 2
begin
set out_arr = call empty size
end
else
begin
set tuple h w = shape at slice : 2 :
set out_arr = call empty tuple h * w + shape at slice 2 : :
end
for i in range shape at 0
begin
set out_arr at i = arr at where flatten_ == i
end
return out_arr
end function | def flatten(self, arr: np.ndarray):
if len(arr.shape) == 2:
out_arr = np.empty(arr.size)
else:
h,w = arr.shape[:2]
out_arr = np.empty((h*w,)+arr.shape[2:])
for i in range(out_arr.shape[0]):
out_arr[i] = arr[np.where(self.flatten_==i)]
retur... | Python | nomic_cornstack_python_v1 |
function insert conn tab fld val
begin
try
begin
set cur = call cursor
set sql = string INSERT INTO + tab + string ( + fld + string ) VALUES( + val + string );COMMIT;
execute cur sql
close cur
end
except tuple Exception DatabaseError as error
begin
print error
end
end function | def insert(conn,tab,fld,val):
try:
cur = conn.cursor()
sql = "INSERT INTO " + tab + "(" + fld + ") VALUES(" + val + ");COMMIT;"
cur.execute(sql)
cur.close()
except (Exception,psycopg2.DatabaseError) as error:
print(error) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import glob
import subprocess
import argparse
set cardDir = string /media/lurbano/K-1 II/DCIM/
set compDir = string /home/lurbano/Pictures/K1-II/
set parser = call ArgumentParser
call add_argument string -t string --type type=str default=string jpg help=string file type (case sensitive): '... | #!/usr/bin/env python3
import glob
import subprocess
import argparse
cardDir = '/media/lurbano/K-1 II/DCIM/'
compDir = '/home/lurbano/Pictures/K1-II/'
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--type", type=str, default="jpg", help = "file type (case sensitive): 'jpg' or 'raw'")
args = parser.pa... | Python | zaydzuhri_stack_edu_python |
function get_feature_meta_default x y feature_names=none label_name=string label labels=none featuredefs=none
begin
if feature_names is none
begin
set f_names = call Factor list comprehension string F%d % i + 1 for i in range shape at 1 sort=false
end
else
begin
if shape at 1 != length feature_names
begin
raise call Va... | def get_feature_meta_default(x, y, feature_names=None,
label_name='label', labels=None, featuredefs=None):
if feature_names is None:
f_names = Factor(["F%d" % (i+1) for i in range(x.shape[1])], sort=False)
else:
if x.shape[1] != len(feature_names):
raise ... | Python | nomic_cornstack_python_v1 |
string Python OODP Tutorial 4: Inheritance - Creating Subclasses
class Employee
begin
comment class variable;
set raise_amount = 1.04
comment constructor
function __init__ self first last pay
begin
set first = first
set last = last
set email = format string {}.{}@company.com first last
set pay = pay
end function
commen... | """
Python OODP Tutorial 4: Inheritance - Creating Subclasses
"""
class Employee:
raise_amount = 1.04 # class variable;
def __init__(self, first, last, pay): # constructor
self.first = first
self.last = last
self.email = "{}.{}@company.com".format(first, last)
self.pay = pay
... | Python | zaydzuhri_stack_edu_python |
class Rolling_Hash extends object
begin
function __init__ self s
begin
set HASH_BASE = 10
set seqlen = length s
set p = 17
set n = seqlen - 1
set h = 0
for c in s
begin
set h = h + ordinal c * HASH_BASE ^ n
set n = n - 1
end
set curhash = h % p
end function
function current_hash self
begin
return curhash
end function
f... | class Rolling_Hash(object):
def __init__(self, s):
self.HASH_BASE = 10
self.seqlen = len(s)
self.p = 17
n = self.seqlen - 1
h = 0
for c in s:
h += ord(c) * (self.HASH_BASE ** n)
n -= 1
self.curhash = h%self.p
def current_hash(sel... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
comment author huxh
comment time 2020/7/4 10:09 PM
function rightSideView root
begin
set stack = list tuple root 0
set res = dict
set max_depth = - 1
while stack
begin
set tuple node depth = pop stack
set max_depth = max depth max_depth
if node
begin
set res at depth = val
append stack tuple right... | # coding=utf-8
# author huxh
# time 2020/7/4 10:09 PM
def rightSideView(root):
stack = [(root, 0)]
res = {}
max_depth = -1
while stack:
node, depth = stack.pop()
max_depth = max(depth, max_depth)
if node:
res[depth] = node.val
stack.append((node.right... | Python | zaydzuhri_stack_edu_python |
function configDict config
begin
set config_dict = dict
set line_number = 0
if type config == str
begin
set config_object = call splitlines
end
else
begin
return string ERROR: config not type str
end
for tuple index line in enumerate config_object
begin
if not boolean match string ^\s|! line
begin
set line_number = in... | def configDict(config):
config_dict = {}
line_number = 0
if type(config) == str:
config_object = config.splitlines()
else:
return "ERROR: config not type str"
for index, line in enumerate(config_object):
if not bool(re.match("^\s|!", line)):
line_number = index
... | Python | nomic_cornstack_python_v1 |
for x in range 0 n + 1
begin
set sum = sum + x
end
print sum | for x in range(0,n+1):
sum=sum+x;
print(sum);
| Python | zaydzuhri_stack_edu_python |
for i in range length my_array
begin
for j in range i + 1 length my_array
begin
if my_array at i < my_array at j
begin
set tuple my_array at i my_array at j = tuple my_array at j my_array at i
end
end
end
for num in my_array
begin
print num
end | for i in range(len(my_array)):
for j in range(i+1, len(my_array)):
if my_array[i] < my_array[j]:
my_array[i], my_array[j] = my_array[j], my_array[i]
for num in my_array:
print(num) | Python | jtatman_500k |
from rest_framework import serializers
from django_redis import get_redis_connection
from redis import RedisError
from apps.users.models import User
import logging
import re
from magic.settings import REGEX_MOBILE
set logger = call getLogger string magic
class ImageCodeCheckSerializer extends Serializer
begin
string 检查... | from rest_framework import serializers
from django_redis import get_redis_connection
from redis import RedisError
from apps.users.models import User
import logging
import re
from magic.settings import REGEX_MOBILE
logger = logging.getLogger('magic')
class ImageCodeCheckSerializer(serializers.Serializer):
"""检查图片验证... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment Global variable
set result = list
set v = list string c string a string t string d string o string g
set cap = length v
set m = list 0 * cap
set cnt = 0
function generateSubset n
begin
global cnt
if n == cap
begin
set cnt = cnt + 1
print format string No {}: cnt result
end
else
begin... | #! /usr/bin/python3
# Global variable
result = []
v = ['c', 'a', 't', 'd', 'o', 'g']
cap = len(v)
m = [0] * cap
cnt = 0
def generateSubset(n):
global cnt
if n == cap:
cnt += 1
print('No {}: '.format(cnt), result)
else:
for i in range(cap):
if m[i] == 1:
continue
else:
m[i] = 1
result.appe... | Python | zaydzuhri_stack_edu_python |
function Init self *args
begin
return call BRepAlgo_FaceRestrictor_Init self *args
end function | def Init(self, *args):
return _BRepAlgo.BRepAlgo_FaceRestrictor_Init(self, *args) | Python | nomic_cornstack_python_v1 |
string Noah Brown CS 1410-602 Febuary 9th, 2020 Book Recommendation Project
comment Reading in the list of books from the file and making a list of them.
set readBooks = open string booklist.txt string r
set bookList = list
for book in readBooks
begin
set tempList = split strip book string ,
append bookList tuple temp... | """
Noah Brown
CS 1410-602
Febuary 9th, 2020
Book Recommendation Project
"""
#Reading in the list of books from the file and making a list of them.
readBooks = open("booklist.txt", "r")
bookList = []
for book in readBooks:
tempList = book.strip().split(",")
bookList.append((tempList[0],tempList[1]))
#Reading... | Python | zaydzuhri_stack_edu_python |
function move_right current_node
begin
set node = list list current_node at 0 list current_node at 1 list current_node at 2
set coordinate = list
set target_coordinate = list
set target_value = 0
set temp_value = 0
for row in range 0 3
begin
for tile in range 0 3
begin
set temp_value = node at row at tile
if temp_val... | def move_right(current_node:list)->list:
node = [list(current_node[0]),list(current_node[1]),list(current_node[2])]
coordinate = []
target_coordinate = []
target_value = 0
temp_value = 0
for row in range(0,3):
for tile in range(0,3):
temp_value = node[row][tile]
i... | Python | nomic_cornstack_python_v1 |
function test_get_score_with_pe_grader self
begin
set combinedoe = call CombinedOpenEndedV1Module test_system location definition descriptor static_data=static_data metadata=metadata instance_state=loads INSTANCE_INCONSISTENT_STATE2
set score_dict = call get_score
assert not equal score_dict at string score 15.0
end fu... | def test_get_score_with_pe_grader(self):
combinedoe = CombinedOpenEndedV1Module(self.test_system,
self.location,
self.definition,
self.descriptor,
... | Python | nomic_cornstack_python_v1 |
string 1) Write a function that prompts the user for their name and then greets them. You should process the string by removing any whitespace and converting the string to title case. If after processing the string you're left with an empty string, the function should replace the empty string with "World" in the output... | """ 1) Write a function that prompts the user for their name and then greets them. You should process the string by removing any whitespace and
converting the string to title case.
If after processing the string you're left with an empty string, the function should replace the empty string with "World" in the output.... | Python | zaydzuhri_stack_edu_python |
import os
import time
import subprocess
function buildUtilityMenu
begin
call system if expression name == string nt then string cls else string clear
end function | import os
import time
import subprocess
def buildUtilityMenu():
os.system('cls' if os.name == 'nt' else 'clear') | Python | zaydzuhri_stack_edu_python |
from data_structures import Queue
function test_queue
begin
set f = queue
set test_array = list comprehension i for i in range 100
for i in test_array
begin
call enqueue i
end
set result = list
while not call is_empty
begin
append result deque
end
assert test_array == result
end function | from data_structures import Queue
def test_queue():
f = Queue()
test_array = [i for i in range(100)]
for i in test_array:
f.enqueue(i)
result = []
while not f.is_empty():
result.append(f.deque())
assert test_array == result
| Python | zaydzuhri_stack_edu_python |
function idTchan1 self
begin
return call Sigma3ff2HfftWW_idTchan1 self
end function | def idTchan1(self):
return _pythia8.Sigma3ff2HfftWW_idTchan1(self) | Python | nomic_cornstack_python_v1 |
function sort_corners self corners
begin
set center = sum corners axis=0 / 4
set sorted_corners = sorted corners key=lambda p -> call atan2 p at 0 at 0 - center at 0 at 0 p at 0 at 1 - center at 0 at 1 reverse=true
return call roll sorted_corners 1 axis=0
end function | def sort_corners(self, corners: np.ndarray):
center = np.sum(corners, axis=0) / 4
sorted_corners = sorted(
corners,
key=lambda p: math.atan2(p[0][0] - center[0][0], p[0][1] - center[0][1]),
reverse=True,
)
return np.roll(sorted_corners, 1, axis=... | Python | nomic_cornstack_python_v1 |
function retrieve_non_existing_post_fails self
begin
call create_post
set response = get client reverse string posts:update-post args=list uuid 4 HTTP_AUTHORIZATION=format string token {} token
return response
end function | def retrieve_non_existing_post_fails(self):
self.create_post()
response = self.client.get(
reverse('posts:update-post', args=[uuid.uuid4()]),
HTTP_AUTHORIZATION='token {}'.format(self.token))
return response | Python | nomic_cornstack_python_v1 |
function get_nh_tun_dip self
begin
return integer get self string nhr_tun_dip
end function | def get_nh_tun_dip(self):
return int(self.get('nhr_tun_dip')) | Python | nomic_cornstack_python_v1 |
import flask
import shop
set messages = dict string spy tuple string You need to be registered to use our shop, sorry string bg-danger text-white ; string ordered tuple string Your order was sent, thanks! string bg-success text-white ; string bye tuple string Good bye, thanks! string bg-info text-white
set app = call F... | import flask
import shop
messages = {
'spy': ('You need to be registered to use our shop, sorry', 'bg-danger text-white'),
'ordered': ('Your order was sent, thanks!', 'bg-success text-white'),
'bye': ('Good bye, thanks!', 'bg-info text-white'),
}
app = flask.Flask(__name__, static_url_path='/s')
@app.... | Python | zaydzuhri_stack_edu_python |
string Aneri Shah Homework 12 To add web pages into the application that takes data from the database and adds in the HTML pages.
from flask import Flask , render_template
import sqlite3
from typing import Dict , List
set app : Flask = call Flask __name__
string Adding the database file
set DB_FILE : str = string /User... | """
Aneri Shah
Homework 12
To add web pages into the application that takes data from the database and adds in the HTML pages.
"""
from flask import Flask, render_template
import sqlite3
from typing import Dict, List
app: Flask = Flask(__name__)
""" Adding the database file """
DB_FILE: str = "/Users/anerishah/Des... | Python | zaydzuhri_stack_edu_python |
function test_list_queues
begin
set mock_run = call MagicMock return_value=dict string retcode 0 ; string stdout string saltstack 0 celeryev.234-234 10 ; string stderr string
with dictionary __salt__ dict string cmd.run_all mock_run
begin
assert call list_queues == dict string saltstack list string 0 ; string celeryev.... | def test_list_queues():
mock_run = MagicMock(
return_value={
"retcode": 0,
"stdout": "saltstack\t0\nceleryev.234-234\t10",
"stderr": "",
}
)
with patch.dict(rabbitmq.__salt__, {"cmd.run_all": mock_run}):
assert rabbitmq.list_queues() == {
... | Python | nomic_cornstack_python_v1 |
function decode_training self encoder_states one_hot_outputs mask_inference_inputs
begin
set tuple first_prediction decoder_state = call decode_init encoder_states mask_inference_inputs
set predictions = list first_prediction
set seq_max_len = shape at 1
for i in range seq_max_len - 1
begin
set tuple decoder_state pred... | def decode_training(self, encoder_states, one_hot_outputs,
mask_inference_inputs):
first_prediction, decoder_state = self.decode_init(
encoder_states, mask_inference_inputs)
predictions = [first_prediction]
seq_max_len = one_hot_outputs.shape[1]
for i ... | Python | nomic_cornstack_python_v1 |
function test_reclassify_unloaded_community self
begin
class ClassTestA extends DebugCommunity
begin
pass
end class
class ClassTestB extends DebugCommunity
begin
pass
end class
comment no communities should exist
assert equal list comprehension call load_community _dispersy master for master in call get_master_members ... | def test_reclassify_unloaded_community(self):
class ClassTestA(DebugCommunity):
pass
class ClassTestB(DebugCommunity):
pass
# no communities should exist
self.assertEqual([ClassTestA.load_community(self._dispersy, master) for master in ClassTestA.get_master_memb... | Python | nomic_cornstack_python_v1 |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
function wrangle_autism
begin
string This function will acquire data locally and turn datas... | import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def wrangle_autism():
'''
This function will acquire data locally and turn dataset... | Python | zaydzuhri_stack_edu_python |
function _ event
begin
set b = current_buffer
set empty_lines_required = accept_input_on_enter or 10000
function at_the_end b
begin
string we consider the cursor at the end when there is no text after the cursor, or only whitespace.
set text = text_after_cursor
return text == string or is space text and not string in... | def _(event):
b = event.current_buffer
empty_lines_required = python_input.accept_input_on_enter or 10000
def at_the_end(b):
"""we consider the cursor at the end when there is no text after
the cursor, or only whitespace."""
text = b.document.text_after_curso... | Python | nomic_cornstack_python_v1 |
function stack self level dropna
begin
return call call register stack self level=level dropna=dropna
end function | def stack(self, level, dropna):
return DataFrameDefault.register(pandas.DataFrame.stack)(
self, level=level, dropna=dropna
) | Python | nomic_cornstack_python_v1 |
function bend mapping source
begin
set res = dict
for tuple k value in call iteritems
begin
if is instance value Bender
begin
try
begin
set newv = call value source
end
except Exception as e
begin
set m = format string Error for key {}: {} k string e
raise call BendingException m
end
end
else
if is instance value list... | def bend(mapping, source):
res = {}
for k, value in mapping.iteritems():
if isinstance(value, Bender):
try:
newv = value(source)
except Exception as e:
m = 'Error for key {}: {}'.format(k, str(e))
raise BendingException(m)
e... | Python | nomic_cornstack_python_v1 |
function push x
begin
append stack x
end function
function pop
begin
if length stack == 0
begin
print - 1
end
else
begin
print pop stack
end
end function
function size
begin
print length stack
end function
function empty
begin
if length stack == 0
begin
print 1
end
else
begin
print 0
end
end function
function top
begin... | def push(x):
stack.append(x)
def pop():
if len(stack) == 0:
print(-1)
else:
print(stack.pop())
def size():
print(len(stack))
def empty():
if len(stack) == 0:
print(1)
else:
print(0)
def top():
if len(stack) == 0:
print(-1)
else:
print(s... | Python | zaydzuhri_stack_edu_python |
string 最初在一个记事本上只有一个字符 'A'。你每次可以对这个记事本进行两种操作: Copy All (复制全部) : 你可以复制这个记事本中的所有字符(部分的复制是不允许的)。 Paste (粘贴) : 你可以粘贴你上一次复制的字符。 给定一个数字 n 。你需要使用最少的操作次数,在记事本中打印出恰好 n 个 'A'。输出能够打印出 n 个 'A' 的最少操作次数。 示例 1: 输入: 3 输出: 3 解释: 最初, 我们只有一个字符 'A'。 第 1 步, 我们使用 Copy All 操作。 第 2 步, 我们使用 Paste 操作来获得 'AA'。 第 3 步, 我们使用 Paste 操作来获得 'AAA'。 说明: ... | '''
最初在一个记事本上只有一个字符 'A'。你每次可以对这个记事本进行两种操作:
Copy All (复制全部) : 你可以复制这个记事本中的所有字符(部分的复制是不允许的)。
Paste (粘贴) : 你可以粘贴你上一次复制的字符。
给定一个数字 n 。你需要使用最少的操作次数,在记事本中打印出恰好 n 个 'A'。输出能够打印出 n 个 'A' 的最少操作次数。
示例 1:
输入: 3
输出: 3
解释:
最初, 我们只有一个字符 'A'。
第 1 步, 我们使用 Copy All 操作。
第 2 步, 我们使用 Paste 操作来获得 'AA'。
第 3 步, 我们使用 Paste 操作... | Python | zaydzuhri_stack_edu_python |
function integrate f a b args=tuple minintervals=1 limit=200 tol=1e-10
begin
set fv = call vectorize f
set intervals = list
set limits = linear space a b minintervals + 1
for tuple left right in zip limits at slice : - 1 : limits at slice 1 : :
begin
set tuple I err = call integrate_gausskronrod fv left right args... | def integrate(f, a, b, args=(), minintervals=1, limit=200, tol=1e-10):
fv = np.vectorize(f)
intervals = []
limits = np.linspace(a, b, minintervals+1)
for left, right in zip(limits[:-1], limits[1:]):
I, err = integrate_gausskronrod(fv, left, right, args)
bisect.insort(intervals, (err, l... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import matplotlib.pyplot as plt
import db
import numpy as np
string x = [] # memory y = [] # execution time conn = db.init() c = conn.cursor() for a in c.execute('select * from single'): x.append(a[3]) # memory y.append(a[2]) # exec ## Figure 1 # Subplot 1 plt.figure(1) plt.subplot(2, 1, 1) plt... | #!/usr/bin/python
import matplotlib.pyplot as plt
import db
import numpy as np
"""
x = [] # memory
y = [] # execution time
conn = db.init()
c = conn.cursor()
for a in c.execute('select * from single'):
x.append(a[3]) # memory
y.append(a[2]) # exec
## Figure 1
# Subplot 1
plt.figure(1)
plt.subplot(2, 1, 1)... | Python | zaydzuhri_stack_edu_python |
function get_source self source
begin
if source not in sources
begin
raise call ValueError string source " { source } " not in minbar table. Look in self.sources for full list
end
return call reduce_table table params=dict string name source
end function | def get_source(self, source):
if source not in self.sources:
raise ValueError(f'source "{source}" not in minbar table. '
'Look in self.sources for full list')
return grid_tools.reduce_table(self.table, params={'name': source}) | Python | nomic_cornstack_python_v1 |
function getModelId self
begin
set res_obj = call getModelPreferences
if res_obj and string identifier in res_obj and res_obj at string identifier
begin
return res_obj at string identifier
end
return string
end function | def getModelId(self):
res_obj = self.getModelPreferences()
if res_obj and "identifier" in res_obj and res_obj["identifier"]:
return res_obj["identifier"]
return "" | Python | nomic_cornstack_python_v1 |
from java.lang import Math
from tactical.engine.config import BattleFunctionConfiguration
class BattleFunctions extends BattleFunctionConfiguration
begin
comment Gets the percent chance that the given target will dodge the attackers attack. This
comment number should be between 0-100
function getDodgePercent self attac... | from java.lang import Math
from tactical.engine.config import BattleFunctionConfiguration
class BattleFunctions(BattleFunctionConfiguration):
# Gets the percent chance that the given target will dodge the attackers attack. This
# number should be between 0-100
def getDodgePercent(self, attacker, targe... | Python | zaydzuhri_stack_edu_python |
import sys
if __name__ == string __main__
begin
set model_outputs = list none * length argv - 1
for i in range length argv - 1
begin
set model_outputs at i = read lines open argv at i + 1 string r
end
end | import sys
if __name__ == '__main__':
model_outputs = [None]*(len(sys.argv)-1)
for i in range(len(sys.argv)-1):
model_outputs[i] = open(sys.argv[i+1], 'r').readlines() | Python | zaydzuhri_stack_edu_python |
string Python Programming of Blockchain was a series of three lectures given within the Graduate Course 'Blockchain and Future Society' Offered in the Fall Semester 2018 at GIST, Rep. of Korea. The instructor was Prof. Heung-No Lee. The blockchain developed in the course was not meant to be complete. Instead, aim was t... | '''
Python Programming of Blockchain
was a series of three lectures given within the Graduate Course
'Blockchain and Future Society'
Offered in the Fall Semester 2018 at
GIST, Rep. of Korea. The instructor was Prof. Heung-No Lee.
The blockchain developed in the co... | Python | zaydzuhri_stack_edu_python |
function estimator dataset routine n_neighbors=5 n_runs=1 n_resamplings=10
begin
set routine_length = length routine
set estimates = list
set X = ones tuple routine_length 2
set X at tuple slice : : 0 = list comprehension log x for x in routine
for _ in range n_runs
begin
set mean_lengths = zeros routine_length
for... | def estimator(dataset, routine, n_neighbors=5, n_runs=1, n_resamplings=10):
routine_length = len(routine)
estimates = []
X = np.ones((routine_length, 2))
X[:, 0] = [np.log(x) for x in routine]
for _ in range(n_runs):
mean_lengths = np.zeros(routine_length)
for index, n_points in enumerate(routine):
... | Python | nomic_cornstack_python_v1 |
function __init__ self definition=none do_validate=false
begin
if not definition
begin
set definition = dict
end
set _definition = definition
if string version not in _definition
begin
set _definition at string version = DEFAULT_VERSION
end
if _definition at string version != DEFAULT_VERSION
begin
set msg = string %s ... | def __init__(self, definition=None, do_validate=False):
if not definition:
definition = {}
self._definition = definition
if 'version' not in self._definition:
self._definition['version'] = DEFAULT_VERSION
if self._definition['version'] != DEFAULT_VERSION:
... | 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.