code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_classifier self
begin
return model
end function | def get_classifier(self):
return self.model | Python | nomic_cornstack_python_v1 |
comment Multiples of 3 and 5
comment Problem 1
comment If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9.
comment The sum of these multiples is 23.
comment Find the sum of all the multiples of 3 or 5 below 1000.
function main
begin
call naive 1000
call functional_sum 1000
e... | # Multiples of 3 and 5
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def main():
naive(1000)
functional_sum(1000)
def series_function(multiple, limit):
n... | Python | zaydzuhri_stack_edu_python |
function execute_ssm_automation ssm_document ssm_document_name cfn_output_params cfn_installed_alarms ssm_test_cache ssm_input_parameters
begin
set parameters = call parse_input_parameters cfn_output_params cfn_installed_alarms ssm_test_cache ssm_input_parameters
set execution_id = execute ssm_document ssm_document_nam... | def execute_ssm_automation(ssm_document, ssm_document_name, cfn_output_params, cfn_installed_alarms, ssm_test_cache,
ssm_input_parameters):
parameters = ssm_document.parse_input_parameters(cfn_output_params, cfn_installed_alarms, ssm_test_cache,
... | Python | nomic_cornstack_python_v1 |
function findTag bufferNumber changedTick
begin
comment DOC {{{
comment }}}
comment CODE {{{
comment try to find the best tag {{{
try
begin
comment get the tags data for the current buffer
set tuple tagLineNumbers tags = call getTags bufferNumber changedTick
comment link to vim's internal data {{{
set currentBuffer = b... | def findTag(bufferNumber, changedTick):
# DOC {{{
# }}}
# CODE {{{
# try to find the best tag {{{
try:
# get the tags data for the current buffer
tagLineNumbers, tags = getTags(bufferNumber, changedTick)
# link to vim's internal data {{{
currentBuffer = vim.current.... | Python | nomic_cornstack_python_v1 |
function _newIdentifier self
begin
string Make a new identifier for an as-yet uncreated model object. @rtype: C{int}
set id = call _allocateID
set _idsToObjects at id = _NO_OBJECT_MARKER
set _lastValues at id = none
return id
end function | def _newIdentifier(self):
"""
Make a new identifier for an as-yet uncreated model object.
@rtype: C{int}
"""
id = self._allocateID()
self._idsToObjects[id] = self._NO_OBJECT_MARKER
self._lastValues[id] = None
return id | Python | jtatman_500k |
class Calculator
begin
function add self num1 num2
begin
set num1_total = call total_number_by_digits num1
set num2_total = call total_number_by_digits num2
return num1_total + num2_total
end function
function substraction self num1 num2
begin
set num1_total = call total_number_by_digits num1
set num2_total = call tota... | class Calculator:
def add(self, num1: int, num2: int) -> int:
num1_total = self.total_number_by_digits(num1)
num2_total = self.total_number_by_digits(num2)
return num1_total + num2_total
def substraction(self, num1: int, num2: int) -> int:
num1_total = self.total_number_by_digit... | Python | zaydzuhri_stack_edu_python |
import gi
call require_version string Gtk string 3.0
from gi.repository import GLib , Gtk , GObject
call require_version string GdkX11 string 3.0
import question
class SettingsWindow extends Window
begin
function __init__ self parent cur_questions cur_time
begin
set cur_questions = cur_questions
set parent = parent
cal... | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, GObject
gi.require_version('GdkX11', '3.0')
import question
class SettingsWindow(Gtk.Window):#
def __init__(self, parent, cur_questions, cur_time):
self.cur_questions = cur_questions
self.parent = parent
G... | Python | zaydzuhri_stack_edu_python |
async function sendmessage bot channel sender args
begin
if length args == 0
begin
return string Usage: + commandPrefix + string groupadd <groupname> <nickname> <phonenumber>
end
if not call get_group args at 0
begin
await call message channel string Group not found: { args at 0 }
return
end
call send_to_group args at ... | async def sendmessage(bot: fido, channel: str, sender: str, args: List[str]):
if len(args) == 0:
return "Usage: " + IRC.commandPrefix + "groupadd <groupname> <nickname> <phonenumber>"
if not get_group(args[0]):
await bot.message(channel, f"Group not found: {args[0]}")
return
send_to_... | Python | nomic_cornstack_python_v1 |
function get_worker self
begin
if _worker is none
begin
set _worker = get Worker db worker_id
end
return _worker
end function | def get_worker(self) -> Worker:
if self._worker is None:
self._worker = Worker.get(self.db, self.worker_id)
return self._worker | Python | nomic_cornstack_python_v1 |
function warn_if_chunking_would_increase_performance ds crit_size_in_MB=100
begin
set nbytes_in_MB = nbytes / 1024 ^ 2
if not call is_dask_collection ds
begin
if nbytes_in_MB > crit_size_in_MB and NCPU >= 4
begin
warn string Consider chunking input `ds` along other dimensions than needed by algorithm, e.g. spatial dime... | def warn_if_chunking_would_increase_performance(ds, crit_size_in_MB=100):
nbytes_in_MB = ds.nbytes / (1024 ** 2)
if not dask.is_dask_collection(ds):
if nbytes_in_MB > crit_size_in_MB and NCPU >= 4:
warnings.warn(
"Consider chunking input `ds` along other dimensions than "
... | Python | nomic_cornstack_python_v1 |
if N == 0
begin
print string { 1 }
end
else
begin
set l = list 1
for i in range 2 N + 1
begin
append l i * l at i - 2
end
set r = list comprehension 1 / i for i in l
print string { sum r + 1 }
end | if N == 0:
print(f"{1:.8f}")
else:
l = [1]
for i in range(2, N+1):
l.append(i*l[i-2])
r = [1/i for i in l]
print(f"{sum(r)+1:.8f}")
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
function cache_decorator original_function
begin
comment Реализовать декоратор который кэширует результаты вызова функции (есть в лекции)
comment Применить для функции calculator (в calculator.py уже есть import функции cache_decorator)
comment Настоятельно прошу н... | #!/usr/bin/python
# -*- coding: utf-8 -*-
def cache_decorator(original_function):
# Реализовать декоратор который кэширует результаты вызова функции (есть в лекции)
# Применить для функции calculator (в calculator.py уже есть import функции cache_decorator)
# Настоятельно прошу написать декоратор руками, а ... | Python | zaydzuhri_stack_edu_python |
function item_from_party request
begin
set result = item user POST at string sku
return call JSONHttpResponse result
end function | def item_from_party(request):
result = item( request.user, request.POST['sku'] )
return JSONHttpResponse(result) | Python | nomic_cornstack_python_v1 |
from os import walk , path
import hashlib
import sys
function get_hash file_name
begin
with open file_name string rb as f
begin
set file_hash = md5
while chunk := read f 8192
begin
update file_hash chunk
end
return hex digest file_hash
end
end function
function get_size file_name
begin
return get size path file_name
en... | from os import walk, path
import hashlib
import sys
def get_hash(file_name):
with open(file_name, "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
return file_hash.hexdigest()
def get_size(file_name):
return path.get... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from sys import argv
import math
from matplotlib import pyplot as plt
function random_ric k n
begin
string Initialized by ric
set prob = zeros tuple n k
for i in range n
begin
set a = random 3
set a = a / sum
set prob at i = a
end
return prob
end function
function gmm ric data k n d sigma
begin
strin... | import numpy as np
from sys import argv
import math
from matplotlib import pyplot as plt
def random_ric(k,n):
'''
Initialized by ric
'''
prob =np.zeros((n,k))
for i in range(n):
a = np.random.random(3)
a /= a.sum()
prob[i]= a
return prob
def gmm(ric,data,k,n,d,sigma):
'''
Gaussian Mixture Model and EM... | Python | zaydzuhri_stack_edu_python |
function disabled self
begin
return get pulumi self string disabled
end function | def disabled(self) -> bool:
return pulumi.get(self, "disabled") | Python | nomic_cornstack_python_v1 |
function in_trash self in_trash
begin
set _in_trash = in_trash
end function | def in_trash(self, in_trash):
self._in_trash = in_trash | Python | nomic_cornstack_python_v1 |
import cv2
import os
import time
import numpy as np
import matplotlib
set colorList = list
for tuple subdir dirs files in walk string ../Resources/Bullets
begin
for filename in files
begin
set filepath = subdir + sep + filename
if ends with filepath string .jpg or ends with filepath string .png
begin
print filepath
en... | import cv2
import os
import time
import numpy as np
import matplotlib
colorList = []
for subdir, dirs, files in os.walk("../Resources/Bullets"):
for filename in files:
filepath = subdir + os.sep + filename
if filepath.endswith(".jpg") or filepath.endswith(".png"):
print(filepath)
... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
function function1
begin
print string Menu item clicked
end function
set root = call Tk
comment main menu
set mymenu = call Menu root
comment tells python this is the menu we are using right now
call config menu=mymenu
comment passing submenu into the main menu
set submenu = call Menu mymenu
set s... | from tkinter import *
def function1():
print("Menu item clicked")
root = Tk()
mymenu = Menu(root) # main menu
root.config(menu=mymenu) # tells python this is the menu we are using right now
submenu = Menu(mymenu) # passing submenu into the main menu
submenu2 = Menu(mymenu)
mymenu.add_cascade(label="File", m... | Python | zaydzuhri_stack_edu_python |
function wait_for_complete self
begin
join self
return time - _startTime
end function | def wait_for_complete(self):
self.join()
return time.time() - self._startTime | Python | nomic_cornstack_python_v1 |
import request
function reverse
begin
comment url that gives access to the string that needs to be reversed
set url = string http://challenge.code2040.org/api/reverse
comment My personal token
set myToken = string 0b051b7208115ccaaa141dc38779ec45f
comment url that must be returned to validate the reversed string
set ur... | import request
def reverse():
#url that gives access to the string that needs to be reversed
url = "http://challenge.code2040.org/api/reverse"
#My personal token
myToken = "0b051b7208115ccaaa141dc38779ec45f"
#url that must be returned to validate the reversed string
urlValidate = "http://challenge.cod... | Python | zaydzuhri_stack_edu_python |
import os
from diregex_semantics import Matcher
from diregex_parser import parse
import diregex_lexer
from diregex_ir import *
from regex_env import RegexEnv
print get current directory
change directory string ../test/testdir4
function match diregex
begin
set ast = parse diregex
comment print(ast)
set matcher = call Ma... | import os
from diregex_semantics import Matcher
from diregex_parser import parse
import diregex_lexer
from diregex_ir import *
from regex_env import RegexEnv
print(os.getcwd())
os.chdir('../test/testdir4')
def match(diregex):
ast = parse(diregex)
#print(ast)
matcher = Matcher()
emptyEnv = RegexEnv()
... | Python | zaydzuhri_stack_edu_python |
function overfit_deselect self data_check=true verbose=true
begin
comment Print out.
if verbose
begin
print string Over-fit spin deselection:
end
comment Test if sequence data exists.
if not call exists_mol_res_spin_data
begin
raise RelaxNoSequenceError
end
comment Is structural data required?
set need_vect = false
if ... | def overfit_deselect(self, data_check=True, verbose=True):
# Print out.
if verbose:
print("\nOver-fit spin deselection:")
# Test if sequence data exists.
if not exists_mol_res_spin_data():
raise RelaxNoSequenceError
# Is structural data required?
... | Python | nomic_cornstack_python_v1 |
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
class DfWine
begin
function __init__ self
begin
set data = read csv string ../missing-data/wine.data header=none
set columns = list string Class label string Alcohol string Malic acid string Ash str... | from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
class DfWine:
def __init__(self):
self.data = pd.read_csv('../missing-data/wine.data', header=None)
self.columns = [
'Class label',
'Alcohol',
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function exist self board word
begin
function recursion i j k
begin
if i < 0 or i == length board or j < 0 or j == length board at i or board at i at j != word at k
begin
return false
end
if k == length word - 1
begin
return true
end
set tmp = board at i at j
set board at i at j = string #
set res ... | class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def recursion(i, j, k):
if i < 0 or i == len(board) or j < 0 or j == len(board[i]) or board[i][j] != word[k]: return False
if k == len(word) - 1: return True
tmp = board[i][j]
... | Python | zaydzuhri_stack_edu_python |
import requests
import json
from API_Automation_Nose.Data import env
from API_Automation_Nose.Lib.Rest_library import Authorizer
decorator authoriser
function request_maker endpoint_url request_method payload=dict params=dict headers=dict
begin
set supported_urls = list string /
set supported_method_type = list strin... | import requests
import json
from API_Automation_Nose.Data import env
from API_Automation_Nose.Lib.Rest_library import Authorizer
@Authorizer.authoriser
def request_maker( endpoint_url, request_method,payload = {}, params = {}, headers={}):
supported_urls = ['/']
supported_method_type = ['get', 'post']
if e... | Python | zaydzuhri_stack_edu_python |
function __check_if_valid__ self
begin
pass
end function | def __check_if_valid__(self):
pass | Python | nomic_cornstack_python_v1 |
import contextlib
import sys
import logging
set log = call getLogger __name__
decorator contextmanager
function nested *managers
begin
string Like contextlib.nested but takes callables returning context managers, to avoid the major reason why contextlib.nested was deprecated. This version also logs any exceptions early... | import contextlib
import sys
import logging
log = logging.getLogger(__name__)
@contextlib.contextmanager
def nested(*managers):
"""
Like contextlib.nested but takes callables returning context
managers, to avoid the major reason why contextlib.nested was
deprecated.
This version also logs any exc... | Python | zaydzuhri_stack_edu_python |
function test_no_scan_nor_field_boundaries self
begin
set dst = string ngc5921.no_scan_nor_field_bounds.ms
set timebin = string 6000s
set ref = datadir + string ngc5921.no_scan_nor_field_bounds_2.ms.ref
set rtol = 1e-07
set list expwt expwtsp expflag expfrow expdata = call _get_dst_cols ref
for combine in list string c... | def test_no_scan_nor_field_boundaries(self):
dst = "ngc5921.no_scan_nor_field_bounds.ms"
timebin = "6000s"
ref = datadir + "ngc5921.no_scan_nor_field_bounds_2.ms.ref"
rtol = 1e-7
[expwt, expwtsp, expflag, expfrow, expdata] = _get_dst_cols(ref)
for combine in ["corr,scan,f... | Python | nomic_cornstack_python_v1 |
function add_pattern self _freq
begin
append patterns call Pattern length patterns _freq
return length patterns - 1
end function | def add_pattern(self, _freq):
self.patterns.append(Pattern(len(self.patterns), _freq))
return len(self.patterns)-1 | Python | nomic_cornstack_python_v1 |
function cancel_replace_wield self item
begin
call send_event string Nevermind.
end function
comment item/armor equipping: (not wielding) | def cancel_replace_wield(self, item):
self.send_event("Nevermind.")
# item/armor equipping: (not wielding) | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
set image_path = string F:\processed_captcha\5o3m.jpg
function getAvgContour cont
begin
set arealist = list
for c in cont
begin
set area = call contourArea c
append arealist area
end
set avg = sum arealist / length arealist
comment print(f'Avg Contour Area ... | import cv2
import numpy as np
import matplotlib.pyplot as plt
image_path = "F:\\processed_captcha\\5o3m.jpg"
def getAvgContour(cont):
arealist = []
for c in cont:
area = cv2.contourArea(c)
arealist.append(area)
avg = sum(arealist)/len(arealist)
# print(f'Avg Contour Area : {avg}')
r... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
if __name__ == string __main__
begin
set HLA_region = string chr6:29691116–33054976
set start = 29691116
set end = 33054976
set disease_class = dictionary
set all_class = set
set df = call read_excel string ../phenotype/disease_class_manual.xlsx
set list1 = call tolist
for each in list1
begin
set co... | import pandas as pd
if __name__ == '__main__':
HLA_region = 'chr6:29691116–33054976'
start = 29691116
end = 33054976
disease_class = dict()
all_class = set()
df = pd.read_excel('../phenotype/disease_class_manual.xlsx')
list1 = df.values.tolist()
for each in list1:
code = eac... | Python | zaydzuhri_stack_edu_python |
function set_index grid coord value
begin
set tuple x y = coord
set grid at x + y * ROWS = value
end function | def set_index(grid: List[Optional[str]], coord: Tuple[int,int], value: str) -> None:
x,y =coord
grid[x+(y*ROWS)] = value | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Provides support for the Yokogawa 6370 optical spectrum analyzer.
comment IMPORTS #####################################################################
from __future__ import absolute_import
from __future__ import division
from enum import IntEnum , Enum... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides support for the Yokogawa 6370 optical spectrum analyzer.
"""
# IMPORTS #####################################################################
from __future__ import absolute_import
from __future__ import division
from enum import IntEnum, Enum
import quantit... | Python | zaydzuhri_stack_edu_python |
function _init_lookup self
begin
if not _lookup_dict
begin
set _lookup_dict = dict string is_descendant_of dict ; string mutually_exclusive_of dict
end
end function | def _init_lookup(self):
if not self._lookup_dict:
self._lookup_dict = {
"is_descendant_of": {},
"mutually_exclusive_of": {}
} | Python | nomic_cornstack_python_v1 |
import numpy as np
import math
import sys
set file_input = string /media/sreeganesh/Windows/Users/GMachine/Documents/Studies/S7/NTC/NTC_Assignment/Transposition/cryptanalysis/BruteForce/input.txt
set file_output = string /media/sreeganesh/Windows/Users/GMachine/Documents/Studies/S7/NTC/NTC_Assignment/Transposition/cryp... | import numpy as np
import math
import sys
file_input = "/media/sreeganesh/Windows/Users/GMachine/Documents/Studies/S7/NTC/NTC_Assignment/Transposition/cryptanalysis/BruteForce/input.txt"
file_output = "/media/sreeganesh/Windows/Users/GMachine/Documents/Studies/S7/NTC/NTC_Assignment/Transposition/cryptanalysis/BruteFor... | Python | zaydzuhri_stack_edu_python |
function run_transformation_dict transformation_dict result_callback=none
begin
comment TODO: add type annotation and all kinds of validation...
from import database_sink
set transformation_buffer = call tf_get_buffer transformation_dict
set transformation = call calculate_checksum transformation_buffer
call cache_buf... | def run_transformation_dict(transformation_dict, result_callback=None):
# TODO: add type annotation and all kinds of validation...
from .. import database_sink
transformation_buffer = tf_get_buffer(transformation_dict)
transformation = calculate_checksum(transformation_buffer)
cache_buffer(transfor... | Python | nomic_cornstack_python_v1 |
import itertools
function solution nums
begin
set answer = 0
function prime n
begin
set limit = integer n ^ 1 / 2
for i in range 2 limit + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
sort nums
for i in call combinations nums 3
begin
print i
print sum i
if call prime sum i
begin
set answer ... | import itertools
def solution(nums):
answer = 0
def prime(n):
limit = int(n**(1/2))
for i in range(2, limit+1):
if n%i==0: return False
return True
nums.sort()
for i in itertools.combinations(nums, 3):
print(i)
print(sum(i))
if prime(sum(i))... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import tushare as ts
import matplotlib
import talib
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter , date2num
from mpl_finance import candlestick_ohlc
call use string ggplot
comment 通过股票代码获取股票数据,这里没有指定开始及结束日期
comment 002351 漫步者
comment 300510... | import pandas as pd
import tushare as ts
import matplotlib
import talib
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter,date2num
from mpl_finance import candlestick_ohlc
matplotlib.style.use("ggplot")
# 通过股票代码获取股票数据,这里没有指定开始及结束日期
# 002351 漫步者
# 300510 金冠
# 600... | Python | zaydzuhri_stack_edu_python |
function _get_region_fluxes header_nobkgd data_nobkgd data_orig data_masks apertures
begin
debug string Getting background uncertainty
comment Get the background error (which is the same for all regions)
set background_uncertainty = call _get_background_uncertainty data_nobkgd data_orig data_masks
comment Add the fluxe... | def _get_region_fluxes(header_nobkgd, data_nobkgd, data_orig, data_masks, apertures):
log.debug("Getting background uncertainty")
# Get the background error (which is the same for all regions)
background_uncertainty = _get_background_uncertainty(data_nobkgd, data_orig, data_masks)
# Add the fluxes wi... | Python | nomic_cornstack_python_v1 |
function create_time self
begin
return _create_time
end function | def create_time(self):
return self._create_time | Python | nomic_cornstack_python_v1 |
function test_init resident_names hospital_names capacities seed
begin
set tuple residents hospitals game = call make_game resident_names hospital_names capacities seed
for tuple resident game_resident in zip residents residents
begin
assert name == name
assert pref_names == pref_names
end
for tuple hospital game_hospi... | def test_init(resident_names, hospital_names, capacities, seed):
residents, hospitals, game = make_game(
resident_names, hospital_names, capacities, seed
)
for resident, game_resident in zip(residents, game.residents):
assert resident.name == game_resident.name
assert resident.pref... | Python | nomic_cornstack_python_v1 |
comment Alternative solution without using the + operator
print str1 end=string
print str2 | # Alternative solution without using the + operator
print(str1, end="")
print(str2) | Python | jtatman_500k |
function create_file_dataset self name categories=none project=none mission=none hidden=none published=none horizontal_srs_wkt=none vertical_srs_wkt=none dataset_format=none geometry=none properties=none file_count=1 components=none **kwargs
begin
if not components
begin
set components = call _generate_comp_names strin... | def create_file_dataset(self, *,
name: str,
categories: Sequence[str] = None,
project: ResourceId = None,
mission: ResourceId = None,
hidden: bool = None,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string 1- Convert MEG file to excel file 2- Run the script 3- Execute in Notepad : * ctr + H * search mode : Extended * in the "find what" cell : ' * in the "replace with" cell : (4 or 5 spaces) * Replace ALL
from pandas import DataFrame
import pandas as pd
comment convert MEG file to exce... | # -*- coding: utf-8 -*-
"""
1- Convert MEG file to excel file
2- Run the script
3- Execute in Notepad :
* ctr + H
* search mode : Extended
* in the "find what" cell : '\t
* in the "replace with" cell : (4 or 5 spaces)
* Replace ALL
"""
from pandas import DataFrame
import pandas as pd
#convert M... | Python | zaydzuhri_stack_edu_python |
function test_data_allow_new self
begin
add user_permissions get objects codename=string manage_tags
set form = call form user=user
assert equal attrs at string data-allow-new string true
end function | def test_data_allow_new(self):
self.user.user_permissions.add(
model.Permission.objects.get(codename="manage_tags"))
form = self.form(user=self.user)
self.assertEqual(
form.fields["add_tags"].widget.attrs["data-allow-new"], "true") | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
call use string ggplot
set operations_data = list 2 5 1 1
set ids = list 0 1 2 3
set series = call Series operations_data
comment Plot the figure.
figure
set ax = plot kind=string bar color=string cornflowerblue
call set_xlabel string Number of clus... | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.style.use('ggplot')
operations_data = [2,5,1,1]
ids = [0,1,2,3]
series = pd.Series(operations_data)
# Plot the figure.
plt.figure()
ax = series.plot(kind='bar', color="cornflowerblue")
ax.set_xlabel('Number of clusters with more than 1 invo... | Python | zaydzuhri_stack_edu_python |
function GET self
begin
set client = call GetClient
if call useBulk
begin
set bulkdata = call QueryNetworks list NET_FIELDS false
return call MapBulkFields bulkdata NET_FIELDS
end
else
begin
set data = call QueryNetworks list list string name false
set networknames = list comprehension row at 0 for row in data
return... | def GET(self):
client = self.GetClient()
if self.useBulk():
bulkdata = client.QueryNetworks([], NET_FIELDS, False)
return baserlib.MapBulkFields(bulkdata, NET_FIELDS)
else:
data = client.QueryNetworks([], ["name"], False)
networknames = [row[0] for row in data]
return baserlib... | Python | nomic_cornstack_python_v1 |
function publish payload info groupId
begin
comment Here `payload` contains the `payload` from the `broadcast()`
comment invocation (see below). You can return `MySubscription.SKIP`
comment if you wish to suppress the notification to a particular
comment client. For example, this allows to avoid notifications for
comme... | def publish(payload, info, groupId):
# Here `payload` contains the `payload` from the `broadcast()`
# invocation (see below). You can return `MySubscription.SKIP`
# if you wish to suppress the notification to a particular
# client. For example, this allows to avoid notifications for
... | Python | nomic_cornstack_python_v1 |
function render_hor_bar_chart title values labels height
begin
info string Rendering horizontal bar chart
set bar_chart = call HorizontalBar show_legend=false height=height
set title = title
add bar_chart string values
set x_labels = labels
set bar_chart = call render_data_uri
return bar_chart
end function | def render_hor_bar_chart(title, values, labels, height):
logging.info('Rendering horizontal bar chart')
bar_chart = pygal.HorizontalBar(show_legend=False, height=height)
bar_chart.title = title
bar_chart.add("", values)
bar_chart.x_labels = labels
bar_chart = bar_chart.render_data_uri()
re... | Python | nomic_cornstack_python_v1 |
for num in range 11
begin
if num == 5
begin
continue
end
if num % 2 == 0
begin
print num
end
end | for num in range(11):
if num == 5:
continue
if num % 2 == 0:
print(num)
| Python | jtatman_500k |
function __new__ cls prefix precheck=none mention_prefix_enabled=true category_name_rule=none command_name_rule=none default_category_name=none prefix_ignore_case=true
begin
if category_name_rule is not none
begin
call test_name_rule category_name_rule string category_name_rule
end
if command_name_rule is not none
begi... | def __new__(
cls,
prefix,
*,
precheck = None,
mention_prefix_enabled = True,
category_name_rule = None,
command_name_rule = None,
default_category_name = None,
prefix_ignore_case = True,
):
if (category_name_rule is not None):
... | Python | nomic_cornstack_python_v1 |
if gi >= 50000
begin
set gi = 0.2
end
else
begin
set gi = 0.1
end
print string Last Name: + lastName + string number of dependents: + string nod + string adjusted gross income: + string ag + string Income tax: + string 100 | if gi >= 50000:
gi = 0.2
else:
gi = 0.1
print("Last Name:" + lastName + "number of dependents:" + str(nod) + "adjusted gross income:" + str(ag) + "Income tax:" + str(100))
| Python | zaydzuhri_stack_edu_python |
function search_list lst num
begin
for i in range length lst
begin
if lst at i == num
begin
return i
end
end
return - 1
end function | def search_list(lst, num):
for i in range(len(lst)):
if lst[i] == num:
return i
return -1 | Python | jtatman_500k |
function largerst_str str_arr
begin
set N = length str_arr
set c = list 0 * N
comment Index of string with maximum unique characters
set m = 0
for j in range N
begin
comment Array indicating any alphabet included or not
set character = list false * 26
comment Count number of unique alphabet included or not included
for... | def largerst_str(str_arr):
N = len(str_arr)
c = [0] * N
# Index of string with maximum unique characters
m = 0
for j in range(N):
# Array indicating any alphabet included or not
character = [False] * 26
# Count number of unique alphabet included or not included
fo... | Python | zaydzuhri_stack_edu_python |
function find_common_characters string1 string2
begin
comment Convert strings to lowercase and remove non-alphabetic characters
set string1 = join string filter isalpha lower string1
set string2 = join string filter isalpha lower string2
comment Initialize a dictionary to store the common characters and their occurre... | def find_common_characters(string1, string2):
# Convert strings to lowercase and remove non-alphabetic characters
string1 = ''.join(filter(str.isalpha, string1.lower()))
string2 = ''.join(filter(str.isalpha, string2.lower()))
# Initialize a dictionary to store the common characters and their occurr... | Python | jtatman_500k |
class PLTeam extends object
begin
function __init__ self teamData=none teamName=none
begin
set data = dict
if teamData is not none
begin
set data at string teamName = teamNames at teamData at 0
set data at string homePlayed = integer teamData at 1
set data at string homeWon = integer teamData at 2
set data at string h... | class PLTeam(object):
def __init__(self, teamData=None, teamName=None):
self.data = {}
if teamData is not None:
self.data['teamName'] = teamNames[teamData[0]]
self.data['homePlayed'] = int(teamData[1])
self.data['homeWon'] = int(teamData[2])
self.data... | Python | zaydzuhri_stack_edu_python |
for i in range integer nums at 1
begin
set out = out * nums at 0
end
print out | for i in range(int(nums[1])):
out=out*nums[0]
print(out) | Python | zaydzuhri_stack_edu_python |
function render_doc request doc_name
begin
set doc = DOCS at string / + doc_name
if not doc
begin
raise call Http404
end
return call render doc request
end function | def render_doc(request, doc_name):
doc = DOCS['/' + doc_name]
if not doc:
raise Http404()
return doc.render(doc, request) | Python | nomic_cornstack_python_v1 |
import pandas as pd
from matplotlib import pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.stattools import adfuller as ADF
comment 参数初始化
set discfile = string D:/GitHub/load_forecast_TimeSeries/data/arima_data.xls
comment 读取数据,指定日期列为指标,Pandas自动将“日期”列识别为Datetime格式
set data = call r... | import pandas as pd
from matplotlib import pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.stattools import adfuller as ADF
# 参数初始化
discfile = 'D:/GitHub/load_forecast_TimeSeries/data/arima_data.xls'
# 读取数据,指定日期列为指标,Pandas自动将“日期”列识别为Datetime格式
data = pd.read_excel(discfile, index... | Python | zaydzuhri_stack_edu_python |
function test_fit_with_random_state self
begin
set tuple X y = call get_dataset_for_regression
set rgr = call StackingRegressor base_estimators_types=list RandomForestRegressor KNeighborsRegressor base_estimators_params=list dict string n_estimators 3 dict string n_neighbors 1 splitter=call KFold shuffle=true random_st... | def test_fit_with_random_state(self) -> type(None):
X, y = get_dataset_for_regression()
rgr = StackingRegressor(
base_estimators_types=[RandomForestRegressor, KNeighborsRegressor],
base_estimators_params=[{'n_estimators': 3}, {'n_neighbors': 1}],
splitter=KFold(shuffl... | Python | nomic_cornstack_python_v1 |
function __init__ self screen
begin
call __init__ self
set image = call Surface tuple 80 80
call fill tuple 255 255 0
call circle image tuple 0 0 200 tuple 40 40 40
set rect = call get_rect
set radius = 40
set top = random integer 0 call get_height - bottom
set left = random integer 0 call get_width - right
end functio... | def __init__(self, screen: pygame.Surface) -> None:
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((80,80))
self.image.fill((255, 255, 0))
pygame.draw.circle(self.image, (0, 0, 200), (40,40), 40)
self.rect = self.image.get_rect()
self.radius = 40
... | Python | nomic_cornstack_python_v1 |
function setup_with_endpoint self mac=string 00:11:22:33:33:33
begin
set args = call get_args
call write_config_file call create_config_file args
call execute_tool args test_mode=true
set ip = string 3.4.3.4
assert false call verify_remote_site_has_entry mac ip string intersite-testsuite string l3out string intersite-t... | def setup_with_endpoint(self, mac='00:11:22:33:33:33'):
args = self.get_args()
self.write_config_file(self.create_config_file(), args)
execute_tool(args, test_mode=True)
ip = '3.4.3.4'
self.assertFalse(self.verify_remote_site_has_entry(mac, ip, 'intersite-testsuite', 'l3out', '... | Python | nomic_cornstack_python_v1 |
function parse text
begin
string Parse response into an instance of the appropriate child class.
comment Trim the start and end markers, and ensure only lowercase is used
if starts with text MARKER_START and ends with text MARKER_END
begin
set text = lower text at slice 1 : length text - 1 :
end
comment No-op; can just... | def parse(text) -> Optional['Response']:
"""Parse response into an instance of the appropriate child class."""
# Trim the start and end markers, and ensure only lowercase is used
if text.startswith(MARKER_START) and text.endswith(MARKER_END):
text = text[1:len(text)-1].lower()
... | Python | jtatman_500k |
function run_predictor scraped_data period
begin
set finalized_data = list
for stock_data in scraped_data
begin
print string * Making predictions for stock_data at string stock string ....
set historical_data = stock_data at string stock_historical_data
set df = historical_data at list string Close
comment get the clo... | def run_predictor(scraped_data, period):
finalized_data = []
for stock_data in scraped_data:
print("\n* Making predictions for", stock_data["stock"], "....")
historical_data = stock_data["stock_historical_data"]
df = historical_data[
["Close"]
] # get the close p... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 18-9-19 下午12:46
comment @File : demo.py
comment @Software: PyCharm
comment @Author : wxw
comment @Contact : xwwei@lighten.ai
comment @Desc :
import tensorflow as tf
import cv2
import numpy as np
from scipy.spatial.distance import pdist
class Sia... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-9-19 下午12:46
# @File : demo.py
# @Software: PyCharm
# @Author : wxw
# @Contact : xwwei@lighten.ai
# @Desc :
import tensorflow as tf
import cv2
import numpy as np
from scipy.spatial.distance import pdist
class SiameseNet(object):
##默认输入4*4
de... | Python | zaydzuhri_stack_edu_python |
function SetWholeExtent self p_int p_int_1 p_int_2 p_int_3 p_int_4 p_int_5
begin
Ellipsis
end function | def SetWholeExtent(self, p_int, p_int_1, p_int_2, p_int_3, p_int_4, p_int_5):
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Date : 2020-09-19 00:11:25
comment @Author : Your Name (you@example.org)
comment @Link : link
comment @Version : 1.0.0
comment 已弃用
import os
from PIL import ImageGrab
import numpy as np
import cv2
import datetime
import imageio
import time
import math
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-09-19 00:11:25
# @Author : Your Name (you@example.org)
# @Link : link
# @Version : 1.0.0
# 已弃用
import os
from PIL import ImageGrab
import numpy as np
import cv2
import datetime
import imageio
import time
import math
from moviepy.editor import *
import... | Python | zaydzuhri_stack_edu_python |
string Script to make a netCDF file from BOB binary output
import numpy as np
import glob
comment import matplotlib
comment matplotlib.use('qt5agg')
comment import matplotlib.pyplot as plt
import xarray as xr
comment import matplotlib.path as mpath
comment import cartopy.crs as ccrs
function ds_from_BOB run_dir vars re... | '''
Script to make a netCDF file from BOB binary output
'''
import numpy as np
import glob
# import matplotlib
# matplotlib.use('qt5agg')
# import matplotlib.pyplot as plt
import xarray as xr
# import matplotlib.path as mpath
#import cartopy.crs as ccrs
def ds_from_BOB(run_dir, vars, res, time_step=0.25,units=None):
... | Python | zaydzuhri_stack_edu_python |
function action self
begin
return get pulumi self string action
end function | def action(self) -> str:
return pulumi.get(self, "action") | Python | nomic_cornstack_python_v1 |
function _catalog
begin
set request = call getRequest
try
begin
return _catalog
end
except AttributeError
begin
set site = call getSite
if site is none
begin
if request is not none
begin
set _catalog = none
end
return
end
set catalog = call getToolByName site string portal_catalog none
if request is not none
begin
set ... | def _catalog():
request = getRequest()
try:
return request._catalog
except AttributeError:
site = getSite()
if site is None:
if request is not None:
request._catalog = None
return
catalog = getToolByName(site, "portal_catalog", None)
... | Python | nomic_cornstack_python_v1 |
string Desafio 001 Crie um programa que escreva "Olá Mundo" na tela.
set msg = string Olá, Mundo!
print msg
set nome = input string Olá, qual o seu nome?
print string É um grande prazer te conhecer, nome
set email = input string Qual o seu e-mail ?
set data_nascimento = input string Qual a data do seu nascimento ?
set ... | """Desafio 001
Crie um programa que escreva "Olá Mundo" na tela.
"""
msg = ("Olá, Mundo!")
print(msg)
nome=input("Olá, qual o seu nome? ")
print("É um grande prazer te conhecer,",nome)
email=input("Qual o seu e-mail ?")
data_nascimento=input("Qual a data do seu nascimento ?")
naturalidade=input("Onde você nasceu?"... | Python | zaydzuhri_stack_edu_python |
function handle_message self message
begin
if _closed
begin
raise exception string Bot closed.
end
set message_text : str = strip message at string text
if call is_possible_command message_text
begin
try
begin
set parsed_command = call parse_command message_text
end
except ParseError
begin
call send_message ABOUT_MESSA... | def handle_message(self, message):
if self._closed:
raise Exception("Bot closed.")
message_text: str = message["text"].strip()
if is_possible_command(message_text):
try:
parsed_command = parse_command(message_text)
except ParseError:
... | Python | nomic_cornstack_python_v1 |
function _interpol self T_muI T_muF mu_I mu_F
begin
function viscosity x a b
begin
return a * x ^ b
end function
comment changed boundary conditions to avoid division by ]
set xdata = list T_muI T_muF
set ydata = list mu_I mu_F
set tuple popt pcov = curve fit viscosity xdata ydata p0=tuple 6.0 1.0
set tuple a b = popt
... | def _interpol(self, T_muI, T_muF, mu_I, mu_F):
def viscosity(x, a, b):
return a * (x**b)
xdata = [T_muI, T_muF] # changed boundary conditions to avoid division by ]
ydata = [mu_I, mu_F]
popt, pcov = curve_fit(viscosity, xdata, ydata, p0=(6.0, 1.0))
a, b = popt
... | Python | nomic_cornstack_python_v1 |
import checksumdir
import sys
import os
function get_dir_hash directory
begin
if exists path directory
begin
return call dirhash directory string sha256
end
else
begin
return - 1
end
end function | import checksumdir
import sys
import os
def get_dir_hash(directory):
if os.path.exists(directory):
return checksumdir.dirhash(directory, 'sha256')
else:
return -1
| Python | zaydzuhri_stack_edu_python |
function dequeue self filestring
begin
for tup in votelist
begin
if filestring == tup at 0
begin
remove votelist tup
return tup
end
end
return none
end function | def dequeue(self, filestring):
for tup in self.votelist:
if filestring == tup[0]:
self.votelist.remove(tup)
return tup
return None | Python | nomic_cornstack_python_v1 |
from typing import Optional
import numpy as np
from scipy.sparse import issparse
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.utils import check_array , check_X_y
from sklearn.utils.validation import check_is_fitted
fr... | from typing import Optional
import numpy as np
from scipy.sparse import issparse
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.utils import check_array, check_X_y
from sklearn.utils.validation import check_is_fitted
fr... | Python | zaydzuhri_stack_edu_python |
import logging , os
from logging.handlers import RotatingFileHandler
import os.path as p
comment Set up root logger
comment name of this logger is root
set logger = call getLogger
call setLevel DEBUG
set formatter = call Formatter string %(asctime)s - %(name)s - %(levelname)s - %(message)s
set sh = call StreamHandler
c... | import logging, os
from logging.handlers import RotatingFileHandler
import os.path as p
# Set up root logger
logger = logging.getLogger() #name of this logger is root
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
sh = logging.StreamHandler()
sh... | Python | zaydzuhri_stack_edu_python |
function cameraOut
begin
set archive = call OArchive string camera1.abc
set simpleCamObj = call OCamera call getTop string simpleCam
set samp = call CameraSample
set samp
set camObj = call OCamera call getTop string cam
set camSchema = call getSchema
call addOp call FilmBackXformOp kScaleFilmBackOperation string scale
... | def cameraOut():
archive = OArchive("camera1.abc")
simpleCamObj = OCamera(archive.getTop(), "simpleCam")
samp = CameraSample()
simpleCamObj.getSchema().set(samp)
camObj = OCamera(archive.getTop(), "cam")
camSchema = camObj.getSchema()
samp.addOp(FilmBackXformOp(kScaleFilmBackOperation, "sc... | Python | nomic_cornstack_python_v1 |
function server_side_encryption_customer_algorithm self
begin
set result = get _values string server_side_encryption_customer_algorithm
return result
end function | def server_side_encryption_customer_algorithm(
self,
) -> typing.Optional[builtins.str]:
result = self._values.get("server_side_encryption_customer_algorithm")
return result | Python | nomic_cornstack_python_v1 |
function _get_label_features _label _id
begin
comment get features
set _contours = call find_contours array _label == _id dtype=int 0
if length _contours > 0
begin
set _length = sum square root sum call roll _contours at 0 1 axis=0 - _contours at 0 ^ 2 axis=1
end
else
begin
set _length = 0
end
set _size = sum _label ==... | def _get_label_features(_label, _id):
# get features
_contours = measure.find_contours(np.array(_label==_id, dtype=np.int), 0)
if len(_contours) > 0:
_length = np.sum(np.sqrt(np.sum((np.roll(_contours[0],1,axis=0) - _contours[0])**2, axis=1)))
else:
_length = 0
... | Python | nomic_cornstack_python_v1 |
function parseComponents obj bandpass
begin
set bandpass_to_dex = dict string u 0 ; string g 1 ; string r 2 ; string i 3 ; string z 4 ; string y 5
set output = list
set first_surface = list
set second_surface = none
for att in attributes
begin
if string second surface in attributes at att at string Notes
begin
set se... | def parseComponents(obj, bandpass):
bandpass_to_dex = {'u':0, 'g':1, 'r':2, 'i':3, 'z':4, 'y':5}
output = []
first_surface = []
second_surface = None
for att in obj.attributes:
if 'second surface' in obj.attributes[att]['Notes']:
second_surface = []
break
name... | Python | nomic_cornstack_python_v1 |
function test_spin_loop_multiatom self
begin
comment Spin data.
set select = list 0 1 1 0
set name = list string NH string NH string N5 string N5
comment Loop over the spins.
set i = 0
for spin in call spin_loop string @NH|@N5
begin
comment Test the selection.
assert equal select select at i
comment Test the spin names... | def test_spin_loop_multiatom(self):
# Spin data.
select = [0, 1, 1, 0]
name = ['NH', 'NH', 'N5', 'N5']
# Loop over the spins.
i = 0
for spin in mol_res_spin.spin_loop('@NH|@N5'):
# Test the selection.
self.assertEqual(spin.select, select[i])
... | Python | nomic_cornstack_python_v1 |
import socket
import sys
import threading
function read_msg sock_cli friend_req_queue
begin
while true
begin
set data = call recv 65535
if length data == 0
begin
break
end
set tuple cmd message = split data b'|' 1
set cmd = decode cmd string utf-8
if cmd == string message
begin
set message = decode message string utf-8... | import socket
import sys
import threading
def read_msg(sock_cli, friend_req_queue):
while True:
data = sock_cli.recv(65535)
if len(data) == 0:
break
cmd, message = data.split(b"|", 1)
cmd = cmd.decode("utf-8")
if cmd == "message":
message ... | Python | zaydzuhri_stack_edu_python |
from random import randint
comment one card of the pack
class Card extends object
begin
function __init__ self suit value
begin
assert suit in list string clubs string diamonds string hearts string spades
assert value in list string A + range 2 11 + list string J string Q string K
call __setattr__ self string suit suit... | from random import randint
# one card of the pack
class Card(object):
def __init__(self, suit, value):
assert suit in ['clubs', 'diamonds', 'hearts', 'spades']
assert value in ['A'] + range(2, 11)+['J', 'Q', 'K']
object.__setattr__(self, "suit", suit)
object.__setattr__(self, "value", value)
def __setattr__... | Python | zaydzuhri_stack_edu_python |
if var == string +
begin
print var1 + var2
end
else
if var == string -
begin
print var1 - var2
end
else
if var == string /
begin
print var1 / var2
end
else
if var == string *
begin
print var1 * var2
end
else
begin
print string invalid
end | if var=='+':
print(var1+var2)
elif var=='-':
print(var1-var2)
elif var=='/':
print(var1/var2)
elif var=='*':
print(var1*var2)
else:
print("invalid")
| Python | zaydzuhri_stack_edu_python |
function GetMaxRefitIteration self
begin
return call itkSparseFieldFourthOrderLevelSetImageFilterID3ID3_GetMaxRefitIteration self
end function | def GetMaxRefitIteration(self):
return _itkSparseFieldFourthOrderLevelSetImageFilterPython.itkSparseFieldFourthOrderLevelSetImageFilterID3ID3_GetMaxRefitIteration(self) | Python | nomic_cornstack_python_v1 |
function __call__ self x
begin
comment Calculating the Deckkers Aarts' function
set f = 10 ^ 5 * x at 0 ^ 2 + x at 1 ^ 2 - x at 0 ^ 2 + x at 1 ^ 2 ^ 2 + 10 ^ - 5 * x at 0 ^ 2 + x at 1 ^ 2 ^ 4
return f
end function | def __call__(self, x):
# Calculating the Deckkers Aarts' function
f = 10 ** 5 * x[0] ** 2 + x[1] ** 2 - \
(x[0] ** 2 + x[1] ** 2) ** 2 + 10 ** - \
5 * (x[0] ** 2 + x[1] ** 2) ** 4
return f | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string Review: Objects literals (int, str, float) Conditionals and Looping Constructs (if, while, for) Functions (def) Tuples (), lists [], and dictionaries {} Mutability and immutability Today: Practice using strings, tuples, lists, and dicts to solve problems To practice with lists, condition... | #!/usr/bin/python
"""
Review:
Objects literals (int, str, float)
Conditionals and Looping Constructs (if, while, for)
Functions (def)
Tuples (), lists [], and dictionaries {}
Mutability and immutability
Today:
Practice using strings, tuples, lists, and dicts to solve problems
To practice with ... | Python | zaydzuhri_stack_edu_python |
function kSelect arr k
begin
comment if len(arr) == 1 and k == 0:
comment return arr[0]
set n = length arr
set pivot_idx = random integer 0 n - 1
set tuple partitioned_arr pivot_index = call partition arr pivot_idx
if pivot_index < k
begin
set sub_arr = partitioned_arr at slice pivot_index + 1 : :
return call kSelect... | def kSelect(arr: list, k: int) -> int:
# if len(arr) == 1 and k == 0:
# return arr[0]
n = len(arr)
pivot_idx = random.randint(0,n-1)
partitioned_arr, pivot_index = partition(arr, pivot_idx)
if pivot_index < k:
sub_arr = partitioned_arr[pivot_index+1:]
return kSelect(sub_a... | Python | nomic_cornstack_python_v1 |
function on dependency_class
begin
return lambda -> get injector dependency_class
end function | def on(dependency_class: Type[T]) -> Callable[[], T]:
return lambda: injector.get(dependency_class) | Python | nomic_cornstack_python_v1 |
import pdb
set x_axis = 6
set y_axis = 8
for x in range x_axis
begin
print string
for y in range y_axis
begin
if y == y_axis
begin
print y
end
else
begin
print y end=string
comment continue, step, next
call set_trace
end
end
end | import pdb;
x_axis = 6
y_axis = 8
for x in range(x_axis):
print("")
for y in range(y_axis):
if y == y_axis:
print(y)
else:
print(y,end=" ")
pdb.set_trace() #continue, step, next | Python | zaydzuhri_stack_edu_python |
function display self
begin
comment make sure clock/latch are low to start (should already be the case)
call output clock 0
call output latch 0
comment write out all the data (bit banging!)
for led in state at slice : : - 1
begin
call output data led
call output clock 1
call output clock 0
end
comment toggle latch to... | def display(self):
# make sure clock/latch are low to start (should already be the case)
GPIO.output(self.clock, 0)
GPIO.output(self.latch, 0)
# write out all the data (bit banging!)
for led in self.state[::-1]:
GPIO.output(self.data, led)
GPIO.output(self.clock, 1)
GPIO.output(se... | Python | nomic_cornstack_python_v1 |
function create_licence license_dto
begin
set new_licence_id = call create_from_dto license_dto
return new_licence_id
end function | def create_licence(license_dto: LicenseDTO) -> int:
new_licence_id = License.create_from_dto(license_dto)
return new_licence_id | Python | nomic_cornstack_python_v1 |
string Created on 2013年9月5日 @author: Administrator
from xml.dom import minidom
function get_attrvalue node attrname
begin
return if expression node then call getAttribute attrname else string
end function
function get_nodevalue node index=0
begin
return if expression node then nodeValue else string
end function
funct... | '''
Created on 2013年9月5日
@author: Administrator
'''
from xml.dom import minidom
def get_attrvalue(node, attrname):
return node.getAttribute(attrname) if node else ''
def get_nodevalue(node, index = 0):
return node.childNodes[index].nodeValue if node else ''
def set_nodevalue(node, value,index = 0):
if n... | Python | zaydzuhri_stack_edu_python |
function generate_ideal self
begin
return call StageParameters self *self._ideal_values()
end function | def generate_ideal(self):
return StageParameters(self, *self._ideal_values()) | Python | nomic_cornstack_python_v1 |
function loss self X y=none
begin
set X = as type X dtype
set mode = if expression y is none then string test else string train
comment Set train/test mode for batchnorm params since they
comment behave differently during training and testing.
if use_batchnorm
begin
for bn_param in bn_params
begin
set bn_param at strin... | def loss(self, X, y=None):
X = X.astype(self.dtype)
mode = 'test' if y is None else 'train'
# Set train/test mode for batchnorm params since they
# behave differently during training and testing.
if self.use_batchnorm:
for bn_param in self.bn_params:
... | Python | nomic_cornstack_python_v1 |
comment !python
import string
function decode str_num base
begin
string Decode given number from given base to base 10. str_num -- string representation of number in given base base -- base of given number
assert 2 <= base <= 36
comment TODO: Decode number
comment return int(str_num, base)
set sum = 0
for tuple index d... | #!python
import string
def decode(str_num, base):
"""
Decode given number from given base to base 10.
str_num -- string representation of number in given base
base -- base of given number
"""
assert 2 <= base <= 36
# TODO: Decode number
# return int(str_num, base)
sum = 0
for ... | Python | zaydzuhri_stack_edu_python |
function query_dqsegdb cls flags *args **kwargs
begin
string Query the advanced LIGO DQSegDB for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of su... | def query_dqsegdb(cls, flags, *args, **kwargs):
"""Query the advanced LIGO DQSegDB for a list of flags.
Parameters
----------
flags : `iterable`
A list of flag names for which to query.
*args
Either, two `float`-like numbers indicating the
GP... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.