code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function cal_preference dat
begin
set preference = ones shape
set preference at dat == 0 = 0
return call matrix preference
end function | def cal_preference(dat):
preference = np.ones(dat.shape)
preference[dat == 0] = 0
return np.matrix(preference) | Python | nomic_cornstack_python_v1 |
function add_outliner self outliner_type outliner_widget
begin
if outliner_type in _outliners
begin
warning format string Outliner {} already exists! outliner_widget
return
end
set _outliners at outliner_type = outliner_widget
call addWidget outliner_widget
end function | def add_outliner(self, outliner_type, outliner_widget):
if outliner_type in self._outliners:
LOGGER.warning('Outliner {} already exists!'.format(outliner_widget))
return
self._outliners[outliner_type] = outliner_widget
self._outliners_stack.addWidget(outliner_widget) | Python | nomic_cornstack_python_v1 |
function send_request self make request i req_num
begin
set i = i + 1
with open string data_collection/stats_file.txt string a as output_file
begin
write output_file string Rep # { i } Req # { req_num }
set nl_req = request + string
write output_file nl_req
end
call run_reqs request
return 0
end function | def send_request(self, make, request, i, req_num):
i += 1
with open('data_collection/stats_file.txt', 'a') as output_file:
output_file.write(f"Rep #{i} Req #{req_num} ")
nl_req = request + "\n"
output_file.write(nl_req)
make.run_reqs(request)
... | Python | nomic_cornstack_python_v1 |
function find_applications_need_refreshing_365_days_plus
begin
set query = format string SELECT * from applications WHERE {days_since_scrape} >= 29.5 AND 365 <= {days_since_received} days_since_scrape=SQL_DAYS_SINCE_SCRAPE days_since_received=SQL_DAYS_SINCE_RECEIVED
return list query db query
end function | def find_applications_need_refreshing_365_days_plus():
query = (
'SELECT * from applications WHERE '
' {days_since_scrape} >= 29.5 AND '
' 365 <= {days_since_received}'.format(
days_since_scrape=SQL_DAYS_SINCE_SCRAPE,
days_since_received=SQL_DAYS_SINCE_... | Python | nomic_cornstack_python_v1 |
function trim_data self low up
begin
print string total data length length data at string ax
for key in data
begin
set data at key = data at key at slice low : up + 1 :
end
end function | def trim_data(self, low, up):
print("total data length", len(self.data["ax"]))
for key in self.data:
self.data[key] = self.data[key][low:up+1] | Python | nomic_cornstack_python_v1 |
function test_card_info_lookup self
begin
pass
end function | def test_card_info_lookup(self):
pass | Python | nomic_cornstack_python_v1 |
function check_ref_format cls name no_slashes=false
begin
set params = if expression no_slashes then tuple string --allow-onelevel name else tuple name
return returncode == 0
end function | def check_ref_format(cls, name, no_slashes=False):
params = ("--allow-onelevel", name) if no_slashes else (name,)
return subprocess.run(("git", "check-ref-format") + params).returncode == 0 | Python | nomic_cornstack_python_v1 |
import datetime
from time import sleep
import requests
function print_messages messages
begin
set beauty_time = call fromtimestamp message at string time
set beauty_time = string format time beauty_time string %Y/%m/%d %H:%M
print beauty_time message at string name
print message at string text
print
end function
set af... | import datetime
from time import sleep
import requests
def print_messages(messages):
beauty_time = datetime.datetime.fromtimestamp(message['time'])
beauty_time = beauty_time.strftime('%Y/%m/%d %H:%M')
print(beauty_time, message['name'])
print(message['text'])
print()
after = 0
while True:
r... | Python | zaydzuhri_stack_edu_python |
function user_retrieve_index self uid
begin
set out = dict
for p in call iterdir
begin
if call is_dir or call is_symlink
begin
continue
end
if starts with stem string _
begin
continue
end
set tuple endpoint timestamp = call split_endpoint_timestamp p
set out at timestamp = endpoint
end
return tuple generator expressio... | def user_retrieve_index(self, uid):
out = {}
for p in self.path.joinpath(uid).iterdir():
if p.is_dir() or p.is_symlink():
continue
if p.stem.startswith("_"):
continue
endpoint, timestamp = split_endpoint_timestamp(p)
out[... | Python | nomic_cornstack_python_v1 |
comment imports
import pygame
import random
import time
call init
call init
comment ----- Gera tela principal
set WIDTH = 620
set HEIGHT = 310
set window = call set_mode tuple WIDTH HEIGHT
call set_caption string Luigi Run
set screen = call set_mode tuple 620 310 0 32
comment ----- Inicia assets
set obstaculo_WIDTH = 5... | #imports
import pygame
import random
import time
pygame.init()
pygame.mixer.init()
# ----- Gera tela principal
WIDTH = 620
HEIGHT = 310
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Luigi Run')
screen = pygame.display.set_mode((620, 310),0,32)
# ----- Inicia assets
obstaculo_WIDTH = ... | Python | zaydzuhri_stack_edu_python |
function _lookup self
begin
for contact in shortlist
begin
if contact not in contacted
begin
comment Guard to ensure only ALPHA requests are ever active at any
comment one time
if length pending_requests >= ALPHA
begin
break
end
set tuple uuid future = call send_find contact target message_type
set pending_requests at ... | def _lookup(self):
for contact in self.shortlist:
if contact not in self.contacted:
# Guard to ensure only ALPHA requests are ever active at any
# one time
if len(self.pending_requests) >= constants.ALPHA:
break
uui... | Python | nomic_cornstack_python_v1 |
function hyperparameter_optimization_random X y *argv
begin
set clf_best_params = dict
comment Iterate over all (classifier, hyperparameters) pairs
for tuple clf params in argv
begin
comment Run randomized search
set n_iter_search = 10
set random_search = randomized search cv clf param_distributions=params n_iter=n_it... | def hyperparameter_optimization_random(X, y, *argv):
clf_best_params = {}
# Iterate over all (classifier, hyperparameters) pairs
for clf, params in argv:
# Run randomized search
n_iter_search = 10
random_search = RandomizedSearchCV(
clf, param_distributions=params, n_i... | Python | nomic_cornstack_python_v1 |
function fix_fabs_ppop_country row
begin
comment replace ppop country codes from US territories with USA, move them into the state slot
if upper place_of_perform_country_c in country_code_map and upper place_of_perform_country_c != string USA
begin
set place_of_perfor_state_code = country_code_map at upper place_of_per... | def fix_fabs_ppop_country(row):
# replace ppop country codes from US territories with USA, move them into the state slot
if row.place_of_perform_country_c.upper() in country_code_map and row.place_of_perform_country_c.upper() != 'USA':
row.place_of_perfor_state_code = country_code_map[row.place_of_perfo... | Python | nomic_cornstack_python_v1 |
function infer_type_with_broadcast typea typeb primitive_type
begin
comment broadcast
if not call is_tensor typea and not call is_tensor typeb
begin
comment both typea and typeb are not tensors
return primitive_type
end
if call is_tensor typea and not call is_tensor typeb
begin
comment a is tensor, b is not
return tens... | def infer_type_with_broadcast(typea, typeb, primitive_type):
# broadcast
if not types.is_tensor(typea) and not types.is_tensor(typeb):
# both typea and typeb are not tensors
return primitive_type
if types.is_tensor(typea) and not types.is_tensor(typeb):
# a is tensor, b is not
... | Python | nomic_cornstack_python_v1 |
function get_brands_page_links brands_page_link
begin
set soup = call get_soup brands_page_link
set all_brands_boxes = find soup string div id=string content-content
set all_brands_links = find all all_brands_boxes string a
comment Get brand links
set brand_links = list comprehension get link string href for link in se... | def get_brands_page_links(brands_page_link):
soup = get_soup(brands_page_link)
all_brands_boxes = soup.find('div', id='content-content')
all_brands_links = all_brands_boxes.find_all('a')
# Get brand links
brand_links = [link.get('href') for link in all_brands_boxes.select('div.brand_name > a:nth-of... | Python | nomic_cornstack_python_v1 |
function full_text_search_title self term
begin
if not client
begin
call connect
end
set query = call full_text_search_title term
return call aggregate query
end function | def full_text_search_title(self, term: str):
if not self.client:
self.connect()
query = templates.full_text_search_title(term)
return self.client.moviebuff.engtitles.aggregate(query) | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import math
comment 给出pdb&cif的路径######################################
set path = string F:\Ds_analyze\PDB_itp_g96
set files_name = list directory path
comment 获取文件夹下文件名######################################
set x = list directory path
print x
comment 获取pdb文件名,不要后缀,用于写itp和g96的材料文件名#########... | import os
import numpy as np
import math
##############################################给出pdb&cif的路径######################################
path="F:\Ds_analyze\PDB_itp_g96"
files_name=os.listdir(path)
##############################################获取文件夹下文件名######################################
x=os.listdir(pat... | Python | zaydzuhri_stack_edu_python |
function acquire self
begin
if _acquired
begin
return
end
debug format string Acquiring OS file descriptor for transport - {} path
set tuple _fd _read_mtu _write_mtu = call TryAcquire
set _fd = call take
set _socket = call socket fileno=_fd
debug format string Successfully acquired OS file descriptor - fd={}, readMTU={... | def acquire(self):
if self._acquired:
return
logger.debug("Acquiring OS file descriptor for transport - {}".format(
self._proxy.path))
self._fd, self._read_mtu, self._write_mtu = \
self._proxy.proxy.TryAcquire()
self._fd = self._fd.take()
self... | Python | nomic_cornstack_python_v1 |
function __init__ self N L dtype=call dtype string complex128 existing=none
begin
if existing is none
begin
set L = L
set N = N
set chi = 1
set I = call eye N
set dtype = dtype
set dim = N ^ L
comment create a dictionary to store tensors
set Ws = dictionary
for i in range L
begin
set W = zeros tuple chi chi N N dtype=d... | def __init__(self, N, L, dtype=np.dtype('complex128'), existing=None,):
if existing is None:
self.L = L
self.N = N
self.chi = 1
self.I = np.eye(N)
self.dtype = dtype
self.dim = N**L
Ws = dict() # create a dictionary to store te... | Python | nomic_cornstack_python_v1 |
function auto_get *args
begin
return call auto_get *args
end function | def auto_get(*args):
return _idaapi.auto_get(*args) | Python | nomic_cornstack_python_v1 |
function Area r
begin
return r at 2 * r at 3
end function | def Area(r):
return r[2]*r[3] | Python | nomic_cornstack_python_v1 |
for j in x
begin
set counter = 0
set m = arr at slice : :
for i in range length arr
begin
set m at i = m at i - j
end
comment print(m)
for i in range length m
begin
if m at i == 1 or m at i == 0
begin
set counter = counter + 1
end
end
append count counter
end
print max count | for j in x:
counter=0
m=arr[:]
for i in range(len(arr)):
m[i]-=j
# print(m)
for i in range(len(m)):
if m[i]==1 or m[i]==0:
counter+=1
count.append(counter)
print(max(count))
| Python | zaydzuhri_stack_edu_python |
comment t.append(6) tuples are immutable
comment tuples van contain mutable
set t = tuple list 1 2 3 list 3 4 5
set t at 0 at 0 = 10
print t
comment defining variables using tuples
set t = tuple 10 20 30
set tuple a b c = t
print format string a = {}, b = {}, c = {} a b c | # t.append(6) tuples are immutable
t = ([1,2,3],[3,4,5]) # tuples van contain mutable
t[0][0] = 10
print(t)
# defining variables using tuples
t = 10,20,30
a, b, c = t
print('a = {}, b = {}, c = {}'.format(a,b,c)) | Python | zaydzuhri_stack_edu_python |
comment objective_1= isolate question in survey ASL220_00.000 male How do you think of yourself (sexual orientation) multiple choice 2016
comment objective_2 = isolate question in survey ASL240_00.000 female How do you think of yourself (sexual orientation) multiple choice 2016
comment overall objective, repeat for eac... | #objective_1= isolate question in survey ASL220_00.000 male How do you think of yourself (sexual orientation) multiple choice 2016
#objective_2 = isolate question in survey ASL240_00.000 female How do you think of yourself (sexual orientation) multiple choice 2016
#overall objective, repeat for each survey from 2016, 2... | Python | zaydzuhri_stack_edu_python |
function _read_resm_m self tomodir
begin
string Read in the resolution matrix of an inversion Parameters ---------- tomodir: string directory path to a tomodir
set resm_file = tomodir + sep + string inv + sep + string res_m.diag
if not is file path resm_file
begin
print format string res_m.diag not found: {0} resm_file... | def _read_resm_m(self, tomodir):
"""Read in the resolution matrix of an inversion
Parameters
----------
tomodir: string
directory path to a tomodir
"""
resm_file = tomodir + os.sep + 'inv' + os.sep + 'res_m.diag'
if not os.path.isfile(resm_file):
... | Python | jtatman_500k |
function set_all_db_signal_receivers receiver_data
begin
for tuple signal receivers in items receiver_data
begin
set receivers = receivers
end
end function | def set_all_db_signal_receivers(receiver_data):
for (signal, receivers) in receiver_data.items():
signal.receivers = receivers | Python | nomic_cornstack_python_v1 |
function predict self seed predict_length threshold
begin
assert shape == tuple 48 input_length msg string Wrong input seed dimensions!
end function
comment implement in child class! | def predict(self, seed, predict_length, threshold):
assert seed.shape == (48, self.input_length), 'Wrong input seed dimensions!'
# implement in child class! | Python | nomic_cornstack_python_v1 |
function test_iterator_length self
begin
set iterator = disk_iterator
next
set cur = call get_cur_offset
set length = call length
while call valid
begin
next
set next = call get_cur_offset
assert equal length next - cur
set cur = next
set length = call length
end
end function | def test_iterator_length(self) -> None:
iterator = self.sstable.disk_iterator
iterator.next()
cur = iterator.get_cur_offset()
length = iterator.length()
while iterator.valid():
iterator.next()
next = iterator.get_cur_offset()
self.assertEqual(l... | Python | nomic_cornstack_python_v1 |
from collections import Counter
function most_frequent string
begin
set data = split string string
set data1 = counter data
return call most_common 1 at 0
end function
set txt = string Python is a powerful language that is used for a wide range of applications
assert call most_frequent txt == tuple string is 2
print st... | from collections import Counter
def most_frequent(string):
data = string.split(" ")
data1 = Counter(data)
return data1.most_common(1)[0]
txt = "Python is a powerful language that is used for a wide range of applications"
assert most_frequent(txt) == ('is', 2)
print("Most frequent word is : ", most_frequent(... | Python | jtatman_500k |
function test_get_onto_terms_associated_with_gene self
begin
set query_string = list tuple string geneId string geneId_example
set response = open format string /api/ontologies/terms/associatedWithGene{format} format=string format_example method=string GET query_string=query_string
call assert200 response string Respon... | def test_get_onto_terms_associated_with_gene(self):
query_string = [('geneId', 'geneId_example')]
response = self.client.open(
'/api/ontologies/terms/associatedWithGene{format}'.format(format='format_example'),
method='GET',
query_string=query_string)
self.ass... | Python | nomic_cornstack_python_v1 |
function forward self output1 output2 label
begin
set euclidean_distance = call pairwise_distance output1 output2
set clamped = clamp torch margin - euclidean_distance min=0.0
set similar_loss = 1 - label * 0.5 * power euclidean_distance 2
set dissimilar_loss = label * 0.5 * power clamped 2
set contrastive_loss = simil... | def forward(self, output1, output2, label):
euclidean_distance = F.pairwise_distance(output1, output2)
clamped = torch.clamp(self.margin - euclidean_distance, min=0.0)
similar_loss = (1 - label) * 0.5 * torch.pow(euclidean_distance, 2)
dissimilar_loss = label * 0.5 * torch.pow(clamped, 2... | Python | nomic_cornstack_python_v1 |
string A hash table (dictionary) class that uses linear probing to make sure no collisions occur. Author: Oscar A. Nieves Updated: August 9, 2021
class HashTable
begin
function __init__ self MAX=10
begin
set MAX = MAX
set arr = list comprehension none for i in range MAX
set keys = list list list
end function
function... | """
A hash table (dictionary) class that uses
linear probing to make sure no collisions occur.
Author: Oscar A. Nieves
Updated: August 9, 2021
"""
class HashTable:
def __init__(self,MAX=10):
self.MAX = MAX
self.arr = [None for i in range(self.MAX)]
self.keys = [ [], [] ]
def get_hash(s... | Python | zaydzuhri_stack_edu_python |
function _get_result self course
begin
set course_overview = call get_from_id id
return data
end function | def _get_result(self, course):
course_overview = CourseOverview.get_from_id(course.id)
return self.serializer_class(course_overview, context={'request': self._get_request()}).data | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , jsonify
from flask_httpauth import HTTPBasicAuth
from datetime import datetime
import os
import pymysql
import json
set app = call Flask __name__
set auth = call HTTPBasicAuth
function get_database_connection
begin
set dbhost = environ at string DB_HOST
set dbuser = environ at string... | from flask import Flask, request, jsonify
from flask_httpauth import HTTPBasicAuth
from datetime import datetime
import os
import pymysql
import json
app = Flask(__name__)
auth = HTTPBasicAuth()
def get_database_connection():
dbhost = os.environ['DB_HOST']
dbuser = os.environ['DB_USER']
dbpass = os.enviro... | Python | zaydzuhri_stack_edu_python |
function test_subtract_bg self titan
begin
set lbg0 = labelblocksgroups at 0
set lbg1 = labelblocksgroups at 1
call assert_almost_equal data_norm at string E01 at slice : : 2 list 601.72 641.505 674.355 706.774 3
assert data is not none
assert data at string E01 at slice : : 2 == list 11192.0 11932.0 12543.0 13146.... | def test_subtract_bg(self, titan: TitrationAnalysis) -> None:
lbg0 = titan.labelblocksgroups[0]
lbg1 = titan.labelblocksgroups[1]
assert_almost_equal(
lbg0.data_norm["E01"][::2], [601.72, 641.505, 674.355, 706.774], 3
)
assert lbg0.data is not None
assert lbg0... | Python | nomic_cornstack_python_v1 |
function getLearningData corpus vocab
begin
set tuple labels data = tuple list list
global importantFrequentWordDic
for sent in trainingSents
begin
set trans = initialTransition
while trans and next
begin
set tuple tokenIdxs posIdxs = call getTransData trans vocab
append data call asarray concatenate tuple tokenIdxs ... | def getLearningData(corpus, vocab):
labels, data = [], []
global importantFrequentWordDic
for sent in corpus.trainingSents:
trans = sent.initialTransition
while trans and trans.next:
tokenIdxs, posIdxs = getTransData(trans, vocab)
data.append(np.asarray(np.concatenate... | Python | nomic_cornstack_python_v1 |
function process_exp_value exp_data
begin
set VALUE_XPATH = string hunterdb:Value/child::text()
set DOI_XPATH = string hunterdb:Source/hunterdb:DOI/child::text()
set PREFERRED_XPATH = string @hunterdb:preferredValue
set doi_values = call xpath DOI_XPATH namespaces=HUNTER_DB_NAMESPACE_DICT
set values_values = call xpath... | def process_exp_value(exp_data):
VALUE_XPATH = 'hunterdb:Value/child::text()'
DOI_XPATH = 'hunterdb:Source/hunterdb:DOI/child::text()'
PREFERRED_XPATH = '@hunterdb:preferredValue'
doi_values = exp_data.xpath(DOI_XPATH, namespaces=HUNTER_DB_NAMESPACE_DICT)
values_values = exp_data.xpath(VALUE_XPATH, ... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
set rcParams at string font.sans-serif = string SimHei
set rcParams at string axes.unicode_minus = false
set data = load np string ../data/国民经济核算季度数据.npz
set name = data at string columns
comment 提取其中的values数组,数据的存在位置
set values = data at ... | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
data = np.load('../data/国民经济核算季度数据.npz')
name = data['columns']
values = data['values']## 提取其中的values数组,数据的存在位置
p = plt.figure(figsize=(12,12)) ##设置画布
## 散点图
... | Python | zaydzuhri_stack_edu_python |
string Let’s assume that there are a total of n courses labeled from 0 to n-1. Some courses may have prerequisites. A list of prerequisites is specified such that if prerequisities=a,b , you must take course b before course a Given the total number of courses n and a list of the prerequisite pairs, return the course or... | """
Let’s assume that there are a total of n courses labeled from 0 to n-1. Some courses may have prerequisites. A list of prerequisites is specified such that if
prerequisities=a,b , you must take course b before course a
Given the total number of courses n and a list of the prerequisite pairs, return the course o... | Python | zaydzuhri_stack_edu_python |
function get_different_number arr
begin
if length arr == 1 and arr at 0 != 0
begin
return 0
end
comment we are looping through the entire array
comment we then compare the index of the array to the element of that array
comment if they do not equal we return the last element of the array + 1
set s = set arr
comment cre... | def get_different_number(arr):
if len(arr) == 1 and arr[0] != 0:
return 0
# we are looping through the entire array
# we then compare the index of the array to the element of that array
# if they do not equal we return the last element of the array + 1
s = set(arr)
# create a set from o... | Python | zaydzuhri_stack_edu_python |
function plotRange df_desc figsize=tuple 16 3
begin
figure figsize=figsize
subplot 131
plot kind=string bar
subplot 132
plot kind=string bar
subplot 133
plot kind=string bar
show
end function | def plotRange(df_desc,figsize=(16,3)):
plt.figure(figsize=figsize)
plt.subplot(131)
df_desc.loc["min"].plot(kind="bar")
plt.subplot(132)
df_desc.loc["50%"].plot(kind="bar")
plt.subplot(133)
df_desc.loc["max"].plot(kind="bar")
plt.show(); | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
comment Assign outA to Right Motor
set r = call LargeMotor string outA
comment Designate outB to be Left Motor
set l = call LargeMotor string outB
call run_to_rel_pos position_sp=2160 speed_sp=900 stop_action=string hold
call run_to_rel_pos p... | #!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
r = LargeMotor('outA') #Assign outA to Right Motor
l = LargeMotor('outB') # Designate outB to be Left Motor
l.run_to_rel_pos(position_sp=2160, speed_sp=900, stop_action="hold")
r.run_to_rel_pos(position_sp=2160, speed_sp=900, stop_action="hold")
#... | Python | zaydzuhri_stack_edu_python |
function lambda_handler event context
begin
print string event.session.application.applicationId= + event at string session at string application at string applicationId
string Uncomment this if statement and populate with your skill's application ID to prevent someone else from configuring a skill that sends requests ... | def lambda_handler(event, context):
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"""
Uncomment this if statement and populate with your skill's application ID to
prevent someone else from configuring a skill that sends requests to ... | Python | nomic_cornstack_python_v1 |
function _download_webpage_handle self url_or_request video_id note=none errnote=none
begin
set urlh = call _request_webpage url_or_request video_id note errnote
set content_type = get headers string Content-Type string
set m = match string [a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+) content_type
if m
begin
set ... | def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None):
urlh = self._request_webpage(url_or_request, video_id, note, errnote)
content_type = urlh.headers.get('Content-Type', '')
m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
... | Python | nomic_cornstack_python_v1 |
function create_node self resource_object
begin
call add_node resource_object
return true
end function | def create_node(self,resource_object):
self.web.add_node(resource_object)
return True | Python | nomic_cornstack_python_v1 |
function add_question self prompt correct_answer
begin
set prompt = prompt
set correct_answer = correct_answer
set new_question = call __init__ question=prompt answer=correct_answer
comment adds the new question to the list of exam questions
append exam_questions q_and_a
end function | def add_question(self, prompt, correct_answer):
self.prompt = prompt
self.correct_answer = correct_answer
self.new_question = super(AbstractExam, self).__init__(question=self.prompt, answer=self.correct_answer)
# adds the new question to the list of exam questions
self.exam_qu... | Python | nomic_cornstack_python_v1 |
function value_shape self
begin
return tuple
end function | def value_shape(self):
return () | Python | nomic_cornstack_python_v1 |
function create_and_pull
begin
set created : List at Container = list
decorator wraps _create_and_pull
function ret *args remove=true **kwargs
begin
set container = call _create_and_pull *args keyword kwargs
if remove
begin
append created container
end
return container
end function
yield ret
for c in created
begin
rem... | def create_and_pull():
created: List[Container] = []
@wraps(_create_and_pull)
def ret(*args, remove=True, **kwargs):
container = _create_and_pull(*args, **kwargs)
if remove:
created.append(container)
return container
yield ret
for c in created:
c.remove(... | Python | nomic_cornstack_python_v1 |
comment LJ Benson Email: ljbenson21@gmail.com
import requests
import json
comment I made a JSON string variable so that I could pass in my token and my url to github
set json_string = string {"token" : "32003a47cded737d82e38ec1fc226905", "github" : "https://github.com/ljBenson21/Code-2040-Challenge.git"}
comment I load... | ##################################
# LJ Benson Email: ljbenson21@gmail.com
#################################
import requests
import json
# I made a JSON string variable so that I could pass in my token and my url to github
json_string = '{"token" : "32003a47cded737d82e38ec1fc226905", "github" : "https://githu... | Python | zaydzuhri_stack_edu_python |
function add_client self endpoint
begin
with _lock
begin
set sock = call socket PUB
call connect endpoint
set return_ = call _Return sock
set _clients at endpoint = sock
set _client_returns at endpoint = return_
end
end function | def add_client(self, endpoint):
with self._lock:
sock = self._zmq.socket(zmq.PUB)
sock.connect(endpoint)
return_ = Server._Return(sock)
self._clients[endpoint] = sock
self._client_returns[endpoint] = return_ | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import numpy.polynomial.polynomial as poly
comment does not call it but is necessary
from mpl_toolkits.mplot3d import Axes3D
function plot_pair_correlation x y name
begin
set font = dict string family string serif ; string... | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import numpy.polynomial.polynomial as poly
# does not call it but is necessary
from mpl_toolkits.mplot3d import Axes3D
def plot_pair_correlation(x, y, name):
font = {
'family': 'serif',
'color': 'dar... | Python | zaydzuhri_stack_edu_python |
comment https://www.programiz.com/python-programming/user-defined-exception
class SpillOverError extends Exception
begin
string Raised when a structrure spills out of grid width or height
pass
end class | # https://www.programiz.com/python-programming/user-defined-exception
class SpillOverError(Exception):
"""Raised when a structrure spills out of grid width or height"""
pass | Python | zaydzuhri_stack_edu_python |
function is_leaf node
begin
return left is none and right is none
end function
function decode root s
begin
set result = string
set current = root
for bit in s
begin
if bit == string 0
begin
set current = left
end
else
begin
set current = right
end
if call is_leaf current
begin
set result = result + data
set current =... | def is_leaf(node):
return node.left is None and node.right is None
def decode(root, s):
result = ''
current = root
for bit in s:
if bit == '0':
current = current.left
else:
current = current.right
if is_leaf(current):
result += current.data... | Python | zaydzuhri_stack_edu_python |
function set_actions self
begin
set postprocess_items = call get_items
set actions = list
for tuple action options in items postprocess_items
begin
set options = if expression options is none then dictionary else options
set args = get options string args tuple
set kwargs = get options string kwargs dictionary
set args... | def set_actions(self):
postprocess_items = self.get_items()
actions = list()
for action, options in postprocess_items.items():
options = dict() if options is None else options
args = options.get("args", tuple())
kwargs = options.get("kwargs", dict())
... | Python | nomic_cornstack_python_v1 |
function test_generate_molecule_object_dict_with_values self
begin
set source = string COCC(=O)NC=1C=CC=C(NC(=O)C)C1
set format = string smiles
set values = dict string a 1
set m = call generate_molecule_object_dict source format values
call assertEquals 4 length m
assert true string uuid in m
assert true string source... | def test_generate_molecule_object_dict_with_values(self):
source = 'COCC(=O)NC=1C=CC=C(NC(=O)C)C1'
format = 'smiles'
values = {'a':1}
m = utils.generate_molecule_object_dict(source, format, values)
self.assertEquals(4, len(m))
self.assertTrue('uuid' in m)
self.a... | Python | nomic_cornstack_python_v1 |
function now_playing
begin
try
begin
set movie_repo = call MoviesRepository TMDB_API_KEY
set response = call now_playing
end
except HTTPError as err
begin
comment print (err.response.text.status_message)
set r = call jsonify json response
set status_code = status_code
return r
end
except Exception as e
begin
set r = ca... | def now_playing():
try:
movie_repo = MoviesRepository(TMDB_API_KEY)
response = movie_repo.now_playing()
except HTTPError as err:
# print (err.response.text.status_message)
r = jsonify(err.response.json())
r.status_code = err.response.status_code
return r
excep... | Python | nomic_cornstack_python_v1 |
function unhandled_keys self size key
begin
if key == string
begin
call toggle_flag
end
else
begin
return key
end
end function | def unhandled_keys(self, size, key):
if key == " ":
self.get_node().toggle_flag()
else:
return key | Python | nomic_cornstack_python_v1 |
function update_path_effects self
begin
set effects = list values extra_path_effects
append effects call Normal
call set_path_effects effects
end function | def update_path_effects(self) -> None:
effects = list(self.extra_path_effects.values())
effects.append(pe.Normal())
self.set_path_effects(effects) | Python | nomic_cornstack_python_v1 |
function test_additive_mode values_list num_samples_list true_values_list mode
begin
set metric = call AdditiveMetric mode=mode
for tuple value num_samples true_value in zip values_list num_samples_list true_values_list
begin
update metric value=value num_samples=num_samples
set tuple mean _ = call compute
assert call ... | def test_additive_mode(
values_list: Union[Iterable[float], Iterable[torch.Tensor]],
num_samples_list: Iterable[int],
true_values_list: Iterable[float],
mode: Iterable[str],
):
metric = AdditiveMetric(mode=mode)
for value, num_samples, true_value in zip(
values_list, num_samples_list, tr... | Python | nomic_cornstack_python_v1 |
from nose.tools import *
from gothonweb.map import *
from mock import patch
from mock import MagicMock
function test_room
begin
set gold = call Room string GoldRoom string This room has gold in it you can grab. There's a door to the north. generic_action_funtion
call assert_equal name string GoldRoom
call assert_equal ... | from nose.tools import *
from gothonweb.map import *
from mock import patch
from mock import MagicMock
def test_room():
gold = Room("GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north.""", generic_action_funtion)
assert_equal(gold.name, "GoldRoom")
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
comment Reference: https://byjus.com/linear-regression-formula
function read
begin
set data = call loadtxt string pressure
set X = data at tuple slice : : 2
set Y = data at tuple slice : : 3
return tuple X Y
end function
function displayXY X Y
begin
plot X Y stri... | import numpy as np
import matplotlib.pyplot as plt
# Reference: https://byjus.com/linear-regression-formula
def read():
data = np.loadtxt("pressure")
X = data[:,2]
Y = data[:,3]
return X,Y
def displayXY(X,Y):
plt.plot(X,Y,'ro')
plt.show()
def fitRegressionLine(X,Y):
X = X.reshape(-1,1)
Y = Y.reshape(-1,1)
... | Python | zaydzuhri_stack_edu_python |
function handle self *args **options
begin
comment they look strange but are what comes over from wordpress API
comment im giessing there are redirects in place to make this work
set SOURCES = dict string sample-page string aac ; string home-2 string commissioning ; string nhs-england-and-nhs-improvement-corona-virus s... | def handle(self, *args, **options):
# they look strange but are what comes over from wordpress API
# im giessing there are redirects in place to make this work
SOURCES = {
'sample-page': 'aac',
'home-2': 'commissioning',
'nhs-england-and-nhs-improvement-coron... | Python | nomic_cornstack_python_v1 |
function sredarf x y z
begin
set sa = x + y + z
set sa = sa / 3
return sa
end function
while true
begin
print string Для завершения работы программы напечатайте "STOP" string
set x = input string Введите первое число:
if lower x == string stop
begin
print string Программа завершилась
break
end
else
begin
set x = intege... | def sredarf(x, y, z):
sa = x + y + z
sa = sa / 3
return(sa)
while True:
print('Для завершения работы программы напечатайте "STOP"', '\n')
x = input('Введите первое число: ')
if x.lower() == 'stop':
print('Программа завершилась')
break
else:
x = int(x)
... | Python | zaydzuhri_stack_edu_python |
function reset self
begin
assert running msg string Tried to reset a LoopingCall that was not running.
if call is not none
begin
call cancel
set call = none
set starttime = call seconds
call _scheduleFrom starttime
end
end function | def reset(self):
assert self.running, ("Tried to reset a LoopingCall that was "
"not running.")
if self.call is not None:
self.call.cancel()
self.call = None
self.starttime = self.clock.seconds()
self._scheduleFrom(self.startt... | Python | nomic_cornstack_python_v1 |
string "Additional API Types and Functions" description: functions and types used by the API and additional useful types and functions usage: lock: simplistic lock class for managing concurrent access stack: simplistic concurrency-safe stack class for shared stacks queue: simplistic concurrency-safe queue class for sha... | """"Additional API Types and Functions"
description:
functions and types used by the API and additional useful types and functions
usage:
lock: simplistic lock class for managing concurrent access
stack: simplistic concurrency-safe stack class for shared stacks
queue: simplistic concurrency-safe queue class for s... | Python | zaydzuhri_stack_edu_python |
function dispatch_gen settings rmgseed=0
begin
comment Seed with a specific seed if one was provided
if rmgseed != 0
begin
print string seed: + string rmgseed
seed rmgseed
end
set module_name = string modules.%s.__init__ % module_name
set rmg_module = call __import__ module_name fromlist=list module_name
set max_attemp... | def dispatch_gen(settings, rmgseed = 0):
# Seed with a specific seed if one was provided
if rmgseed != 0:
print("seed:" + str(rmgseed))
seed(rmgseed)
module_name = "modules.%s.__init__" % settings.module_name
rmg_module = __import__(module_name, fromlist=[module_name])
max_attempts = 5
for i in range(max... | Python | nomic_cornstack_python_v1 |
from enum import Enum
class Position
begin
function __init__ self pan tilt zoom
begin
set pan = pan
set tilt = tilt
set zoom = zoom
end function
function log self
begin
print string pan string tilt string zoom
end function
end class
class Camera
begin
function __init__ self serial_number position camera_type
begin
set ... | from enum import Enum
class Position:
def __init__(self, pan, tilt, zoom):
self.pan = pan
self.tilt = tilt
self.zoom = zoom
def log(self):
print(str(self.pan), str(self.tilt), str(self.zoom))
class Camera:
def __init__(self, serial_number, position, camera_type):
s... | Python | zaydzuhri_stack_edu_python |
function makeSelectionMap self
begin
for element in find all string cc:selection-depends ns
begin
comment req=element.attrib["req"]
set selIds = attrib at string ids
set slaveId = attrib at string id
for selId in split selIds string ,
begin
set reqs = list
if selId in selMap
begin
set reqs = selMap at selId
end
append... | def makeSelectionMap(self):
for element in self.root.findall( 'cc:selection-depends', ns):
# req=element.attrib["req"]
selIds=element.attrib["ids"]
slaveId=self.up(element).attrib["id"]
for selId in selIds.split(','):
reqs=[]
if sel... | Python | nomic_cornstack_python_v1 |
comment Problem No.: 4358
comment Solver: Jinmin Goh
comment Date: 20220914
comment URL: https://www.acmicpc.net/problem/4358
import sys
function main
begin
set tree_dict = dict
set total = 0
set temp = right strip read line stdin
while temp
begin
if temp not in tree_dict
begin
set tree_dict at temp = 0
end
set tree_d... | # Problem No.: 4358
# Solver: Jinmin Goh
# Date: 20220914
# URL: https://www.acmicpc.net/problem/4358
import sys
def main():
tree_dict = {}
total = 0
temp = sys.stdin.readline().rstrip()
while temp:
if temp not in tree_dict:
tree_dict[temp] = 0
tre... | Python | zaydzuhri_stack_edu_python |
from utils import dict_to_str , kcv , l_to_str
from abc import ABC , abstractmethod
class Database extends ABC
begin
function __init__ self
begin
set DB = none
end function
decorator abstractmethod
function connect self *args
begin
pass
end function
function __del__ self
begin
if DB is not none
begin
close DB
end
end f... | from utils import dict_to_str, kcv, l_to_str
from abc import ABC, abstractmethod
class Database(ABC):
def __init__(self):
self.DB = None
@abstractmethod
def connect(self, *args):
pass
def __del__(self):
if self.DB is not None:
self.DB.close()
def df(self, tab... | Python | zaydzuhri_stack_edu_python |
comment Salario bruto
set totalbruto = decimal timegain * timework
comment Desconto no I.R
set Ir = totalbruto * 0.11
set inss = totalbruto * 0.08
set sind = totalbruto * 0.05
set des = Ir + inss + sind
set salaliq = totalbruto - des
comment Resultado
print string Bruto total = R$: totalbruto
print string Imposto de re... | #Salario bruto
totalbruto =float(timegain * timework)
#Desconto no I.R
Ir = totalbruto * 0.11
inss = totalbruto * 0.08
sind = totalbruto * 0.05
des = Ir + inss + sind
salaliq = totalbruto - des
#Resultado
print('Bruto total = R$:',totalbruto)
print('Imposto de renda = R$:',Ir)
print('INSS = R$:',inss)
print('Sindi... | Python | zaydzuhri_stack_edu_python |
import os
import GCPutil
import SoundUtil
import DictionaryUtil
class DicManager
begin
set translator = none
set tts = none
set sound_player = none
set dic_db = none
set cur_word = none
set new_word = none
set cur_dictionary = none
function __init__ self
begin
print string Initialize Dictionary Manager...
call init_dir... | import os
import GCPutil
import SoundUtil
import DictionaryUtil
class DicManager:
translator = None
tts = None
sound_player = None
dic_db = None
cur_word = None
new_word = None
cur_dictionary = None
def __init__(self):
print('Initialize Dictionary Manager...')
self.in... | Python | zaydzuhri_stack_edu_python |
from io import open
comment Abro el archivo en modo lectura
set archivo_texto = open string data.txt string r
comment Para abrir un archivo como R y W, usamos "r+"
comment Leo el contenido y genero una lista por lineas del archivo_texto
set texto_lineas = read lines archivo_texto
comment Despues de hacer una primera le... | from io import open
archivo_texto=open("data.txt","r") #Abro el archivo en modo lectura
#Para abrir un archivo como R y W, usamos "r+"
texto_lineas=archivo_texto.readlines() #Leo el contenido y genero una lista por lineas del archivo_texto
#Despues de hacer una primera lectura el cursor del archivo queda al final,
... | Python | zaydzuhri_stack_edu_python |
import os.path
set d = dict
print string 歡迎進入成績查詢系統
function buildMenu
begin
print string 1.建立成績
print string 2.列出所有成績
print string 3.查詢成績
print string 4.離開
set sel = integer input string 輸入選項:
return sel
end function
if is file path string scores.txt
begin
print string 存在
set fo = open string scores.txt string r
set ... | import os.path
d={}
print("歡迎進入成績查詢系統")
def buildMenu():
print("1.建立成績")
print("2.列出所有成績")
print("3.查詢成績")
print("4.離開")
sel=int(input("輸入選項:"))
return sel
if os.path.isfile("scores.txt"):
print("存在")
fo=open("scores.txt","r")
x=fo.read()
else:
pr... | Python | zaydzuhri_stack_edu_python |
function handle_config self kwargs local_args=none
begin
comment Get all superclass configurations
set superclasses = list __class__
set configs = list
while any superclasses
begin
set superclass = pop superclasses
set superclasses = superclasses + __bases__
if has attribute superclass string CONFIG
begin
append config... | def handle_config(self, kwargs, local_args=None):
# Get all superclass configurations
superclasses = [self.__class__]
configs = list()
while any(superclasses):
superclass = superclasses.pop()
superclasses += superclass.__bases__
if hasattr(superclass, "CONFIG"):
confi... | Python | nomic_cornstack_python_v1 |
function event_m10_02_x15 z41=1002000 z42=1002099
begin
string State 0,1: Flag reset
call SetEventFlagsInRange z41 z42 0
string State 2: End state
return 0
end function | def event_m10_02_x15(z41=1002000, z42=1002099):
"""State 0,1: Flag reset"""
SetEventFlagsInRange(z41, z42, 0)
"""State 2: End state"""
return 0 | Python | nomic_cornstack_python_v1 |
function get_bytes records
begin
return sum generator expression transferred for r in records
end function | def get_bytes(records):
return sum(r.transferred for r in records) | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup as BS
import sys
import os
import re
comment Get the current working directory
set parent_dir = get current directory
set cwd = argv at 1
set file_MS = argv at 1
set dir_path = file_MS at slice : reverse find file_MS string \ :
set file_name = file_MS at slice reverse find file_MS string... | from bs4 import BeautifulSoup as BS
import sys
import os
import re
# Get the current working directory
parent_dir = os.getcwd()
cwd = sys.argv[1]
file_MS = sys.argv[1]
dir_path = file_MS[:file_MS.rfind('\\')]
file_name = file_MS[file_MS.rfind('\\')+1:]
file_Libre = dir_path + '\\___FILES___\\' + file_name
# Store B... | Python | zaydzuhri_stack_edu_python |
function delete_password self
begin
remove password_list self
end function
comment for password in password_list:
comment if password.account.lower() == account.lower():
comment cls.password_list.remove(password) | def delete_password(self):
Password.password_list.remove(self)
# for password in password_list:
# if password.account.lower() == account.lower():
# cls.password_list.remove(password) | Python | nomic_cornstack_python_v1 |
function getCurrentPlayer self
begin
if log is not none
begin
write log string Returning the current player
end
if verbose
begin
print string Returning the current player
end
return currentplayer
end function | def getCurrentPlayer(self):
if self.log is not None:
self.log.write("Returning the current player\n")
if self.verbose:
print("Returning the current player")
return self.currentplayer | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
import settings
set points1 = list list 332 240 list 1057 233 list 174 670 list 1227 663
set ratioX = WIDTH * 1.0 / 1366
set ratioY = HEIGHT * 1.0 / 768
set points1 = list comprehension list integer x * ratioX integer y * ratioY for tuple x y in points1
set pointsCell = list list 0 0 list ... | import numpy as np
import cv2
import settings
points1 = [[332, 240], [1057, 233], [174, 670], [1227, 663]]
ratioX = settings.WIDTH * 1.0 / 1366
ratioY = settings.HEIGHT * 1.0 / 768
points1 = [[int(x * ratioX), int(y * ratioY)] for x,y in points1 ]
pointsCell = [[0, 0], [settings.WIDTH, 0], [0, settings.HEIGHT], [se... | Python | zaydzuhri_stack_edu_python |
from Panda import *
comment Simple recursion (counting)
set w = call warpSpeed position=call P3 0 0 0 size=0
comment Define a function to make a line of pandas of a given length
comment You need the following:
comment A parameter "number" which tells you how many more panda to make
comment A parameter "place" which tel... | from Panda import *
# Simple recursion (counting)
w = warpSpeed(position = P3(0,0,0), size = 0)
# Define a function to make a line of pandas of a given length
# You need the following:
# A parameter "number" which tells you how many more panda to make
# A parameter "place" which tells you where the last pan... | Python | zaydzuhri_stack_edu_python |
function declination day_of_year_
begin
return 23.45 * call sin_deg 284 + day_of_year_ * 360 / 365
end function | def declination(day_of_year_: np.array) -> np.array:
return 23.45 * sin_deg(((284 + day_of_year_) * 360) / 365) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import torch
import numpy as np
from PIL import Image
function process_image image
begin
string Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array
comment Process a PIL image for use in a PyTorch model
set mean = array list 0.485 0.456 0.406
set std = array list 0.... | import pandas as pd
import torch
import numpy as np
from PIL import Image
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Process a PIL image for use in a PyTorch model
mean = np.array([0.485, 0.456, 0.406])
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class LogisticRegression
begin
function __init__ self learning_rate=0.001 max_iter=1000
begin
set learning_rate = learning_rate
set max_iter = max_iter
set weights = none
end function
function sigmoid self z
begin
return 1 / 1 + exp - z
end function
function fit self X y
begin
comment add bias term t... | import numpy as np
class LogisticRegression:
def __init__(self, learning_rate=0.001, max_iter=1000):
self.learning_rate = learning_rate
self.max_iter = max_iter
self.weights = None
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def fit(self, X, y):
# add bias t... | Python | jtatman_500k |
function test_find_neighbors self
begin
print string id: + call id
assert equal call neighbors list list 7 0 0 list 0 0 0 list 0 0 1 1
end function | def test_find_neighbors(self):
print ( "id: " + self.id())
self.assertEqual(circle.neighbors([[7, 0, 0], [0, 0, 0], [0, 0, 1]]), 1) | Python | nomic_cornstack_python_v1 |
function upsampling_block net style_weights interpolation_factor filters kernel_size strides activation depthwise_separable_conv
begin
set net = call call UpSampling2D interpolation_factor interpolation=string nearest net
set net = call conv_block net style_weights filters=filters kernel_size=kernel_size strides=stride... | def upsampling_block(net, style_weights, interpolation_factor, filters,
kernel_size, strides, activation,
depthwise_separable_conv):
net = UpSampling2D(interpolation_factor, interpolation="nearest")(net)
net = conv_block(net,
style_weights,
... | Python | nomic_cornstack_python_v1 |
import re
import time
from discord.ext import commands
set MINUTE = 60
set HOUR = 3600
set DAY = 86400
class Timestamp extends Converter
begin
async function convert self ctx argument
begin
if match string ^[0-9]{10}$ argument I
begin
set stamp = integer argument
if stamp < time
begin
raise call BadArgument message=str... | import re
import time
from discord.ext import commands
MINUTE = 60
HOUR = 3600
DAY = 86400
class Timestamp(commands.Converter):
async def convert(self, ctx, argument):
if re.match(r"^[0-9]{10}$", argument, re.I):
stamp = int(argument)
if stamp < time.time():
raise... | Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function __init__ self **kwargs
begin
call __init__ self keyword kwargs
comment upper limit of this interaction
set _capacity = none
comment which variable limits the capacity (could be produced or consumed?)
set _capacity_var = none
comment dependent signals for this interaction
set _signals = set
comment crossrefs ob... | def __init__(self, **kwargs):
Base.__init__(self, **kwargs)
self._capacity = None # upper limit of this interaction
self._capacity_var = None # which variable limits the capacity (could be produced or consumed?)
self._signals = set() # dependent signals for this int... | Python | nomic_cornstack_python_v1 |
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
import math
import datetime as dt
import numpy as np
from math import sqrt
import pandas as pd
from copy import deepcopy
import matplotlib.pyplot as plt
function simulate startdate enddate stocks alloc
begin
s... | import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
import math
import datetime as dt
import numpy as np
from math import sqrt
import pandas as pd
from copy import deepcopy
import matplotlib.pyplot as plt
def simulate(startdate, enddate, stocks, alloc):
... | Python | zaydzuhri_stack_edu_python |
function norm_residual self
begin
return fixed_point_residual
end function | def norm_residual(self) -> float:
return self.fixed_point_residual | Python | nomic_cornstack_python_v1 |
import pytest
decorator fixture scope=string class
function setup
begin
print string I will be executing first
yield
print string This line will execute after the steps in fixtureDemo method
end function
decorator fixture
function dataLoad
begin
print string Profile data required for test cases.
return list string Yash... | import pytest
@pytest.fixture(scope="class")
def setup():
print("I will be executing first")
yield
print("This line will execute after the steps in fixtureDemo method")
@pytest.fixture()
def dataLoad():
print("Profile data required for test cases.")
return ["Yashaswi", "Thannir", "yasha... | Python | zaydzuhri_stack_edu_python |
class hotel
begin
print string WELCOME TO KAiLASH DA DHABA
print
function __init__ self gt=0 tt=0 v=0 n=0
begin
set gt = gt
set tt = tt
set n = n
set v = v
end function
function veg self
begin
print string VEG MENU
print string 1.Masala Dosa-----Rs40 string 2.Vadapav-----Rs15 string 3.Samosa-----Rs18 string 4.Veg Thali... | class hotel:
print (" WELCOME TO KAiLASH DA DHABA ")
print()
def __init__(self,gt=0,tt=0,v=0,n=0):
self.gt=gt
self.tt=tt
self.n=n
self.v=v
def veg(self):
print(" VEG MENU ")
print("1.Masala Dosa-----Rs40","2.Vadap... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
comment 默认参数与位置参数的位置问题
comment def power(x,n = 2):
comment s = 1
comment while n > 0:
comment n = n -1
comment s = s * x
comment return s
comment print(power(2))
comment print(power(2,2))
comment print(power(2,3))
comment def power3(n = 2,x):
comment s = 1
comment while n > 0:
comment n = n -1
comm... | #coding:utf-8
#默认参数与位置参数的位置问题
# def power(x,n = 2):
# s = 1
# while n > 0:
# n = n -1
# s = s * x
# return s
# print(power(2))
# print(power(2,2))
# print(power(2,3))
# def power3(n = 2,x):
# s = 1
# while n > 0:
# n = n -1
# s = s * x
# return s
# print(power3(2,2))
# print(power3(2))
# def infor(nam... | Python | zaydzuhri_stack_edu_python |
set token = string 560362215:AAGRC9JTOhG5tzhhGNYRDj2YCVMnjThP9u4
set first_word = list string Ты string Вы
set second_word = list string многоуважаемый string простой string грандиозный string придурковатый string дрянной string хреновый string тупа
set third_word = list string сударь string кончалыга string питон stri... | token = "560362215:AAGRC9JTOhG5tzhhGNYRDj2YCVMnjThP9u4"
first_word = ['Ты', 'Вы']
second_word = ['многоуважаемый', 'простой', 'грандиозный', 'придурковатый', 'дрянной', 'хреновый', 'тупа']
third_word = ['сударь', 'кончалыга', 'питон', 'жаба', 'хрыч', 'ювелир', 'челик']
fourth_word = ['обдристался', 'постоял', 'прогол... | Python | zaydzuhri_stack_edu_python |
function test_fma_nan_param_okarray_nannum_oknum_none_a_43 self
begin
comment This version is expected to pass.
call fma okarrayx oknumy oknumz matherrors=true
comment This should raise an error.
with assert raises ArithmeticError
begin
call fma okarrayx nannumy oknumz
end
end function | def test_fma_nan_param_okarray_nannum_oknum_none_a_43(self):
# This version is expected to pass.
arrayfunc.fma(self.okarrayx, self.oknumy, self.oknumz, matherrors=True)
# This should raise an error.
with self.assertRaises(ArithmeticError):
arrayfunc.fma(self.okarrayx, self.nannumy, self.oknumz) | Python | nomic_cornstack_python_v1 |
function mydef01
begin
print string 일반 함수입니다.
end function
function mydef02 n m
begin
print n * m
end function | def mydef01():
print("일반 함수입니다.")
def mydef02(n, m):
print(n*m) | Python | zaydzuhri_stack_edu_python |
class UniqueId
begin
string A class used for assigning unique IDs
function __init__ self initial_value=0
begin
set num = initial_value
end function
function next_id self
begin
string Returns the next avaiable ID
set num = num + 1
return num - 1
end function
end class | class UniqueId:
"""
A class used for assigning unique IDs
"""
def __init__(self, initial_value=0):
self.num = initial_value
def next_id(self):
"""
Returns the next avaiable ID
"""
self.num += 1
return self.num - 1
| Python | zaydzuhri_stack_edu_python |
import re
set message = string Call me 415-555-1011 tomorrow, or at 415-555-9999 on my office number
comment Creating Regular Expression Object
set phoneNumRegex = compile string (\d\d\d)-(\d\d\d-\d\d\d\d)
set match_object = search message
print find all message
set area = call group 1
set number = call group 2
print a... | import re
message = "Call me 415-555-1011 tomorrow, or at 415-555-9999 on my office number"
# Creating Regular Expression Object
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
match_object = phoneNumRegex.search(message)
print(phoneNumRegex.findall(message))
area = match_object.group(1)
number = match_o... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.