code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function timestamp self timestamp
begin
comment noqa: E501
if client_side_validation and timestamp is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `timestamp`, must not be `None`
end
set _timestamp = timestamp
end function | def timestamp(self, timestamp):
if self.local_vars_configuration.client_side_validation and timestamp is None: # noqa: E501
raise ValueError("Invalid value for `timestamp`, must not be `None`") # noqa: E501
self._timestamp = timestamp | Python | nomic_cornstack_python_v1 |
function start_server server_address server names clients
begin
print string Chat session successfully connected on: { server_address at 0 }
call listen
while true
begin
set tuple connection client_address = call accept
set name = split decode call recv BUFFERSIZE FORMAT SEPARATOR at 3
append names name
print string Ne... | def start_server(server_address, server, names, clients):
print(f'Chat session successfully connected on: {server_address[0]}')
server.listen()
while True:
connection, client_address = server.accept()
name = connection.recv(BUFFERSIZE).decode(FORMAT).split(SEPARATOR)[3]
names.appe... | Python | nomic_cornstack_python_v1 |
function vol rad
begin
pass
end function
function ran_check num low high
begin
if num in range low high + 1
begin
print string { num } is in the range between { low } and { high }
end
else
begin
print string { num } is not in the range between { low } and { high }
end
end function
comment ran_check(5,2,7)
function ran_... | def vol(rad):
pass
def ran_check(num,low,high):
if num in range(low,high+1):
print(f'{num} is in the range between {low} and {high}')
else:
print(f'{num} is not in the range between {low} and {high}')
#ran_check(5,2,7)
def ran_bool(num,low,high):
return num in range(low,high+1)
#print(ran_bool(14,... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
set DIFFS = tuple tuple 1 0 tuple 0 - 1 tuple - 1 0 tuple 0 1
set DS = tuple tuple 1 0 tuple 1 - 1 tuple 0 - 1 tuple - 1 - 1 tuple - 1 0 tuple - 1 1 tuple 0 1 tuple 1 1
function get_limit limit
begin
set memo = default dictionary int
set memo at tuple 0 0 = 1
set coords = list 0 0
se... | from collections import defaultdict
DIFFS = ((1, 0), (0, -1), (-1, 0), (0, 1))
DS = ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1))
def get_limit(limit):
memo = defaultdict(int)
memo[(0, 0)] = 1
coords = [0, 0]
steps = 1
direction = 0
i = 1
while True:
for... | Python | zaydzuhri_stack_edu_python |
function evaluate self
begin
if length preconnected == 0
begin
comment print("nothing connected")
return bias
end
set summation = 0
for i in range length weights
begin
set summation = summation + weights at i * evaluate preconnected at i
end
set summation = summation + bias
if summation < 0
begin
return 0
end
else
begi... | def evaluate(self):
if len(self.preconnected) == 0:
# print("nothing connected")
return self.bias
summation = 0
for i in range(len(self.weights)):
summation += self.weights[i]*self.preconnected[i].evaluate()
summation += self.bias
if summation < 0:
return 0
else:
return 1 | Python | nomic_cornstack_python_v1 |
class m_Building
begin
function set_building_name self buliding_name
begin
set buliding_name = buliding_name
end function
function set_buliding_id self buliding_id
begin
set buliding_id = buliding_id
end function
function get_building_name self
begin
return buliding_name
end function
function get_buliding_id self
begin... | class m_Building():
def set_building_name(self,buliding_name):
self.buliding_name = buliding_name
def set_buliding_id(self,buliding_id):
self.buliding_id = buliding_id
def get_building_name(self):
return self.buliding_name
def get_buliding_id(self):
return self.bulidi... | Python | zaydzuhri_stack_edu_python |
function _read_evoked_besa_mul fname verbose
begin
with open fname as f
begin
set header = strip read line f
set ch_names = split strip read line f
end
set fields = call _parse_header header
set data = call loadtxt fname skiprows=2 ndmin=2
if length ch_names != shape at 1
begin
raise call RuntimeError string Mismatch b... | def _read_evoked_besa_mul(fname, verbose):
with open(fname) as f:
header = f.readline().strip()
ch_names = f.readline().strip().split()
fields = _parse_header(header)
data = np.loadtxt(fname, skiprows=2, ndmin=2)
if len(ch_names) != data.shape[1]:
raise RuntimeError(
... | Python | nomic_cornstack_python_v1 |
function make_title table_name col
begin
return replace replace replace replace replace table_name string aggregate_ string string panel_ string string .csv string string _log_ string string log_ string + string + replace col string _ttl string
end function | def make_title(table_name, col):
return (table_name.replace('aggregate_', '')
.replace('panel_', '')
.replace('.csv', '')
.replace('_log_', '')
.replace('log_', '') +
' ' +
col.replace('_ttl', '')) | Python | nomic_cornstack_python_v1 |
import pytesseract
import PIL
import cv2 as cv
from PIL import Image , ImageDraw
set face_cascade = call CascadeClassifier haarcascades + string haarcascade_frontalface_default.xml
set eye_cascade = call CascadeClassifier haarcascades + string haarcascade_frontalface_default.xml
set tesseract_cmd = string C:\Program Fi... | import pytesseract
import PIL
import cv2 as cv
from PIL import Image, ImageDraw
face_cascade=cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade=cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml')
pytesseract.pytesseract.tesseract_cmd = r'C:\Prog... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
from sklearn.ensemble import AdaBoostClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
set dataset = re... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sklearn.ensemble import AdaBoostClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import metrics
dataset = pd.read_csv('/User... | Python | zaydzuhri_stack_edu_python |
function mag self
begin
set result = x ^ 2 + y ^ 2 + z ^ 2 ^ 0.5
return result
end function | def mag(self):
result = (self.x**2 + self.y**2 + self.z**2)**0.5
return result | Python | nomic_cornstack_python_v1 |
function get_hmac password
begin
if password_salt is none
begin
raise call RuntimeError string The configuration value `SECURITY_PASSWORD_SALT` must not be None when the value of `SECURITY_PASSWORD_HASH` is set to "%s" % password_hash
end
set h = call new encode password_salt string utf-8 encode password string utf-8 s... | def get_hmac(password):
if _security.password_salt is None:
raise RuntimeError(
'The configuration value `SECURITY_PASSWORD_SALT` must '
'not be None when the value of `SECURITY_PASSWORD_HASH` is '
'set to "%s"' % _security.password_hash)
h = hmac.new(_securit... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import base_requests
from termcolor import *
import main_excute
comment -- P 获取余额
function get_user_balance
begin
for i in range 1 2
begin
set api_name = string 获取用户账户余额
set url = string v1/account/balance
set params = dict
comment "token": "e91e153a262e53fe3ea4da8dada3f305"
set result = post url ... | # coding=utf-8
import base_requests
from termcolor import *
import main_excute
# -- P 获取余额
def get_user_balance():
for i in range(1, 2):
api_name = '获取用户账户余额'
url = 'v1/account/balance'
params = {
# "token": "e91e153a262e53fe3ea4da8dada3f305"
}
result = base_r... | Python | zaydzuhri_stack_edu_python |
function user_stats df
begin
print string Calculating User Stats...
set start_time = time
comment Display counts of user types
set user_type = value counts df at string User Type
print string User Type -
for tuple type count in call iteritems
begin
print format string {}, count {} type count
end
comment Display counts ... | def user_stats(df):
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_type = df['User Type'].value_counts()
print("User Type -")
for type, count in user_type.iteritems():
print(" {}, count {}".format(type, count))
# Display coun... | Python | nomic_cornstack_python_v1 |
comment 1 Multi String Search
comment mine
class Trie
begin
function __init__ self
begin
set root = dict
set endSymbol = string *
end function
function add self word
begin
set node = root
for letter in word
begin
if letter not in node
begin
set node at letter = dict
end
set node = node at letter
end
set node at endSy... | # 1 Multi String Search
# mine
class Trie:
def __init__(self):
self.root = {}
self.endSymbol = '*'
def add(self, word):
node = self.root
for letter in word:
if letter not in node:
node[letter] = {}
node = node[letter]
node[self.endSymbol] = word
def multiStringSearch(bigString, smallStrings):
... | Python | zaydzuhri_stack_edu_python |
function testTsysLLSp self
begin
call _runTest string tsys true keys tsys_funcs string linear,linear
end function | def testTsysLLSp(self):
self._runTest('tsys', True, self.tsys_funcs.keys(), 'linear,linear') | Python | nomic_cornstack_python_v1 |
function exp1x t a2 b2 c2
begin
return - a2 * exp - b2 * t - c2
end function | def exp1x(t, a2, b2, c2):
return -a2 * np.exp(-b2 * (t-c2)) | Python | nomic_cornstack_python_v1 |
function IsVPCNameValid vpc
begin
if length vpc < 1 or length vpc > 63
begin
return false
end
return boolean match string ^[a-z]$|^[a-z][a-z0-9-]*[a-z0-9]$ vpc
end function | def IsVPCNameValid(vpc):
if len(vpc) < 1 or len(vpc) > 63:
return False
return bool(re.match('^[a-z]$|^[a-z][a-z0-9-]*[a-z0-9]$', vpc)) | Python | nomic_cornstack_python_v1 |
from border import Border
from display import Display
class SideBorder extends Border
begin
function __init__ self display ch
begin
call __init__ display
set _border_char = ch
end function
function get_columns self
begin
return 1 + call get_columns + 1
end function
function get_rows self
begin
return call get_rows
end ... | from border import Border
from display import Display
class SideBorder(Border):
def __init__(self, display: Display, ch: str):
super().__init__(display)
self._border_char = ch
def get_columns(self) -> int:
return 1 + self._display.get_columns() + 1
def get_rows(self) -> int:
... | Python | zaydzuhri_stack_edu_python |
function array_to_image img_np
begin
comment [RGB, H, W] -> [H, W, RGB]
set arr = transpose img_np list 1 2 0
if dtype in list float32 float64
begin
comment Transform pixel color data to color values in the usual byte representation (uint8).
set arr = call clip_to_uint8 arr
end
else
begin
assert dtype == uint8
end
retu... | def array_to_image(img_np):
arr = img_np.transpose([1, 2, 0]) # [RGB, H, W] -> [H, W, RGB]
if arr.dtype in [np.float32, np.float64]:
# Transform pixel color data to color values in the usual byte representation (uint8).
arr = clip_to_uint8(arr)
else:
assert arr.dtype == np.uint8
... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
string @author: mcfee @description:测试is和== @file: test_is.py @time: 2020/7/9 上午10:31
class Person
begin
function __init__ self
begin
set name = 22
end function
function __eq__ self other
begin
return name == name
end function
end class
set p1 = call Person
set p2 = call Person
print p1 is p2
print ... | #coding:utf-8
"""
@author: mcfee
@description:测试is和==
@file: test_is.py
@time: 2020/7/9 上午10:31
"""
class Person:
def __init__(self):
self.name=22
def __eq__(self, other):
return self.name==other.name
p1=Person()
p2=Person()
print(p1 is p2)
print(p1==p2) | Python | zaydzuhri_stack_edu_python |
function _limit_cache self
begin
with lock
begin
for tuple topic topic_cache in items items
begin
while length topic_cache > max_cache_size
begin
set lru_stamp = last_accessed at topic at 0 at 1
set cache_index = call bisect_left topic_cache tuple lru_stamp none
assert topic_cache at cache_index at 0 == lru_stamp
del t... | def _limit_cache(self):
with self.lock:
for topic, topic_cache in self.items.items():
while len(topic_cache) > self.max_cache_size:
lru_stamp = self.last_accessed[topic][0][1]
cache_index = bisect.bisect_left(topic_cache, (lru_stamp, None))
... | Python | nomic_cornstack_python_v1 |
function calcula_aumento salario
begin
if salario > 1250
begin
set a = salario * 10 / 100
return a
end
else
begin
set b = salario * 15 / 100
return b
end
end function | def calcula_aumento(salario):
if salario > 1250:
a = (salario*10)/100
return (a)
else:
b = (salario*15)/100
return (b) | Python | zaydzuhri_stack_edu_python |
function definitions self value
begin
set value_list = list value
set value_set = set value_list
assert length value_list == length value_set and set _definitions == value_set msg string Set of values do not match, this function can only reorder values, values must be unique
set _definitions = value_list
end function | def definitions(self, value):
value_list = list(value)
value_set = set(value_list)
assert len(value_list) == len(value_set) and set(self._definitions) == value_set, \
"Set of values do not match, this function can only reorder values, values must be unique"
self._definitions ... | Python | nomic_cornstack_python_v1 |
function area self
begin
return _area
end function | def area(self):
return self._area | Python | nomic_cornstack_python_v1 |
function pyplot_to_tensor pyplot_figure
begin
set x = call pyplot_to_numpy pyplot_figure=pyplot_figure
return x
end function | def pyplot_to_tensor(pyplot_figure):
x = pyplot_to_numpy(pyplot_figure=pyplot_figure)
return x | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment Define your item pipelines here
comment Don't forget to add your pipeline to the ITEM_PIPELINES setting
comment See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
class DangdangbookPipeline extends object
begin
function process_item self item spider
begin
c... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
class DangdangbookPipeline(object):
def process_item(self, item, spider):
self.save_file (item)
... | Python | zaydzuhri_stack_edu_python |
function write_aligned_header text alignment=string left level=3
begin
call markdown string <div style='text-align: { alignment } ;'> <h { level } > { text } </h { level } > </div> unsafe_allow_html=true
end function | def write_aligned_header(text: str, alignment: str = "left", level: int = 3):
st.markdown(
f"""
<div style='text-align: {alignment};'>
<h{level}>{text}</h{level}>
</div>
""",
unsafe_allow_html=True,
) | Python | nomic_cornstack_python_v1 |
function strip_line line
begin
set info = split line string |
for i in range length info
begin
set info at i = strip info at i
end
return info
end function | def strip_line(line):
info = line.split('|')
for i in range(len(info)):
info[i] = info[i].strip()
return info | Python | nomic_cornstack_python_v1 |
function insert self string
begin
if not is instance string str
begin
raise call ValueError string Strings only.
end
set curr = head
set word_finished = true
set string = lower string
for i in range length string
begin
if string at i in children
begin
set curr = children at string at i
end
else
begin
set word_finished ... | def insert(self, string):
if not isinstance(string, str):
raise ValueError("Strings only.")
curr = self.head
word_finished = True
string = string.lower()
for i in range(len(string)):
if string[i] in curr.children:
curr = curr.children[stri... | Python | nomic_cornstack_python_v1 |
string Project 9 CSE 231 -Prompts use to make a selection of given choices -if users chooses first selection, passwords are cracked from given text files by forming a hash and crossreferencing it with hashes create from common passwords -if the user chooses the second, common words within passwords are found by inputti... | '''
Project 9 CSE 231
-Prompts use to make a selection of given choices
-if users chooses first selection, passwords are cracked from given text files
by forming a hash and crossreferencing it with hashes create from common
passwords
-if the user chooses the second, common words within passwords are found by
inputting... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
string .. moduleauthor:: Torbjörn Klatt <t.klatt@fz-juelich.de>
import logging
import os
import pathlib
import shutil
import subprocess as sp
set _log = call getLogger __name__
function get_exe_path executable
begin
set path = call Path executable
set builtin = false
if call is_absolute
begin
debug... | # coding=utf-8
"""
.. moduleauthor:: Torbjörn Klatt <t.klatt@fz-juelich.de>
"""
import logging
import os
import pathlib
import shutil
import subprocess as sp
_log = logging.getLogger(__name__)
def get_exe_path(executable):
path = pathlib.Path(executable)
builtin = False
if path.is_absolute():
_l... | Python | zaydzuhri_stack_edu_python |
function read self file_name
begin
info string hdf5 format: Reading filename %s % file_name
with call File file_name string r as f
begin
set particle_grp = f at string particles
set num_particles = attrs at string number_particles
set particles = call CarrayContainer num_particles
comment populate arrays with data
for ... | def read(self, file_name):
phdLogger.info("hdf5 format: Reading filename %s" % file_name)
with h5py.File(file_name, "r") as f:
particle_grp = f["particles"]
num_particles = particle_grp.attrs["number_particles"]
particles = CarrayContainer(num_particles)
... | Python | nomic_cornstack_python_v1 |
function cast *args
begin
return call itkFiniteDifferenceImageFilterIVF22IVF22_cast *args
end function | def cast(*args):
return _itkFiniteDifferenceImageFilterPython.itkFiniteDifferenceImageFilterIVF22IVF22_cast(*args) | Python | nomic_cornstack_python_v1 |
function compute_kde POIlons POIlats bandwidth
begin
set kernel = call gaussian_kde tuple POIlons POIlats bw_method=bandwidth
return kernel
end function | def compute_kde(POIlons, POIlats, bandwidth):
kernel = gaussian_kde((POIlons, POIlats), bw_method=bandwidth)
return kernel | Python | nomic_cornstack_python_v1 |
function parse_from_sequence_example serialized list_size=none context_feature_spec=none example_feature_spec=none size_feature_name=none mask_feature_name=none shuffle_examples=false seed=none
begin
set parser = call _SequenceExampleParser list_size=list_size context_feature_spec=context_feature_spec example_feature_s... | def parse_from_sequence_example(serialized,
list_size=None,
context_feature_spec=None,
example_feature_spec=None,
size_feature_name=None,
mask_feature_name=None... | Python | nomic_cornstack_python_v1 |
function sample_timegrid time_grid xlim batch_size
begin
set tuple xmin xmax = xlim
set tuple start_time end_time = time_interval
set list_points = list
for t in time_grid at slice : - 1 :
begin
set tt = t * ones list batch_size 1
comment t = start_time + torch.rand([batch_size, 1])*(end_time-start_time)
set x = xmi... | def sample_timegrid(time_grid, xlim, batch_size):
xmin, xmax = xlim
start_time,end_time = time_interval
list_points = []
for t in time_grid[:-1]:
tt = t*torch.ones([batch_size,1])
#t = start_time + torch.rand([batch_size, 1])*(end_time-start_time)
x = xmin + torch.rand([batch_siz... | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
import json
from models import prison , news
set input_file = open string prison.json string r encoding=string big5
set json_array = load json input_file
comment print(json_array)
for item in json_array
begin
print string prison_name: + item at string prison_name
set url_do... | import requests
from bs4 import BeautifulSoup
import json
from models import prison, news
input_file = open ('prison.json', "r", encoding="big5")
json_array = json.load(input_file)
#print(json_array)
for item in json_array:
print("prison_name:" + item['prison_name'])
url_domain = item['prison_domain_name']
... | Python | zaydzuhri_stack_edu_python |
import pyautogui as AI
call typewrite string ls
sleep 1
call hotkey string enter
comment Code executed. | import pyautogui as AI
AI.typewrite("ls")
time.sleep(1)
AI.hotkey('enter')
# Code executed.
| Python | flytech_python_25k |
comment 오름차순 정렬 = data.sort() / 역순 = data.reverse()
function bubbleSort data
begin
comment 4, 3, 2, 1
for i in range length data - 1 0 - 1
begin
comment 4, 3, 2, 1
for j in range 0 i
begin
if data at j > data at j + 1
begin
set tuple data at j data at j + 1 = tuple data at j + 1 data at j
end
end
end
end function
set d... | # 오름차순 정렬 = data.sort() / 역순 = data.reverse()
def bubbleSort(data):
for i in range(len(data)-1, 0, -1): # 4, 3, 2, 1
for j in range(0, i): #4, 3, 2, 1
if data[j] > data[j + 1]:
data[j], data[j+1] = data[j+1], data[j]
data = [55, 7, 78, 12, 42]
bubbleSort(data)
print(data)
... | Python | zaydzuhri_stack_edu_python |
for i in range 100
begin
print input
end | for i in range(100):
print(input())
| Python | zaydzuhri_stack_edu_python |
function parse_log_line str_line
begin
set log_line = split str_line
set log_event = dict string date log_line at 0 ; string verbosity log_line at 1 ; string thread log_line at 2 ; string module log_line at 3 ; string message join string log_line at slice 4 : : ; string logs list str_line
return log_event
end functio... | def parse_log_line(str_line):
log_line = str_line.split()
log_event = {
'date': log_line[0],
'verbosity': log_line[1],
'thread': log_line[2],
'module': log_line[3],
'message': ' '.join(log_line[4:]),
'logs': [str_line]
}
... | Python | nomic_cornstack_python_v1 |
function rand_ktensor shape rank norm=none random_state=none
begin
comment Check input.
set rns = call _check_random_state random_state
comment Randomize low-rank factor matrices i.i.d. uniform random elements.
set factors = call KTensor list comprehension uniform 0.0 1.0 size=tuple i rank for i in shape
return call _r... | def rand_ktensor(shape, rank, norm=None, random_state=None):
# Check input.
rns = _check_random_state(random_state)
# Randomize low-rank factor matrices i.i.d. uniform random elements.
factors = KTensor([rns.uniform(0.0, 1.0, size=(i, rank)) for i in shape])
return _rescale_tensor(factors, norm) | Python | nomic_cornstack_python_v1 |
function _check_test_parameters test_images test_labels
begin
try
begin
if shape at 0 != shape at 0
begin
raise call ValueError string Parameters test_images and test_labels have different lengths
end
if shape at 0 == 0
begin
raise call ValueError string Parameters test_images and test_labels should not be empty
end
en... | def _check_test_parameters(test_images, test_labels):
try:
if test_images.shape[0] != test_labels.shape[0]:
raise ValueError("Parameters test_images and test_labels have different lengths")
if test_images.shape[0] == 0:
raise ValueError("Parameters te... | Python | nomic_cornstack_python_v1 |
set num = 50
set x = num
while x != 0
begin
if num % x == 0
begin
if num * x == x
begin
print x string ====> string is prime
set x = x - 1
end
end
else
begin
print string { x } ====> not a prime.
set x = x - 1
end
end | num = 50
x = num
while(x != 0):
if num%x == 0:
if num*x == x:
print(x, "====>", "is prime")
x -= 1
else:
print(f"{x} ====> not a prime.")
x -= 1
| Python | zaydzuhri_stack_edu_python |
comment ! _*_coding_*_:utf-8
comment ! /usr/local/bin/python3
string check the identifier must be start with alpha + _ other char must be alpha + number + _
import string
set alpha = ascii_letters + string _
set number = digits
function idcheck
begin
print string welcome to the identifier check version 1
print string s... | #! _*_coding_*_:utf-8
#! /usr/local/bin/python3
"""
check the identifier
must be start with alpha + _
other char must be alpha + number + _
"""
import string
alpha=string.ascii_letters+"_"
number=string.digits
def idcheck():
print("welcome to the identifier check version 1")
print("st... | Python | zaydzuhri_stack_edu_python |
function populate_audit_fields self event
begin
string Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model
set updated = _data
set original =... | def populate_audit_fields(self, event):
"""Populates the the audit JSON fields with raw data from the model, so
all changes can be tracked and diffed.
Args:
event (Event): The Event instance to attach the data to
instance (fleaker.db.Model): The newly created/updated mod... | Python | jtatman_500k |
class Solution
begin
function maximalNetworkRank self n roads
begin
set maxRank = 0
set adj = default dictionary set
comment Construct adjency list 'adj', where adj[node] stores all nodes connected to 'node'.
for road in roads
begin
add adj at road at 0 road at 1
add adj at road at 1 road at 0
end
comment Iterate on ea... | class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
maxRank = 0
adj = defaultdict(set)
# Construct adjency list 'adj', where adj[node] stores all nodes connected to 'node'.
for road in roads:
adj[road[0]].add(road[1])
adj[road[... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import geopandas
import seaborn as sns
from matplotlib import pyplot as plt
call set_option string display.max_rows none string display.max_columns none
string Vyhodnocení nehod pro jednotlivé značky v jednotlivých rocích
function make_df filename=string accidents.pkl.gz
begin
set df = call read_pic... | import pandas as pd
import geopandas
import seaborn as sns
from matplotlib import pyplot as plt
pd.set_option("display.max_rows", None, "display.max_columns", None)
'''
Vyhodnocení nehod pro jednotlivé značky v jednotlivých rocích
'''
def make_df(filename='accidents.pkl.gz'):
df = pd.read_pickle("accidents.pkl.gz... | Python | zaydzuhri_stack_edu_python |
function to_meme self
begin
set motif_id = replace id string string _
if motif_id == string
begin
set motif_id = string unnamed
end
set m = string MOTIF %s % motif_id
set m = m + string BL MOTIF %s width=0 seqs=0 % motif_id
set m = m + string letter-probability matrix: alength= 4 w= %s nsites= %s E= 0 % tuple length ... | def to_meme(self):
motif_id = self.id.replace(" ", "_")
if motif_id == "":
motif_id = "unnamed"
m = "MOTIF %s\n" % motif_id
m += "BL MOTIF %s width=0 seqs=0\n" % motif_id
m += "letter-probability matrix: alength= 4 w= %s nsites= %s E= 0\n" % (
len(self),... | Python | nomic_cornstack_python_v1 |
function left_rotate_array arr d
begin
set n = length arr
if d % n == 0
begin
return
end
for _ in range d
begin
set i = 0
set temp = arr at 0
for i in range n - 1
begin
set arr at i = arr at i + 1
end
set arr at n - 1 = temp
end
end function
if __name__ == string __main__
begin
set arr = list 1 2 3 4 5
set d = 2
call l... | def left_rotate_array(arr, d):
n = len(arr)
if d % n == 0:
return
for _ in range(d):
i = 0
temp = arr[0]
for i in range(n - 1):
arr[i] = arr[i + 1]
arr[n - 1] = temp
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
d = 2
left_rotate_array(arr... | Python | flytech_python_25k |
comment coding = utf-8
import time
import random
import urllib
import urllib.request
import base64
import re
from PIL import Image
from selenium import webdriver
from base.find_element import seleniumWebdriver
class RegisterCode
begin
function __init__ self driver
begin
set driver = driver
end function
function get_cod... | #coding = utf-8
import time
import random
import urllib
import urllib.request
import base64
import re
from PIL import Image
from selenium import webdriver
from base.find_element import seleniumWebdriver
class RegisterCode():
def __init__(self,driver):
self.driver = driver
def get_code_image(self,key_... | Python | zaydzuhri_stack_edu_python |
comment README
comment This Library/Utility has been developed by Pooria Ahmadi and feel free to edit it and use it easily :), If you want, you can send me the edited version and let me add the edited ones to base library and mention you in the main file.
comment !!! Please don't sell this Utility !!!
comment Discord: ... | #README
#This Library/Utility has been developed by Pooria Ahmadi and feel free to edit it and use it easily :), If you want, you can send me the edited version and let me add the edited ones to base library and mention you in the main file.
#!!! Please don't sell this Utility !!!
#Discord: https://discord.gg/F6MV4P... | Python | zaydzuhri_stack_edu_python |
function prepare self config **kwargs
begin
pass
end function | def prepare(self, config, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
from functools import lru_cache
decorator least recent cache maxsize=none
function count_solutions coins n money
begin
comment There is exactly one way to represent 0 cents: the empty set
if money == 0
begin
return 1
end
else
comment Cannot represent negative money or without coins
if money < 0 or n < 1
begin
return 0
... | from functools import lru_cache
@lru_cache(maxsize=None)
def count_solutions(coins: tuple, n: int, money: int) -> int:
# There is exactly one way to represent 0 cents: the empty set
if money == 0:
return 1
# Cannot represent negative money or without coins
elif money < 0 or n < 1:
retu... | Python | zaydzuhri_stack_edu_python |
from atcoder.dsu import DSU
set tuple N M = generator expression integer x for x in split input
set edges = list
for _ in range M
begin
set tuple A B C = generator expression integer x for x in split input
append edges tuple C A - 1 B - 1
end
sort edges reverse=true
set dsu = call DSU N
set total = 0
for tuple c a b i... | from atcoder.dsu import DSU
N, M = (int(x) for x in input().split())
edges = []
for _ in range(M):
A, B, C = (int(x) for x in input().split())
edges.append((C, A-1, B-1))
edges.sort(reverse=True)
dsu = DSU(N)
total = 0
for c, a, b in edges:
if not dsu.same(a, b):
dsu.merge(a, b)
total += c
print(total) | Python | zaydzuhri_stack_edu_python |
from collections import Counter
import pandas as pd
class Node
begin
function __init__ self value left=none right=none
begin
set right = right
set left = left
set value = value
end function
end class
function count_string string
begin
set string_count = counter string
if length string_count < 1
begin
raise call Asserti... | from collections import Counter
import pandas as pd
class Node:
def __init__(self, value, left=None, right=None):
self.right = right
self.left = left
self.value = value
def count_string(string):
string_count = Counter(string)
if len(string_count) < 1:
raise AssertionErr... | Python | zaydzuhri_stack_edu_python |
comment sharpen image
import cv2
import numpy
set img = call imread string ../TestImages/SnowLeo2.jpg
comment blur = cv2.GaussianBlur(img, (3, 3), 0)
set blur = call blur img tuple 3 3 15
set f = call addWeighted img 2 blur - 1 0
image show string O img
image show string Sharpened f
call waitKey 0
call destroyAllWindow... | #sharpen image
import cv2
import numpy
img = cv2.imread("../TestImages/SnowLeo2.jpg")
# blur = cv2.GaussianBlur(img, (3, 3), 0)
blur = cv2.blur(img, (3, 3), 15)
f = cv2.addWeighted(img,2,blur,-1,0)
cv2.imshow("O", img)
cv2.imshow("Sharpened", f)
cv2.waitKey(0)
cv2.destroyAllWindows() | Python | zaydzuhri_stack_edu_python |
function set_solver solver adjacency
begin
if solver == string auto
begin
set solver : str = call auto_solver nnz
end
if solver == string lanczos
begin
set solver : EigSolver = call LanczosEig
end
else
begin
comment pragma: no cover
set solver : EigSolver = call HalkoEig
end
return solver
end function | def set_solver(solver: str, adjacency):
if solver == 'auto':
solver: str = auto_solver(adjacency.nnz)
if solver == 'lanczos':
solver: EigSolver = LanczosEig()
else: # pragma: no cover
solver: EigSolver = HalkoEig()
return solver | Python | nomic_cornstack_python_v1 |
import math
class Unwrapper
begin
function __init__ self thresh
begin
set thresh = thresh
set prev = 0
end function
function unwrap self val
begin
set num = 0
if val - prev < - 1 * thresh
begin
set num = val + 2 * pi
end
else
if val - prev > thresh
begin
set num = val - 2 * pi
end
else
begin
set num = val
end
set prev ... | import math
class Unwrapper:
def __init__(self, thresh):
self.thresh = thresh
self.prev = 0
def unwrap(self, val):
num = 0
if val - self.prev < -1*self.thresh:
num = val + 2*math.pi
elif val - self.prev > self.thresh:
num = val - 2*ma... | Python | zaydzuhri_stack_edu_python |
import os
import csv
comment start out empty lists
set bank_date = list
set count = 0
set bank_change = list
set max_value = 0
set min_value = 100000
set max_month = string month
set min_month = string Month
set previous_profitloss = 867884
comment total months and total sum
comment bankcsv = os.path.join('..','PYBAN... | import os
import csv
#start out empty lists
bank_date = []
count = 0
bank_change=[]
max_value= 0
min_value= 100000
max_month="month"
min_month="Month"
previous_profitloss=867884
#total months and total sum
#bankcsv = os.path.join('..','PYBANK', 'Resources', 'budget_data.csv')
#with open(bankcsv, 'r') as text:
# c... | Python | zaydzuhri_stack_edu_python |
function conda_install_requirements venv
begin
comment Upload the requirements file.
put call files string requirements string base.txt call home string base.txt
put call files string requirements string prod.txt call home string prod.txt
comment Activate the virtual environment.
set activate = format string {0}/bin/ac... | def conda_install_requirements(venv):
# Upload the requirements file.
put(utils.files('requirements', 'base.txt'), utils.home('base.txt'))
put(utils.files('requirements', 'prod.txt'), utils.home('prod.txt'))
# Activate the virtual environment.
activate = '{0}/bin/activate'.format(utils.home('apps',... | Python | nomic_cornstack_python_v1 |
from random import uniform
function NormalizePhrases phrases
begin
for tuple key phrase in call iteritems
begin
set totalConnections = 0.0
comment Sum up all the connections made
for tuple linkedPhrase connections in call iteritems
begin
set totalConnections = totalConnections + connections
end
comment Normalize those ... | from random import uniform
def NormalizePhrases(phrases):
for key, phrase in phrases.iteritems():
totalConnections = 0.0
# Sum up all the connections made
for linkedPhrase, connections in phrase.iteritems():
totalConnections += connections
# Normalize those conne... | Python | zaydzuhri_stack_edu_python |
function __ntot__ ss
begin
set nss = 0
for i in range length ss
begin
set nss = nss + length ss at i - 1
end
return nss
end function | def __ntot__(ss):
nss = 0
for i in range(len(ss)):
nss = nss + len(ss[i])-1
return nss | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
from data_preparation.user_finder import User_Finder
from statistics import mean
import sys
string This class is analyze the change of affect over a period of 7 days from 29.04.2019 to 05.05.2019 and correlate with real world scenario, if ther... | import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
from data_preparation.user_finder import User_Finder
from statistics import mean
import sys
"""
This class is analyze the change of affect over a period of 7 days from 29.04.2019 to 05.05.2019 and correlate with real world scenario, if ... | Python | zaydzuhri_stack_edu_python |
function test_skip_blacklisted_file
begin
set package_data = open string tests/resources/libraryblacklist/errors.xpi
set package = call XPIManager package_data mode=string r name=string errors.xpi
set err = call ErrorBundle
call test_packed_packages err package
end function | def test_skip_blacklisted_file():
package_data = open("tests/resources/libraryblacklist/errors.xpi")
package = XPIManager(package_data, mode="r", name="errors.xpi")
err = ErrorBundle()
test_content.test_packed_packages(err, package)
| Python | nomic_cornstack_python_v1 |
function struct_copy tokens s_table
begin
comment NOTE: needs to accept a.* = b.*
function is_a_eq_b_pattern tokens s_table
begin
return string ID in tokens at i and string UNKNOWN in tokens at i + 1 and tokens at i + 1 at string UNKNOWN == string = and string ID in tokens at i + 2 and tokens at i + 3 at string UNKNOWN... | def struct_copy(tokens, s_table) :
# NOTE: needs to accept a.* = b.*
def is_a_eq_b_pattern(tokens, s_table):
return ('ID' in tokens[i] and
'UNKNOWN' in tokens[i+1] and
tokens[i+1]['UNKNOWN'] == '=' and
'ID' in tokens[i+2] and
toke... | Python | nomic_cornstack_python_v1 |
function add a b
begin
return a + b
end function
function sub a b
begin
return a - b
end function
function mul a b
begin
return a * b
end function
function div a b
begin
return a / b
end function
function floor_div a b
begin
return a // b
end function
function expo a b
begin
return a ^ b
end function
print string 1. Ad... | def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
def floor_div(a, b):
return a // b
def expo(a, b):
return a ** b
print("1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n5. Floor Division \n6.Exponent")
wh... | Python | zaydzuhri_stack_edu_python |
function get_time_estimate self start_latitude start_longitude customer_uuid=none product_id=none
begin
string Get the ETA for Uber products. :param start_latitude: Starting latitude. :param start_longitude: Starting longitude. :param customer_uuid: (Optional) Customer unique ID. :param product_id: (Optional) If ETA is... | def get_time_estimate(self, start_latitude, start_longitude, customer_uuid=None, product_id=None):
"""
Get the ETA for Uber products.
:param start_latitude: Starting latitude.
:param start_longitude: Starting longitude.
:param customer_uuid: (Optional) Customer unique ID.
... | Python | jtatman_500k |
import os
function python38_lang file
begin
set data = string python3.8 %s % file
return split data
end function
function gpp_lang file
begin
call system string g++ %s -o main % file
return split string ./main
end function | import os
def python38_lang(file: str) -> list:
data = "python3.8 %s" % file
return data.split()
def gpp_lang(file: str) -> list:
os.system("g++ %s -o main" % file)
return "./main".split()
| Python | zaydzuhri_stack_edu_python |
from cmu_112_graphics import *
from calendarLayout import *
from inputBox import *
comment DRAWING
comment CALENDAR VIEW #########
function draw_title_headers app canvas x0 y0 x1 y1
begin
comment draws the titles for the days of week (i.e. Sun, Mon, Tue...)
if calendarMode == string week
begin
set tuple newX0 newY0 new... | from cmu_112_graphics import *
from calendarLayout import *
from inputBox import *
##############################
# DRAWING
##############################
######### CALENDAR VIEW #########
def draw_title_headers(app, canvas, x0, y0, x1, y1):
#draws the titles for the days of week (i.e. Sun, Mon, Tue...)
if a... | Python | zaydzuhri_stack_edu_python |
function sync_data_template self src_subdir_abs dst_subdir_abs
begin
set subdir = dict
set subdir at string src_dir_abs = right strip src_subdir_abs string /
set subdir at string dst_dir_abs = right strip dst_subdir_abs string /
comment list of files to be synced
set subdir at string src_dir_fls = list
comment list o... | def sync_data_template(self, src_subdir_abs, dst_subdir_abs):
subdir = {}
subdir["src_dir_abs"] = src_subdir_abs.rstrip("/")
subdir["dst_dir_abs"] = dst_subdir_abs.rstrip("/")
# list of files to be synced
subdir["src_dir_fls"] = []
# list of files present in the destina... | Python | nomic_cornstack_python_v1 |
function scoreboard_json_ctftime _
begin
set standings = list
set scores = call scores list string team string team__user list string team__user__username
for tuple rank tuple team team_points in enumerate items scores start=1
begin
set task_stats = default dictionary lambda -> dict string points 0.0
for point_type i... | def scoreboard_json_ctftime(_):
standings = []
scores = calculations.scores(['team', 'team__user'], ['team__user__username'])
for rank, (team, team_points) in enumerate(scores.items(), start=1):
task_stats = defaultdict(lambda: {'points': 0.0})
for point_type in ('offense', 'defense', 'sla... | Python | nomic_cornstack_python_v1 |
for i in range t
begin
set n = integer input
for j in range n
begin
set tuple I N Q = map int split input
set x = integer N / 2
if N % 2 == 0 or I == Q
begin
print x
end
else
begin
print 1 + x
end
end
end | for i in range(t):
n = int(input())
for j in range(n):
I,N,Q = map(int , input().split())
x = int(N/2)
if N%2==0 or I==Q:
print(x)
else:
print(1+x)
| Python | zaydzuhri_stack_edu_python |
from src.state import State , Turn
import chess
function init_board
begin
string Initialize checkers board (8x8)
set board = list string w string - string w string - string w string - string w string - string - string w string - string w string - string w string - string w string w string - string w string - string w s... | from src.state import State, Turn
import chess
def init_board():
"""
Initialize checkers board (8x8)
"""
board = ['w', '-', 'w', '-', 'w', '-', 'w', '-',
'-', 'w', '-', 'w', '-', 'w', '-', 'w',
'w', '-', 'w', '-', 'w', '-', 'w', '-',
'-', '-', '-', '-', '-', '-'... | Python | zaydzuhri_stack_edu_python |
comment Write a Python function to multiply all the numbers in a list.
comment Sample list = [8,2,3,-1,7]
set lst = list 8 2 3 - 1 7
set m = 1
for i in lst
begin
set m = m * i
end
print m | # Write a Python function to multiply all the numbers in a list.
#Sample list = [8,2,3,-1,7]
lst=[8,2,3,-1,7]
m=1
for i in lst:
m=m*i
print(m)
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set N = integer input string Digite o numero de pessoas detectadas:
for i in range 1 N + 1 1
begin
set i = integer input string Tempo de funcionamento:
end | # -*- coding: utf-8 -*-
N=int(input('Digite o numero de pessoas detectadas: ' ))
for i in range(1,N+1,1):
i=int(input('Tempo de funcionamento: '))
| Python | zaydzuhri_stack_edu_python |
from unittest import TestCase
from updateChapters import chap_1_placer
class TestChap1Placer extends TestCase
begin
function test_chap1_placer self
begin
call assertEquals call chap_1_placer list string WordsAndSomeMoreWords string SampleEquation string \end{document} list string \subsection*{Generalities} string \para... | from unittest import TestCase
from updateChapters import chap_1_placer
class TestChap1Placer(TestCase):
def test_chap1_placer(self):
self.assertEquals(chap_1_placer(['WordsAndSomeMoreWords', 'SampleEquation', '\\end{document}']
, ['\\subsection*{Generalities}', '\\... | Python | zaydzuhri_stack_edu_python |
function __call__ self x_range=none y_range=none width=600 height=600
begin
set canvas = call Canvas plot_width=integer width * width_scale plot_height=integer height * height_scale x_range=x_range y_range=y_range
set bins = call bypixel df canvas glyph agg antialias=antialiased
set img = call color_fn call transform_f... | def __call__(self, x_range=None, y_range=None, width=600, height=600):
canvas = core.Canvas(plot_width=int(width*self.width_scale),
plot_height=int(height*self.height_scale),
x_range=x_range, y_range=y_range)
bins = core.bypixel(self.df, canvas, ... | Python | nomic_cornstack_python_v1 |
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json
with open string config.json string r as cc
begin
set params = load json cc at string params
end
function verification_email email
begin
set s = call SMTP string smtp.gmail.com 587
comment start TLS for securi... | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json
with open('config.json','r') as cc:
params = json.load(cc)["params"]
def verification_email(email):
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Auth... | Python | zaydzuhri_stack_edu_python |
function use_temporary_file session srcpath timeout=60 * 30 **kwargs
begin
comment Create a temporary folder in destination
set tuple retcode out _ = call run_script session string mktemp -d timeout=timeout
if retcode != 0 or length out < 1
begin
raise call TempDirException string Unable to create temporary files
end
s... | def use_temporary_file(session, srcpath, timeout=60*30, **kwargs):
# Create a temporary folder in destination
retcode, out, _ = run_script(session, 'mktemp -d', timeout=timeout)
if retcode != 0 or len(out) < 1:
raise TempDirException("Unable to create temporary files")
tempdir = out[-1].strip(... | Python | nomic_cornstack_python_v1 |
function test_Eprime
begin
set M_d = call MatterDominated Omega0_m=0.3075
set cosmo = call Planck15
set a = call logspace - 3 0
comment Computing reference E' value with old code
set E_prim_back = call efunc_prime a
comment Computing new E' function with tensorflow
set E_n = call dEa cosmo a
call assert_allclose E_prim... | def test_Eprime():
M_d = MatterDominated(Omega0_m=0.3075)
cosmo = flowpm.cosmology.Planck15()
a = np.logspace(-3, 0)
# Computing reference E' value with old code
E_prim_back = M_d.efunc_prime(a)
# Computing new E' function with tensorflow
E_n = dEa(cosmo, a)
assert_allclose(E_prim_back, E_n, rtol=1e-4... | Python | nomic_cornstack_python_v1 |
function returnFileTypes self primary_only=false
begin
if primary_only
begin
comment We only return the types for the primary files.
set ret = list
for ftype in keys files
begin
if ftype == string dir
begin
set match = re_primary_dirname
end
else
begin
set match = re_primary_filename
end
comment As soon as we find a p... | def returnFileTypes(self, primary_only=False):
if primary_only:
ret = [] # We only return the types for the primary files.
for ftype in self.files.keys():
if ftype == 'dir':
match = misc.re_primary_dirname
else:
matc... | Python | nomic_cornstack_python_v1 |
import time
comment Function to check if a number is prime
function is_prime n
begin
if n < 2
begin
return false
end
for i in range 2 integer n ^ 0.5 + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
comment Caching mechanism for prime numbers
set prime_cache = dict
comment Modified function ... | import time
# Function to check if a number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Caching mechanism for prime numbers
prime_cache = {}
# Modified function to check if a number is prime usi... | Python | jtatman_500k |
import os
from socket import gethostbyname , gethostname
set host = call gethostbyname call gethostname
call system string arp -a > temp.txt
set i = 0
print host at slice : 4 :
with open string temp.txt as fp
begin
for line in fp
begin
set line = split line at slice : 2 :
comment 过滤第一个 []、第二个 [借口\192.168.254.47]/本机、... | import os
from socket import gethostbyname,gethostname
host = gethostbyname(gethostname())
os.system('arp -a > temp.txt')
i = 0
print(host[:4])
with open('temp.txt') as fp:
for line in fp:
line = line.split()[:2]
# 过滤第一个 []、第二个 [借口\192.168.254.47]/本机、第三个 [Internet, 地址]
if line and line[0].s... | Python | zaydzuhri_stack_edu_python |
import copy
import itertools
import numpy as np
import crayons
from product import *
import matplotlib.pyplot as plt
import scipy.optimize
from constants import *
from fact.graph.edge import *
from fact.graph.product import *
from fact.graph.util import *
function leg_difference l0 l1
begin
set products = list
if l0 i... | import copy
import itertools
import numpy as np
import crayons
from product import *
import matplotlib.pyplot as plt
import scipy.optimize
from constants import *
from fact.graph.edge import *
from fact.graph.product import *
from fact.graph.util import *
def leg_difference(l0, l1):
products = []
if l0 i... | Python | zaydzuhri_stack_edu_python |
function stop_sign_detected_callback self msg
begin
comment distance of the stop sign
comment print "Stop Sign Destected"
set dist = distance
end function
comment if self.mode==Mode.TRACK:
comment if close enough and in nav mode, stop | def stop_sign_detected_callback(self, msg):
# distance of the stop sign
# print "Stop Sign Destected"
dist = msg.distance
# if self.mode==Mode.TRACK:
# if close enough and in nav mode, stop | Python | nomic_cornstack_python_v1 |
function mark_invalidation_hash_dirty self
begin
string Invalidates memoized fingerprints for this target, including those in payloads. Exposed for testing. :API: public
set _cached_fingerprint_map = dict
set _cached_all_transitive_fingerprint_map = dict
set _cached_direct_transitive_fingerprint_map = dict
set _cach... | def mark_invalidation_hash_dirty(self):
"""Invalidates memoized fingerprints for this target, including those in payloads.
Exposed for testing.
:API: public
"""
self._cached_fingerprint_map = {}
self._cached_all_transitive_fingerprint_map = {}
self._cached_direct_transitive_fingerprint_map... | Python | jtatman_500k |
comment dis 与 set
comment 测试dis
set disTest = dict string weixinjie 100 ; string laoma 100 ; string zhangrui 100
print disTest
comment 获取value可以通过key的方式获得,如果获取一个不存在的key则会报错
print disTest at string weixinjie
comment dis的数据可以通过动态添加进去
set disTest at string 新加入的数据 = string 我是新加入的数据
print disTest
comment 多次采用同样的key来添加,后加入的v... | # dis 与 set
# 测试dis
disTest = {'weixinjie': 100, "laoma": 100, "zhangrui": 100}
print(disTest)
# 获取value可以通过key的方式获得,如果获取一个不存在的key则会报错
print(disTest['weixinjie'])
# dis的数据可以通过动态添加进去
disTest['新加入的数据'] = "我是新加入的数据"
print(disTest)
# 多次采用同样的key来添加,后加入的value会冲掉前一个value
disTest['新加入的数据'] = "weixinjie"
print(disTest)
# 要避... | Python | zaydzuhri_stack_edu_python |
comment Суммирование неопределенного количества чисел
print string Введите слово 'stop' для получения результата
set summa = 0
while true
begin
set x = input string Введите число:
if x == string stop
begin
break
end
try
begin
set x = integer x
end
except ValueError
begin
print string Необходимо ввести целое число!
end
... | #Суммирование неопределенного количества чисел
print("Введите слово 'stop' для получения результата\n")
summa = 0
while True:
x = input("Введите число: \n")
if x == "stop":
break
try:
x = int(x)
except ValueError:
print("Необходимо ввести целое число!")
els... | Python | zaydzuhri_stack_edu_python |
function get_cluster_parcel_usage self cluster_name
begin
return call get_cluster_parcel_usage cluster_name=cluster_name
end function | def get_cluster_parcel_usage(self, cluster_name):
return self.api_client.get_cluster_parcel_usage(cluster_name=cluster_name) | Python | nomic_cornstack_python_v1 |
function draw_war_cards self
begin
set war_cards = list
if length hand < 3
begin
for _ in cards
begin
append war_cards remove hand
end
end
else
begin
for _ in range 3
begin
append war_cards remove hand
end
end
return war_cards
end function | def draw_war_cards(self):
war_cards = []
if (len(self.hand) < 3):
for _ in self.hand.cards:
war_cards.append(self.hand.remove())
else:
for _ in range(3):
war_cards.append(self.hand.remove())
return war_cards | Python | nomic_cornstack_python_v1 |
import re
from collections import defaultdict
from data import load_day
set bags = default dictionary dict
function parse_data luggage_rules
begin
for rule in luggage_rules
begin
set outside_bag = call groups at 0
for tuple count inside_bag in find all string (\d+) (\w+ \w+) bags? rule
begin
set bags at outside_bag at ... | import re
from collections import defaultdict
from data import load_day
bags = defaultdict(dict)
def parse_data(luggage_rules):
for rule in luggage_rules:
outside_bag = re.match(r'(.*) bags contain', rule).groups()[0]
for count, inside_bag in re.findall(r'(\d+) (\w+ \w+) bags?', rule):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import numpy as np
import random as rand
from matplotlib import pyplot as plt
string This code was written using the following source as a guide. https://www.acsu.buffalo.edu/~phygons/cp2/topic5/topic5.pdf Last accessed on Dec. 11th 2017.
class Atom extends object
begin
string The Atom class i... | #!/usr/bin/python3
import numpy as np
import random as rand
from matplotlib import pyplot as plt
"""This code was written using the following source as a guide.
https://www.acsu.buffalo.edu/~phygons/cp2/topic5/topic5.pdf
Last accessed on Dec. 11th 2017.
"""
class Atom(object):
"""The Atom class is used t... | Python | zaydzuhri_stack_edu_python |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
comment load data
set samples = list string sample 1 from AuthorA string sample 2 from AuthorA string sample 1 from AuthorB st... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
# load data
samples = [
"sample 1 from AuthorA",
"sample 2 from AuthorA",
"sample 1 from AuthorB",
"sample 2 from Aut... | Python | jtatman_500k |
import matplotlib.pyplot as plt
import numpy as np
import math
comment Vehicle parameters
comment I30 based.
comment [m]
set OVERHANG_FRONT = 0.9
comment [m]
set OVERHANG_REAR = 0.8
comment [m]
set WHEELBASE = 2.6
comment [m]
set WHEEL_LEN = 0.3
comment [m]
set WHEEL_WIDTH = 0.185
comment [m] length btw wheels.
set TRA... | import matplotlib.pyplot as plt
import numpy as np
import math
# Vehicle parameters
# I30 based.
OVERHANG_FRONT = 0.9 # [m]
OVERHANG_REAR = 0.8 # [m]
WHEELBASE = 2.60 # [m]
WHEEL_LEN = 0.3 # [m]
WHEEL_WIDTH = 0.185 # [m]
TRACK = 1.50 # [m] length btw wheels.
WIDTH = 1.9 # [... | Python | zaydzuhri_stack_edu_python |
function test_rpow
begin
comment Test for reversed exponent with scalar Rnode object and float value
set x = call Rnode 0.11
set z = 2 ^ x
set grad_value = 1.0
try
begin
assert value == 2 ^ value
end
comment assert x.grad() == x.value ** 2 * np.log(x.value)
except AssertionError as e
begin
print e
end
end function
comm... | def test_rpow():
# Test for reversed exponent with scalar Rnode object and float value
x = Rnode(0.11)
z = 2 ** x
z.grad_value = 1.0
try:
assert z.value == 2 ** x.value
# assert x.grad() == x.value ** 2 * np.log(x.value)
except AssertionError as e:
print(e)
# Test f... | Python | nomic_cornstack_python_v1 |
function format_word_split txt
begin
comment possessives
set tt = lower sub string 's\b string txt
comment weird stuff
set tt = sub string [\.\,\;\:\'\"\(\)\&\%\*\+\[\]\=\?\!/] string tt
comment hyphen -> space
set tt = sub string [\-\s]+ string tt
comment single letter -> space
set tt = sub string [a-z] string tt
... | def format_word_split(txt):
tt = re.sub(r"'s\b", '', txt).lower() # possessives
tt = re.sub(r'[\.\,\;\:\'\"\(\)\&\%\*\+\[\]\=\?\!/]', '', tt) # weird stuff
tt = re.sub(r'[\-\s]+', ' ', tt) # hyphen -> space
tt = re.sub(r' [a-z] ', ' ', tt) # single letter -> space
tt = re.sub(r' [0-9]* ', ' ', t... | Python | nomic_cornstack_python_v1 |
function _validate_readers readers
begin
if not is instance readers Sequence
begin
raise call TypeError format string input argument must be a list or tuple of readers/files. Got type {} type readers
end
comment get a reader for each entry, and make sure that they are sicd type
comment validate each entry
set the_reade... | def _validate_readers(readers: Sequence[SICDTypeReader]) -> Tuple[SICDTypeReader, ...]:
if not isinstance(readers, Sequence):
raise TypeError('input argument must be a list or tuple of readers/files. Got type {}'.format(type(readers)))
# get a reader for each entry, and make sure that they... | Python | nomic_cornstack_python_v1 |
function process_catalog type1 cat config RA DEC z=string Redshift RAf=string RA DECf=string DEC origin=string Origin
begin
comment Skip unwanted catalogues
if call unwanted_catalogue meta at string name call set_unwanted_list type1 config
begin
return none
end
comment Make a list of potential column that contain redsh... | def process_catalog(
type1, cat, config, RA, DEC, z="Redshift", RAf="RA", DECf="DEC", origin="Origin"
):
# Skip unwanted catalogues
if unwanted_catalogue(cat.meta["name"], set_unwanted_list(type1, config)):
return None
# Make a list of potential column that contain redshift information
col_... | 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.