code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_select_same_element_multiple_times self
begin
set sink = call TObserver
set obs = call MergeSelectorObservable left=left right=right
comment scheduler=self.scheduler,
call observe call init_observer_info sink
set ack_left = call on_next_list list select_next select_completed
set ack_right = call on_next_l... | def test_select_same_element_multiple_times(self):
sink = TObserver()
obs = MergeSelectorObservable(
left=self.left,
right=self.right,
# scheduler=self.scheduler,
)
obs.observe(init_observer_info(sink))
ack_left = self.left.on_next_list([selec... | Python | nomic_cornstack_python_v1 |
function density *args **kwargs
begin
pass
end function | def density(*args, **kwargs) -> Any:
pass | Python | nomic_cornstack_python_v1 |
string Problem 2 [20 points]. Preprocess all the files using assignment #4. Save all preprocessed documents in a single directory which will be the input to the next assignment, index construction. Send the TA a link to a dropbox directory where your preprocessed crawled documents are.
import re
import os
import Porter... | """
Problem 2 [20 points]. Preprocess all the files using assignment #4. Save all
preprocessed documents in a single directory which will be the input to
the next assignment, index construction. Send the TA a link to a dropbox
directory where your preprocessed crawled documents are.
"""
import re
import os
import Po... | Python | zaydzuhri_stack_edu_python |
comment https://www.lintcode.com/problem/course-schedule/description?_from=ladder&&fromId=1
from collections import deque
class Solution
begin
string @param: numCourses: a total of n courses @param: prerequisites: a list of prerequisite pairs @return: true if can finish all courses or false
function canFinish_v1 self n... | # https://www.lintcode.com/problem/course-schedule/description?_from=ladder&&fromId=1
from collections import deque
class Solution:
"""
@param: numCourses: a total of n courses
@param: prerequisites: a list of prerequisite pairs
@return: true if can finish all courses or false
"""
def canFini... | Python | zaydzuhri_stack_edu_python |
function group_records G class_label cutoff=0
begin
set groups = dict
for tuple n node in call nodes_iter data=true
begin
set c = node at class_label
if is instance c list
begin
for e in c
begin
if e not in groups
begin
set groups at e = list
end
append groups at e n
end
end
else
begin
if c not in groups
begin
set gr... | def group_records(G, class_label, cutoff=0):
groups = {}
for n, node in G.nodes_iter(data=True):
c = node[class_label]
if isinstance(c, list):
for e in c:
if e not in groups:
groups[e] = []
groups[e].append(n)
else:
... | Python | nomic_cornstack_python_v1 |
string Find the year with max people alive
class Person
begin
function __init__ self birth=none death=none
begin
set birth = birth
set death = death
end function
end class
function getPopulationPeak people
begin
set maxBirthYear = call getMaxBirthYear people
set deltas = call getDeltas people maxBirthYear
set currentSu... | ''' Find the year with max people alive '''
class Person:
def __init__(self, birth=None, death=None):
self.birth=birth
self.death=death
def getPopulationPeak(people):
maxBirthYear = getMaxBirthYear(people)
deltas = getDeltas(people, maxBirthYear)
currentSum = 0
maxSum = 0
maxYear = 0
for year i... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pylab as plt
import pandas as pd
from itertools import cycle
function plot_improves data den dead apxt et mark line label=none
begin
set resimp = iat at 0
set improves = dict
for tuple nres utils in call iteritems
begin
set improves at nres = list utils at 0
for u in utils at slice 1 : :
begin
appe... | import matplotlib.pylab as plt
import pandas as pd
from itertools import cycle
def plot_improves(data, den, dead, apxt, et, mark, line, label=None):
resimp = data.loc[(data.et == et) & (data.dead == dead) &
(data.den == den) & (data.apxt == apxt) &
(data.ntgts == ntgts)... | Python | zaydzuhri_stack_edu_python |
function plot_separate_info_plane_layer_view MI_object name color_l show_flag save_flag
begin
print string creating separate info plane layer view plot
set activations = act_func
set tuple fig axes = call subplots length activations 2 sharex=true sharey=true
call set_figheight 30
call set_figwidth 15
call subplots_adju... | def plot_separate_info_plane_layer_view(MI_object, name, color_l, show_flag, save_flag):
print("creating separate info plane layer view plot")
activations = MI_object.act_func
fig, axes = plt.subplots(len(activations),2,sharex=True,sharey=True)
fig.set_figheight(30)
fig.set_figwidth(15)
plt.sub... | Python | nomic_cornstack_python_v1 |
function fit self X y validation_sets=none epochs=10
begin
set tuple X Y = call check_X_y X y
comment Dict for storing epoch info.
set epoch_records = dict
comment Initialize the weights.
set weights_ = uniform low=- 0.01 high=0.01 size=shape at 1
for epoch in range epochs
begin
comment Calculate learning rate based o... | def fit(self, X, y, validation_sets=None, epochs=10):
X, Y = check_X_y(X, y)
# Dict for storing epoch info.
self.epoch_records = {}
# Initialize the weights.
self.weights_ = np.random.uniform(low=-0.01, high=0.01, size=X.shape[1])
for epoch in ... | Python | nomic_cornstack_python_v1 |
from enum import Enum
class Colours extends Enum
begin
string Colours of a piece
set white = string white
set red = string red
set blue = string blue
set orange = string orange
set green = string green
set yellow = string yellow
end class | from enum import Enum
class Colours(Enum):
"""Colours of a piece"""
white = 'white'
red = 'red'
blue = 'blue'
orange = 'orange'
green = 'green'
yellow = 'yellow'
| Python | zaydzuhri_stack_edu_python |
function test num
begin
print string 在函数内部 %d 对应的内存地址:%d % tuple num call id num
set result = string hello
print string 函数返回值的地址:%d % call id result
return result
end function
set a = 10
comment id() 查看变量内存地址
print string a的内存地址是:%d % call id a
set r = call test a
print string 返回值内存地址:%d % call id r | def test(num):
print("在函数内部 %d 对应的内存地址:%d" %(num,id(num)))
result = "hello"
print("函数返回值的地址:%d" % id(result))
return result
a = 10
print("a的内存地址是:%d" %id(a)) # id() 查看变量内存地址
r = test(a)
print("返回值内存地址:%d" %id(r)) | Python | zaydzuhri_stack_edu_python |
comment Beginner Sum of Numbers
comment input: any two numbers, positive or negative, as a and b
comment output: print the sum all numbers between a and b; including a and b
comment pseudo-code:
comment test for equality
comment if equal print a
comment if a greater than b
comment loop through the value of each number ... | # Beginner Sum of Numbers
#
# input: any two numbers, positive or negative, as a and b
# output: print the sum all numbers between a and b; including a and b
#
# pseudo-code:
# test for equality
# if equal print a
#
# if a greater than b
# loop through the value of each number between b and a
# accumu... | Python | zaydzuhri_stack_edu_python |
function _rec_perform self node x y inverse out curdim
begin
if length shape == 1
begin
comment Numpy advanced indexing works in this case
if inverse
begin
set out at y = x at slice : :
end
else
begin
set out at slice : : = x at y
end
if __version__ <= string 1.6.1 and size != call uint32 size
begin
warn string N... | def _rec_perform(self, node, x, y, inverse, out, curdim):
if len(x.shape) == 1:
# Numpy advanced indexing works in this case
if inverse:
out[y] = x[:]
else:
out[:] = x[y]
if (numpy.__version__ <= '1.6.1' and
out.... | Python | nomic_cornstack_python_v1 |
function _format_uri uid
begin
if call _is_legacy_uid uid
begin
raise call ValueError string should use legacy URI format for UIDs in (0..10)
end
set uid = string uid
return format string {root}/{path}/{uid}/{uid}.txt root=string http://www.gutenberg.lib.md.us path=join string / uid at slice : length uid - 1 : uid=uid... | def _format_uri(uid):
if _is_legacy_uid(uid):
raise ValueError('should use legacy URI format for UIDs in (0..10)')
uid = str(uid)
return '{root}/{path}/{uid}/{uid}.txt'.format(
root=r'http://www.gutenberg.lib.md.us',
path='/'.join(uid[:len(uid) - 1]),
uid=uid) | Python | nomic_cornstack_python_v1 |
function setFakeSrc self addr
begin
set fake_addr = addr
end function | def setFakeSrc(self, addr):
self.fake_addr = addr | Python | nomic_cornstack_python_v1 |
import csv
class Database
begin
set FirstNameToken = string First Name
set LastNameToken = string Last Name
function __init__ self String_pathToCsvDB=none
begin
set __List_fields = list FirstNameToken LastNameToken
set __List_db = list
if String_pathToCsvDB != none
begin
set File_csv = open String_pathToCsvDB
set Dict... | import csv
class Database:
FirstNameToken = 'First Name'
LastNameToken = 'Last Name'
def __init__(self, String_pathToCsvDB = None):
self.__List_fields = [Database.FirstNameToken, Database.LastNameToken]
self.__List_db = []
if String_pathToCsvDB != None:
File_csv = open(... | Python | zaydzuhri_stack_edu_python |
from Grammar import *
comment Takes a raw grammar (based on the DDT extraction) and makes it binary (CNF) and normalizes it's counts into our probabilities.
function convert_to_probabilistic_chomsky rawgrammar
begin
set grammar = call Grammar
set leftsideOcc = dict
for x in rules
begin
if rule_head in leftsideOcc
begi... | from Grammar import *
# Takes a raw grammar (based on the DDT extraction) and makes it binary (CNF) and normalizes it's counts into our probabilities.
def convert_to_probabilistic_chomsky(rawgrammar):
grammar = Grammar()
leftsideOcc = {}
for x in rawgrammar.rules:
if x.rule_head in leftsideOcc:
leftsideOcc[x... | Python | zaydzuhri_stack_edu_python |
function vowel_count string
begin
set count = 0
set vowels = string aeiou
for char in lower string
begin
if char in vowels
begin
set count = count + 1
end
end
return count
end function
print call vowel_count string Hello World | def vowel_count(string):
count = 0
vowels = 'aeiou'
for char in string.lower():
if char in vowels:
count += 1
return count
print(vowel_count("Hello World")) | Python | jtatman_500k |
comment Program to Find oldest person from their inputted age
set age1 = integer input string Enter First Person Age:
set age2 = integer input string Enter Second Person Age:
set age3 = integer input string Enter Thrid Person Age:
if age1 > age2 and age1 > age3
begin
print string Elder one is First Person and His age i... | # Program to Find oldest person from their inputted age
age1=int(input("Enter First Person Age:"))
age2=int(input("Enter Second Person Age:"))
age3=int(input("Enter Thrid Person Age:"))
if age1>age2 and age1>age3:
print(F"Elder one is First Person and His age is {age1} years")
elif age2>age3:
print(F... | Python | zaydzuhri_stack_edu_python |
function get_lat_long place_name
begin
set lat_lng_response_data = call get_json GMAPS_BASE_URL + string ?address= + replace place_name string string %
set lat_lng_data = lat_lng_response_data at string results at 0 at string geometry at string location
set latitude = lat_lng_data at string lat
set longitude = lat_lng... | def get_lat_long(place_name):
lat_lng_response_data = get_json(GMAPS_BASE_URL+"?address="+(place_name.replace(' ','%')))
lat_lng_data = lat_lng_response_data["results"][0]["geometry"]["location"]
latitude = lat_lng_data['lat']
longitude = lat_lng_data['lng']
return (latitude, longitude) | Python | nomic_cornstack_python_v1 |
comment Advent of Code 2021 - Day: 24
comment Imports (Always imports data based on the folder and file name)
from aocd import data , submit
function solve lines
begin
comment We need to simply find all the pairs of numbers, i.e. the numbers on lines 6 and 16 and store them.
set pairs = list comprehension tuple integer... | # Advent of Code 2021 - Day: 24
# Imports (Always imports data based on the folder and file name)
from aocd import data, submit
def solve(lines):
# We need to simply find all the pairs of numbers, i.e. the numbers on lines 6 and 16 and store them.
pairs = [(int(lines[i * 18 + 5][6:]), int(lines[i * 18 + 15][6:])) fo... | Python | jtatman_500k |
import datetime
import os
import pandas as pd
from asgiref.sync import async_to_sync
from reports_parser.config import DOCS_PATH
from reports_parser.utils import get_name , get_prev_monday
class ReportFormer
begin
string this class converts csv database to csv report
function get_files_list self
begin
string returns li... | import datetime
import os
import pandas as pd
from asgiref.sync import async_to_sync
from reports_parser.config import DOCS_PATH
from reports_parser.utils import get_name, get_prev_monday
class ReportFormer:
"""this class converts csv database to csv report"""
def get_files_list(self) -> list:
"""r... | Python | zaydzuhri_stack_edu_python |
function test_numerical_vs_analytical self
begin
comment this is only for personal interest and is not so much related to project
comment define a threshold
set arbitrary_acceptable_threshold = 0.1
comment generate trajectory object
set trajectory_generator = call SpringTrajectoryGenerator
comment get numerical acceler... | def test_numerical_vs_analytical(self):
# this is only for personal interest and is not so much related to project
# define a threshold
arbitrary_acceptable_threshold = 0.1
# generate trajectory object
trajectory_generator = SpringTrajectoryGenerator()
# get numerical acc... | Python | nomic_cornstack_python_v1 |
import pybullet
import pybullet_envs
import gym
from gym import wrappers
import numpy as np
from sac_implementation import Agent
from utils import plot_learning_curve
if __name__ == string __main__
begin
comment environment = gym.make('InvertedPendulumBulletEnv-v0') AntBulletEnv-v0 BipedalWalker-v3
set environment = ca... | import pybullet
import pybullet_envs
import gym
from gym import wrappers
import numpy as np
from sac_implementation import Agent
from utils import plot_learning_curve
if __name__ == '__main__':
# environment = gym.make('InvertedPendulumBulletEnv-v0') AntBulletEnv-v0 BipedalWalker-v3
environment = gym.make('Ant... | Python | zaydzuhri_stack_edu_python |
comment ========================================================================
comment Script to compute the mean expression levels of each stain for each cell.
comment ========================================================================
import pandas as pd
import numpy as np
import re
import os
comment =========... | # ========================================================================
# Script to compute the mean expression levels of each stain for each cell.
# ========================================================================
import pandas as pd
import numpy as np
import re
import os
# ================================... | Python | zaydzuhri_stack_edu_python |
function save_jsonl_file data data_jsonl remove_null=true
begin
with open data_jsonl string w as fp
begin
for datum in data
begin
set datum_dict = call cast Dict at tuple str Any dump datum
if remove_null
begin
write fp dumps call remove_null_fields_in_dict datum_dict
end
else
begin
write fp dumps datum_dict
end
write ... | def save_jsonl_file(
data: Iterable[_TDatum], data_jsonl: str, remove_null: bool = True
) -> None:
with open(data_jsonl, "w") as fp:
for datum in data:
datum_dict = cast(Dict[str, Any], jsons.dump(datum))
if remove_null:
fp.write(json.dumps(remove_null_fields_in_d... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
set array = list - 7 - 3 1 9 22 30
function sortedSquaredArray array
begin
set lp = 0
set rp = length array - 1
set squared_array = list comprehension 0 for _ in array
for idx in reversed range length array
begin
if absolute array at lp > absolute array at rp
begin
set squared_array at idx = a... | #!/usr/bin/python3
array = [-7, -3, 1, 9, 22, 30]
def sortedSquaredArray(array):
lp = 0
rp = len(array) - 1
squared_array = [ 0 for _ in array ]
for idx in reversed(range(len(array))):
if abs(array[lp]) > abs(array[rp]):
squared_array[idx] = array[lp] ** 2
lp += 1
... | Python | zaydzuhri_stack_edu_python |
function _parse_metadata in_file
begin
set metadata = dict
with open in_file as in_handle
begin
set reader = reader in_handle
while 1
begin
set header = next
if not starts with header at 0 string #
begin
break
end
end
set keys = list comprehension strip x for x in header at slice 1 : :
for sinfo in generator express... | def _parse_metadata(in_file):
metadata = {}
with open(in_file) as in_handle:
reader = csv.reader(in_handle)
while 1:
header = reader.next()
if not header[0].startswith("#"):
break
keys = [x.strip() for x in header[1:]]
for sinfo in... | Python | nomic_cornstack_python_v1 |
comment 通过SPI连接bmp388和esp32
comment download bmp388.py and downloadAndRun this demo
import bmp388
from machine import Pin , SPI
import time
comment selection pin D3/pin26
set D3 = 26
comment create SPI object
set spi = call SPI baudrate=100000 polarity=1 phase=0 sck=call Pin 18 mosi=call Pin 23 miso=call Pin 19
comment... | #通过SPI连接bmp388和esp32
#download bmp388.py and downloadAndRun this demo
import bmp388
from machine import Pin,SPI
import time
#selection pin D3/pin26
D3 = 26
#create SPI object
spi = SPI(baudrate=100000, polarity=1, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
#将片选引脚设置为输出模式
cs = Pin(D3,Pin.OUT)
#create SPI通信的bm... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import json
import csv
from sklearn.decomposition import PCA
import datetime
string json data processing methods
function activate activity_json
begin
string :return:
set activity_json = string activity_json
if activity_json == string nan or string type not in activity_json
begin
... | import pandas as pd
import numpy as np
import json
import csv
from sklearn.decomposition import PCA
import datetime
"""
json data processing methods
"""
def activate(activity_json):
"""
:return:
"""
activity_json = str(activity_json)
if activity_json == 'nan' or 'type' not in activity_json:
... | Python | zaydzuhri_stack_edu_python |
function x_edges self
begin
set log_masses = call log10 masses
set log_half_widths = log_masses at slice 1 : : - log_masses at slice 0 : - 1 : / 2
set last_mass = log_masses at - 1 + log_half_widths at - 1
set log_masses at slice 0 : - 1 : = log_masses at slice 0 : - 1 : - log_half_widths
set log_masses at - 1 = l... | def x_edges(self):
log_masses = np.log10(self.masses)
log_half_widths = (log_masses[1:] - log_masses[0:-1]) /2
last_mass = log_masses[-1] + log_half_widths[-1]
log_masses[0:-1] -= log_half_widths
log_masses[-1] -= log_half_widths[-1]
log_masses = np.append(log_masses, las... | Python | nomic_cornstack_python_v1 |
function restart_scan self
begin
call __init__ tiff_file_location chip_dimension scan_id load_frames=false
end function | def restart_scan(self):
self.__init__(self.tiff_file_location, self.chip_dimension, self.scan_id, load_frames=False) | Python | nomic_cornstack_python_v1 |
function f_is_first captcha
begin
set image = captcha at tuple slice 19 : 46 :
set col_sum = sum image axis=0
set col_sum_list = list col_sum
return col_sum_list at slice 28 : 36 : == list 3570 3570 0 1020 1020 0 510 510
end function | def f_is_first(captcha):
image = captcha[19:46,]
col_sum = np.sum(image, axis = 0)
col_sum_list = list(col_sum)
return(col_sum_list[28:36] == [3570, 3570, 0 , 1020, 1020, 0, 510, 510]) | Python | nomic_cornstack_python_v1 |
function isprime x
begin
for i in range 2 x
begin
if x % i == 0
begin
return 0
end
end
return 1
end function
comment 2 already counted
set count = 1
comment starting from 3 (see below, p+1)
set p = 2
while count <= 10000
begin
set p = p + 1
set count = count + call isprime p
end | def isprime(x):
for i in range(2, x):
if x % i == 0:
return 0
return 1
count = 1 # 2 already counted
p = 2 # starting from 3 (see below, p+1)
while count <= 10000:
p = p + 1
count = count + isprime(p)
| Python | zaydzuhri_stack_edu_python |
function respond_from_unrecognized_faculty self message tags
begin
for professor in PROFESSORS
begin
if professor in tags
begin
set professor = professor
return call go_to_state string specific_faculty
end
end
return call finish string fail
end function | def respond_from_unrecognized_faculty(self, message, tags):
for professor in self.PROFESSORS:
if professor in tags:
self.professor = professor
return self.go_to_state('specific_faculty')
return self.finish('fail') | Python | nomic_cornstack_python_v1 |
function test_setdefault self
begin
set value = set default group string a
assert equal value get group string a
end function | def test_setdefault(self):
value = self.group.setdefault('a')
self.assertEqual(value, self.group.get('a')) | Python | nomic_cornstack_python_v1 |
function export_to_excel self excel_file_name
begin
set writer = call ExcelWriter excel_file_name
call to_excel writer string Snapshots
save
log 2 string Results saved to excel file '%s' % excel_file_name
end function | def export_to_excel(self, excel_file_name):
writer = pd.ExcelWriter(excel_file_name)
self.snapshots.to_excel(writer,'Snapshots')
writer.save()
log(2, "Results saved to excel file '%s'" % excel_file_name) | Python | nomic_cornstack_python_v1 |
string " @authors Josivan Medeiros and Natália Azevedo
comment for .sh like command call
import subprocess
comment import os.system # for system(cmd)
function bash_command cmd
begin
popen list string /bin/bash string -c cmd
end function
class GPIO
begin
set leddir = string /sys/class/gpio/
function __init__ self name g... | """
" @authors Josivan Medeiros and Natália Azevedo
"""
import subprocess # for .sh like command call
#import os.system # for system(cmd)
def bash_command(cmd):
subprocess.Popen(['/bin/bash', '-c', cmd])
class GPIO:
leddir = "/sys/class/gpio/"
def __init__(self, name, gpiodir):
self.name = na... | Python | zaydzuhri_stack_edu_python |
function _check_unit_ids self X=none unit_ids=none fit=false
begin
function a_contains_b a b
begin
string Returns True iff 'b' is a subset of 'a'.
for bb in b
begin
if bb not in a
begin
warning format string {} was not found in set bb
return false
end
end
return true
end function
if is instance X BinnedEventArray
begin... | def _check_unit_ids(self,*, X=None, unit_ids=None, fit=False):
def a_contains_b(a, b):
"""Returns True iff 'b' is a subset of 'a'."""
for bb in b:
if bb not in a:
logging.warning("{} was not found in set".format(bb))
return False
... | Python | nomic_cornstack_python_v1 |
import math
set a = integer input string Dame el valor de a:
set b = integer input string Dame el valor de b:
set c = integer input string Dame el valor de c:
set x1 = 0
set par1 = b * b
set par2 = 4 * a * c
set x1 = par1 - par2
if x1 < 0
begin
set temp1 = x1 * - 1
end
if temp1 > 0
begin
set raiz1 = square root temp1
s... | import math
a = (int(input("Dame el valor de a:" )))
b = (int(input("Dame el valor de b:" )))
c = (int(input("Dame el valor de c:" )))
x1 = 0
par1=(b*b)
par2=(4*a*c)
x1 = (par1)-(par2)
if x1<0:
temp1=x1*(-1)
if temp1>0 :
raiz1=(math.sqrt(temp1))
a = a * 2
print("x1=(",'-'... | Python | zaydzuhri_stack_edu_python |
function _by_weight_then_from_protocol_specificity edge_1 edge_2
begin
comment edge_1 and edge_2 are edges, of the form (mro_distance, offer)
set tuple mro_distance_1 offer_1 = edge_1
set tuple mro_distance_2 offer_2 = edge_2
comment First, compare the MRO distance.
if mro_distance_1 < mro_distance_2
begin
return - 1
e... | def _by_weight_then_from_protocol_specificity(edge_1, edge_2):
# edge_1 and edge_2 are edges, of the form (mro_distance, offer)
mro_distance_1, offer_1 = edge_1
mro_distance_2, offer_2 = edge_2
# First, compare the MRO distance.
if mro_distance_1 < mro_distance_2:
return -1
elif mro_d... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function __init__ self
begin
pass
end function
function merge_sort self arr start end
begin
print string start { start } end { end }
if start == end
begin
return list arr at start
end
set mid = start + end - start // 2
print string mid { mid }
set a = call merge_sort arr start mid
set b = call merg... | class Solution:
def __init__(self):
pass
def merge_sort(self, arr, start, end):
print(f'start {start} end {end}')
if start == end:
return [arr[start]]
mid = start + (end - start) // 2
print(f'mid {mid}')
a = self.merge_sort(arr, start, mid)
b... | Python | zaydzuhri_stack_edu_python |
function load_stopwords self path
begin
if path
begin
with open path as f
begin
set stopwords = set call splitlines
end
end
else
begin
set stopwords = set call splitlines
end
end function | def load_stopwords(self, path):
if path:
with open(path) as f:
self.stopwords = set(f.read().splitlines())
else:
self.stopwords = set(
pkgutil
.get_data('textplot', 'data/stopwords.txt')
.decode('utf8')
... | Python | nomic_cornstack_python_v1 |
for i in conutries
begin
print i + string , i have more money now!!!!!! i am coming to see you!!
end | for i in conutries:
print(i + ', i have more money now!!!!!! i am coming to see you!!') | Python | zaydzuhri_stack_edu_python |
function oh_get_member_data token
begin
set req = get requests format string {}/api/direct-sharing/project/exchange-member/ OPENHUMANS_OH_BASE_URL params=dict string access_token token
if status_code == 200
begin
return json req
end
raise exception format string Status code {} status_code
return none
end function | def oh_get_member_data(token):
req = requests.get(
'{}/api/direct-sharing/project/exchange-member/'
.format(settings.OPENHUMANS_OH_BASE_URL),
params={'access_token': token}
)
if req.status_code == 200:
return req.json()
raise Exception('Status code {}'.format(req.stat... | Python | nomic_cornstack_python_v1 |
function unroll_dict dictionary key
begin
assert type dictionary is dict msg call TypeError string Dictionary passed is not type dict. Of type { type dictionary }
return list map lambda x -> x at key values dictionary
end function | def unroll_dict(dictionary, key) -> list:
assert type(dictionary) is dict,TypeError(f'Dictionary passed is not type dict. Of type {type(dictionary)}')
return list(map(lambda x: x[key], dictionary.values())) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment 模型预测
import os , json
import numpy as np
comment from bert.extract_feature import BertVector
from keras.models import load_model
from att import Attention
from albert_zh.extract_feature import BertVector
comment 加载训练效果最好的模型
set model_dir = string ./models
set files = list directory... | # -*- coding: utf-8 -*-
# 模型预测
import os, json
import numpy as np
# from bert.extract_feature import BertVector
from keras.models import load_model
from att import Attention
from albert_zh.extract_feature import BertVector
# 加载训练效果最好的模型
model_dir = './models'
files = os.listdir(model_dir)
models_path = [os.path.join... | Python | zaydzuhri_stack_edu_python |
function make_decoder_model embedding_matrix
begin
set tuple cat_dim emb_dim = shape
set embed = embedding cat_dim emb_dim weights=list embedding_matrix trainable=false
comment batch_input_shape = (batch_size, num_steps),
set old_softy = call TimeDistributed dense cat_dim activation=string softmax
set model = sequentia... | def make_decoder_model(embedding_matrix):
cat_dim, emb_dim = embedding_matrix.shape
embed = Embedding(cat_dim,
emb_dim,
#batch_input_shape = (batch_size, num_steps),
weights=[embedding_matrix],
trainable=False)
old_softy = TimeDistribut... | Python | nomic_cornstack_python_v1 |
function calc_Brice1975 self Do E ro ri T
begin
set D_n = Do * exp - 4.0 * pi * Avagadro * E * 0.5 * ro * ro - ri ^ 2.0 - ro - ri ^ 3.0 / 3.0 / R * T
return D_n
end function | def calc_Brice1975(self, Do, E, ro, ri, T):
D_n = Do * np.exp(-4. * np.pi * const.Avagadro * E * ((0.5 * ro * (ro - ri)**2.) - ((ro - ri)**3.)/3.) / (const.R * T))
return (D_n) | Python | nomic_cornstack_python_v1 |
function __streamHandler__ signum frame
begin
raise exception string end of time
end function | def __streamHandler__(signum, frame):
raise Exception("end of time") | Python | nomic_cornstack_python_v1 |
function Drain job_id project_id=none
begin
set project_id = project_id or call GetProject
set job = call Job requestedState=JOB_STATE_DRAINED
set request = call DataflowProjectsJobsUpdateRequest jobId=job_id projectId=project_id job=job
try
begin
return update call GetService request
end
except HttpError as error
begi... | def Drain(job_id, project_id=None):
project_id = project_id or GetProject()
job = GetMessagesModule().Job(requestedState=(
GetMessagesModule().Job.RequestedStateValueValuesEnum.JOB_STATE_DRAINED
))
request = GetMessagesModule().DataflowProjectsJobsUpdateRequest(
jobId=job_id, projectId=p... | Python | nomic_cornstack_python_v1 |
function visualize self observation action
begin
pass
end function | def visualize(self, observation, action):
pass | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
set w = 4
set h = 3
set d = 70
figure figsize=tuple w h dpi=d
set y1 = list 2 3 4.5
set y2 = list 1 1.5 5
plot y1
plot y2
grid
save figure string out.png | import matplotlib.pyplot as plt
w = 4
h = 3
d = 70
plt.figure(figsize=(w, h), dpi=d)
y1 = [2, 3, 4.5]
y2 = [1, 1.5, 5]
plt.plot(y1)
plt.plot(y2)
plt.grid()
plt.savefig("out.png")
| Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
from Tkinter import *
import socket
class ventanaServer
begin
function __init__ self
begin
set nombre_equipo = call gethostname
set direccion = call gethostbyname nombre_equipo
set root = call Tk
title root string ESPERANDO CONEXION...
call iconbitmap default=string C:/Program files/Eusebi... | #! /usr/bin/env python
from Tkinter import *
import socket
class ventanaServer:
def __init__(self):
nombre_equipo = socket.gethostname()
self.direccion = socket.gethostbyname(nombre_equipo)
self.root = Tk()
self.root.title("ESPERANDO CONEXION...")
self.root.iconbitmap(default=r'C:/Program files/Eusebio la... | Python | zaydzuhri_stack_edu_python |
function __eq__ self other
begin
comment type: (Options) -> bool
if is instance other Options
begin
return call dialect_eq dialect dialect and encoding == encoding and columntypes == columntypes and rowspec == rowspec and group_separator == group_separator and decimal_separator == decimal_separator
end
else
begin
retur... | def __eq__(self, other):
# type: (Options) -> bool
if isinstance(other, Options):
return (dialect_eq(self.dialect, other.dialect) and
self.encoding == other.encoding and
self.columntypes == other.columntypes and
self.rowspec == othe... | Python | nomic_cornstack_python_v1 |
import json
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
set imgs_dir = string ../../data/mydata/images
set json_file = string ../../data/mydata/all.json
set img_w = 1024
set img_h = 1024
set N = 50
if __name__ == string __main__
begin
if not exists path imgs_dir
begin
m... | import json
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
imgs_dir = '../../data/mydata/images'
json_file = '../../data/mydata/all.json'
img_w = 1024
img_h = 1024
N = 50
if __name__ == "__main__":
if not os.path.exists(imgs_dir):
os.makedirs(imgs_dir)
l... | Python | zaydzuhri_stack_edu_python |
import re
import xml.etree.ElementTree as ET
import pymongo
class KMLParse extends object
begin
function __init__ self
begin
set polygons = list
end function
function parse self file
begin
set tree = parse ET file
set root = get root tree
set ns = dictionary url=string http://www.opengis.net/kml/2.2
set placemarks = f... | import re
import xml.etree.ElementTree as ET
import pymongo
class KMLParse(object):
def __init__(self):
self.polygons = []
def parse(self, file):
tree = ET.parse(file)
root = tree.getroot()
ns = dict(url='http://www.opengis.net/kml/2.2')
placemarks = root.findall('.//url:Placemark', ns)
for placemar... | Python | zaydzuhri_stack_edu_python |
import warnings
filter warnings string ignore
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import env
import os
function wrangle_telco
begin
string Read telco_data csv file into a pandas DataFrame, only returns two-year contract customers and desired columns, drop any row... | import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import env
import os
def wrangle_telco():
'''
Read telco_data csv file into a pandas DataFrame,
only returns two-year contract customers and desired columns,
d... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function smallestRangeII self A K
begin
comment res至少是(A[-1]-K)-(A[0]+K),很有可能比这个范围大
sort A
set res = A at - 1 - A at 0
for i in range length A - 1
begin
comment 记住吧,不懂为啥,但感觉也对
set ma = max A at - 1 - K A at i + K
set mn = min A at 0 + K A at i + 1 - K
set res = min res ma - mn
end
return res
end fu... | class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
# res至少是(A[-1]-K)-(A[0]+K),很有可能比这个范围大
A.sort()
res=A[-1]-A[0]
for i in range(len(A)-1):
ma=max(A[-1]-K,A[i]+K)# 记住吧,不懂为啥,但感觉也对
mn=min(A[0]+K,A[i+1]-K)
res=min(res,ma-... | Python | zaydzuhri_stack_edu_python |
import math
function is_prime_palindrome n
begin
comment Step 1: Check if the number is a positive integer
if not is instance n int or n <= 0
begin
return false
end
comment Step 2: Check if the number is prime
if not call is_prime n
begin
return false
end
comment Step 3: Check if the number is a palindrome
if string n ... | import math
def is_prime_palindrome(n):
# Step 1: Check if the number is a positive integer
if not isinstance(n, int) or n <= 0:
return False
# Step 2: Check if the number is prime
if not is_prime(n):
return False
# Step 3: Check if the number is a palindrome
if str(n) != str(... | Python | jtatman_500k |
function __getattr__ self name
begin
if name in __fields__
begin
try
begin
return __dict__ at string __model__ at name
end
except KeyError
begin
set default = call get_default
return set default __dict__ at string __model__ name default
end
end
else
begin
raise call AttributeError name
end
end function | def __getattr__(self, name):
if name in self.__fields__:
try:
return self.__dict__['__model__'][name]
except KeyError:
default = self.__fields__[name].get_default()
return self.__dict__['__model__'].setdefault(name, default)
else:
... | Python | nomic_cornstack_python_v1 |
comment Librerias
import cv2
import numpy as np
from collections import deque
from statistics import mean
comment Iniciar camara
set captura = call VideoCapture 0
set RobMov = 0
set azx = deque
set rox = deque
set vex = deque
set cex = deque
set rosx = deque
set amx = deque
set azy = deque
set roy = deque
set vey = deq... | #Librerias
import cv2
import numpy as np
from collections import deque
from statistics import mean
#Iniciar camara
captura = cv2.VideoCapture(0)
RobMov =0
azx = deque()
rox = deque()
vex = deque()
cex = deque()
rosx = deque()
amx = deque()
azy = deque()
roy = deque()
vey = deque()
cey = deque()
... | Python | zaydzuhri_stack_edu_python |
function get_atril_array self
begin
return atril
end function | def get_atril_array(self):
return self.atril | Python | nomic_cornstack_python_v1 |
from functools import reduce
set suma = lambda l -> reduce lambda x y -> x + y l 0 | from functools import reduce
suma = lambda l: reduce(lambda x, y: x + y, l, 0) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Schedule changes checker for http://itmm.unn.ru Downloads schedule web-page (http://itmm.unn.ru/studentam/raspisanie), parses it to extract changes, link to schedule file, time of last change, downloads schedule file, send all via email. Script strongly... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Schedule changes checker for http://itmm.unn.ru
Downloads schedule web-page (http://itmm.unn.ru/studentam/raspisanie),
parses it to extract changes, link to schedule file, time of last change,
downloads schedule file,
send all via email.
Script strongly depends on fo... | Python | zaydzuhri_stack_edu_python |
import pyautogui , sys
import curses
comment Using module keyboard
import keyboard
comment pyautogui.typewrite('Hello world!', interval=0.25)
function writeToFile aString
begin
with open string log.txt string a as f
begin
write f aString
end
end function
function checkForStringInFile aString
begin
with open string log.... | import pyautogui, sys
import curses
import keyboard #Using module keyboard
# pyautogui.typewrite('Hello world!', interval=0.25)
def writeToFile(aString):
with open('log.txt', "a") as f:
f.write(aString)
def checkForStringInFile(aString):
with open('log.txt', 'a') as f:
lines = f.readlines()
... | Python | zaydzuhri_stack_edu_python |
comment Return the word with an added "s" if n != 1.
comment Optional set plural form.
function pluralize s=string n=0 pluralForm=none
begin
if n != 1
begin
if pluralForm is none
begin
set s = s + string s
end
else
begin
set s = pluralForm
end
end
return s
end function | # Return the word with an added "s" if n != 1.
# Optional set plural form.
def pluralize(s="", n=0, pluralForm=None):
if n != 1:
if pluralForm is None:
s += "s"
else:
s = pluralForm
return s | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
from db import get_user_data
function pie_plot_creation u_id d_from d_to title
begin
string Данная функция нужна для построения круговой диаграммы по данным пользователя. Круговая диаграмма может быть построена: - за сегодня - за текущий месяц - за предыдущий месяц :param u_id: id пользо... | import matplotlib.pyplot as plt
from db import get_user_data
def pie_plot_creation(u_id, d_from, d_to, title):
"""
Данная функция нужна для построения круговой диаграммы по данным пользователя.
Круговая диаграмма может быть построена:
- за сегодня
- за текущий месяц
- за предыдущий месяц
:... | Python | zaydzuhri_stack_edu_python |
import pylab as p
import matplotlib.numerix as nx
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.collections import LineCollection
from matplotlib.colors import rgb2hex
import random , math
comment Lambert Conformal map of lower 48 states.
set m = call Basemap llcrnrlon=- 119 llcrnrlat=22 urcrnrlon... | import pylab as p
import matplotlib.numerix as nx
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.collections import LineCollection
from matplotlib.colors import rgb2hex
import random, math
# Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcr... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy.sparse as sp
import multiprocessing as mp
function apply_parallel mat_list coeffs processes=cpu count
begin
set res = array string d zeros shape at 0
set count = min processes length mat_list
set p = list comprehension process target=f args=tuple mat_list integer i * shape at 0 / count i... | import numpy as np
import scipy.sparse as sp
import multiprocessing as mp
def apply_parallel(mat_list , coeffs , processes=mp.cpu_count()):
res = mp.Array("d", np.zeros(coeffs.shape[0]))
count = min(processes, len(mat_list))
p = [mp.Process(target=f, args = (mat_list, int(i*coeffs.shape[0]/count), int((i+1... | Python | zaydzuhri_stack_edu_python |
from datetime import date
set nascimento = integer input string Digite em que ano você nasceu:
set data_atual = today
set idade = year - nascimento
print format string Como a idade do jovem é {} anos, temos que: idade
if idade > 1 and idade < 18
begin
print string Você ainda vai se alistar no serviço militar!
set tempo... | from datetime import date
nascimento = int(input('Digite em que ano você nasceu: '))
data_atual = date.today()
idade = data_atual.year - nascimento
print('Como a idade do jovem é {} anos, temos que: '.format(idade))
if idade > 1 and idade < 18:
print('Você ainda vai se alistar no serviço militar!')
t... | Python | zaydzuhri_stack_edu_python |
function part_geom xyz vtxdist=none comm=none **kw
begin
set xyz = call asarray xyz dtype=float32
if ndim != 2
begin
raise call ValueError string coordinates must be 2D array
end
if shape at 1 not in tuple 2 3
begin
raise call ValueError string must be either 2D or 3D
end
comment NOTE: we initialize MPI here (if needed... | def part_geom(xyz, vtxdist=None, comm=None, **kw):
xyz = np.asarray(xyz, dtype=np.float32)
if xyz.ndim != 2:
raise ValueError("coordinates must be 2D array")
if xyz.shape[1] not in (2, 3):
raise ValueError("must be either 2D or 3D")
comm = get_comm(comm) # NOTE: we initialize MPI here (... | Python | nomic_cornstack_python_v1 |
from ldap_connection import BaseDN
from ldap_function import make_connection , readCredential
import datetime
from pushbullet_sender import send_pushbullet_notif
from ldap3.utils.conv import escape_bytes
set PathCredential_ldap = string ignore/ldap_credential.json
set BaseDN = call readCredential PathCredential_ldap st... | from ldap_connection import BaseDN
from ldap_function import make_connection,readCredential
import datetime
from pushbullet_sender import send_pushbullet_notif
from ldap3.utils.conv import escape_bytes
PathCredential_ldap = "ignore/ldap_credential.json"
BaseDN = readCredential(PathCredential_ldap,"baseDN")
#check if ... | Python | zaydzuhri_stack_edu_python |
function getInput
begin
try
begin
set infile = open string data.txt string r
end
except IOError
begin
print string File IO Error
call quit
end
finally
begin
return read infile
end
end function
function putOutput arr
begin
try
begin
set outfile = open string merge.out string w
end
except IOError
begin
print string File ... | def getInput():
try:
infile = open('data.txt', 'r')
except IOError:
print("File IO Error")
quit()
finally:
return infile.read()
def putOutput(arr):
try:
outfile = open('merge.out', 'w')
except IOError:
print("File IO Error")
quit... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: Utf-8 -*
from typing import Tuple
import pygame
function create_surface size
begin
return call convert_alpha
end function | # -*- coding: Utf-8 -*
from typing import Tuple
import pygame
def create_surface(size: Tuple[int, int]) -> pygame.Surface:
return pygame.Surface(size, flags=pygame.SRCALPHA|pygame.HWSURFACE).convert_alpha()
| Python | zaydzuhri_stack_edu_python |
from controllers import *
function get_course_data_students_test students
begin
string Test 01 - contents of students
set test01_pass = true
set test01_error = string
if length students != 1
begin
set test01_pass = false
set test01_error = test01_error + string More or less than one student reported (there should be o... | from controllers import *
def get_course_data_students_test(students):
""" Test 01 - contents of students """
test01_pass = True
test01_error = ""
if len(students) != 1:
test01_pass = False
test01_error += "More or less than one student reported (there should be one). "
if students:
for student... | Python | zaydzuhri_stack_edu_python |
function nexus_assets_claim_asset self txid
begin
if session_id == none
begin
return call __error string Not logged in
end
set parms = format string ?pin={}&session={}&txid={} pin session_id txid
set url = format assets_url sdk_url string claim/asset + parms
set json_data = call __get url
return json_data
end function | def nexus_assets_claim_asset(self, txid):
if (self.session_id == None): return(self.__error("Not logged in"))
parms = "?pin={}&session={}&txid={}".format(self.pin, self.session_id,
txid)
url = assets_url.format(sdk_url, "claim/asset") + parms
json_data = self.__get(url)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/local/bin/python
import os
call system string clear
set answer = string Watson
print string Let us play a game.
print string What is the name of the computer that played on Jeopardy ?
set response = call raw_input
if response == answer
begin
print string That is correct
end
else
begin
print string Sorry !... | #!/usr/local/bin/python
import os
os.system('clear')
answer = "Watson"
print("Let us play a game.")
print("What is the name of the computer that played on Jeopardy ? ")
response = raw_input()
if response == answer:
print("That is correct")
else:
print("Sorry ! Guess again : ")
response = raw_input()
... | Python | zaydzuhri_stack_edu_python |
import math
class Point
begin
function __init__ self canvas x=0 y=0 width=0 color=string red velocity=0
begin
set canvas = canvas
set x = x
set y = y
set width = width
set color = color
set velocity = 1
set angle = 0 * pi / 180
set __turning_const = 2.4
set __velocity_const = 0.01
end function
function save_obj self
be... | import math
class Point():
def __init__(self, canvas, x = 0, y = 0, width = 0, color = 'red', velocity = 0):
self.canvas = canvas
self.x = x
self.y = y
self.width = width
self.color = color
self.velocity = 1
self.angle = 0 * math.pi / 180
self.__turn... | Python | zaydzuhri_stack_edu_python |
function this_is_js
begin
return false
end function | def this_is_js():
return False | Python | nomic_cornstack_python_v1 |
import functools
import typing
import string
import random
import pytest
comment Lösung Teil 1.
function list_filter x xs
begin
string Function to filter elements of a list. Args: x(int): Given number xs(list): Given list with numbers Return: res(list): A list only containing the elements of xs that are <= x
set res = ... | import functools
import typing
import string
import random
import pytest
# Lösung Teil 1.
def list_filter(x: int, xs: list) -> list:
"""Function to filter elements of a list.
Args:
x(int): Given number
xs(list): Given list with numbers
Return:
res(list): A list only co... | Python | zaydzuhri_stack_edu_python |
function increment_car_count self
begin
set car_count = car_count + 1
end function | def increment_car_count(self):
self.car_count += 1 | Python | nomic_cornstack_python_v1 |
function parse_sfx_relative_time input_time
begin
set match = match string -([0-9]+)([a-zA-z]) input_time
if match
begin
set unit = call group 2
if unit in SFX_TIME_MULT
begin
set delta = integer call group 1 * SFX_TIME_MULT at unit
return integer time * 1000 - delta
end
set allowed = join string , keys SFX_TIME_MULT
p... | def parse_sfx_relative_time(input_time: str) -> int:
match = re.match(r"-([0-9]+)([a-zA-z])", input_time)
if match:
unit = match.group(2)
if unit in SFX_TIME_MULT:
delta = int(match.group(1)) * SFX_TIME_MULT[unit]
return int(time.time()) * 1000 - delta
allowed = "... | Python | nomic_cornstack_python_v1 |
async function execute self child_order
begin
print string Emir is executing, { parent_order_no } - { sliced_no }
try
begin
set TWAP_CALCULATOR = call TWAP_CALCULATOR symbol=security_id var_storages=VAR_STORAGES last_n_minutes=parent_slice_interval
await call calculate_twap
call trade twap_=twap_val
if order_no is not ... | async def execute(self, child_order):
print(f"Emir is executing, {child_order.parent_order_no}-{child_order.sliced_no}")
try:
TWAP_CALCULATOR = self.TWAP_CALCULATOR(symbol=child_order.security_id,
var_storages=self.VAR_STORAGES,
... | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
class Solution
begin
function findOrder self numCourses prerequisites
begin
set dict_list = default dictionary list
set degree = list 0 * numCourses
set res = list
for tuple course needed in prerequisites
begin
append dict_list at needed course
set degree at course = degree at cours... | from collections import defaultdict
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
dict_list = defaultdict(list)
degree = [0] * numCourses
res = []
for course,needed in prerequisites:
dict_list[needed].append(co... | Python | zaydzuhri_stack_edu_python |
comment Scenario 3: Multiple long carrier route lists
comment You have 5 carrier route lists, each with 10,000,000 (10M) entries (in arbitrary order) and a list of 10,000 phone numbers. How can you speed up your route cost lookup solution to handle this larger dataset?
import glob
import os
comment Imports for benchmar... | # Scenario 3: Multiple long carrier route lists
# You have 5 carrier route lists, each with 10,000,000 (10M) entries (in arbitrary order) and a list of 10,000 phone numbers. How can you speed up your route cost lookup solution to handle this larger dataset?
import glob
import os
# Imports for benchmarking
import time
... | Python | zaydzuhri_stack_edu_python |
string implement power(x, k), where x is a real value k is always a nonnegative integer
function power x k
begin
if k == 1
begin
return x
end
else
if k == 0
begin
return 1
end
else
begin
return x * call power x k - 1
end
end function | '''
implement power(x, k), where x is a real value
k is always a nonnegative integer
'''
def power(x, k):
if k == 1:
return x
elif k == 0:
return 1
else:
return x*power(x, k-1)
| Python | zaydzuhri_stack_edu_python |
set i = 9
while i >= 1
begin
for j in range 1 i
begin
print i - j end=string
end
set i = i - 1
print
end | i=9
while(i >= 1):
for j in range(1, i):
print(i-j, end=" ")
i = i-1
print()
| Python | zaydzuhri_stack_edu_python |
function raw x
begin
try
begin
return bytes x
end
except TypeError
begin
return bytes x encoding=string utf8
end
end function | def raw(x):
try:
return bytes(x)
except TypeError:
return bytes(x, encoding="utf8") | Python | nomic_cornstack_python_v1 |
function description self description
begin
set _description = description
end function | def description(self, description):
self._description = description | Python | nomic_cornstack_python_v1 |
function printPoly list
begin
set polyStr = string P(x) =
for i in range length list
begin
set term = list at i at 0
set coef = list at i at 1
if coef >= 0
begin
set polyStr = polyStr + string +
end
set polyStr = polyStr + string coef + string x^ + string term + string
end
return polyStr
end function
function calPoly ... | def printPoly(list):
polyStr = "P(x) = "
for i in range(len(list)):
term = list[i][0]
coef = list[i][1]
if (coef >= 0):
polyStr += "+"
polyStr += str(coef) + "x^" + str(term) + " "
return polyStr
def calPoly(xVal, mylist):
retValue = 0
for i in range(... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isIsomorphic self s t
begin
set seen = dict
for tuple p w in zip s t
begin
if p not in seen and w not in values seen
begin
set seen at p = w
end
else
if p not in seen or seen at p != w
begin
return false
end
end
return true
end function
end class | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
seen={}
for p,w in zip(s,t):
if p not in seen and w not in seen.values():
seen[p]=w
elif p not in seen or seen[p]!=w:
return False
return True
| Python | zaydzuhri_stack_edu_python |
function get_lip_max self
begin
if _fitted
begin
return call get_lip_max
end
else
begin
raise call ValueError string call ``fit`` before calling ``get_lip_max``
end
end function | def get_lip_max(self) -> float:
if self._fitted:
return self._model.get_lip_max()
else:
raise ValueError("call ``fit`` before calling ``get_lip_max``") | Python | nomic_cornstack_python_v1 |
function as_xml self parent
begin
set n = call newChild none string N none
call newTextChild none string FAMILY call to_utf8 family
call newTextChild none string GIVEN call to_utf8 given
call newTextChild none string MIDDLE call to_utf8 middle
call newTextChild none string PREFIX call to_utf8 prefix
call newTextChild n... | def as_xml(self,parent):
n=parent.newChild(None,"N",None)
n.newTextChild(None,"FAMILY",to_utf8(self.family))
n.newTextChild(None,"GIVEN",to_utf8(self.given))
n.newTextChild(None,"MIDDLE",to_utf8(self.middle))
n.newTextChild(None,"PREFIX",to_utf8(self.prefix))
n.newT... | Python | nomic_cornstack_python_v1 |
if nbFruits % nbPersonnes == 0
begin
print string oui
end
else
begin
print string non
end | if nbFruits % nbPersonnes == 0:
print("oui")
else:
print("non") | Python | zaydzuhri_stack_edu_python |
class Pants
begin
function __init__ self color waist_size length price
begin
set color = color
set waist_size = waist_size
set length = length
set price = price
end function
function change_price self new_price
begin
set price = new_price
end function
function discount self discount_val
begin
return price - price * dis... | class Pants:
def __init__(self, color, waist_size, length, price):
self.color = color
self.waist_size = waist_size
self.length = length
self.price = price
def change_price(self, new_price):
self.price = new_price
def discount(self, discount_val):
return self... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import os , sys , getopt
function prepare_latency_file filename nodeID
begin
comment get start time
set f = open filename string r
set first = split replace replace read line f string [ string string ] string string ,
set starttime = decimal first at 4
close f
comment process file
set f = o... | #!/usr/bin/env python
import os, sys, getopt
def prepare_latency_file(filename, nodeID):
# get start time
f = open(filename, "r")
first = f.readline().replace("[", "").replace("]", "").split(",")
starttime = float(first[4])
f.close()
# process file
f = open(filename, "r")
out = open("t... | Python | zaydzuhri_stack_edu_python |
if __name__ == string __main__
begin
set tuple n p q = list map int split strip input
set total = 0
set ans = 0
function combine n_ c
begin
if n_ == c
begin
return 1
end
if c == 0
begin
return 1
end
set n1 = 1
for i in range n_ - c n + 1
begin
set n1 = n1 * i
end
set n2 = 1
for i in range 1 c + 1
begin
set n2 = n2 * i
... | if __name__ == "__main__":
n, p, q = list(map(int, input().strip().split()))
total = 0
ans = 0
def combine(n_, c):
if n_ == c:
return 1
if c == 0:
return 1
n1 = 1
for i in range(n_-c, n+1):
n1 *= i
n2 = 1
for i in range... | Python | zaydzuhri_stack_edu_python |
function test_biz_not_loggedin self
begin
call credentials
set payload = dict string title string test ; string description string test ; string address string test ; string city string test ; string phone string +989123456789
set res = post BIZ_URL payload
assert equal status_code HTTP_401_UNAUTHORIZED
end function | def test_biz_not_loggedin(self):
self.client.credentials()
payload = {
"title": "test",
"description": "test",
"address": "test",
"city": "test",
"phone": "+989123456789"
}
res = self.client.post(BIZ_URL, payload)
... | Python | nomic_cornstack_python_v1 |
function test_view self
begin
set response = get client reverse string makeReports:import-assessment kwargs=dict string report pk + string ?year=2019&dp= + string pk + string &slo= + string pk
call assertEquals status_code 200
call assertContains response string mport
end function | def test_view(self):
response = self.client.get(reverse('makeReports:import-assessment',kwargs={'report':self.rpt.pk})+"?year=2019&dp="+str(self.slo2.report.degreeProgram.pk)+"&slo="+str(self.slo2.pk))
self.assertEquals(response.status_code,200)
self.assertContains(response,"mport") | 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.