code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_conv2d_transpose_failure shape stride dilation groups err_msg dtype
begin
seed 0
set out_channels = 8
set tuple model _ = call _get_model shape=shape kernel_h=1 kernel_w=1 input_zp=0 input_sc=1 kernel_zp=0 kernel_sc=1 output_zp=0 output_sc=1 stride=stride dilation=dilation groups=groups kernel_layout=stri... | def test_conv2d_transpose_failure(
shape,
stride,
dilation,
groups,
err_msg,
dtype,
):
np.random.seed(0)
out_channels = 8
model, _ = _get_model(
shape=shape,
kernel_h=1,
kernel_w=1,
input_zp=0,
input_sc=1,
kernel_zp=0,
kernel_s... | Python | nomic_cornstack_python_v1 |
function ListRecursively store pattern callback
begin
set results = yield call Task ListAllKeys store prefix=call PrefixFromPattern pattern
call callback results
end function | def ListRecursively(store, pattern, callback):
results = yield gen.Task(ListAllKeys, store, prefix=PrefixFromPattern(pattern))
callback(results) | Python | nomic_cornstack_python_v1 |
function read_dataset dname
begin
string Read example datasets. Parameters ---------- dname : string Name of dataset to read (without extension). Must be a valid dataset present in pingouin.datasets Returns ------- data : pd.DataFrame Dataset Examples -------- Load the ANOVA dataset >>> from pingouin import read_datase... | def read_dataset(dname):
"""Read example datasets.
Parameters
----------
dname : string
Name of dataset to read (without extension).
Must be a valid dataset present in pingouin.datasets
Returns
-------
data : pd.DataFrame
Dataset
Examples
--------
Load ... | Python | jtatman_500k |
import numpy as np
set np_arr1 = random tuple 10 1
print np_arr1
set mean = mean np np_arr1
print string Mean: mean
print string * * 10
print string
print string Question2
import numpy as np
set np_arr2 = random tuple 20 1
print np_arr2
set variance = variance np np_arr2
print string Variance: variance
set std_dev = st... | import numpy as np
np_arr1=np.random.random((10,1))
print(np_arr1)
mean=np.mean(np_arr1)
print("Mean: ",mean)
print('*'*10)
print('\n')
print("Question2")
import numpy as np
np_arr2=np.random.random((20,1))
print(np_arr2)
variance=np.var(np_arr2)
print("Variance: ",variance)
std_dev=np.std(np_arr2)
print("Standard Dev... | Python | zaydzuhri_stack_edu_python |
function test_index self
begin
set result = get client string /
assert equal status string 200 OK
assert in b'Lipstick' data
end function | def test_index(self):
result = self.client.get('/')
self.assertEqual(result.status, '200 OK')
self.assertIn(b'Lipstick', result.data) | Python | nomic_cornstack_python_v1 |
function setAlias self alias name plug add=string True
begin
pass
end function | def setAlias(self, alias, name, plug, add='True'):
pass | Python | nomic_cornstack_python_v1 |
dict string cells list dict string cell_type string code ; string execution_count 6 ; string metadata dict ; string outputs list ; string source list string import os string import csv dict string cell_type string code ; string execution_count 8 ; string metadata dict ; string outputs list ; string source list stri... | {
"cells": [
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import csv"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"#import csv file\n",
"path = '/Users/phil... | Python | zaydzuhri_stack_edu_python |
if a > 40
begin
print string tien luong truoc thue cua ban la: + string tienluong + tienluong / 2
print string tien luong sau thue cua ban la: + string tienluong + tienluong / 2 / 100 * 90
end
else
begin
print string tien luong truoc thue cua ban la: + string tienluong
print string tien luong sau thue cua ban la: + str... | if a>40:
print("tien luong truoc thue cua ban la:"+str(tienluong+tienluong/2))
print("tien luong sau thue cua ban la:" + str(((tienluong + tienluong / 2) / 100) * 90))
else:
print("tien luong truoc thue cua ban la:"+str(tienluong))
print("tien luong sau thue cua ban la:" + str((tienluong/100)*90))
| Python | zaydzuhri_stack_edu_python |
function encode_password pw_str method=string sha-512
begin
set p = popen string mkpasswd -m { method } { pw_str } shell=true stdout=PIPE stderr=PIPE
set tuple out err = tuple out err
set err_str = decode strip read stdoud string UTF-8
if err_str
begin
raise call ValueError err_str
end
return decode strip read stdout s... | def encode_password(pw_str: str, method: str = "sha-512") -> str:
p = Popen(
f"mkpasswd -m {method} {pw_str}",
shell=True, stdout=PIPE, stderr=PIPE
)
(out, err) = (p.out, p.err)
err_str = err.stdoud.read().strip().decode("UTF-8")
if err_str:
raise ValueError(err_str)
retu... | Python | nomic_cornstack_python_v1 |
function export_builds_results_to_googlesheet self sheet_name=string E2E Workloads sheet_index=3
begin
comment Collect data and export to Google doc spreadsheet
info string Exporting Jenkins data to google spreadsheet
set g_sheet = call GoogleSpreadSheetAPI sheet_name=sheet_name sheet_index=sheet_index
for tuple build ... | def export_builds_results_to_googlesheet(
self, sheet_name="E2E Workloads", sheet_index=3
):
# Collect data and export to Google doc spreadsheet
log.info("Exporting Jenkins data to google spreadsheet")
g_sheet = GoogleSpreadSheetAPI(sheet_name=sheet_name, sheet_index=sheet_index)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import sys
import os
import subprocess
import feedparser
import datetime
set USER = argv at 1
set URL = string http://gdata.youtube.com/feeds/base/users/ + USER + string /newsubscriptionvideos
set DOWNLOADDIR = string /home/markus/platte1000/downloads/youtube/
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import feedparser
import datetime
USER = sys.argv[1]
URL = 'http://gdata.youtube.com/feeds/base/users/'+USER+'/newsubscriptionvideos'
DOWNLOADDIR = '/home/markus/platte1000/downloads/youtube/'
class Downloaded:
def __init__(self, ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import os
import sys
import cv2
from math import floor
set g_event_status = dict string event none
set g_images = dict
set g_rendered_images = dict
function computeRatio p q img
begin
set rp = tuple decimal p at 0 / shape at slice : 2 : at 1 decimal p at 1 / shape at slice : 2 : at 0
... | #!/usr/bin/env python
import os
import sys
import cv2
from math import floor
g_event_status = {'event': None}
g_images = {}
g_rendered_images = {}
def computeRatio(p, q, img):
rp = (float(p[0]) / img.shape[:2][1],
float(p[1]) / img.shape[:2][0])
rq = (float(q[0]) / img.shape[:2][1],
float(... | Python | zaydzuhri_stack_edu_python |
function val_to_str val tab_level=0
begin
set tab_str = string + string * TAB_WIDTH * tab_level
if type val == str
begin
return tab_str + val
end
comment For sequence types produce a comma seperated listing
try
begin
comment prescribed way to check for iteration...
iterate val
comment Just because I like the fixed wi... | def val_to_str(val ,tab_level=0):
tab_str = '' + ' '*TAB_WIDTH*tab_level
if type(val) == str:
return tab_str + val
try: # For sequence types produce a comma seperated listing
iter(val) # prescribed way to check for iteration...
# Just because I like the fixed width numbers
st... | Python | nomic_cornstack_python_v1 |
function _set_mib self v load=false
begin
string Setter method for mib, mapped from YANG variable /snmp_server/mib (container) If this variable is read-only (config: false) in the source YANG file, then _set_mib is considered as a private method. Backends looking to populate this variable should do so via calling thisO... | def _set_mib(self, v, load=False):
"""
Setter method for mib, mapped from YANG variable /snmp_server/mib (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mib is considered as a private
method. Backends looking to populate this variable should
do so via... | Python | jtatman_500k |
function handle self *args **options
begin
set supported_microarray_platforms = list comprehension x at string platform_accession for x in call get_supported_microarray_platforms
set supported_rnaseq_platforms = list comprehension replace x string string for x in call get_supported_rnaseq_platforms
set all_supported_p... | def handle(self, *args, **options):
supported_microarray_platforms = [
x["platform_accession"] for x in get_supported_microarray_platforms()
]
supported_rnaseq_platforms = [x.replace(" ", "") for x in get_supported_rnaseq_platforms()]
all_supported_platforms = (
s... | Python | nomic_cornstack_python_v1 |
function get_token self session **kwargs
begin
return none
end function | def get_token(self, session, **kwargs):
return None | Python | nomic_cornstack_python_v1 |
function get_pending_jobs self
begin
try
begin
set result = all
set result_dict = call result_dict result
end
except SQLAlchemyError as err
begin
error string sql exception [%s] string err
return false
end
return result_dict
end function | def get_pending_jobs(self):
try:
result = self._session.query(JobEntity).\
filter(JobEntity.status == 'PENDING').\
order_by(asc(JobEntity.queued)).\
all()
result_dict = self.result_dict(result)
except SQLAlchemyError as err:
... | Python | nomic_cornstack_python_v1 |
function test_log self
begin
comment Ensure the log array starts empty.
set zeros = zeros tuple log_buffer 14 + 3 + 5
call assert_array_equal zeros log_array
comment Calling reset should create a log entry.
call reset
set entry_1 = log_array at tuple 0 slice : :
comment Episode:
assert equal entry_1 at 0 0
comment A... | def test_log(self):
# Ensure the log array starts empty.
zeros = np.zeros((self.log_buffer, 14 + 3 + 5))
np.testing.assert_array_equal(zeros, self.env.log_array)
# Calling reset should create a log entry.
self.env.reset()
entry_1 = self.env.log_array[0, :]
# Epi... | Python | nomic_cornstack_python_v1 |
function test_missingPrefix self
begin
call makeRLine pre=false
set fields = call parseRLine line
call assertAllFieldsAreNone fields
end function | def test_missingPrefix(self):
self.makeRLine(pre=False)
fields = networkstatus.parseRLine(self.line)
self.assertAllFieldsAreNone(fields) | Python | nomic_cornstack_python_v1 |
function start_requests self
begin
set url = string http://www.filmweb.pl/search/film?q=&startYear=1888&endYear=&startRate=&endRate=&startCount=&endCount=&sort=COUNT&sortAscending=false&page=
for i in range 1 5
begin
set url2 = url + string i
yield call Request url=url2 callback=parse
end
end function | def start_requests(self):
url = 'http://www.filmweb.pl/search/film?q=&startYear=1888&endYear=&startRate=&endRate=&startCount=&endCount=&sort=COUNT&sortAscending=false&page='
for i in range(1, 5):
url2 = url + str(i)
yield scrapy.Request(url=url2, callback=self.parse) | Python | nomic_cornstack_python_v1 |
from algorithms.textMatch import calculateTextMatch
from algorithms.imageMatch import ImageMatch
from utilities.queries import *
from utilities.utilities import round_float_number , distance_percentage
from services.loggerService import LoggerService
import functools
set MAX_PRICE_DISTANCE_PERCENTAGE = 50
set MIN_MATCH... | from algorithms.textMatch import calculateTextMatch
from algorithms.imageMatch import ImageMatch
from utilities.queries import *
from utilities.utilities import round_float_number, distance_percentage
from services.loggerService import LoggerService
import functools
MAX_PRICE_DISTANCE_PERCENTAGE = 50
MIN_MATCH_RATE =... | Python | zaydzuhri_stack_edu_python |
comment Focus Learning: Python Level 1
comment For loops
comment Nov 20, 2020
comment Kavan Lam
comment If we wanted to print the numbers from 0 to 5
print 0
print 1
print 2
print 3
print 4
print 5
comment What if we wanted to print the numbers from 0 to 100
comment This is not going to be fun... is there an easier met... | # Focus Learning: Python Level 1
# For loops
# Nov 20, 2020
# Kavan Lam
# If we wanted to print the numbers from 0 to 5
print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
# What if we wanted to print the numbers from 0 to 100
# This is not going to be fun... is there an easier method
# Ex 1
prin... | Python | zaydzuhri_stack_edu_python |
function from_dict cls _dict
begin
set args = dict
if string message in _dict
begin
set args at string message = get _dict string message
end
return call cls keyword args
end function | def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError':
args = {}
if 'message' in _dict:
args['message'] = _dict.get('message')
return cls(**args) | Python | nomic_cornstack_python_v1 |
function index_doc self docid object
begin
if callable discriminator
begin
set value = call discriminator object _marker
end
else
begin
set value = get attribute object discriminator _marker
end
if value is _marker
begin
comment unindex the previous value
call unindex_doc docid
add _not_indexed docid
return none
end
if... | def index_doc(self, docid, object):
if callable(self.discriminator):
value = self.discriminator(object, _marker)
else:
value = getattr(object, self.discriminator, _marker)
if value is _marker:
# unindex the previous value
self.unindex_doc(docid)
... | Python | nomic_cornstack_python_v1 |
import FindMattes as fm
import tkinter as tk
from tkinter import filedialog
from tkinter import simpledialog as sd
from os import listdir
import os
from pathlib import Path
comment fm.createMatte("/Users/amithannigeri/Desktop/python-codes/AutoRoto01/ManyCycle.png","/Users/amithannigeri/Desktop/python-codes/AutoRoto01/M... | import FindMattes as fm
import tkinter as tk
from tkinter import filedialog
from tkinter import simpledialog as sd
from os import listdir
import os
from pathlib import Path
#fm.createMatte("/Users/amithannigeri/Desktop/python-codes/AutoRoto01/ManyCycle.png","/Users/amithannigeri/Desktop/python-codes/AutoRoto01/ManyCycl... | Python | zaydzuhri_stack_edu_python |
function setup_logging log_to_local_only=false env=none
begin
if env is none
begin
set env = call Env
end
call dictConfig logging_config
set logger = call getLogger
if not log_to_local_only
begin
comment Assumes the environment variable APPINSIGHTS_INSTRUMENTATION_KEY is already set
set azure_log_handler = call AzureLo... | def setup_logging(log_to_local_only: bool = False, env: Env = None):
if env is None:
env = Env()
logging.config.dictConfig(logging_config)
logger = getLogger()
if not log_to_local_only:
# Assumes the environment variable APPINSIGHTS_INSTRUMENTATION_KEY is already set
azure_log_hand... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 生成器
comment 通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
comment 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
set li... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 生成器
# 通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
# 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
list =(x+x for x in range(100))
print... | Python | zaydzuhri_stack_edu_python |
function undo_great_circle self proper_motion declination
begin
set secant = 1 / cos declination
return as type secant * proper_motion string float32
end function | def undo_great_circle(self,
proper_motion: Union[np.float32, np.ndarray],
declination: Union[np.float32, np.ndarray]
) -> Union[np.float32, np.ndarray]:
secant = 1 / np.cos(declination)
return (secant * proper_motion).astype(... | Python | nomic_cornstack_python_v1 |
function test_fmt_param self
begin
set rv = get app string /abs/adap-org/9303001?fmt=txt
assert equal status_code 200 string get abs with fmt=txt
assert equal mimetype string text/plain string check mimetype is text/plain
set rv = get app string /abs/adap-org/9303001?fmt=foo
comment Should this be 400 instead?
assert e... | def test_fmt_param(self):
rv = self.app.get('/abs/adap-org/9303001?fmt=txt')
self.assertEqual(rv.status_code, 200,
'get abs with fmt=txt')
self.assertEqual(rv.mimetype, 'text/plain',
'check mimetype is text/plain')
rv = self.app.get('/ab... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment coding=utf-8
string Created on 2015-11-1 @author: ymy
comment 找出chardet.html里的url
import os , re , sys
function grepfile text
begin
set txt = call splitlines
for i in txt
begin
set m = match txt
if not m
begin
continue
end
write stdout txt
end
close txt
end function | #!/usr/bin/python
#coding=utf-8
'''
Created on 2015-11-1
@author: ymy
'''
#找出chardet.html里的url
import os, re, sys
def grepfile(text):
txt = os.popen('cat chardet.html').read().splitlines()
for i in txt:
m = re.match(txt)
if not m:
continue
sys.stdout.write(txt)
txt.... | Python | zaydzuhri_stack_edu_python |
function count self
begin
return _count
end function | def count(self):
return self._count | Python | nomic_cornstack_python_v1 |
import random
comment both functions take no input and return 1 if correct and 0 if wrong
function easy_question
begin
set a = random integer 1 10
set b = random integer 1 10
set c = random integer 1 2
end function | import random
# both functions take no input and return 1 if correct and 0 if wrong
def easy_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
c = random.randint(1, 2) | Python | zaydzuhri_stack_edu_python |
function rasterize rows columns values row_index_func col_index_func default_func=lambda r c -> none
begin
set i_values = iterate values
for tuple i row in enumerate rows
begin
for tuple j col in enumerate columns
begin
if i == 0 and j == 0
begin
set curr_val = next i_values call default_func row col
end
if curr_val is... | def rasterize(rows, columns, values, row_index_func, col_index_func, default_func=lambda r, c: None):
i_values = iter(values)
for i, row in enumerate(rows):
for j, col in enumerate(columns):
if i == 0 and j == 0:
curr_val = next(i_values, default_func(row, col))
... | Python | nomic_cornstack_python_v1 |
import psycopg2
import redis
import json
import os
from bottle import Bottle , request
class Sender extends Bottle
begin
function __init__ self
begin
call __init__
call route string / method=string POST callback=send_message
set redis_host = call getenv string REDIS_HOST string queue
set net_queue = call StrictRedis ho... | import psycopg2
import redis
import json
import os
from bottle import Bottle, request
class Sender(Bottle):
def __init__(self):
super().__init__()
self.route('/', method='POST', callback=self.send_message)
redis_host = os.getenv('REDIS_HOST', 'queue')
self.net_queue = redis.StrictRedis(host=redis_ho... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvLayer extends Module
begin
function __init__ self in_channels out_channels kernel_size stride padding
begin
call __init__
set layer = sequential conv 2d in_channels out_channels kernel_size stride padding call BatchNorm2d out_channels leaky re... | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvLayer(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding):
super().__init__()
self.layer=nn.Sequential(
nn.Conv2d(in_channels,out_channels,kernel_size,stride,padding),
... | Python | zaydzuhri_stack_edu_python |
function body_file self
begin
return _body_file
end function | def body_file(self):
return self._body_file | Python | nomic_cornstack_python_v1 |
function draw self effect=none
begin
set draw = drawable
call fill
call rleblit clock_colon pos=tuple 2 * 48 80 fg=46518
set on_screen = tuple - 1 - 1 - 1 - 1 - 1 - 1
update self
call draw
end function | def draw(self, effect=None):
draw = watch.drawable
draw.fill()
draw.rleblit(digits.clock_colon, pos=(2*48, 80), fg=0xb5b6)
self.on_screen = ( -1, -1, -1, -1, -1, -1 )
self.update()
self.meter.draw() | Python | nomic_cornstack_python_v1 |
function deselect_widget self widget
begin
if not call is_selected widget
begin
return
end
set widget_index = index _current_widgets widget
pop _current_widgets widget_index
call _unfill_background widget
end function | def deselect_widget(self, widget):
if not self.is_selected(widget):
return
widget_index = self._parent._current_widgets.index(widget)
self._parent._current_widgets.pop(widget_index)
self._unfill_background(widget) | Python | nomic_cornstack_python_v1 |
function solve num
begin
set num1 = list comprehension 0 for i in range length num
set num2 = list comprehension 0 for i in range length num
set remain = 0
for tuple index charac in enumerate num
begin
set val = integer charac
set div = remain * 10 + val / 2
set num1 at index = div
if index == length num - 1
begin
set ... | def solve(num):
num1 = [0 for i in range(len(num))]
num2 = [0 for i in range(len(num))]
remain = 0
for index, charac in enumerate(num):
val = int(charac)
div = (remain*10+val)/2
num1[index] = div
if index == len(num) - 1:
num2[index] = remain*10 + val - div
... | Python | zaydzuhri_stack_edu_python |
function ott_loudness_mode self ott_loudness_mode
begin
comment type: (OttLoudnessMode) -> None
if ott_loudness_mode is not none
begin
if not is instance ott_loudness_mode OttLoudnessMode
begin
raise call TypeError string Invalid type for `ott_loudness_mode`, type has to be `OttLoudnessMode`
end
end
set _ott_loudness_m... | def ott_loudness_mode(self, ott_loudness_mode):
# type: (OttLoudnessMode) -> None
if ott_loudness_mode is not None:
if not isinstance(ott_loudness_mode, OttLoudnessMode):
raise TypeError("Invalid type for `ott_loudness_mode`, type has to be `OttLoudnessMode`")
self.... | Python | nomic_cornstack_python_v1 |
comment vamos a capturar errores: errores de valor, y de division por cero.
comment el bucle infinito nos sirve para asegurarnos de que se introduzca correctamente los valores.
comment se sale de el, cuando se han introducido correctamente.
function dividir
begin
while true
begin
try
begin
set num1 = integer input stri... | # vamos a capturar errores: errores de valor, y de division por cero.
# el bucle infinito nos sirve para asegurarnos de que se introduzca correctamente los valores.
#se sale de el, cuando se han introducido correctamente.
def dividir():
while True:
try:
num1 =int(input("primer numero, dividendo: "))
... | Python | zaydzuhri_stack_edu_python |
comment 8.22: Open the weather_newyork.html page in a browser, and
comment use your mouse pointer to select and copy just the first 5
comment rows of the data, excluding the headers. Use
comment pd.read_clipboard() to read the copied data into a
comment DataFrame.
import pandas as pd | # 8.22: Open the weather_newyork.html page in a browser, and
# use your mouse pointer to select and copy just the first 5
# rows of the data, excluding the headers. Use
# pd.read_clipboard() to read the copied data into a
# DataFrame.
import pandas as pd
| Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy.stats import linregress
from scipy.stats.stats import pearsonr
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from dataloading import normalize_by_behavior_report_type
function create_adjacency_matrix data edge_weight_func perturbation_type
begin
if perturb... | import numpy as np
from scipy.stats import linregress
from scipy.stats.stats import pearsonr
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from dataloading import normalize_by_behavior_report_type
def create_adjacency_matrix(data, edge_weight_func, perturbation_type):
if perturb... | Python | zaydzuhri_stack_edu_python |
function _calc_vanmarcke1975_ccdf n a
begin
set args = call carray a n
set x = args at 0
set num_zero_crossings = args at 1
set bandwidth_eff = args at 2
return 1 - 1 - exp - x ^ 2 / 2 * exp - 1 * num_zero_crossings * 1 - exp - 1 * square root pi / 2 * bandwidth_eff * x / exp x ^ 2 / 2 - 1
end function | def _calc_vanmarcke1975_ccdf(n, a):
args = numba.carray(a, n)
x = args[0]
num_zero_crossings = args[1]
bandwidth_eff = args[2]
return (1 - (1 - np.exp(-x ** 2 / 2)) * np.exp(-1 * num_zero_crossings * (
1 - np.exp(-1 * np.sqrt(np.pi / 2) * bandwidth_eff * x)) /
... | Python | nomic_cornstack_python_v1 |
function __init__ self status_code=string resp_content=none
begin
if resp_content
begin
set message = format string API server returned [{}] status code status_code
if string errorCode in resp_content
begin
set message = message + format string , and API returned [{}] error code resp_content at string errorCode
end
if... | def __init__(
self,
status_code: str = '',
resp_content: dict = None
) -> None:
if resp_content:
message = "API server returned [{}] status code".format(
status_code)
if "errorCode" in resp_content:
message += ", an... | Python | nomic_cornstack_python_v1 |
function slackMessage sMessage
begin
set sChannel = string # + call getConfig string slack string channel
print string Posting slack message to %s: %s % tuple sChannel sMessage
post call getConfig string slack string url data=dumps dict string text sMessage ; string channel sChannel ; string user call getConfig string ... | def slackMessage(sMessage):
sChannel = '#' + getConfig('slack', 'channel')
print("Posting slack message to %s: %s" % (sChannel, sMessage))
requests.post(getConfig('slack', 'url'), data=json.dumps({'text': sMessage,
'channel': sChannel,
... | Python | nomic_cornstack_python_v1 |
function read_grayscaleimage filename size
begin
set img = read open filename string rb
set img = call frombytes string L size img
save string tmp.jpeg
set image_array = array img
return image_array
end function | def read_grayscaleimage(filename, size):
img = open(filename, 'rb').read()
img = Image.frombytes('L', size , img)
img.save("tmp.jpeg")
image_array = np.array((img))
return image_array | Python | nomic_cornstack_python_v1 |
function test_amin_nonfinite_inf_02 self
begin
set result = call amin data_inf
assert equal result min data_inf
end function | def test_amin_nonfinite_inf_02(self):
result = arrayfunc.amin(self.data_inf )
self.assertEqual(result, min(self.data_inf)) | Python | nomic_cornstack_python_v1 |
function elec_delay self tau
begin
set tau = tau + tau
if evaluated
begin
set Ftheta = Ft
set Fphi = Fp
set sh = call shape Ftheta
set e = exp 2 * pi * 1j * fGHz at tuple none none slice : : * tau
comment E = np.outer(e, ones(sh[1] * sh[2]))
comment Fth = Ftheta.reshape(sh[0], sh[1] * sh[2])
comment EFth = Fth * E
c... | def elec_delay(self,tau):
self.tau = self.tau+tau
if self.evaluated:
Ftheta = self.Ft
Fphi = self.Fp
sh = np.shape(Ftheta)
e = np.exp(2 * np.pi * 1j * self.fGHz[None,None,:]* tau)
#E = np.outer(e, ones(sh[1] * sh[2]))
#Fth = Ftheta... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys
set nodesDic = dict
set explored = list
set stack = list
set queue = list
class Link
begin
function __init__ self N2 cost
begin
comment self.N1 = N1
set N2 = N2
set cost = cost
end function
end class
class Node
begin
function __init__ self name
begin
set name = name
set heur_cost... | #!/usr/bin/python
import sys
nodesDic = {}
explored = []
stack = []
queue = []
class Link:
def __init__ (self, N2, cost):
#self.N1 = N1
self.N2 = N2
self.cost = cost
class Node:
def __init__ (self, name):
self.name = name
self.heur_cost = 0
self.links = []
class Path:
def __init__ (self):
self.pat... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return string %s,%s % tuple call isoformat call isoformat
end function | def __str__(self):
return '%s,%s' % (self.start.isoformat(), self.end.isoformat()) | Python | nomic_cornstack_python_v1 |
import pygame
import Components
import MainPage
from Pages import Page
class HopperPage extends Page
begin
function __init__ self
begin
call __init__ self
set backgroundColor = call Color string dark red
set components = list call Label list 150 50 150 string Hopper list string red string black call Container 312 0 128... | import pygame
import Components
import MainPage
from Pages import Page
class HopperPage(Page.Page):
def __init__(self):
Page.Page.__init__(self)
self.backgroundColor = pygame.Color("dark red")
self.components = [
Components.Label.Label([150, 50], 150, "Hopper", ["red", "black"]... | Python | zaydzuhri_stack_edu_python |
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
import seaborn as sns
from mlxtend.plotting import plot_confusion_matrix... | from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
import seaborn as sns
from mlxtend.plotting import plot_confusio... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
comment @time : 2019-12-11 16:32
comment @author : xulei
comment @project: Fluent_Python
from random import shuffle
from chapter11.c11_4_FrenchDeck import FrenchDeck
set deck = call FrenchDeck
function set_card deck position card
begin
set _cards at position = card
end function
set __setite... | # -*- coding:utf-8 -*-
# @time : 2019-12-11 16:32
# @author : xulei
# @project: Fluent_Python
from random import shuffle
from chapter11.c11_4_FrenchDeck import FrenchDeck
deck = FrenchDeck()
def set_card(deck, position, card):
deck._cards[position] = card
FrenchDeck.__setitem__ = set_card
shuffle(deck)
pr... | Python | zaydzuhri_stack_edu_python |
function check_document
begin
function check_document actual test
begin
string Check that documents match.
set actual_keys = keys actual
set test_keys = keys test
assert actual_keys == test_keys
for key in test_keys
begin
assert key in actual_keys
if key == string xrefs
begin
assert set actual at key == set test at key... | def check_document():
def check_document(actual, test):
"""Check that documents match."""
actual_keys = actual.keys()
test_keys = test.keys()
assert actual_keys == test_keys
for key in test_keys:
assert key in actual_keys
if key == "xrefs":
... | Python | nomic_cornstack_python_v1 |
comment !/bin/python
comment Generates a collection of dummy social media data
from random import choice , randint , random
from time import strftime
from datetime import timedelta , datetime
from openpyxl import Workbook
import xlrd
comment Reads lines "NIKE 23 14 45" from 7days.xlsx which is the count of pos, neg and... | #!/bin/python
# Generates a collection of dummy social media data
from random import choice, randint, random
from time import strftime
from datetime import timedelta, datetime
from openpyxl import Workbook
import xlrd
#Reads lines "NIKE 23 14 45" from 7days.xlsx which is the count of pos, neg and neu post... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import tensorflow as tf
function getClassifier featureColumns
begin
set classifier = call DNNClassifier feature_columns=featureColumns hidden_units=list 10 500 10 n_classes=10 optimizer=call GradientDescentOptimizer learning_rate=0.1
return classifier
end function
function getData
begin
set training... | import pandas as pd
import tensorflow as tf
def getClassifier(featureColumns):
classifier = tf.estimator.DNNClassifier(
feature_columns = featureColumns,
hidden_units = [10, 500, 10],
n_classes = 10,
optimizer=tf.train.GradientDescentOptimizer(
learning_rate=0.1,)
)
... | Python | zaydzuhri_stack_edu_python |
function gcd
begin
set m = integer call raw_input string enter any number
print m
set n = integer call raw_input string enter any number
print n
set fm = list
for i in range 1 m + 1
begin
if m % i == 0
begin
append fm i
end
end
print fm
set fn = list
for i in range 1 n + 1
begin
if n % i == 0
begin
append fn i
end
en... | def gcd():
m=int(raw_input("enter any number"))
print(m)
n=int(raw_input("enter any number"))
print(n)
fm=[]
for i in range(1,m+1):
if m%i==0:
fm.append(i)
print(fm)
fn=[]
for i in range(1,n+1):
if n%i==0:
fn.append(i)
print(fn)
cf=[]
for i in fm:
if i in fn:
cf.append(i)
print(cf)... | Python | zaydzuhri_stack_edu_python |
function solve
begin
comment for an mxn grid, there are:
comment m(m+1)n(n+1)/4 rectangles
set r = 0
set mb = 0
set nb = 0
for m in range 1 2001
begin
comment we look, by bisection, for nL such that:
comment m(m+1)nL(nL+1)/4 < 2000000 < m(m+1)(nL+1)(nL+2)/4
set nL = 1
set nU = 2001
while nU - nL > 1
begin
set nM = nL +... | def solve():
# for an mxn grid, there are:
# m(m+1)n(n+1)/4 rectangles
r = 0
mb = 0
nb = 0
for m in range(1, 2001):
# we look, by bisection, for nL such that:
# m(m+1)nL(nL+1)/4 < 2000000 < m(m+1)(nL+1)(nL+2)/4
nL = 1
nU = 2001
while nU - nL > 1:
... | Python | zaydzuhri_stack_edu_python |
import os
import csv
set files = list
try
begin
make directories string ./turtle_files2
end
except OSError as e
begin
pass
end
function turn2rdflist line
begin
set a = split replace replace replace replace line string >, string string > string string " string string ; string string <
set track_list = string (
for i in... | import os
import csv
files = []
try:
os.makedirs('./turtle_files2')
except OSError as e:
pass
def turn2rdflist(line):
a = line.replace(">,", '').replace(">", '').replace('"', '').replace(" ;\n", '').split('<')
track_list = "( "
for i in range(1, len(a)):
track_split = a[i].split(" ")[1:]... | Python | zaydzuhri_stack_edu_python |
string File name: cannyEdge.py Author: Haoyuan(Steve) Zhang Date created: 9/10/2017
string File clarification: Canny edge detector - Input: A color image I = uint8(H, W, 3), where H, W are two dimensions of the image - Output: An edge map E = logical(H, W) - TO DO: Complete three main functions findDerivatives, nonMaxS... | '''
File name: cannyEdge.py
Author: Haoyuan(Steve) Zhang
Date created: 9/10/2017
'''
'''
File clarification:
Canny edge detector
- Input: A color image I = uint8(H, W, 3), where H, W are two dimensions of the image
- Output: An edge map E = logical(H, W)
- TO DO: Complete three main functions... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set _parseStringMock = call SimpleMock
set parseString = _parseStringMock
set _createFileStorerMock = call SimpleMock
set createFileStorer = _createFileStorerMock
set _fileStorerMock = call SimpleMock
set _datastoreHandler = call DataStoreHandler _fileStorerMock
end function | def setUp(self):
self._parseStringMock = SimpleMock()
datastores.parseString = self._parseStringMock
self._createFileStorerMock = SimpleMock()
handler.createFileStorer = self._createFileStorerMock
self._fileStorerMock = SimpleMock()
self._datastoreHandler ... | Python | nomic_cornstack_python_v1 |
from tkinter import *
from pytube import YouTube
import time
set root = call Tk
title root string YouTube Downloader
call geometry string 500x500
function download
begin
pass
global e1
set string = get e1
set yt = call YouTube string string
set videos = all
set l = list
for v in videos
begin
append l string v
end
comm... | from tkinter import *
from pytube import YouTube
import time
root=Tk()
root.title("YouTube Downloader")
root.geometry("500x500")
def download():
pass
global e1
string=e1.get()
yt = YouTube(str(string))
videos = yt.streams.filter(subtype='mp4').all()
l=[]
for v in videos:
l.... | Python | zaydzuhri_stack_edu_python |
comment Advent of Code 2020
comment Day 8, Part 1
comment December 13, 2020
set file_name = string day8-input.dat
with open file_name as file_contents
begin
set line_content = read lines file_contents
comment intialize variables and file length
set curr_row = 0
set accum = 0
set executed = set
set length = length line_... | # Advent of Code 2020
# Day 8, Part 1
# December 13, 2020
file_name = "day8-input.dat"
with open(file_name) as file_contents:
line_content = file_contents.readlines()
# intialize variables and file length
curr_row = 0
accum = 0
executed = set()
length = len(line_content) - 1
while curr_row... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template
from flask import request , redirect , url_for
set app = call Flask __name__
set config at string SQLALCHEMY_DATABASE_URI = string postgresql://postgres:jason@localhost/apitest
set db = call SQLAlchemy app
class User exten... | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template
from flask import request, redirect, url_for
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:jason@localhost/apitest'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db... | Python | zaydzuhri_stack_edu_python |
import argparse
import torch
from torchvision import datasets , transforms
from PIL import Image
import numpy as np
import json
comment Function to parse command-line arguments
function get_args mode=string train
begin
comment Add arguments
if mode == string train
begin
set parser = call ArgumentParser description=stri... | import argparse
import torch
from torchvision import datasets, transforms
from PIL import Image
import numpy as np
import json
## Function to parse command-line arguments
def get_args(mode='train'):
## Add arguments
if (mode == 'train'):
parser = argparse.ArgumentParser(description='AI Model Trainer.'... | Python | zaydzuhri_stack_edu_python |
function apply self transaction context
begin
set state = call MarketplaceState context=context timeout=3
set userstate = call UserState context=context timeout=3
set mnemonic_state = call SecretState context=context timeout=3
set payload = call MarketplacePayload payload=payload
try
begin
comment check if the transact... | def apply(self, transaction, context):
state = MarketplaceState(context=context, timeout=3)
userstate = user_state.UserState(context=context, timeout=3)
mnemonic_state = secret_state.SecretState(context=context, timeout=3)
payload = MarketplacePayload(payload=transaction.payload)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf8 -*-
comment @author: 刘慧玲 2018/5/22 19:16
function test2
begin
print string test2
end function
comment 直角三角形判断
function ispositive num
begin
try
begin
integer num
end
except any
begin
return false
end
try else
begin
if integer num <= 0 or integer num > 200
begin
retur... | #!/usr/bin/env python
#-*- coding:utf8 -*-
#@author: 刘慧玲 2018/5/22 19:16
def test2():
print("test2")
# 直角三角形判断
def ispositive(num):
try:
int(num)
except:
return False
else:
if int(num) <= 0 or int(num) > 200:
return False
else:
return True
def... | Python | zaydzuhri_stack_edu_python |
from generator.collection_generator import CollectionGenerator
from reader.json_reader import JSONReader
from reader.html_reader import HTMLReader as xml_read
class DynamicCollection extends CollectionGenerator
begin
comment UPCOMING FEATURES
comment -Indexed scoping
comment +can reference index of final target, rather... | from generator.collection_generator import CollectionGenerator
from reader.json_reader import JSONReader
from reader.html_reader import HTMLReader as xml_read
class DynamicCollection(CollectionGenerator):
#UPCOMING FEATURES
# -Indexed scoping
# +can reference index of final target, rather than being screwed at t... | Python | zaydzuhri_stack_edu_python |
function feedback
begin
set url = string https://aka.ms/azure-devops-cli-feedback
print string Thank you for taking the time to share your feedback. Please submit your feedback on the following web + format string page: {url} url=url
end function | def feedback():
url = 'https://aka.ms/azure-devops-cli-feedback'
print('Thank you for taking the time to share your feedback. Please submit your feedback on the following web ' +
'page: {url}'.format(url=url)) | Python | nomic_cornstack_python_v1 |
import pymysql
from dotenv import load_dotenv
from flask import request
import pytz
from datetime import datetime , timedelta
import os
call load_dotenv
set user = call getenv string SQL_USER
set psw = call getenv string SQL_PSW
set host = call getenv string SQL_HOST
class Recom
begin
function __init__ self *args **kwa... | import pymysql
from dotenv import load_dotenv
from flask import request
import pytz
from datetime import datetime, timedelta
import os
load_dotenv()
user = os.getenv("SQL_USER")
psw = os.getenv("SQL_PSW")
host = os.getenv("SQL_HOST")
class Recom():
def __init__(self, *args, **kwargs):
self.db = pymysq... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
comment 读取图像
set img = call imread string ../img/test14.bmp
print shape
comment 对图像进行均值滤波
set img_mean = call blur img tuple 5 5
call putText img_mean string img_mean tuple 50 50 FONT_HERSHEY_SIMPLEX 1.5 tuple 255 0 0 4
comment 对图像进行中值滤波
set img_median = call medianBlur img 5
call putText ... | import cv2
import numpy as np
# 读取图像
img = cv2.imread('../img/test14.bmp')
print(img.shape)
#对图像进行均值滤波
img_mean = cv2.blur(img, (5, 5))
cv2.putText(img_mean,"img_mean",(50,50),cv2.FONT_HERSHEY_SIMPLEX,1.5,(255,0,0),4)
#对图像进行中值滤波
img_median = cv2.medianBlur(img, 5)
cv2.putText(img_median,"img_median",(50,50),cv2.FONT_... | Python | zaydzuhri_stack_edu_python |
import os
from math import floor
import numpy as np
import csv
import matplotlib.pyplot as plt
from CONSTANTS import SINGLE_CAR , JOINING_PROCESS , PREPARE_JOINING , PLATOON , MERGING , LEAVING_PROCESS , LEFT , NO_PLATOONING , NEW_SPAWNED , AMOUNT_RANDOM_CARS
set COLORS = list string tab:blue string tab:orange string t... | import os
from math import floor
import numpy as np
import csv
import matplotlib.pyplot as plt
from CONSTANTS import SINGLE_CAR, JOINING_PROCESS, PREPARE_JOINING, PLATOON, MERGING, LEAVING_PROCESS, LEFT, \
NO_PLATOONING, NEW_SPAWNED, AMOUNT_RANDOM_CARS
COLORS = ['tab:blue', 'tab:orange', 'tab:brown', 'tab:purpl... | Python | zaydzuhri_stack_edu_python |
from sys import stdin
comment 입력.
set testcase = integer read line stdin
comment 정답 초기 리스트.
set answer_arr = list 0 1 2 2
comment N의 범위가 1000까지 이므로,
for i in range 4 1001
begin
comment 짝수면 n의 절반의 정답 + 바로 이전의 값.
if i % 2 == 0
begin
append answer_arr answer_arr at i // 2 + answer_arr at i - 1
end
else
begin
comment 홀수면 바... | from sys import stdin
# 입력.
testcase = int(stdin.readline())
# 정답 초기 리스트.
answer_arr = [0,1,2,2]
# N의 범위가 1000까지 이므로,
for i in range(4,1001):
# 짝수면 n의 절반의 정답 + 바로 이전의 값.
if i%2 == 0:
answer_arr.append(answer_arr[i//2]+answer_arr[i-1])
# 홀수면 바로 이전의 값.
else:
answer_arr.append(answer_a... | Python | zaydzuhri_stack_edu_python |
set vowels = list string a string e string i string o string u
for letter in reversed vowels
begin
print letter
end | vowels = ['a', 'e', 'i', 'o', 'u']
for letter in reversed(vowels):
print(letter)
| Python | jtatman_500k |
from typing import Sequence
import graphviz
from flloat.parser.ltlf import LTLfParser
from pythomata.core import SymbolType
from pythomata.impl.symbolic import SymbolicDFA
from sympy import Symbol
from sympy.logic.boolalg import And , Or , Not
from sympy.logic.boolalg import BooleanAtom
from monitoring_rewards.core imp... | from typing import Sequence
import graphviz
from flloat.parser.ltlf import LTLfParser
from pythomata.core import SymbolType
from pythomata.impl.symbolic import SymbolicDFA
from sympy import Symbol
from sympy.logic.boolalg import And, Or, Not
from sympy.logic.boolalg import BooleanAtom
from monitoring_rewards.core imp... | Python | zaydzuhri_stack_edu_python |
function __init__ self filename=none
begin
set _alphabet = set
set filename = filename
if filename is not none
begin
call _load_from_file filename
end
call __init__
end function | def __init__(self, filename=None):
self._alphabet = set()
self.filename = filename
if filename is not None:
self._load_from_file(filename)
super(SubwordTextEncoder, self).__init__() | Python | nomic_cornstack_python_v1 |
import yagmail
import requests
from bs4 import BeautifulSoup
import time
import random
from hidden import bot_email , bot_key , mail_to
function send_email bot_email bot_key mail_to
begin
set subject = string Automated GFX Bot message
set content = string New IN STOCK item(s) reported! Email comfirmation is now turned ... | import yagmail
import requests
from bs4 import BeautifulSoup
import time
import random
from hidden import bot_email, bot_key, mail_to
def send_email(bot_email, bot_key, mail_to):
subject = "Automated GFX Bot message"
content = "New IN STOCK item(s) reported! Email comfirmation is now turned off."
... | Python | zaydzuhri_stack_edu_python |
comment Advent of Code 2020 Day 16
import re
set f = open string C:/Users/Simon/OneDrive/Home Stuff/Python/Advent of Code/2020/2020-16.txt
set contents = read f
set input = call splitlines
class System
begin
function __init__ self input
begin
set p1 = compile string (^.+): (\d+)\-(\d+) or (\d+)\-(\d+)$
set valid = set
... | #Advent of Code 2020 Day 16
import re
f = open('C:/Users/Simon/OneDrive/Home Stuff/Python/Advent of Code/2020/2020-16.txt')
contents = f.read()
input=contents.splitlines()
class System():
def __init__(self,input):
p1=re.compile('(^.+): (\d+)\-(\d+) or (\d+)\-(\d+)$')
self.valid=set()
sel... | Python | zaydzuhri_stack_edu_python |
from keras.models import Sequential
from keras.layers import Dense , Conv1D , Flatten , Input , LSTM
from keras.models import Model
from keras.callbacks import EarlyStopping
import keras
function create_cnn_model_1 input_size=10
begin
set inp = input shape=tuple input_size 4
set x = call conv 1d 3 kernel_size=3 activat... | from keras.models import Sequential
from keras.layers import Dense, Conv1D, Flatten, Input, LSTM
from keras.models import Model
from keras.callbacks import EarlyStopping
import keras
def create_cnn_model_1(input_size = 10):
inp = Input(shape=(input_size, 4))
x = Conv1D(3, kernel_size=3, activation='relu')(inp... | Python | zaydzuhri_stack_edu_python |
async function infer_type_list_reduce track fn lst dflt
begin
set fn_t = await fn at string type
await call check List lst
set xref = call TransformedReference engine getelement lst
set res_elem_t = await call assert_same call fn_t xref xref dflt
return res_elem_t
end function | async def infer_type_list_reduce(track, fn, lst, dflt):
fn_t = await fn['type']
await track.check(List, lst)
xref = TransformedReference(track.engine, getelement, lst)
res_elem_t = await track.assert_same(fn_t(xref, xref), dflt)
return res_elem_t | Python | nomic_cornstack_python_v1 |
import pyautogui
import cv2 as cv
import numpy as np
import math
string Computing Vision
comment finding pink pixel on part of screen
function find_pink image
begin
set image = call cvtColor image COLOR_RGBA2RGB
comment lower_white = np.array([174, 170, 238])
comment BGR-code of your lowest white
set lower_white = arra... | import pyautogui
import cv2 as cv
import numpy as np
import math
"""Computing Vision"""
#finding pink pixel on part of screen
def find_pink(image):
image = cv.cvtColor(image, cv.COLOR_RGBA2RGB)
#lower_white = np.array([174, 170, 238])
lower_white = np.array([174, 170, 238]) # BGR-code of your lowest whit... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
from queue import Queue
function numConnectedComponents edges n
begin
set graph = default dictionary lambda -> set
function buildGraph
begin
for e in edges
begin
add graph at e at 0 e at 1
add graph at e at 1 e at 0
end
end function
call buildGraph
function dfs
begin
set visited = s... | from collections import defaultdict
from queue import Queue
def numConnectedComponents(edges, n):
graph = defaultdict(lambda: set())
def buildGraph():
for e in edges:
graph[e[0]].add(e[1])
graph[e[1]].add(e[0])
buildGraph()
def dfs():
visited = set()... | Python | zaydzuhri_stack_edu_python |
function test_service
begin
set input_text = get args string input_text
return call jsonify Entered_text=input_text
end function | def test_service():
input_text = request.args.get("input_text")
return jsonify(Entered_text=input_text) | Python | nomic_cornstack_python_v1 |
async function async_step_user self user_input=none
begin
set _errors = dict
if user_input is not none
begin
set host = user_input at CONF_HOST
set port = get user_input CONF_PORT DEFAULT_PORT
await call async_set_unique_id string { host } : { port }
call _abort_if_unique_id_configured
if await call _test_connection u... | async def async_step_user(
self,
user_input: Mapping[str, Any] | None = None,
) -> FlowResult:
self._errors = {}
if user_input is not None:
host = user_input[CONF_HOST]
port = user_input.get(CONF_PORT, DEFAULT_PORT)
await self.async_set_unique_id(f... | Python | nomic_cornstack_python_v1 |
function stopJob jobId pwd url loud=true
begin
return call doPost url + jobId + string /stop dict string pwd loud string string
end function | def stopJob(jobId, pwd, url, loud=True):
return doPost(url + jobId + "/stop", {}, "", pwd, loud, "", "") | Python | nomic_cornstack_python_v1 |
function argument_parser self
begin
set parser = call ArgumentParser description=string Smartbond tool v%s - Dialog Smartbond devices flash management tool % __version__ prog=string ezFlashCLI
call add_argument string -c string --chip help=string Smartbond chip version choices=list string auto string DA14531 string DA1... | def argument_parser(self):
self.parser = argparse.ArgumentParser(
description="Smartbond tool v%s - Dialog Smartbond devices flash management tool"
% __version__,
prog="ezFlashCLI",
)
self.parser.add_argument(
"-c",
"--chip",
... | Python | nomic_cornstack_python_v1 |
function _get_platform_res_limit self
begin
set limit_enabled = false
set limit_cpus = 0
set limit_mem_mib = 0
set system = call _get_system
if system_type == TIS_AIO_BUILD
begin
set limit_enabled = true
set controller_0 = call ihost_get_by_hostname CONTROLLER_0_HOSTNAME
set platform_cpus = call _get_host_cpu_list cont... | def _get_platform_res_limit(self):
limit_enabled = False
limit_cpus = 0
limit_mem_mib = 0
system = self._get_system()
if system.system_type == constants.TIS_AIO_BUILD:
limit_enabled = True
controller_0 = self.dbapi.ihost_get_by_hostname(
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string counter_test.py 계수에 특화된 자료 구조를 제공하는 Counter 클래스를 실험한다.
comment %% 모듈 임포트
import sys
comment Counter 클래스를 이용하려면 clooections 모듈을 임포트해야 한다.
from collections import Counter
from konlpy.tag import Komoran
comment %% 사용자 모듈 임포트
comment WORK_PATH 변수에 사용자의 text-mining-camp 디렉토리 경로를 지정한다.
se... | # -*- coding: utf-8 -*-
"""
counter_test.py
계수에 특화된 자료 구조를 제공하는 Counter 클래스를 실험한다.
"""
# %% 모듈 임포트
import sys
# Counter 클래스를 이용하려면 clooections 모듈을 임포트해야 한다.
from collections import Counter
from konlpy.tag import Komoran
# %% 사용자 모듈 임포트
# WORK_PATH 변수에 사용자의 text-mining-camp 디렉토리 경로를 지정한다.
WORK_PATH="/U... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from dice import die
set pool = range 1 16
set numbers = list
for i in range 9
begin
append numbers pop pool call roll1dX length pool - 1
end | #!/usr/bin/python
from dice import die
pool=range(1,16)
numbers=[]
for i in range(9):
numbers.append(pool.pop(die.roll1dX(len(pool))-1))
| Python | zaydzuhri_stack_edu_python |
function get_entries_by_name self name dns_zone=none
begin
pass
end function | def get_entries_by_name(self, name, dns_zone=None):
pass | Python | nomic_cornstack_python_v1 |
function yolo_box_op operator block
begin
set tuple inputs attrs outputs = call op_io_info operator
set model_name = outputs at string Boxes at 0
set input_shape = shape
set image_size = inputs at string ImgSize
set input_height = input_shape at 2
set input_width = input_shape at 3
set class_num = attrs at string class... | def yolo_box_op(operator, block):
inputs, attrs, outputs = op_io_info(operator)
model_name = outputs['Boxes'][0]
input_shape = block.vars[get_old_name(inputs['X'][0])].shape
image_size = inputs['ImgSize']
input_height = input_shape[2]
input_width = input_shape[3]
class_num = attrs['class_nu... | Python | nomic_cornstack_python_v1 |
string Fetch exercises from bodybuilding.com
import json
import re
from os import path
from sys import exit
from tqdm import tqdm
import requests
from lxml import html
set OUT_FILE_NAME = string bbcom_exercises.json
comment There are a lot more pages than this but they all have no ratings
set MAX_PAGE = 70
function fet... | """
Fetch exercises from bodybuilding.com
"""
import json
import re
from os import path
from sys import exit
from tqdm import tqdm
import requests
from lxml import html
OUT_FILE_NAME = "bbcom_exercises.json"
MAX_PAGE = 70 # There are a lot more pages than this but they all have no ratings
def fetch_exercise_names... | Python | zaydzuhri_stack_edu_python |
comment 한 단어에서 각 알파벳이 처음 등장하는 위치를 찾는 문제
set S = input
set alphabet = list comprehension 0 for _ in range 26
for idx in range 26
begin
if character idx + 97 not in S
begin
set alphabet at idx = - 1
end
else
begin
set alphabet at idx = index S character idx + 97
end
end
print join string map str alphabet | # 한 단어에서 각 알파벳이 처음 등장하는 위치를 찾는 문제
S = input()
alphabet = [0 for _ in range(26)]
for idx in range(26):
if chr(idx+97) not in S:
alphabet[idx] = -1
else:
alphabet[idx] = S.index(chr(idx+97))
print(' '.join(map(str, alphabet)))
| Python | zaydzuhri_stack_edu_python |
function connect
begin
call active true
if not call isconnected
begin
print string Connecting to network
call connect SECRETS at string wifi at string essid SECRETS at string wifi at string pass
set intent = 0
while not call isconnected
begin
print string . end=string
call sleep_ms 1000
set intent = intent + 1
if inten... | def connect():
WLAN.active(True)
if not WLAN.isconnected():
print('Connecting to network')
WLAN.connect(SECRETS['wifi']['essid'], SECRETS['wifi']['pass'])
intent = 0
while not WLAN.isconnected():
print(".", end="")
utime.sleep_ms(1000)
intent =... | Python | nomic_cornstack_python_v1 |
import numpy as np
class GA extends object
begin
function __init__ self DNA_size cross_rate mutation_rate pop_size
begin
comment 等于城市数
set DNA_size = DNA_size
set cross_rate = cross_rate
set mutate_rate = mutation_rate
set pop_size = pop_size
comment pop为种群矩阵,大小为(POP_SIZE, N_CITIES),城市编号从1开始
set pop = vertical stack li... | import numpy as np
class GA(object):
def __init__(self, DNA_size, cross_rate, mutation_rate, pop_size, ):
self.DNA_size = DNA_size # 等于城市数
self.cross_rate = cross_rate
self.mutate_rate = mutation_rate
self.pop_size = pop_size
# pop为种群矩阵,大小为(POP_SIZE, N_CITIES),城市编号从1开始
... | Python | zaydzuhri_stack_edu_python |
from google.appengine.ext import db
class Food extends Model
begin
set name = call StringProperty required=true
set quantity = call IntegerProperty required=true
function list_foods self
begin
set books = call GqlQuery string SELECT * FROM Food
for e in books
begin
write response name + quantity
end
end function
end cl... | from google.appengine.ext import db
class Food(db.Model):
name = db.StringProperty(required=True)
quantity = db.IntegerProperty(required=True)
def list_foods(self):
books = db.GqlQuery("SELECT * FROM Food")
for e in books:
self.response.write(e.name + e.quantity) | Python | zaydzuhri_stack_edu_python |
function reconstruct_classification_queue_to_file self data_queue result_folder suffix save_raw=true
begin
for data_out in iterate get none
begin
set tuple results paths = data_out
comment same-tile_augmentation
if length paths == 1
begin
set results_mean = mean np results axis=0
set predictions = call expand_dims argu... | def reconstruct_classification_queue_to_file(self, data_queue, result_folder, suffix, save_raw=True):
for data_out in iter(data_queue.get, None):
results, paths= data_out
if len(paths) == 1: # same-tile_augmentation
results_mean = np.mean(results, axis=0)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3.6
comment -*- Coding: UTF-8 -*-
string Usa algoritmo genético para resolver o sudoku.
import sys
from numpy import loadtxt
from sudoku import Sudoku
from solucionarsudoku import SolucionarSudoku
set jg = argv at 1
set jogo = call loadtxt jg dtype=int delimiter=string ,
set sudoku = call Su... | #!/usr/bin/env python3.6
# -*- Coding: UTF-8 -*-
"""
Usa algoritmo genético para resolver o sudoku.
"""
import sys
from numpy import loadtxt
from sudoku import Sudoku
from solucionarsudoku import SolucionarSudoku
jg = sys.argv[1]
jogo = loadtxt(jg, dtype=int, delimiter=",")
sudoku = Sudoku()
sudoku.sudoku = jogo
solu... | Python | zaydzuhri_stack_edu_python |
function max_noutput_items self
begin
return call ldpc_decoder_sptr_max_noutput_items self
end function | def max_noutput_items(self):
return _ccsds_swig.ldpc_decoder_sptr_max_noutput_items(self) | 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.