code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function after_request resp
begin
if call get_current_user_id
begin
set csrf_token = csrf_token
comment Set the CSRF cookie even if it's already set, so we renew
comment the expiry timer.
call set_cookie CSRF_COOKIE_NAME csrf_token max_age=CSRF_COOKIE_AGE domain=CSRF_COOKIE_DOMAIN path=CSRF_COOKIE_PATH httponly=CSRF_CO... | def after_request(resp):
if get_current_user_id():
csrf_token = g.csrf_token
# Set the CSRF cookie even if it's already set, so we renew
# the expiry timer.
resp.set_cookie(
api_settings.CSRF_COOKIE_NAME,
csrf_token,
max_age=api_settings.CSRF_COOKI... | Python | nomic_cornstack_python_v1 |
from math import *
from tkinter import *
from time import *
from random import *
set root = call Tk
set screen = call Canvas root width=1000 height=800 background=string paleturquoise
call pack
function setInitialValues
begin
global energy score scoreMultiplier hit upImg downImg leftImg rightImg combo numZeroes lives a... | from math import *
from tkinter import *
from time import *
from random import *
root = Tk()
screen = Canvas(root, width=1000, height=800, background="paleturquoise")
screen.pack()
def setInitialValues():
global energy,score, scoreMultiplier, hit, upImg, downImg, leftImg, rightImg, combo, numZeroes, liv... | Python | zaydzuhri_stack_edu_python |
from time import time
function speed_test fn
begin
function wrapper *args **kwargs
begin
set start = time
call fn *args keyword kwargs
set total = time - start
return string It took { total } sec to execute the function
end function
return wrapper
end function
decorator speed_test
function soma *args
begin
return sum *... | from time import time
def speed_test(fn):
def wrapper(*args, **kwargs):
start = time()
fn(*args, **kwargs)
total = time() - start
return f'It took {total}sec to execute the function'
return wrapper
@speed_test
def soma(*args):
return sum(*args)
print(soma([x for x in ra... | Python | zaydzuhri_stack_edu_python |
string Date:11/13/2019 Author:Group work Group project: output data clean 1. read the dataset 2. calculate the sum score of each student 3. collect the data in a csv file
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
call use string ggplot
set flourishing = read csv string .\O... | """
Date:11/13/2019
Author:Group work
Group project:
output data clean
1. read the dataset
2. calculate the sum score of each student
3. collect the data in a csv file
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
flou... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
import os
import argparse
import neologdn
import MeCab
import pandas as pd
import subprocess
from parse import parse
class PandasTagger extends Tagger
begin
function __init__ self option=string
begin
call __init__ option
set columns = list string 表層形 string 品詞 stri... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import argparse
import neologdn
import MeCab
import pandas as pd
import subprocess
from parse import parse
class PandasTagger(MeCab.Tagger):
def __init__(self, option=""):
super().__init__(option)
self.columns = [
"表層形",
... | Python | zaydzuhri_stack_edu_python |
comment Name:
set terminals = set list string that string this string a string book string flight string meal string money string include string prefer string I string she string me string Houston string NWA string does string from string to string on string near string through
set nonterminals = set list string S stri... | # Name:
terminals = set(['that','this','a','book','flight','meal','money','include','prefer','I','she','me','Houston','NWA','does','from','to','on','near','through'])
nonterminals = set(['S','NP','Nominal','VP','PP','Det','Noun','Verb','Pronoun','Proper-Noun','Aux','Preposition'])
grammar = {'S':[['NP','VP'],['Aux'... | Python | zaydzuhri_stack_edu_python |
function retrieve self request pk=none
begin
return call Response dict string HTTP method string GET
end function | def retrieve(self,request , pk=None):
return Response({'HTTP method':'GET'}) | Python | nomic_cornstack_python_v1 |
function subscription bot update
begin
set chat_id = chat_id
call sendMessage chat_id=chat_id text=SUBSCRIPTION_MSG parse_mode=string markdown disable_web_page_preview=true
call track call get_user_info chat_id at string PID string Checked Subscription
end function | def subscription(bot, update):
chat_id = update.message.chat_id
bot.sendMessage(chat_id=chat_id, text=SUBSCRIPTION_MSG, parse_mode='markdown',
disable_web_page_preview=True)
mp.track(get_user_info(chat_id)['PID'], 'Checked Subscription') | Python | nomic_cornstack_python_v1 |
function fetch_assets self
begin
comment allow overwrites from the commandline
set packages = set split get config string bootstrap-packages string
update packages list string python27
set cmd = get config string bootstrap-local-download-cmd string wget -c -O "{0.local}" "{0.url}"
set items = sorted items bootstrap_fil... | def fetch_assets(self):
# allow overwrites from the commandline
packages = set(
env.instance.config.get('bootstrap-packages', '').split())
packages.update(['python27'])
cmd = env.instance.config.get('bootstrap-local-download-cmd', 'wget -c -O "{0.local}" "{0.url}"')
i... | Python | nomic_cornstack_python_v1 |
import requests
import json
import math
from time import mktime , gmtime , localtime
import time
from supply.models import Brand , Location
class Locate extends object
begin
function geolocate self address
begin
set url = string http://maps.googleapis.com/maps/api/geocode/json?address= + address + string &sensor=false
... | import requests
import json
import math
from time import mktime, gmtime, localtime
import time
from supply.models import Brand, Location
class Locate(object):
def geolocate(self, address):
url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false"
resp = requests... | Python | zaydzuhri_stack_edu_python |
function clean_coords coords
begin
if is instance coords tuple str unicode
begin
set coords = split coords string ,
end
if is instance coords dict
begin
if string lat in coords and string lng in coords
begin
set coords = tuple coords at string lat coords at string lng
end
end
if is instance coords tuple tuple list
begi... | def clean_coords(coords):
if isinstance(coords, (str, unicode)):
coords = coords.split(',')
if isinstance(coords, dict):
if 'lat' in coords and 'lng' in coords:
coords = coords['lat'], coords['lng']
if isinstance(coords, (tuple, list)):
if len(coords) != 2:
... | Python | nomic_cornstack_python_v1 |
function same_col i j
begin
return i - j % 9 == 0
end function | def same_col(i, j):
return (i - j) % 9 == 0 | Python | nomic_cornstack_python_v1 |
function test_creation_mapped_control self
begin
set control = call ControlFactory
comment Map original of control to several assessments to get propagated roles
call generate_control_mappings control
comment Existing control should be updated to create new revision with ACL
put control dict string title string Test Co... | def test_creation_mapped_control(self):
control = factories.ControlFactory()
# Map original of control to several assessments to get propagated roles
self.generate_control_mappings(control)
# Existing control should be updated to create new revision with ACL
self.api.put(control, {"title": "Test Co... | Python | nomic_cornstack_python_v1 |
function check_eyes self person_idx=0
begin
comment If ear < threshold, eye is closed
set eye_aspect_ratio_threshold = 0.2
set reye_closed = false
set reye1 = call get_face_kp string REye1 person_idx=person_idx
set reye2 = call get_face_kp string REye2 person_idx=person_idx
set reye3 = call get_face_kp string REye3 per... | def check_eyes(self, person_idx=0):
eye_aspect_ratio_threshold = 0.2 # If ear < threshold, eye is closed
reye_closed = False
reye1 = self.get_face_kp("REye1", person_idx=person_idx)
reye2 = self.get_face_kp("REye2", person_idx=person_idx)
reye3 = self.get_face_kp("REye... | Python | nomic_cornstack_python_v1 |
function main
begin
set data = call MNISTDataModule batch_size=64
set model = call LitSampleConvNetClassifier
set dp_data = call DPLightningDataModule data
set trainer = call Trainer max_epochs=10 enable_model_summary=false
fit trainer model dp_data
call test model data
comment identical
call test model dp_data
end fun... | def main():
data = MNISTDataModule(batch_size=64)
model = LitSampleConvNetClassifier()
dp_data = DPLightningDataModule(data)
trainer = pl.Trainer(
max_epochs=10,
enable_model_summary=False,
)
trainer.fit(model, dp_data)
trainer.test(model, data)
trainer.test(model, dp_... | Python | nomic_cornstack_python_v1 |
string Helpers to transform data.
from briefy.common.utils.data import Objectify
from enum import Enum
from functools import singledispatch
import colander
import datetime
import json
import typing as t
set HAS_SQLALCHEMY_UTILS = true
try
begin
from sqlalchemy_utils import Country
from sqlalchemy_utils import PhoneNumb... | """Helpers to transform data."""
from briefy.common.utils.data import Objectify
from enum import Enum
from functools import singledispatch
import colander
import datetime
import json
import typing as t
HAS_SQLALCHEMY_UTILS = True
try:
from sqlalchemy_utils import Country
from sqlalchemy_utils import PhoneNum... | Python | zaydzuhri_stack_edu_python |
function ban_from_group request
begin
return call render request string 404.html dict
end function | def ban_from_group(request):
return render(request,"404.html",{}) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
from random import *
set prob = string mst
set cases = list tuple 500 500 500 tuple 500 500 500 tuple 500 500 500 tuple 500 500 500 tuple 10000 100000 10 ^ 9 tuple 30000 100000 10 ^ 9 tuple 50000 100000 10 ^ 9 tuple 70000 100000 10 ^ 9 tuple 80000 100000 10 ^ 9 tuple 90000 100000 10 ^ 9 tuple 1... | #!/usr/bin/python
from random import *
prob = "mst"
cases = [
(500,500,500),
(500,500,500),
(500,500,500),
(500,500,500),
(10000,100000,10**9),
(30000,100000,10**9),
(50000,100000,10**9),
(70000,100000,10**9),
... | Python | zaydzuhri_stack_edu_python |
function snapshot self
begin
set snapshot_dict at string sleep = deep copy sleep
set snapshot_dict at string events = deep copy events
set snapshot_dict at string run_state = deep copy run_state
set snapshot_dict at string redo_times = deep copy redo_times
end function | def snapshot(self):
self.snapshot_dict['sleep'] = copy.deepcopy(self.sleep)
self.snapshot_dict['events'] = copy.deepcopy(self.events)
self.snapshot_dict['run_state'] = copy.deepcopy(self.run_state)
self.snapshot_dict['redo_times'] = copy.deepcopy(self.redo_times) | Python | nomic_cornstack_python_v1 |
set strings = list string hello! string hey, string where, are, you? string I am here
set strings = list comprehension replace replace replace s string , string string ? string string ! string for s in strings
print strings | strings = ['hello!', 'hey,', 'where, are, you?', 'I am here']
strings = [s.replace(",", "").replace("?", "").replace("!", "") for s in strings]
print(strings)
| Python | flytech_python_25k |
function save self fname
begin
with open fname string wb as f
begin
dump self f
end
end function | def save(self, fname):
with open(fname, 'wb') as f:
pickle.dump(self, f) | Python | nomic_cornstack_python_v1 |
function run_cmd command work_dir=none chroot=none redirect=false
begin
if chroot
begin
comment Conventions managed by the web team for the mbed.org build system
set chroot_cmd = list string /usr/sbin/chroot string --userspec=33:33 chroot
for element in command
begin
set chroot_cmd = chroot_cmd + list replace element c... | def run_cmd(command, work_dir=None, chroot=None, redirect=False):
if chroot:
# Conventions managed by the web team for the mbed.org build system
chroot_cmd = [
'/usr/sbin/chroot', '--userspec=33:33', chroot
]
for element in command:
chroot_cmd += [element.repl... | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_infarray_okarray_nannum_none_b_255 self
begin
comment The expected results.
set expected = list comprehension x * y + z for tuple x y z in zip infarrayx okarrayy repeat nannumz
comment Exceptions are turned off so we can use the results to test for correct values.
call fma infarrayx okarrayy... | def test_fma_nan_param_infarray_okarray_nannum_none_b_255(self):
# The expected results.
expected = [(x * y + z) for x,y,z in zip(self.infarrayx, self.okarrayy, itertools.repeat(self.nannumz))]
# Exceptions are turned off so we can use the results to test for correct values.
arrayfunc.fma(self.infarrayx, self.... | Python | nomic_cornstack_python_v1 |
import requests
from datetime import datetime
function fetchAlbumIds artist_id
begin
string Using the Spotify API, take an artist ID and returns a list of album IDs in a list
set url = string https://api.spotify.com/v1/artists/ + artist_id + string /albums?market=US&album_type=album
set req = get requests url
set album... | import requests
from datetime import datetime
def fetchAlbumIds(artist_id):
"""Using the Spotify API, take an artist ID and
returns a list of album IDs in a list
"""
url = "https://api.spotify.com/v1/artists/" + artist_id + "/albums?market=US&album_type=album"
req = requests.get(url)
album_dat... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
from glob import glob
import openmoltools as omt
from joblib import Parallel , delayed
from lxml import etree
import re , os , sys , logging , tempfile , shutil
class _Bond extends object
begin
string Private class representing a bond between two atoms. Supports comparisons.
functi... | from __future__ import print_function
from glob import glob
import openmoltools as omt
from joblib import Parallel, delayed
from lxml import etree
import re, os, sys, logging, tempfile, shutil
class _Bond(object):
"""
Private class representing a bond between two atoms. Supports comparisons.
"""
def ... | Python | zaydzuhri_stack_edu_python |
comment SKU CoE ITE - ParkSooYoung ###
comment Grade 2 , Semester 1 , Chapter 3 , Number 1 ###
comment 삽입 연산
function push item
begin
comment push() = append() , 리스트의 맨 뒤에 item 추가
append stack item
end function
comment top 항목 접근
function peek
begin
if length stack != 0
begin
comment top 항목 = 리스트의 맨 뒤 항목 리턴
return stack... | ### SKU CoE ITE - ParkSooYoung ###
### Grade 2 , Semester 1 , Chapter 3 , Number 1 ###
def push(item): # 삽입 연산
stack.append(item) # push() = append() , 리스트의 맨 뒤에 item 추가
def peek(): # top 항목 접근
if len(stack) != 0:
return stack[-1] # top 항목 = 리스트의 맨 뒤 항목 리턴
def pop(): ... | Python | zaydzuhri_stack_edu_python |
function update_file_metadata self files
begin
set metadata = list
for file in files
begin
set sample_id = split name string -WEX at 0
set paired_end = split split name string read at 1 string . at 0
append metadata dict string sample_id sample_id ; string paired_end paired_end
end
return updated_files
end function | def update_file_metadata(self, files):
metadata = []
for file in files:
sample_id = file.name.split("-WEX")[0]
paired_end = file.name.split("read")[1].split(".")[0]
metadata.append({"sample_id": sample_id, "paired_end": paired_end})
return SetMetadataBulk(to... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
set data = get requests string https://duta.in/news/2017/8/sitemap-index.xml
set soup = call BeautifulSoup text string xml
set p = find all soup string sitemap
for t in p
begin
print t
end | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
data = requests.get('https://duta.in/news/2017/8/sitemap-index.xml')
soup = BeautifulSoup(data.text, 'xml')
p=soup.find_all('sitemap')
for t in p:
print(t)
| Python | zaydzuhri_stack_edu_python |
function main arguments
begin
set vcf1 = arguments at index arguments string --vcf1 + 1
set vcf2 = arguments at index arguments string --vcf2 + 1
set out_file = arguments at index arguments string --out + 1
end function | def main( arguments ):
vcf1 = arguments[ arguments.index('--vcf1')+1 ]
vcf2 = arguments[ arguments.index('--vcf2')+1 ]
out_file = arguments[ arguments.index('--out')+1 ]
| Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import constants
function makeSummary
begin
set df = read csv filePath
set summary = list
set dates = call drop_duplicates
for date in values
begin
comment Date summary
set date_df = df at date == date
comment date_df = date_df.sort_values(["date","time"])
comment Check of types
... | import pandas as pd
import numpy as np
import constants
def makeSummary():
df = pd.read_csv(constants.filePath)
summary = []
dates = df.date.drop_duplicates()
for date in dates.values:
# Date summary
date_df = df[df.date == date]
#date_df = date_df.sort_values(["date","time"])
... | Python | zaydzuhri_stack_edu_python |
string This example solves a variant of the bin packing problem using IBM CP Optimizer Given: - A set of m identical items. Item size is 4-dimensional - A set of n bins with different size. Bin size is 4-dimensional - Allocation constraint: an item can be assigned to some specific bins, represented by a mxn binary matr... | """
This example solves a variant of the bin packing problem using IBM CP Optimizer
Given:
- A set of m identical items. Item size is 4-dimensional
- A set of n bins with different size. Bin size is 4-dimensional
- Allocation constraint: an item can be assigned to some specific bins,
represented by... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set rg = call default_rng 1
string a = np.floor(10 * rg.random((3, 4))) print(a) # shape: displays the dimensions of the array print(a.shape) # ravel: like flattening in wl print(a.ravel()) # sum: add the values in an axis # axis = 0: process by column print(a.sum(axis = 0)) # axis = 1: process by ro... | import numpy as np
rg = np.random.default_rng(1)
'''a = np.floor(10 * rg.random((3, 4)))
print(a)
# shape: displays the dimensions of the array
print(a.shape)
# ravel: like flattening in wl
print(a.ravel())
# sum: add the values in an axis
# axis = 0: process by column
print(a.sum(axis = 0))
# axis = 1: process b... | Python | zaydzuhri_stack_edu_python |
function multiply self value_1 value_2
begin
return value_1 * value_2
end function | def multiply(
self, value_1: Union[int,float], value_2: Union[int,float]) \
-> Union[int,float]:
return value_1 * value_2 | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Calculate the sequence identity between the sequences in an alignment
import sys
from collections import namedtuple
import numpy
import bioinfo
class DifferentLengthsError extends Exception
begin
string Used when two sequences have different lengths
pass
end class
class IncorrectOpt... | #!/usr/bin/env python3
'''
Calculate the sequence identity between the sequences in an alignment
'''
import sys
from collections import namedtuple
import numpy
import bioinfo
class DifferentLengthsError(Exception):
'''
Used when two sequences have different lengths
'''
pass
class IncorrectOptionE... | Python | zaydzuhri_stack_edu_python |
function excel_style row col
begin
set tuple quot rem = divide mod ordinal col - ordinal string A 26
return if expression quot then character quot - 1 + ordinal string A else string + character rem + ordinal string A + string row
end function | def excel_style(row, col):
quot, rem = divmod(ord(col)-ord('A'), 26)
return((chr(quot-1 + ord('A')) if quot else '') +
(chr(rem + ord('A')) + str(row))) | Python | nomic_cornstack_python_v1 |
from difflib import SequenceMatcher
set comparison_tags = list string JJR string RBR string JJS string RBS string RB
comment E.g. Which group from the census is larger: Irish or danish?
function comparison_parse_structure_1 question_parsed
begin
set res = none
set comp_idx = - 1
set sep_idx = - 1
set cc_idx = - 1
for t... | from difflib import SequenceMatcher
comparison_tags = ["JJR", "RBR", "JJS", "RBS", "RB"]
# E.g. Which group from the census is larger: Irish or danish?
def comparison_parse_structure_1(question_parsed):
res = None
comp_idx = -1
sep_idx = -1
cc_idx = -1
for token in question_parsed:
# fir... | Python | zaydzuhri_stack_edu_python |
function __init__ self homology_dimensions maximum_edge_length=inf min_persistence=none homology_coeff_field=11 **kwargs
begin
call __init__ dynamic=true keyword kwargs
set max_edge = maximum_edge_length
set dimensions = homology_dimensions
set min_persistence = if expression min_persistence is not none then min_persis... | def __init__(self, homology_dimensions, maximum_edge_length=np.inf, min_persistence=None, homology_coeff_field=11, **kwargs):
super().__init__(dynamic=True, **kwargs)
self.max_edge = maximum_edge_length
self.dimensions = homology_dimensions
self.min_persistence = min_persistence if min_p... | Python | nomic_cornstack_python_v1 |
function generate serial work_dir_path binary_path vmlinux_path config_path kcov=true reproduce=true syzhub_address=none syzhub_client=none syzhub_key=none on_cuttlefish=false
begin
set devices = dict
set devices at string devices = list serial
set data = dict
set data at string target = string linux/arm64
set data a... | def generate(serial,
work_dir_path,
binary_path,
vmlinux_path,
config_path,
kcov=True,
reproduce=True,
syzhub_address=None,
syzhub_client=None,
syzhub_key=None,
on_cuttlefish=False):
devic... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.decomposition import PCA , NMF
from sklearn.preprocessing import StandardScaler , MaxAbsScaler , MinMaxScaler , normalize , scale
from sklearn.model_selection import train_test_split
import numpy as np
from matplotlib.colors import ListedColormap
from skl... | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.decomposition import PCA, NMF
from sklearn.preprocessing import StandardScaler, MaxAbsScaler, MinMaxScaler, normalize, scale
from sklearn.model_selection import train_test_split
import numpy as np
from matplotlib.colors import ListedColormap
from sklearn.... | Python | zaydzuhri_stack_edu_python |
function test_kw_args_with_positional
begin
assert call fun_opt_kw_params string blue string red string yellow string orange == tuple string blue string red string yellow string orange
end function | def test_kw_args_with_positional():
assert arguments.fun_opt_kw_params('blue', 'red', 'yellow',
'orange') == ('blue', 'red', 'yellow',
'orange') | Python | nomic_cornstack_python_v1 |
function apply_coder text coder
begin
comment store text as individual items in list so can be mutatable
set encode = list text
for i in range length encode
begin
comment checks each char if a letter, if not won't mutate
if encode at i in keys coder
begin
comment replace letter with shifted letter
set encode at i = cod... | def apply_coder(text, coder):
#store text as individual items in list so can be mutatable
encode = list(text)
for i in range(len(encode)):
#checks each char if a letter, if not won't mutate
if encode[i] in coder.keys():
#replace letter with shifted letter
encod... | Python | nomic_cornstack_python_v1 |
function test_get_json_object_lines_for_request self
begin
function mock_logic auth age is_deleted=true
begin
pass
end function
set mock_logic = call add_doctor_attrs mock_logic
set annotation = call ResourceAnnotation mock_logic string GET
set parameters = parameters
set properties = dictionary comprehension k : annot... | def test_get_json_object_lines_for_request(self):
def mock_logic(auth: Auth, age: Age, is_deleted: IsDeleted=True):
pass
mock_logic = add_doctor_attrs(mock_logic)
annotation = ResourceAnnotation(mock_logic, 'GET')
parameters = annotation.logic._doctor_signature.parameters
... | Python | nomic_cornstack_python_v1 |
function _create_switch knx_module config
begin
return call XknxSwitch knx_module name=config at CONF_NAME group_address=config at CONF_ADDRESS group_address_state=get config CONF_STATE_ADDRESS
end function | def _create_switch(knx_module: XKNX, config: ConfigType) -> XknxSwitch:
return XknxSwitch(
knx_module,
name=config[CONF_NAME],
group_address=config[CONF_ADDRESS],
group_address_state=config.get(SwitchSchema.CONF_STATE_ADDRESS),
) | Python | nomic_cornstack_python_v1 |
function degrees2pixels bmaj bmin bpa deltax deltay
begin
set semimaj = bmaj / 2.0 * square root sin pi * bpa / 180.0 ^ 2 / deltax ^ 2 + cos pi * bpa / 180.0 ^ 2 / deltay ^ 2
set semimin = bmin / 2.0 * square root cos pi * bpa / 180.0 ^ 2 / deltax ^ 2 + sin pi * bpa / 180.0 ^ 2 / deltay ^ 2
set theta = pi * bpa / 180
r... | def degrees2pixels(bmaj, bmin, bpa, deltax, deltay):
semimaj = (bmaj / 2.) * (sqrt(
(sin(pi * bpa / 180.)**2) / (deltax**2) +
(cos(pi * bpa / 180.)**2) / (deltay**2))
)
semimin = (bmin / 2.) * (sqrt(
(cos(pi * bpa / 180.)**2) / (deltax**2) +
(sin(pi * bpa / 180.)**2) / (delta... | Python | nomic_cornstack_python_v1 |
import unittest
function calc coords fav pos=list 1 1
begin
comment TODO Dynamically generate grid, then Dijkstra's
comment Generate a grid of dimensions twice the size of target coords
comment Does not guarantee a solution every time for odd inputs,
comment but will be good enough for the problem.
set grid = call gene... | import unittest
def calc(coords, fav, pos=[1, 1]):
# TODO Dynamically generate grid, then Dijkstra's
# Generate a grid of dimensions twice the size of target coords
# Does not guarantee a solution every time for odd inputs,
# but will be good enough for the problem.
grid = generateGrid(coords, fav)
grid[pos[1]][... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
return length _stack
end function | def __len__(self):
return len(self._stack) | Python | nomic_cornstack_python_v1 |
function __get_citations self
begin
comment Replaces weird characters from html and return text
set __judgment_text = replace text string string
comment Searches through text for patterns of Capitalized words with name terms which are followed by v and further capitalized words with name terms as these suggest that it... | def __get_citations(self):
# Replaces weird characters from html and return text
self.__judgment_text = self.__search_results.text.replace('\xa0','')
# Searches through text for patterns of Capitalized words with name terms which are followed by v and further capitalized words with name... | Python | nomic_cornstack_python_v1 |
from tkinter import *
from functools import partial
global ROWS
global COLUMNS
global canvas
global mainWindow
global currentCol
global haveNew
set SQUARE_SIZE = 60
set COIN_RADIUS = 0.8 * SQUARE_SIZE / 2
set BOARD_PADDING = 10
set BUTTON_MARGING = 10
set LARGE_FONT = tuple string Verdana 12
set NORM_FONT = tuple strin... | from tkinter import *
from functools import partial
global ROWS
global COLUMNS
global canvas
global mainWindow
global currentCol
global haveNew
SQUARE_SIZE = 60
COIN_RADIUS = 0.8 * SQUARE_SIZE / 2
BOARD_PADDING = 10
BUTTON_MARGING = 10
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
S... | Python | zaydzuhri_stack_edu_python |
function add_annotation self annotation
begin
add annotations annotation
end function | def add_annotation(self, annotation):
self.annotations.add(annotation) | Python | nomic_cornstack_python_v1 |
comment %%
comment Problem: 02
comment importing cv2
import cv2
comment Using cv2.imread() method
set img = call imread string 4_2.bmp
comment Displaying the image using cv2.imshow()
image show string Original Image img
comment Maintain output window until user presses a key
call waitKey 0
call destroyAllWindows
commen... | #%%
#Problem: 02
#importing cv2
import cv2
# Using cv2.imread() method
img = cv2.imread('4_2.bmp')
# Displaying the image using cv2.imshow()
cv2.imshow('Original Image', img)
#Maintain output window until user presses a key
cv2.waitKey(0)
cv2.destroyAllWindows()
# %%
img1= img[:, :, 0]
img2= img[:, :, 1]
... | Python | zaydzuhri_stack_edu_python |
function save self
begin
set propertyFilter = POST at string propertyId != string false and POST at string propertyId or none
set userId = POST at string userId
set fname = strip POST at string fname
set lname = strip POST at string lname
set email = strip POST at string email
set phone = strip POST at string phone
set... | def save(self):
propertyFilter = request.POST['propertyId'] != 'false' and request.POST['propertyId'] or None
userId = request.POST['userId']
fname = request.POST['fname'].strip()
lname = request.POST['lname'].strip()
email = request.POST['email'].strip()
phone = request... | Python | nomic_cornstack_python_v1 |
comment 직선식 이용한 판별
if x1 != x2
begin
if round y2 - y1 / x2 - x1 * x3 - x1 + y1 1 < y3
begin
if x2 > x1
begin
print 1
end
else
if x2 < x1
begin
print - 1
end
else
begin
print 0
end
end
else
if round y2 - y1 / x2 - x1 * x3 - x1 + y1 1 > y3
begin
if x2 > x1
begin
print - 1
end
else
if x2 < x1
begin
print 1
end
else
begin
... | #직선식 이용한 판별
if x1!=x2:
if round((y2-y1)/(x2-x1)*(x3-x1)+y1,1)<y3:
if x2>x1:
print(1)
elif x2<x1:
print(-1)
else:
print(0)
elif round((y2-y1)/(x2-x1)*(x3-x1)+y1,1)>y3:
if x2>x1:
print(-1)
elif x2<x1:
... | Python | zaydzuhri_stack_edu_python |
import discord
from discord.ext import commands
import re
class Util
begin
function __init__ self client
begin
set client = client
end function
decorator call command
async function ping self
begin
await call say string Pong!
end function
decorator call command
async function say self arg
begin
await call say arg
end f... | import discord
from discord.ext import commands
import re
class Util:
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self):
await self.client.say('Pong!')
@commands.command()
async def say(self, *, arg):
await self.client.say(arg)
@commands.command(pass_context=Tr... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import math , collections , itertools
from collections import deque as dq
from sys import stdin
function readValue valueType
begin
return call valueType read line stdin
end function
class Mouth
begin
set count = 1
decorator classmethod
function answer cls answer
begin
print format string C... | #!/usr/bin/env python3
import math, collections, itertools
from collections import deque as dq
from sys import stdin
def readValue(valueType):
return valueType(stdin.readline())
class Mouth():
count = 1
@classmethod
def answer(cls, answer):
print("Case #{}: {}".format(cls.count, answer))
... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
class Solution
begin
function largestNumber self cost target
begin
set memo = default dictionary lambda -> decimal string -inf
set table = dict
for tuple i c in enumerate cost
begin
set table at c = i
end
function dp target
begin
if target < 0
begin
return decimal string -inf
end
i... | from collections import defaultdict
class Solution:
def largestNumber(self, cost, target):
memo = defaultdict(lambda: float('-inf'))
table = {}
for i, c in enumerate(cost):
table[c] = i
def dp(target):
if target < 0:
return float('... | Python | zaydzuhri_stack_edu_python |
from Tkinter import *
set form = call Tk
set title = string Add New Stock
call Label form text=string Add new Stock font=string Lato 20
set stock_symbol = call Label form text=string Stock font=string Lato 15 fg=string White bg=string Black
grid row=0 column=0
set number_of_units = call Label form text=string Number of... | from Tkinter import *
form = Tk()
form.title=("Add New Stock")
Label(form , text="Add new Stock" , font = "Lato 20")
stock_symbol = Label(form , text= "Stock" , font = "Lato 15" , fg = 'White', bg='Black')
stock_symbol.grid(row=0,column=0)
number_of_units = Label(form , text= "Number of stocks" , font = "La... | Python | zaydzuhri_stack_edu_python |
from utils import Eval
function test_eval1
begin
set e = eval
assert eval string 1+1 == string 2
assert eval string 1+1 == string 2
assert eval string a=1+1 == string
assert eval string a=1+1 == string
assert eval string a=1+1 a == string 2
assert eval string a=1+1 a == string 2
assert eval string a=1+1 a=3 == string... | from utils import Eval
def test_eval1():
e = Eval()
assert e.eval("1+1") == "2"
assert e.eval("1+1\n") == "2"
assert e.eval("a=1+1") == ""
assert e.eval("a=1+1\n") == ""
assert e.eval("a=1+1\na") == "2"
assert e.eval("a=1+1\na\n") == "2"
assert e.eval("a=1+1\na=3") == ""
assert e.ev... | Python | zaydzuhri_stack_edu_python |
class Message extends object
begin
function __init__ self type obj
begin
set type = type
set obj = obj
end function
function __unicode__ self
begin
return string message: %s %s % tuple type obj
end function
function __str__ self
begin
return string call __unicode__
end function
end class | class Message(object):
def __init__(self, type, obj):
self.type = type
self.obj = obj
def __unicode__(self):
return u"message: %s %s"%(self.type, self.obj)
def __str__(self):
return str(self.__unicode__()) | Python | zaydzuhri_stack_edu_python |
function get_link_data_from_soup soup
begin
set link_data = list
if soup == none
begin
return list none none
end
set link = get soup string href
set text = text
if link is not none
begin
set link = strip link
end
if text is not none
begin
set text = strip text
end
append link_data link
append link_data text
return lin... | def get_link_data_from_soup(soup):
link_data = []
if soup == None:
return [None, None]
link = soup.get('href')
text = soup.text
if link is not None:
link = link.strip()
if text is not None:
text = text.strip()
link_data.append(link)
link_data.append(text)... | Python | nomic_cornstack_python_v1 |
function test_format_p_value_for_num_iters self
begin
assert equal call format_p_value_for_num_iters 0.119123123123 100 string 0.12
assert equal call format_p_value_for_num_iters 0.119123123123 250 string 0.12
assert equal call format_p_value_for_num_iters 0.119123123123 1000 string 0.119
comment test num_iters too low... | def test_format_p_value_for_num_iters(self):
self.assertEqual(\
format_p_value_for_num_iters(0.119123123123,100),"0.12")
self.assertEqual(\
format_p_value_for_num_iters(0.119123123123,250),"0.12")
self.assertEqual(\
format_p_value_for_num_iters(0.119123123123,1000),"0.... | Python | nomic_cornstack_python_v1 |
string Fval1 and fval2 Timothy A. Gibbons
function fval1
begin
set yearly = decimal input string Enter the yearly investment:
set apr = decimal input string Enter the annual interest rate:
set years = integer input string Enter the number of years:
for i in range years
begin
set yearly = yearly * 1 + apr
end
print stri... | '''
Fval1 and fval2
Timothy A. Gibbons
'''
def fval1():
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
for i in range(years):
yearly = yearly * (1+apr)
print ("The value in ",years," years is: %... | Python | zaydzuhri_stack_edu_python |
comment https://codingforspeed.com/how-many-ones-between-number-1-to-n/
class Solution extends object
begin
function countDigitOne self n
begin
string :type n: int :rtype: int
if n == 0
begin
return 0
end
if n < 10
begin
return 1
end
set count = 0
set highest = n
set weight = 1
while highest >= 10
begin
set highest = h... | # https://codingforspeed.com/how-many-ones-between-number-1-to-n/
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if (n == 0):
return 0
if (n < 10):
return 1
count = 0
highest ... | Python | zaydzuhri_stack_edu_python |
import csv
from janome.tokenizer import Tokenizer
from janome.analyzer import Analyzer
from janome.charfilter import *
from janome.tokenfilter import *
set output = open string wakati.txt string w newline=string
set char_filters = list call UnicodeNormalizeCharFilter
set token_filters = list call POSKeepFilter list str... | import csv
from janome.tokenizer import Tokenizer
from janome.analyzer import Analyzer
from janome.charfilter import *
from janome.tokenfilter import *
output = open('wakati.txt', 'w', newline="\n")
char_filters = [UnicodeNormalizeCharFilter()]
token_filters = [
POSKeepFilter(['名詞']),
LowerCaseFilter(),
... | Python | zaydzuhri_stack_edu_python |
function def_show_all_parser s_parser
begin
comment show all volumes all details
set show_all_parser = call add_parser string show-all description=string Show all volumes with details in this availability domain. help=string Show all volumes with details in this availability domain.
call add_argument string -t string -... | def def_show_all_parser(s_parser):
#
# show all volumes all details
show_all_parser = s_parser.add_parser('show-all',
description='Show all volumes with details in this availability domain.',
help='Show all volumes with deta... | Python | nomic_cornstack_python_v1 |
function is_playing self
begin
return _is_playing
end function | def is_playing(self) -> bool:
return self._is_playing | Python | nomic_cornstack_python_v1 |
import os , datetime , json , requests
from dotenv import load_dotenv
from pymongo import MongoClient
import enricher , presenter , exporter
import argparse
import bson.json_util
call load_dotenv
comment WELCOME MESSAGE
call say_hi
function parserFunction
begin
comment 02 - INSTRUCTIONS AND ARGUMENTS
set parser = call ... | import os, datetime, json, requests
from dotenv import load_dotenv
from pymongo import MongoClient
import enricher, presenter, exporter
import argparse
import bson.json_util
load_dotenv()
presenter.say_hi() # WELCOME MESSAGE
def parserFunction():
# 02 - INSTRUCTIONS AND ARGUMENTS
parser = argparse.ArgumentPa... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import tkinter.ttk as ttk
set root = call Tk
title root string Nado GUI
comment 파일 프레임
set file_frame = call Frame root
call pack fill=string x padx=5 pady=5
set btn_add_file = call Button file_frame padx=5 pady=5 width=12 text=string 파일추가
call pack side=string left
set btn_del_file = call Button ... | from tkinter import *
import tkinter.ttk as ttk
root = Tk()
root.title('Nado GUI')
# 파일 프레임
file_frame = Frame(root)
file_frame.pack(fill='x',padx=5,pady=5)
btn_add_file = Button(file_frame,padx=5,pady=5,width=12,text='파일추가')
btn_add_file.pack(side='left')
btn_del_file = Button(file_frame,padx=5,pady=5,width=12,te... | Python | zaydzuhri_stack_edu_python |
function word_statistics my_file word2
begin
function get_key value
begin
for tuple k v in items dictionary
begin
if v == value
begin
return k
end
end
end function
set text = open my_file string r
set dictionary = dict
set top_twenty_freq = list
set top_twenty_word = list
set a = read text
set a = lower a
set a = sp... | def word_statistics(my_file, word2):
def get_key(value):
for k, v in dictionary.items():
if v == value:
return k
text = open(my_file, 'r')
dictionary = {}
top_twenty_freq = []
top_twenty_word = []
a = text.read()
a = a.lower()
a = a.split()
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
from util import get_data , plot_data
function compute_daily_returns
begin
set daily_returns = copy df
set daily_returns at slice 1 : : = df at slice 1 : : / values - 1
set ix at tuple 0 slice : : = 0
return daily_returns
end function
function test_run
begin
se... | import pandas as pd
import matplotlib.pyplot as plt
from util import get_data, plot_data
def compute_daily_returns():
daily_returns = df.copy()
daily_returns[1:] = (df[1:]/df[:-1].values) - 1
daily_returns.ix[0,:] = 0
return daily_returns
def test_run():
dates=pd.date_range('2009-01-01','2012,12,31')
symbols ... | Python | zaydzuhri_stack_edu_python |
from pylatex import Document , Section , Subsection , Command , Package , MiniPage , Center
from pylatex.utils import NoEscape , bold
from pylatex.math import Math
function gera_titulo titulo subtitulo=none
begin
return call NoEscape string \textbf{ + titulo + string } + if expression subtitulo then string \\\Large + s... | from pylatex import Document, Section, Subsection, Command, Package, MiniPage, Center
from pylatex.utils import NoEscape, bold
from pylatex.math import Math
def gera_titulo(titulo, subtitulo = None):
return NoEscape(r'\textbf{'+titulo+r'}' + ((r'\\\Large '+subtitulo) if subtitulo else r''))
class DefineColor(Comm... | Python | zaydzuhri_stack_edu_python |
function beat_track input_file output_csv
begin
string Beat tracking function :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save beat event timestamps as a CSV file
print string Loading input_file
set tuple y sr = load librosa input_file sr=22050
commen... | def beat_track(input_file, output_csv):
'''Beat tracking function
:parameters:
- input_file : str
Path to input audio file (wav, mp3, m4a, flac, etc.)
- output_file : str
Path to save beat event timestamps as a CSV file
'''
print('Loading ', input_file)
y, sr = lib... | Python | jtatman_500k |
function __contains__ self item
begin
from Movie import Movie
from Character import Character
if is instance item Movie
begin
for m in flatten data yieldDictKeys=1 scalar=Movie
begin
if call isSame m
begin
return 1
end
end
end
else
if is instance item Character
begin
for m in flatten data yieldDictKeys=1 scalar=Movie
b... | def __contains__(self, item):
from Movie import Movie
from Character import Character
if isinstance(item, Movie):
for m in flatten(self.data, yieldDictKeys=1, scalar=Movie):
if item.isSame(m):
return 1
elif isinstance(item, Character... | Python | nomic_cornstack_python_v1 |
comment Meter attributo nuevo en {MasterKSU.html:[], KASware3.py: [ksu_type_attributes, attributes_guide], KASware3app.js: [ksu_type_attributes, attributes_guide],}
set ksu_types = list list list string Action string Action list list string Proactive string Proactive true list string Reactive string Reactive string li... | # Meter attributo nuevo en {MasterKSU.html:[], KASware3.py: [ksu_type_attributes, attributes_guide], KASware3app.js: [ksu_type_attributes, attributes_guide],}
ksu_types = [
#Actions
[['Action', 'Action'], [
['Proactive', 'Proactive', True],
['Reactive', 'Reactive', ''],
# ['Negative', 'Negative', '']
]],
... | Python | zaydzuhri_stack_edu_python |
set a = string banana
set b = string banana
print a is b | a = "banana"
b = "banana"
print(a is b)
| Python | zaydzuhri_stack_edu_python |
function test_creation_set_none_get_none
begin
set value = 11
set num_a = call Integer value=value
assert call get_soft_bounds == list none none
end function | def test_creation_set_none_get_none():
value = 11
num_a = param.Integer(value=value)
assert num_a.get_soft_bounds() == [None, None] | Python | nomic_cornstack_python_v1 |
function get_card_async callback error_callback id
begin
function server_call callback error_callback id
begin
string Internal closure to thread this call. :param callback: Function that consumes the data (a Card) returned on success. :type callback: function :param error_callback: Function that consumes the exception ... | def get_card_async(callback, error_callback, id):
def server_call(callback, error_callback, id):
"""
Internal closure to thread this call.
:param callback: Function that consumes the data (a Card) returned on success.
:type callback: function
:param error_callback: Function ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Feb 24 15:04:17 2019 @author: dev 67. Add Binary Easy Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output:... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 15:04:17 2019
@author: dev
67. Add Binary
Easy
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Exa... | Python | zaydzuhri_stack_edu_python |
function process_command_line
begin
set parser = call ArgumentParser string %s v%s - This script provides information on shipping routes. % tuple call get_script_name call get_version
call add_argument string -l string --log-filename dest=string log_filename help=string Specify the output log filename. default=none
set... | def process_command_line():
parser = argparse.ArgumentParser(
"%s v%s - This script provides information on shipping routes." % (get_script_name(), get_version()))
parser.add_argument("-l", "--log-filename", dest="log_filename", help="Specify the output log filename.",
default=No... | Python | nomic_cornstack_python_v1 |
function sub iter_a iter_b
begin
return list comprehension a - b for tuple a b in call zip_longest iter_a iter_b fillvalue=0
end function | def sub(iter_a, iter_b):
return [a - b for a, b in zip_longest(iter_a, iter_b, fillvalue=0)] | Python | nomic_cornstack_python_v1 |
function print_solution manager routing solution
begin
print format string Objective: {} miles call ObjectiveValue
set index = start routing 0
set plan_output = string Route for vehicle 0:
set route_distance = 0
while not call IsEnd index
begin
set plan_output = plan_output + format string {} -> call IndexToNode index
... | def print_solution(manager, routing, solution):
print('Objective: {} miles'.format(solution.ObjectiveValue()))
index = routing.Start(0)
plan_output = 'Route for vehicle 0:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} ->'.format(manager.IndexToNode(index))
previous_index = ... | Python | nomic_cornstack_python_v1 |
import numpy as np
import os
set train_transcripts = load np get current directory + string /data/train_transcripts.npy encoding=string bytes
set dev_transcripts = load np get current directory + string /data/dev_transcripts.npy encoding=string bytes
set label_map = dict 0 string ; 1 string ' ; 2 string + ; 3 string -... | import numpy as np
import os
train_transcripts = np.load(os.getcwd() + "/data/train_transcripts.npy", encoding='bytes')
dev_transcripts = np.load(os.getcwd() + "/data/dev_transcripts.npy", encoding='bytes')
label_map = {0: ' ', 1: "'", 2: '+', 3: '-', 4: '.', 5: 'A', 6: 'B', 7: 'C', 8: 'D', 9: 'E', 10: 'F', 11: 'G',... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
function parse_firewall input_
begin
set scanners = call splitlines
return list comprehension list map int split line string : for line in scanners
end function
function get_min_delay firewall
begin
set delay = 0
while call is_costly firewall delay
begin
set delay = delay + 1
end
return de... | # -*- coding: utf-8 -*-
def parse_firewall(input_):
scanners = input_.splitlines()
return [list(map(int, line.split(':'))) for line in scanners]
def get_min_delay(firewall):
delay = 0
while is_costly(firewall, delay):
delay += 1
return delay
def is_costly(firewall, delay):
for dept... | Python | zaydzuhri_stack_edu_python |
function smart_home
begin
set users = string security of user accounts
set dev = string owning the network devices
set architecture = string compromising architecture
print string all potential risks
end function | def smart_home():
users = 'security of user accounts'
dev = 'owning the network devices'
architecture = 'compromising architecture'
print('all potential risks') | Python | nomic_cornstack_python_v1 |
string Problem 2 10.0/10.0 points (graded) Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2
comment Paste your code into this box
set tuple c... | """
Problem 2
10.0/10.0 points (graded)
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
"""
# Paste your code into this box
count, occur ... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
from flask import Flask , json , jsonify , request
from sqlalchemy import func
from models import Weather , app , db
from weather_data import city_ids , api_key
from lib import percent , commit_psql , get_data
import requests
decorator call route string / methods=list string GET string POS... | from datetime import datetime
from flask import Flask, json, jsonify, request
from sqlalchemy import func
from models import Weather, app, db
from weather_data import city_ids, api_key
from lib import percent, commit_psql, get_data
import requests
@app.route('/', methods=['GET', 'POST'])
def weather_api():
if(r... | Python | zaydzuhri_stack_edu_python |
function extract_feature x y is_train=false feature_type=string MFCC
begin
set start_time = call get_time
print format string Extract {} feature... feature_type
set feature = list
set train_data = dict
for i in call tqdm range length x
begin
comment extract mfcc feature based on psf, you can look more detail on psf's... | def extract_feature(x, y, is_train=False, feature_type='MFCC'):
start_time = get_time()
print("Extract {} feature...".format(feature_type))
feature = []
train_data = {}
for i in tqdm(range(len(x))):
# extract mfcc feature based on psf, you can look more detail on psf's website.
if fe... | Python | nomic_cornstack_python_v1 |
with open 0 as f
begin
set tuple N *lr = map int split read f
end
print sum lr at slice 1 : : 2 - sum lr at slice : : 2 + N | with open(0) as f:
N, *lr = map(int, f.read().split())
print(sum(lr[1::2])-sum(lr[::2])+N) | Python | zaydzuhri_stack_edu_python |
string Conditional Basics Q1 a) prompt the user for a day of the week, print out whether the day is Monday or not b) prompt the user for a day of the week, print out whether the day is a weekday or a weekend c) create variables and make up values for the number of hours worked in one week the hourly rate how much the w... | ''' Conditional Basics
Q1 a) prompt the user for a day of the week, print out whether the day is Monday or not
b) prompt the user for a day of the week, print out whether the day is a weekday or a weekend
c) create variables and make up values for
the number of hours worked in one week
the hourly rate
how much the ... | Python | zaydzuhri_stack_edu_python |
function restore_ts self kube_apis transport_server_tls_passthrough_setup
begin
set ts_std_src = string { TEST_DATA } /transport-server-tls-passthrough/standard/transport-server.yaml
set ts_std_res = call create_ts_from_yaml custom_objects ts_std_src namespace
call wait_before_test 1
call pprint ts_std_res
end function | def restore_ts(self, kube_apis, transport_server_tls_passthrough_setup) -> None:
ts_std_src = f"{TEST_DATA}/transport-server-tls-passthrough/standard/transport-server.yaml"
ts_std_res = create_ts_from_yaml(
kube_apis.custom_objects,
ts_std_src,
transport_server_tls_pa... | Python | nomic_cornstack_python_v1 |
from skimage.morphology import skeletonize
import sknw
import numpy as np
import matplotlib.pyplot as plt
import cv2
from characteristic import Characteristic
import os
function eachFile filepath
begin
set file_path_array = list
set pathDir = list directory filepath
for allDir in pathDir
begin
set child = join path st... | from skimage.morphology import skeletonize
import sknw
import numpy as np
import matplotlib.pyplot as plt
import cv2
from characteristic import Characteristic
import os
def eachFile(filepath):
file_path_array = []
pathDir = os.listdir(filepath)
for allDir in pathDir:
child = os.path.join('%s%s' % ... | Python | zaydzuhri_stack_edu_python |
function deallocateFlag self pluginName flag
begin
pass
end function | def deallocateFlag(self, pluginName, flag):
pass | Python | nomic_cornstack_python_v1 |
function build_graph_from_input self input_node
begin
with device device
begin
with call as_default
begin
with call variable_scope string label_placeholders as scope
begin
set label_placeholder = call placeholder float32 shape=label_shape name=string input_labels
end
with call variable_scope string placeholders as scop... | def build_graph_from_input(self, input_node):
with tf.device(self.params.device):
with self.graph.as_default():
with tf.compat.v1.variable_scope("label_placeholders") as scope:
self.label_placeholder = tf.compat.v1.placeholder(tf.float32, shape=self.label_shape,
name="input_label... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Apr 17 10:15:03 2019 @author: GAllison This module is used to read all the raw data in from a FracFocus excel zip file Input is simply the name of the archive file. We expect that file to be in the "sources" directory of the parent folder. All variables are read into ... | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 10:15:03 2019
@author: GAllison
This module is used to read all the raw data in from a FracFocus excel zip file
Input is simply the name of the archive file. We expect that file to be
in the "sources" directory of the parent folder.
All variables are read into the ... | Python | zaydzuhri_stack_edu_python |
from rbf import RBF
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import math
from cl import CL
function generateData noisy sigma
begin
set data = array range 0 2 * pi 0.2
if noisy
begin
set data = data + randn shape at 0 * sigma
end
set data = reshape np data tuple shape at 0 1
return dat... | from rbf import RBF
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import math
from cl import CL
def generateData(noisy,sigma):
data = np.arange(0,2*math.pi,0.2)
if noisy:
data=data+np.random.randn(data.shape[0])*sigma
data=np.reshape(data,(data.shape[0],1))
return... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import os
import re
import sys
import json
import linecache
call reload sys
call setdefaultencoding string utf8
function write2file file_name content
begin
set file_object = open file_name string a
write file_object content
close file_object
end function
function extract_ratio desc
begin
se... | # -*- coding:utf-8 -*-
import os
import re
import sys
import json
import linecache
reload(sys)
sys.setdefaultencoding('utf8')
def write2file(file_name, content):
file_object = open(file_name, 'a')
file_object.write(content)
file_object.close()
def extract_ratio(desc):
pattern = re.compile(r'(\d+%)')
match = ... | Python | zaydzuhri_stack_edu_python |
function get_all_subclasses cls
begin
set all_subclasses = list
for subclass in call __subclasses__
begin
append all_subclasses subclass
extend all_subclasses call get_all_subclasses subclass
end
return all_subclasses
end function | def get_all_subclasses(cls):
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses | Python | nomic_cornstack_python_v1 |
import re
import fileinput
import sys
import json
function process_line_regex line regex
begin
string Process a flat file line and returns matches with the input regex Arguments: line {string} -- input line from flat file regex {compiled regex} -- input compiled regex to search against Returns: {string} -- string match... | import re
import fileinput
import sys
import json
def process_line_regex(line, regex):
"""Process a flat file line and returns matches with the input regex
Arguments:
line {string} -- input line from flat file
regex {compiled regex} -- input compiled regex to search against
Retur... | Python | zaydzuhri_stack_edu_python |
from scipy.integrate import dblquad
from math import cos , sin , pi , sqrt
function integrand n1 n2 k1 k2 t
begin
set p1 = cos n1 * k1 * cos n2 * k2
set p2 = 3 / square root 1 + 4 * cos k1 ^ 2 + 4 * cos k1 * cos k2
set p3 = - p2
return p1 * p2 ^ t + p3 ^ t
end function
comment even t
print call dblquad lambda y x -> ca... | from scipy.integrate import dblquad
from math import cos, sin, pi, sqrt
def integrand(n1, n2, k1, k2, t):
p1 = cos(n1*k1)*cos(n2*k2)
p2 = 3 / sqrt(1 + 4*((cos(k1)**2)) + 4*(cos(k1)*cos(k2)))
p3 = -p2
return p1*((p2**t) + (p3**t))
#even t
print(dblquad(lambda y, x: integrand(1,1,x,y,10), -p... | Python | zaydzuhri_stack_edu_python |
function test_calls_finder_options self
begin
class Test extends Base
begin
set foo = call Scope where=string foo
end class
set rel = call foo
assert equal type rel Relation
assert equal query rel dict string where list string foo
end function | def test_calls_finder_options(self):
class Test(pyperry.base.Base):
foo = Scope(where='foo')
rel = Test.foo()
self.assertEqual(type(rel), pyperry.relation.Relation)
self.assertEqual(rel.query(), { 'where': ['foo'] }) | Python | nomic_cornstack_python_v1 |
function push_right grid
begin
set newgrid = list
comment get the "minigrid"
for x in range 4
begin
set temp = list
for y in range 4
begin
append temp grid at x at y
end
comment remove zeroes
for i in range 4 at slice : : - 1
begin
if i >= 0
begin
if temp at i == 0
begin
del temp at i
end
end
end
comment add the va... | def push_right (grid):
newgrid = []
#get the "minigrid"
for x in range(4):
temp = []
for y in range(4):
temp.append(grid[x][y])
#remove zeroes
for i in range(4)[::-1]:
if i >= 0:
if temp[i] == 0:
... | 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.