code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class BookingError extends Exception
begin
function __init__ self invalid_field msg
begin
set _invalid_field = invalid_field
set _error_message = msg
end function
end class | class BookingError(Exception):
def __init__(self, invalid_field, msg):
self._invalid_field = invalid_field
self._error_message = msg
| Python | zaydzuhri_stack_edu_python |
comment 3) a) Mostrar paso a paso como funcionarıan los algoritmos de insercion y quicksort sobre
comment la siguiente lista de numeros: [9, 12, 1, 4, 2, 8, 15, 21]
comment b) ¿Cual de los dos algoritmos es mas eficiente para ordenar una gran cantidad de elementos?
function ord_insercion lista
begin
for i in range 1 le... | # 3) a) Mostrar paso a paso como funcionarıan los algoritmos de insercion y quicksort sobre
# la siguiente lista de numeros: [9, 12, 1, 4, 2, 8, 15, 21]
# b) ¿Cual de los dos algoritmos es mas eficiente para ordenar una gran cantidad de elementos?
def ord_insercion(lista):
for i in range(1, len(lista)):
v... | Python | zaydzuhri_stack_edu_python |
function begin_write self digest
begin
raise call NotImplementedError
end function | def begin_write(self, digest):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function calcular_verificador rut
begin
set calculo = 0
set contador = 0
for digit in rut
begin
set calculo = calculo + integer digit * Multiplication at contador
set contador = contador + 1
end
set base_sum = calculo
set calculo = calculo / 11
set restar = integer calculo * 11
set restar = base_sum - restar
set calcul... | def calcular_verificador(rut:str):
calculo = 0
contador = 0
for digit in rut:
calculo += int(digit) * Multiplication[contador]
contador += 1
base_sum = calculo
calculo /= 11
restar = int(calculo) * 11
restar = base_sum - restar
calculo = 11 - restar
if calculo ... | Python | zaydzuhri_stack_edu_python |
function find_max arr
begin
return max arr
end function | def find_max(arr):
return max(arr) | Python | iamtarun_python_18k_alpaca |
function explodeString s
begin
set char_map = dict
set groups = list
for c in list s
begin
set char_map at c = 1 + get char_map c 0
end
for tuple k v in items char_map
begin
if k != string
begin
append groups k * v
end
end
return sorted groups
end function | def explodeString(s):
char_map = {}
groups = []
for c in list(s):
char_map[c] = 1 + char_map.get(c, 0)
for k,v in char_map.items():
if k != ' ':
groups.append(k * v)
return sorted(groups)
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2020/9/26 20:26
comment @Author : laisent
string 不同分类的电视剧数量的统计
from data_visualization.show_data import get_data_frame
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
function show_tag_count
begin
string 统计不同分类的电视剧数量 :return:
comment 设置图形大小
figur... | # -*- coding: utf-8 -*-
# @Time : 2020/9/26 20:26
# @Author : laisent
"""
不同分类的电视剧数量的统计
"""
from data_visualization.show_data import get_data_frame
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
def show_tag_count():
"""
统计不同分类的电视剧数量
:return:
"""
# 设置图形大小
plt.fig... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
import parser
import plot
from pandas import *
from numpy import array , isfinite
import operator
from sklearn.cluster import MeanShift , estimate_bandwidth
import numpy as np
import pylab as pl
from itertools import cycle | from collections import Counter
import parser
import plot
from pandas import *
from numpy import array, isfinite
import operator
from sklearn.cluster import MeanShift, estimate_bandwidth
import numpy as np
import pylab as pl
from itertools import cycle
| Python | zaydzuhri_stack_edu_python |
function _generate_sample_indices random_state y target_imbalance_ratio verbose=0
begin
set random_instance = call check_random_state random_state
set class_idxs = call _generate_class_indices y
set class_len = list comprehension length class_idx for class_idx in class_idxs
set minority_class_idx = argument minimum cla... | def _generate_sample_indices(random_state, y, target_imbalance_ratio, verbose=0):
random_instance = check_random_state(random_state)
class_idxs = _generate_class_indices(y)
class_len = [len(class_idx) for class_idx in class_idxs]
minority_class_idx = np.argmin(class_len)
majority_class_idx = np.arg... | Python | nomic_cornstack_python_v1 |
function _is_memory_usage_qualified self
begin
function f level
begin
return string mixed in level or string string in level or string unicode in level
end function
return any generator expression f dist level for level in _inferred_type_levels
end function | def _is_memory_usage_qualified(self) -> bool:
def f(level) -> bool:
return "mixed" in level or "string" in level or "unicode" in level
return any(f(level) for level in self._inferred_type_levels) | Python | nomic_cornstack_python_v1 |
comment !/Users/john/anaconda/bin/python3
comment HTML is following
print string Content-Type: text/html
comment blank line, end of headers
print
print string Hey, this works. | #!/Users/john/anaconda/bin/python3
print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
print('Hey, this works.')
| Python | zaydzuhri_stack_edu_python |
function fillFromStore self store
begin
if not api_key
begin
info string Filling setting "api_key" config store.
set api_key = call _loadSetting store string api_key
end
if not api_secret
begin
info string Filling setting "api_secret" config store.
set api_secret = call _loadSetting store string api_secret
end
end func... | def fillFromStore(self, store):
if not self.api_key:
logger.info('Filling setting "api_key" config store.')
self.api_key = self._loadSetting(store, 'api_key')
if not self.api_secret:
logger.info('Filling setting "api_secret" config store.')
self.api_secret... | Python | nomic_cornstack_python_v1 |
function default_action self
begin
comment Get the the parent robot
set robot = robot_parent
import bge
set component = none
try
begin
set component = objects at local_data at string component
end
except any
begin
set component = none
end
if _robot_frame
begin
comment directly apply local forces and torques to the blen... | def default_action(self):
# Get the the parent robot
robot = self.robot_parent
import bge
component = None
try:
component = bge.logic.getCurrentScene().objects[self.local_data['component']]
except:
component = None
if self._robot_frame:
... | Python | nomic_cornstack_python_v1 |
set sports_list = list string soccer string rugby string hockey
set max_length = 1000
if length sports_list == max_length
begin
print string List has reached maximum length and cannot be modified.
end
else
if length sports_list == 0
begin
append sports_list string excellent
end
else
begin
set last_index = length sports... | sports_list = ['soccer', 'rugby', 'hockey']
max_length = 1000
if len(sports_list) == max_length:
print("List has reached maximum length and cannot be modified.")
elif len(sports_list) == 0:
sports_list.append('excellent')
else:
last_index = len(sports_list)
sports_list[last_index:last_index] = ['excell... | Python | jtatman_500k |
function has_won self
begin
if call card_count == 0
begin
return true
end
return false
end function | def has_won(self) -> bool:
if self.card_count() == 0:
return True
return False | Python | nomic_cornstack_python_v1 |
function _create_examples self lines set_type
begin
set examples = list
for tuple i line in enumerate lines
begin
if i == 0
begin
continue
end
set guid = string %s-%s % tuple set_type line at 0
set text_a = line at 7
set text_b = line at 8
set label = line at - 1
append examples call InputExample guid=guid text_a=text... | def _create_examples(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[7]
text_b = line[8]
label = line[-1]
examples.appen... | Python | nomic_cornstack_python_v1 |
import os , sys , math
comment __debug=True
set __debug = false | import os, sys, math
#__debug=True
__debug=False
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Convert gene abundance in absolute counts to tpm.
import numpy as np
from utils import _handle_io
decorator _handle_io
comment import pandas as pd
comment def convert_to_tpm(input_file_path, output_file_path):
comment gene_abundance = pd.read_csv(input_file_path, sep='\t', index_col=... | #!/usr/bin/env python
"""
Convert gene abundance in absolute counts to tpm.
"""
import numpy as np
from utils import _handle_io
# import pandas as pd
# def convert_to_tpm(input_file_path, output_file_path):
# gene_abundance = pd.read_csv(input_file_path, sep='\t', index_col=['plate', 'well', 'lane'])
# conv... | Python | zaydzuhri_stack_edu_python |
function maxArea h w horizontalCuts verticalCuts
begin
sort horizontalCuts
sort verticalCuts
set maxH = max horizontalCuts at 0 h - horizontalCuts at - 1
set maxV = max verticalCuts at 0 w - verticalCuts at - 1
for i in range 1 length horizontalCuts
begin
set maxH = max maxH horizontalCuts at i - horizontalCuts at i - ... | def maxArea(h, w, horizontalCuts, verticalCuts):
horizontalCuts.sort()
verticalCuts.sort()
maxH = max(horizontalCuts[0], h - horizontalCuts[-1])
maxV = max(verticalCuts[0], w - verticalCuts[-1])
for i in range(1, len(horizontalCuts)):
maxH = max(maxH, horizontalCuts[i] - horizontalCuts[i -... | Python | jtatman_500k |
function __call__ self x
begin
return call complex_derivative func call complex x h=step I=order err=err real=__real imag=__imag
end function | def __call__ ( self , x ) :
return complex_derivative ( self.func ,
complex ( x ) ,
h = self.step ,
I = self.order ,
err = self.err ,
... | Python | nomic_cornstack_python_v1 |
function calcular_iva_servicio cantidad_horas tasa
begin
set tasa = tasa / 100
set iva_servicio = call calcular_precio_servicio cantidad_horas * tasa
return iva_servicio
end function | def calcular_iva_servicio(cantidad_horas, tasa):
tasa = tasa / 100
iva_servicio = calcular_precio_servicio(cantidad_horas) * tasa
return iva_servicio | Python | nomic_cornstack_python_v1 |
function new_wave_grid waves wave_method=string iref iref=0 wave_grid_min=none wave_grid_max=none A_pix=none v_pix=none samp_fact=1.0 **kwargs
begin
if not is instance waves MaskedArray
begin
set waves = array waves mask=waves < 10.0
end
comment Constant km/s
if wave_method == string velocity
begin
set spl = 299792.458... | def new_wave_grid(waves,wave_method='iref',iref=0,wave_grid_min=None,wave_grid_max=None,
A_pix=None,v_pix=None,samp_fact=1.0,**kwargs):
if not isinstance(waves, np.ma.MaskedArray):
waves = np.ma.array(waves,mask=waves<10.0)
if wave_method == 'velocity': # Constant km/s
spl = ... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
call init
set settings = call Settings
set controlador = call controlador
comment lo uso para pruebas de terminal
comment self.screen = pygame.display.set_mode(
comment (self.settings.screen_width, self.settings.screen_height))
set screen = call set_mode tuple 0 0 FULLSCREEN
set screen_widt... | def __init__(self):
pygame.init()
self.settings = Settings()
self.controlador = controlador()
#lo uso para pruebas de terminal
#self.screen = pygame.display.set_mode(
#(self.settings.screen_width, self.settings.screen_height))
self.screen = pygame.display.set... | Python | nomic_cornstack_python_v1 |
function load_stashed_config
begin
try
begin
with open string h5config.json string r as f
begin
set cfg = load json f
end
if not is instance cfg dict
begin
raise TypeError
end
end
except Exception
begin
return dict
end
return cfg
end function | def load_stashed_config():
try:
with open('h5config.json', 'r') as f:
cfg = json.load(f)
if not isinstance(cfg, dict):
raise TypeError
except Exception:
return {}
return cfg | Python | nomic_cornstack_python_v1 |
function test_partie joueur1 joueur2 tableau_invisible_joueur1 tableau_invisible_joueur2
begin
print string plateau du joueur 2 :
call tour_de_jeu joueur1 joueur2 tableau_invisible_joueur2
call rafraichir_position joueur2 porte_avion
call verif_bateau joueur1 porte_avion
print string plateau du joueur 1 :
call tour_de_... | def test_partie(joueur1: object,
joueur2: object,
tableau_invisible_joueur1: list, tableau_invisible_joueur2: list
):
print("plateau du joueur 2 : \n")
tour_de_jeu(joueur1, joueur2, tableau_invisible_joueur2)
rafraichir_position(joueur2, joueur2.porte_avion)... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import math
import time
import datetime
print today
set black = tuple 0 0 0
set blue = tuple 255 0 0
function euclidean_dist0 pointA pointB
begin
set total = decimal 0
for dimension in range 0 length pointA
begin
set total = total + pointA at dimension - pointB at dimension ^ 2
end
set dis... | import cv2
import numpy as np
import math
import time
import datetime
print(datetime.datetime.today())
black = (0,0,0)
blue = (255,0,0)
def euclidean_dist0(pointA, pointB):
total = float(0)
for dimension in range(0, len(pointA)):
total += (pointA[dimension] - pointB[dimension])**2
dist = math.sqrt... | Python | zaydzuhri_stack_edu_python |
function __init__ self x y xVelocity yVelocity rotation
begin
call __init__ x=x y=y width=BOLT_WIDTH height=BOLT_HEIGHT fillcolor=string black linecolor=string black angle=rotation
set _xVelocity = xVelocity
set _yVelocity = yVelocity
end function | def __init__(self, x, y, xVelocity, yVelocity, rotation):
super().__init__(x=x,y=y,width=BOLT_WIDTH,height=BOLT_HEIGHT,
fillcolor='black',linecolor="black", angle=rotation)
self._xVelocity = xVelocity
self._yVelocity = yVelocity | Python | nomic_cornstack_python_v1 |
function __setup_z3_variables self
begin
set comps = call components
set n = num_trans
comment state variables
set aut_qs = list states
set tuple qsort vals = call EnumSort string State list comprehension name for q in aut_qs
set qvals = dict
for tuple q v in call izip aut_qs vals
begin
set qvals at q = v
end
set qvar... | def __setup_z3_variables(self):
comps = self.aut.components()
self.n = comps.num_trans
# state variables
aut_qs = list(comps.states)
self.qsort, vals = EnumSort("State", [q.name for q in aut_qs])
self.qvals = {}
for q, v in izip(aut_qs, vals):
self.... | Python | nomic_cornstack_python_v1 |
function shape self
begin
return _shape
end function | def shape(self):
return self._shape | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function canReach self arr start
begin
string :type arr: List[int] :type start: int :rtype: bool
set left = list
set right = list
for idx in range length arr
begin
set l = idx - arr at idx
set r = idx + arr at idx
comment if l>=0:
append left l
comment else: left.append(-1)
comment... | class Solution(object):
def canReach(self, arr, start):
"""
:type arr: List[int]
:type start: int
:rtype: bool
"""
left = []
right = []
for idx in range(len(arr)):
l = idx-arr[idx]
r = idx+arr[idx]
# if l>=0:
... | Python | zaydzuhri_stack_edu_python |
if vel > 80
begin
print format string Você foi MULTADO! o valor a ser pago é: {:.2f} multa
end
else
begin
print string Você está na velocidade correta!
end | if vel > 80:
print('Você foi MULTADO! o valor a ser pago é: {:.2f}'.format(multa))
else:
print('Você está na velocidade correta! ')
| Python | zaydzuhri_stack_edu_python |
function resource_path self relative_path
begin
set base_path = get attribute sys string _MEIPASS directory name path absolute path path __file__
return join path base_path relative_path
end function | def resource_path(self, relative_path) :
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path) | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
set __author__ = string lc
class Person extends object
begin
comment 定义私有属性
set __money = 1000
set _hello = string happy
set color = string yellow
function get_money self
begin
return __money
end function
comment 构造方法,定义实例属性
function __init__ self name age
begin
set name = name
set age = age
end fu... | #coding:utf-8
__author__ = 'lc'
class Person(object):
#定义私有属性
__money = 1000
_hello = 'happy'
color = 'yellow'
def get_money(self):
return self.__money
#构造方法,定义实例属性
def __init__(self,name,age):
self.name = name
self.age = age
# print('执行init方法')
de... | Python | zaydzuhri_stack_edu_python |
string Created on Sep 14, 2017 @author: riteshagarwal
from java.util.concurrent import TimeUnit
from threading import InterruptedException
import sys
import threading
function shutdown_and_await_termination pool timeout
begin
call shutdown
end function | '''
Created on Sep 14, 2017
@author: riteshagarwal
'''
from java.util.concurrent import TimeUnit
from threading import InterruptedException
import sys
import threading
def shutdown_and_await_termination(pool, timeout):
pool.shutdown() | Python | zaydzuhri_stack_edu_python |
for i in range 5 0 - 1
begin
set guess = integer input string 请输入你猜的数(0~9):
if guess == num
begin
print string 恭喜!你猜中了!
break
end
else
if guess > num
begin
print string 太大,您还有 i - 1 string 次机会
end
else
begin
print string 太小,您还有 i - 1 string 次机会
end
end
print string 抱歉,程序结束了 | for i in range(5,0,-1):
guess=int(input('请输入你猜的数(0~9):'))
if guess == num:
print("恭喜!你猜中了!")
break
elif guess > num:
print("太大,您还有",i-1,"次机会")
else:
print("太小,您还有",i-1,"次机会")
print("抱歉,程序结束了")
| Python | zaydzuhri_stack_edu_python |
import copy
function shallowCopy obj
begin
string 浅复制任意对象 :param obj: :return:
return copy copy obj
end function
function deepCopy obj
begin
string 深复制任意对象 :param obj: :return:
return deep copy obj
end function | import copy
def shallowCopy(obj):
'''
浅复制任意对象
:param obj:
:return:
'''
return copy.copy(obj)
def deepCopy(obj):
'''
深复制任意对象
:param obj:
:return:
'''
return copy.deepcopy(obj) | Python | zaydzuhri_stack_edu_python |
comment if like > 5000 and comment > 1500 and share > 3000:
set conditions = list like > 5000 comment > 1500 share > 30000
if all conditions
begin
print string Awesome video
end
comment if like > 5000 or comment > 1500 or share > 3000:
if any conditions
begin
print string Awesome video2
end
set x = 500
set y = 100
set ... | #if like > 5000 and comment > 1500 and share > 3000:
conditions = [
like > 5000,
comment > 1500,
share > 30000
]
if all(conditions):
print("Awesome video")
#if like > 5000 or comment > 1500 or share > 3000:
if any(conditions):
print("Awesome video2")
x = 500
y = 100
conditions2 = [
x > 120,
... | Python | zaydzuhri_stack_edu_python |
function ex_update_pool self pool
begin
set create_node_elm = call Element string editPool dict string xmlns TYPES_URN
set text = string load_balance_method
set text = service_down_action
set text = string slow_ramp_time
set response = object
set response_code = find text response string responseCode TYPES_URN
return r... | def ex_update_pool(self, pool):
create_node_elm = ET.Element("editPool", {"xmlns": TYPES_URN})
ET.SubElement(create_node_elm, "loadBalanceMethod").text = str(pool.load_balance_method)
ET.SubElement(create_node_elm, "serviceDownAction").text = pool.service_down_action
ET.SubElement(creat... | Python | nomic_cornstack_python_v1 |
function num_bad_votes self
begin
return count filter correct=false
end function | def num_bad_votes(self):
return self.qualities.filter(correct=False).count() | Python | nomic_cornstack_python_v1 |
comment you can change this value for testing
set number = 5
if number > 0
begin
print string Success
end
else
begin
print string Fail
end | number = 5 # you can change this value for testing
if number > 0:
print("Success")
else:
print("Fail")
| Python | flytech_python_25k |
import os
from spmf_line_parsers import parse_line
class SPMFOutputRule extends object
begin
function __init__ self antcedants_int consequents_int stats
begin
set antcedants_int = antcedants_int
set consequents_int = consequents_int
set stats = stats
end function
function give_conf self
begin
if stats and string conf i... | import os
from spmf_line_parsers import parse_line
class SPMFOutputRule(object):
def __init__(self, antcedants_int, consequents_int, stats):
self.antcedants_int = antcedants_int
self.consequents_int = consequents_int
self.stats = stats
def give_conf(self):
if self.stats and ... | Python | zaydzuhri_stack_edu_python |
function _quote value
begin
if not difference set value SAFE_CHARS
begin
return string value
end
if is instance value unicode
begin
return string string " + join string generator expression call _quote_char x for x in value + string "
end
return string string " + join string generator expression call _quote_byte x fo... | def _quote(value):
if not set(value).difference(SAFE_CHARS):
return str(value)
if isinstance(value, unicode):
return str('"' + ''.join(_quote_char(x) for x in value) + '"')
return str('"' + ''.join(_quote_byte(x) for x in value) + '"') | Python | nomic_cornstack_python_v1 |
import numpy as np
from openmdao.api import ExplicitComponent , Problem , Group , IndepVarComp , ExecComp , NonlinearBlockGS , NewtonSolver , DirectSolver , ScipyOptimizeDriver
import math
from openmdao.api import ExplicitComponent , Problem , Group , IndepVarComp , ExecComp , NonlinearBlockGS , NewtonSolver , DirectSo... | import numpy as np
from openmdao.api import ExplicitComponent, Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS, NewtonSolver, DirectSolver, ScipyOptimizeDriver
import math
from openmdao.api import ExplicitComponent, Problem, Group, IndepVarComp, ExecComp, NonlinearBlockGS, NewtonSolver, DirectSolver, ScipyOpt... | Python | zaydzuhri_stack_edu_python |
set fr = open string dishin.txt string r
set items = integer read line fr
set data = split read fr
close fr
set data = list map int data
set total = sum data
set low = min data
set high = max data
set mean = integer total / items
set fw = open string dishout.txt string w
write fw string %d %d %d % tuple low high mean
c... | fr = open('dishin.txt', 'r')
items = int(fr.readline())
data = fr.read().split()
fr.close()
data = list(map(int, data))
total = sum(data)
low = min(data)
high = max(data)
mean = int(total/items)
fw = open('dishout.txt', 'w')
fw.write('%d %d %d' % (low, high, mean))
fw.close()
| Python | zaydzuhri_stack_edu_python |
function sort_by self
begin
comment If sorting by a non required column, figure out the datatype in case
comment we need to backfill.
set column_null_data = string
if sortby not in REQUIRED_COLUMNS
begin
for peak in peaks
begin
set example_value = get peak sortby none
if example_value
begin
if is instance example_valu... | def sort_by(self):
# If sorting by a non required column, figure out the datatype in case
# we need to backfill.
column_null_data = ""
if self.sortby not in REQUIRED_COLUMNS:
for peak in self.peaks:
example_value = peak.get(self.sortby, None)
i... | Python | nomic_cornstack_python_v1 |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from jsonfield import JSONField
import re
set STARTER_CODE = string /* on_post is called when a user you are following makes a post. Pro Tip: You can follow yourself for easier testing */ function on_post(input) {... | from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from jsonfield import JSONField
import re
STARTER_CODE = """
/*
on_post is called when a user you are following makes a post.
Pro Tip: You can follow yourself for easier testing
*/
function on_post(input) {
... | Python | zaydzuhri_stack_edu_python |
function gen_sample mean std seed N=600 K=3 dims=2
begin
set samples = call empty tuple N dims
seed seed
for k in range K
begin
set n = integer N / K
set samples at slice n * k : n * k + 1 : = call normal loc=mean at k scale=std at k ^ 2 size=tuple n dims
end
return samples
end function | def gen_sample(mean: list, std: list, seed: float, N: int = 600, K: int = 3, dims: int = 2):
samples = np.empty((N, dims))
np.random.seed(seed)
for k in range(K):
n = int(N / K)
samples[n * k:n * (k + 1)] = np.random.normal(loc=mean[k], scale=std[k] ** 2, size=(n, dims))
return sample... | Python | nomic_cornstack_python_v1 |
function search_lines self pattern
begin
set pat = compile pattern
for i in range 0 length self
begin
set match = search self at i
if match
begin
return tuple i match
end
end
end function | def search_lines(self, pattern):
pat = re.compile(pattern)
for i in range(0, len(self)):
match = pat.search(self[i])
if match:
return i, match | Python | nomic_cornstack_python_v1 |
for i in range T
begin
set args = split right strip read line inp
set K = integer args at 0
set C = integer args at 1
set S = integer args at 2
if K == S
begin
write out string Case # + string i + 1 + string :
for j in range S - 1
begin
write out string j + 1 + string
end
write out string S + string
end
end | for i in range(T):
args=((inp.readline()).rstrip()).split()
K=int(args[0])
C=int(args[1])
S=int(args[2])
if K==S:
out.write("Case #" + str(i+1) + ": ")
for j in range(S-1):
out.write(str(j+1)+" ")
out.write(str(S)+"\n") | Python | zaydzuhri_stack_edu_python |
function repeater at_least timeout
begin
set timer = call Timer timeout
set repeat = 0
while repeat < at_least or call remaining
begin
yield repeat
set repeat = repeat + 1
end
end function | def repeater(at_least, timeout):
timer = Timer(timeout)
repeat = 0
while repeat < at_least or timer.remaining():
yield repeat
repeat += 1 | Python | nomic_cornstack_python_v1 |
function claimNetworkDevices self networkId serials
begin
set kwargs = locals
set metadata = dict string tags list string networks string configure string devices ; string operation string claimNetworkDevices
set resource = string /networks/ { networkId } /devices/claim
set body_params = list string serials
set payload... | def claimNetworkDevices(self, networkId: str, serials: list):
kwargs = locals()
metadata = {
'tags': ['networks', 'configure', 'devices'],
'operation': 'claimNetworkDevices'
}
resource = f'/networks/{networkId}/devices/claim'
body_params = ['serials', ]... | Python | nomic_cornstack_python_v1 |
class card
begin
function __init__ self rank suit
begin
set rank = rank
set suit = suit
end function
function __cmp__ self other
begin
if cardValueDict at string self < cardValueDict at string other
begin
return - 1
end
else
if cardValueDict at string self < cardValueDict at string other
begin
return 0
end
else
begin
r... | class card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __cmp__(self, other):
if cardValueDict[str(self)] < cardValueDict[str(other)]:
return -1
elif cardValueDict[str(self)] < cardValueDict[str(other)]:
return 0
else:
... | Python | zaydzuhri_stack_edu_python |
function __filter_by_limited_constants math_pred_list file_handler=none
begin
set new_math_pred_list = list
set del_math_pred_list = list
for math_pred in math_pred_list
begin
set tuple var_list sort_list body = math_pred
set constants = find all body
if length constants >= 2 and find body string % == - 1
begin
append ... | def __filter_by_limited_constants(math_pred_list, file_handler=None):
new_math_pred_list = list()
del_math_pred_list = list()
for math_pred in math_pred_list:
var_list, sort_list, body = math_pred
constants = number_pattern.findall(body)
if len(constants)>=2 and body.find('%') ==-1:
del_math_pred_list.appen... | Python | nomic_cornstack_python_v1 |
comment 4
set s1 = 0
set s2 = 0
for i in range 1 2000 2
begin
set s1 = s1 + i
end
for j in range 2 2001 2
begin
set s2 = s2 + j
end
print s1 - s2 | #4
s1=0
s2=0
for i in range (1,2000,2):
s1=s1+i
for j in range (2,2001,2):
s2=s2+j
print(s1-s2) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3.7.2
comment -*- coding: utf-8 -*-
set H = input string 输入您的身高
set W = input string 输入您的体重
set Height = integer H
set Weight = integer W
set BMI = Weight / Height * Height / 10000
print BMI
if BMI < 18.5
begin
print string 过轻
end
else
if BMI <= 25
begin
print string 正常
end
else
if BMI <= 28... | #!/usr/bin/env python3.7.2
#-*- coding: utf-8 -*-
H = input('输入您的身高')
W = input('输入您的体重')
Height = int(H)
Weight = int(W)
BMI = Weight/(Height*Height/10000)
print(BMI)
if BMI < 18.5:
print('过轻')
elif BMI <=25:
print('正常')
elif BMI <=28:
print('过重') | Python | zaydzuhri_stack_edu_python |
import numpy as np
function f w b x
begin
return 1.0 / 1.0 + exp - w * x + b
end function
function grad_w w b x
begin
set fx = f dist w b x
return fx
end function
function grad_b w b x
begin
set fx = f dist w b x
return fx
end function
function loss w b
begin
set error = 0
set error = error + 0.5 * w - b ^ 2
return err... | import numpy as np
def f(w,b,x):
return 1.0 / (1.0 + np.exp(-(w*x + b)))
def grad_w(w,b,x):
fx = f(w,b,x)
return fx
def grad_b(w,b,x):
fx = f(w,b,x)
return fx
def loss(w,b):
error =0
error += 0.5 * (w - b) ** 2
return error
parameters1 = np.load('autoencoder1.npy')
w_e_1 = paramet... | Python | zaydzuhri_stack_edu_python |
string Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7
class Solution extends object
begin
function calculate self... | """
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
"""
class Solution(object):
def calculate(self, s):
... | Python | zaydzuhri_stack_edu_python |
function insert_recur_aux self current idx
begin
comment Base case
if idx < 0
begin
comment when I gone through all of my letters
set link at 0 = call TrieNode
return
end
else
begin
comment calculate index ($, A, B, ...)
comment - ord(a) + terminal string
set index = ordinal genome at idx - ordinal string A + 1
comment... | def insert_recur_aux(self, current, idx):
# Base case
if idx < 0:
# when I gone through all of my letters
current.link[0] = TrieNode()
return
else:
# calculate index ($, A, B, ...)
index = ord(self.genome[idx]) - ord("A") + 1 #... | Python | nomic_cornstack_python_v1 |
function remove_rain_norain_discontinuity R
begin
set R = copy R
set zerovalue = call nanmin R
set threshold = call nanmin R at R > zerovalue
set R at R > zerovalue = R at R > zerovalue - threshold - zerovalue
set R = R - call nanmin R
return R
end function | def remove_rain_norain_discontinuity(R):
R = R.copy()
zerovalue = np.nanmin(R)
threshold = np.nanmin(R[R > zerovalue])
R[R > zerovalue] -= threshold - zerovalue
R -= np.nanmin(R)
return R | Python | nomic_cornstack_python_v1 |
function now_playing update context
begin
with call mpdclient as c
begin
set song = call currentsong
end
comment TODO(shoeffner): Handle properly
call reply_text song
end function | def now_playing(update, context):
with mpdclient() as c:
song = c.currentsong()
# TODO(shoeffner): Handle properly
update.message.reply_text(song) | Python | nomic_cornstack_python_v1 |
function __init__ self logical_name=none port_name=none
begin
call __init__ logical_name=logical_name port_name=port_name port_type=string external
end function | def __init__(self, logical_name=None, port_name=None):
super(External, self).__init__(
logical_name=logical_name,
port_name=port_name,
port_type="external") | Python | nomic_cornstack_python_v1 |
function is_today day
begin
return call Day today == day
end function | def is_today(day):
return model.Day(date.today()) == day | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib
set rcParams at string font.family = string sans-serif
set rcParams at string font.sans-serif = list string Arial
call use string Agg
import matplotlib.pyplot as plt
comment positive
set pos_data = list 2246 4175 7491 17089 3699
comment Negative
set neg_data = list 540388 1438226 20... | import numpy as np
import matplotlib
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['Arial']
matplotlib.use('Agg')
import matplotlib.pyplot as plt
pos_data = [2246,4175,7491,17089,3699] #positive
neg_data=[540388,1438226,2027958,1596290,269799] #Negative
def func(pct, allv... | Python | zaydzuhri_stack_edu_python |
string 1.1 Write a Python Program to implement your own myreduce() function which works exactly like Python's built-in function reduce()
function myreduce function dataset
begin
set a = dataset at 0
for i in dataset at slice 1 : :
begin
set a = call function a i
end
return a
end function
set dataset = list 1 2 3 4 5 ... | '''
1.1 Write a Python Program to implement your own myreduce() function which works exactly like Python's built-in function reduce()
'''
def myreduce(function, dataset):
a = dataset[0]
for i in dataset[1:]:
a = function(a, i)
return a
dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def do_su... | Python | zaydzuhri_stack_edu_python |
import math , base64
function square_root x
begin
print string Square Root Called
set y = square root x
return y
end function
function squared x
begin
print string Squared Called
set y = x * x
return y
end function
function factorial x
begin
if x == 1
begin
return x
end
else
begin
return x * call factorial x - 1
end
en... | import math, base64
def square_root(x):
print('Square Root Called')
y = math.sqrt(x)
return y
def squared(x):
print('Squared Called')
y = x * x
return y
def factorial(x):
if (x == 1):
return x
else:
return x * factorial(x - 1)
def rotateImage(x):
# X is a hash cod... | Python | zaydzuhri_stack_edu_python |
import Filter
class Umbral extends filter
begin
function __init__ self umbral
begin
set umbral = umbral
set minimo = 0
end function
function setMinimo self minimo
begin
set minimo = minimo
end function
function filterSignal self x
begin
if x > umbral
begin
return x
end
else
begin
return minimo
end
end function
end clas... | import Filter
class Umbral(Filter.filter):
def __init__(self, umbral):
self.umbral = umbral
self.minimo = 0
def setMinimo(self, minimo):
self.minimo = minimo
def filterSignal(self,x):
if x > self.umbral:
return x
else:
return self.minimo | Python | zaydzuhri_stack_edu_python |
function _get_generator self raw_data
begin
set stack_parser = call StackParser raw_data
return call stack_collapse
end function | def _get_generator(self, raw_data):
stack_parser = StackParser(raw_data)
return stack_parser.stack_collapse() | Python | nomic_cornstack_python_v1 |
function test_repositories_scan_all_post self
begin
pass
end function | def test_repositories_scan_all_post(self):
pass | Python | nomic_cornstack_python_v1 |
function test_page_init_return self
begin
set out_to_test = call init
set out_type = string type out_to_test
assert equal out_type string <class 'dash.dash.Dash'>
end function | def test_page_init_return(self):
out_to_test = page.init()
out_type = str(type(out_to_test))
self.assertEqual(out_type, "<class 'dash.dash.Dash'>") | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Nov 12 12:49:58 2020 @author: SUBHAM
set s = input string enter string
set s = string + s
set w = 0
set v = 0
set c = 0
set p = 0
for i in range length s
begin
if s at i == string
begin
set w = w + 1
end
else
if s at i == string . or s at i == string , or s at i == ... | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 12:49:58 2020
@author: SUBHAM
"""
s= input("enter string")
s=" "+s
w=0;v=0;c=0;p=0
for i in range(len(s)):
if(s[i]==" "):
w=w+1
elif(s[i]=="." or s[i]=="," or s[i]=="?" or s[i]=="!" or s[i]==":" or s[i]=="'"):
p=p+1 | Python | zaydzuhri_stack_edu_python |
function draw self
begin
return if expression length current > 0 then pop current else none
end function | def draw(self):
return self.current.pop() if len(self.current) > 0 else None | Python | nomic_cornstack_python_v1 |
function test_update_account_credentials self
begin
set loginItem = call LoginItem
set response = open string /api/account/credentials method=string PUT data=dumps loginItem content_type=string application/json
call assert200 response string Response body is : + decode data string utf-8
end function | def test_update_account_credentials(self):
loginItem = LoginItem()
response = self.client.open(
'/api/account/credentials',
method='PUT',
data=json.dumps(loginItem),
content_type='application/json')
self.assert200(response,
'... | Python | nomic_cornstack_python_v1 |
function on self value=1 t=none wait=false
begin
if t is none
begin
set value = value
end
else
begin
call _start_change lambda -> iterate list tuple value t 1 wait
end
end function | def on(self, value=1, t=None, wait=False):
if t is None:
self.value = value
else:
self._start_change(lambda : iter([(value, t), ]), 1, wait) | Python | nomic_cornstack_python_v1 |
comment filters big file, and prints out only data for one day
set f = open string cebu_data/locationupdate.csv string r
comment it's Friday!
set today = string 2013-10-04
set nextweek = string 2013-10-11
set counter = 0
for line in f
begin
set counter = counter + 1
if counter == 1
begin
continue
end
set els = split li... | # filters big file, and prints out only data for one day
f = open("cebu_data/locationupdate.csv","r")
today="2013-10-04" #it's Friday!
nextweek="2013-10-11"
counter=0
for line in f:
counter = counter+1
if counter==1:
continue
els=line.split(";")
| Python | zaydzuhri_stack_edu_python |
function visit_repr self node parent
begin
string visit a Backquote node by returning a fresh instance of it
set newnode = call Repr lineno col_offset parent
call postinit call visit value newnode
return newnode
end function | def visit_repr(self, node, parent):
"""visit a Backquote node by returning a fresh instance of it"""
newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | Python | jtatman_500k |
function get_azure_keyvault_kms_key_vault_network_access self
begin
return call _get_azure_keyvault_kms_key_vault_network_access enable_validation=true
end function | def get_azure_keyvault_kms_key_vault_network_access(self) -> Union[str, None]:
return self._get_azure_keyvault_kms_key_vault_network_access(enable_validation=True) | Python | nomic_cornstack_python_v1 |
function _fraction_latency self users_distances
begin
set users_desired_latency = array list map lambda a -> services_desired_latency at a users_services
set check = users_distances < users_desired_latency
set fraction = call count_nonzero check == true / num_of_users
return fraction
end function | def _fraction_latency(self, users_distances):
users_desired_latency = np.array(list(map(lambda a: self.services_desired_latency[a],
self.users_services)))
check = users_distances < users_desired_latency
fraction = np.count_nonzero(check==True) /... | Python | nomic_cornstack_python_v1 |
function get_default_compute_settings_filenames
begin
return tuple _compute_settings_filename _compute_settings_comments_filename
end function | def get_default_compute_settings_filenames():
return (_compute_settings_filename,_compute_settings_comments_filename) | Python | nomic_cornstack_python_v1 |
function test_get_roles_for_groups_on_domain self
begin
set domain1 = call new_domain_ref
call create_domain domain1 at string id domain1
set group_list = list
set group_id_list = list
set role_list = list
for _ in range 3
begin
set group = call new_group_ref domain_id=domain1 at string id
set group = call create_gr... | def test_get_roles_for_groups_on_domain(self):
domain1 = unit.new_domain_ref()
self.resource_api.create_domain(domain1['id'], domain1)
group_list = []
group_id_list = []
role_list = []
for _ in range(3):
group = unit.new_group_ref(domain_id=domain1['id'])
... | Python | nomic_cornstack_python_v1 |
function modify_block self block_id=none hit_points=none active=none
begin
if block_id is none
begin
set block_id = call get_id
end
else
if block_id == 0
begin
set _int_24 = 0
return
end
else
if hit_points is none
begin
set hit_points = hit_points
end
if hit_points is none
begin
set hit_points = call get_hit_points
end... | def modify_block(self, block_id=None, hit_points=None, active=None):
if block_id is None:
block_id = self.get_id()
elif block_id == 0:
self._int_24 = 0
return
elif hit_points is None:
hit_points = block_config[block_id].hit_points
if hit_p... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment import the time function from the sleep
from time import sleep
comment library
comment import our GPIO library
import RPi.GPIO as GPIO
comment set the board numbering system to BCM
call setmode BCM
comment setup our output pins
setup GPIO 17 OUT
setup GPIO 27 OUT
comment Turn LEDs on
pr... | #!/usr/bin/python
from time import sleep # import the time function from the sleep
# library
import RPi.GPIO as GPIO # import our GPIO library
GPIO.setmode(GPIO.BCM) # set the board numbering system to BCM
# setup our output pins
GPIO.setup(17,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
# Turn LEDs on
print('Light on')
GPIO.outp... | Python | zaydzuhri_stack_edu_python |
function get_builder_image_url benchmark fuzzer docker_registry
begin
return string { docker_registry } /builders/ { fuzzer } / { benchmark }
end function | def get_builder_image_url(benchmark, fuzzer, docker_registry):
return f'{docker_registry}/builders/{fuzzer}/{benchmark}' | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import time
import pigpio
set PIN = 4
set TOGGLE = 10000
comment Connect to local Pi.
set pi = call pi
set s = time
for i in range TOGGLE
begin
write pi PIN 1
write pi PIN 0
end
set e = time
print format string pigpio did {} toggles per second integer TOGGLE / e - s
call stop | #!/usr/bin/env python
import time
import pigpio
PIN=4
TOGGLE=10000
pi = pigpio.pi() # Connect to local Pi.
s = time.time()
for i in range(TOGGLE):
pi.write(PIN, 1)
pi.write(PIN, 0)
e = time.time()
print("pigpio did {} toggles per second".format(int(TOGGLE/(e-s))))
pi.stop()
| Python | zaydzuhri_stack_edu_python |
function login self
begin
set backend = backend
set session at session_id_key = self at string id
set session at session_backend_key = session_backend_val
set session at session_hash_key = call _get_session_hash self at string password
end function | def login(self):
backend = self.backend
self.session[backend.session_id_key] = self["id"]
self.session[backend.session_backend_key] = backend.session_backend_val
self.session[backend.session_hash_key] = self._get_session_hash(
self["password"]
) | Python | nomic_cornstack_python_v1 |
function validate_email self attribute value
begin
if not all map lambda e -> call is_email e value
begin
raise call ValueError string Invalid email in DAG email: { value } .
end
end function | def validate_email(self, attribute, value):
if not all(map(lambda e: is_email(e), value)):
raise ValueError(f"Invalid email in DAG email: {value}.") | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
from import util
class Cave
begin
function __init__ self state rules
begin
set state = default dictionary lambda -> string .
for tuple i c in enumerate state
begin
set state at i = c
end
set rules = default dictionary lambda -> string .
for key in rules
begin
set rules at key = ru... | from collections import defaultdict
from .. import util
class Cave:
def __init__(self, state, rules):
self.state = defaultdict(lambda: '.')
for i, c in enumerate(state):
self.state[i] = c
self.rules = defaultdict(lambda: '.')
for key in rules:
self.rules[key]... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Audio module
import numpy as np
import warnings
from pylab import pause
try
begin
from sounddevice import play
set audio_ok = true
end
except ImportError
begin
set audio_ok = false
end
if not audio_ok
begin
try
begin
from _scikits.audiolab import play
set audio_ok = true
end
except ... | # -*- coding: utf-8 -*-
"""
Audio module
"""
import numpy as np
import warnings
from pylab import pause
try:
from sounddevice import play
audio_ok = True
except ImportError:
audio_ok = False
if not audio_ok:
try:
from _scikits.audiolab import play
audio_ok = True
except ImportErr... | Python | zaydzuhri_stack_edu_python |
import abc
from subprocess import Popen , PIPE
class PartitionInformer extends object
begin
set __metaclass__ = ABCMeta
decorator abstractmethod
function disk_list self
begin
pass
end function
decorator abstractmethod
function partition_list self n
begin
pass
end function
end class
class WindowsInformer extends Partiti... | import abc
from subprocess import Popen, PIPE
class PartitionInformer(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def disk_list(self):
pass
@abc.abstractmethod
def partition_list(self, n):
pass
class WindowsInformer(PartitionInformer):
def disk_list(self):
... | Python | zaydzuhri_stack_edu_python |
import redis
import json
class Database
begin
function __init__ self pw=none
begin
set r = call Redis host=string localhost port=6379 password=pw
end function
function instance self
begin
return r
end function
function peek self
begin
for x in keys r
begin
if call contains string block
begin
print decode x decode get r... | import redis
import json
class Database:
def __init__(self,pw=None):
self.r = redis.Redis(host='localhost', port=6379, password=pw)
def instance(self):
return self.r
def peek(self):
for x in self.r.keys():
if x.decode().contains("block"):
print(x.decod... | Python | zaydzuhri_stack_edu_python |
function identity arg
begin
return arg
end function | def identity(arg):
return arg | Python | nomic_cornstack_python_v1 |
comment fibonacci recursion
function fib_rec n
begin
if n == 1
begin
return 1
end
else
if n == 2
begin
return 1
end
else
begin
return call fib_rec n - 1 + call fib_rec n - 2
end
end function
comment fibonacci memo
set memo = dict 1 1 ; 2 1
function fib_mem n
begin
if n in memo
begin
return memo at n
end
else
begin
set ... | # fibonacci recursion
def fib_rec(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return fib_rec(n - 1) + fib_rec(n - 2)
#fibonacci memo
memo = {
1: 1,
2: 1
}
def fib_mem(n):
if n in memo:
return memo[n]
else:
res = fib_mem(n -... | Python | zaydzuhri_stack_edu_python |
function change_flaring self flaw zlaw=none polycoeff=none h0=none c=none Rf=none zd=none ffit_array=none fitdegree=none Rlimit=none zcut=none
begin
set sigma0 = sigma0
set Rd = Rd
set Rd2 = Rd2
set alpha = alpha
set Rcut = Rcut
if zcut is none
begin
set zcut = zcut
end
if zlaw is none
begin
set zlaw = zlaw
end
else
be... | def change_flaring(self,flaw,zlaw=None,polycoeff=None,h0=None,c=None,Rf=None,zd=None,ffit_array=None,fitdegree=None,Rlimit=None, zcut=None):
sigma0=self.sigma0
Rd=self.Rd
Rd2=self.Rd2
alpha=self.alpha
Rcut=self.Rcut
if zcut is None:
zcut=self.zcut
if ... | Python | nomic_cornstack_python_v1 |
function calc_F self peq
begin
return dot log peq
end function | def calc_F(self, peq):
return self.dmat_d_.dot(np.log(peq)) | Python | nomic_cornstack_python_v1 |
function autoDLin self y0 u0 *args
begin
set tuple dfdy dfdu ydoterr = call autoLin y0 u0 *args
return tuple call eye length y0 + dt * dfdy dt * dfdu dt * ydoterr
end function | def autoDLin(self, y0, u0, *args):
dfdy, dfdu, ydoterr = self.autoLin(y0, u0, *args)
return np.eye(len(y0)) + self.dt * dfdy, self.dt * dfdu, self.dt * ydoterr | Python | nomic_cornstack_python_v1 |
function best_goals self
begin
set lowest_value = list
set lowest_name = list
for i in range _limit
begin
append lowest_value decimal string inf
append lowest_name string
end
for need in needs
begin
if value < lowest_value at 0
begin
set lowest_value at 2 = lowest_value at 1
set lowest_name at 2 = lowest_name at 1
se... | def best_goals(self):
lowest_value = []
lowest_name = []
for i in range(self._limit):
lowest_value.append(float("inf"))
lowest_name.append("")
for need in self.agent.needs:
if need.value < lowest_value[0]:
lowest_value[2] = lowest_val... | Python | nomic_cornstack_python_v1 |
function __init__ self module intrinsic_dimension device=0
begin
call __init__
comment Hide this from inspection by get_parameters()
set m = list module
set name_base_localname = list
comment Stores the initial value: \theta_{0}^{D}
set initial_value = dictionary
comment Fastfood parameters
set fastfood_params = dict ... | def __init__(self, module, intrinsic_dimension, device=0):
super(FastfoodWrap, self).__init__()
# Hide this from inspection by get_parameters()
self.m = [module]
self.name_base_localname = []
# Stores the initial value: \theta_{0}^{D}
self.initial_value = dict()
... | Python | nomic_cornstack_python_v1 |
function flight_bytes self
begin
set total = _total_bytes
if _ack_eliciting
begin
set total = total + tell buffer
end
return total
end function | def flight_bytes(self) -> int:
total = self._total_bytes
if self._ack_eliciting:
total += self.buffer.tell()
return total | Python | nomic_cornstack_python_v1 |
function cycle_len d
begin
set history = dict
set tuple num cnt = tuple 1 0
while true
begin
set digit = num * 10 % d
set num = digit
if call has_key digit
begin
return cnt - history at digit
end
else
begin
set history at digit = cnt
end
set cnt = cnt + 1
end
end function
set cycle = map lambda x -> call cycle_len x r... | def cycle_len(d):
history = {}
num, cnt = 1, 0
while True:
digit = (num * 10) % d
num = digit
if history.has_key(digit):
return cnt - history[digit]
else:
history[digit] = cnt
cnt = cnt + 1
cycle = map(lambda x :cycle_len(x), range(1, 1000)) | Python | zaydzuhri_stack_edu_python |
function plot_confusion_matrix cm classes normalize=false title=string Matriz de Confusion cmap=Blues
begin
image show cm interpolation=string nearest cmap=cmap
title plt title
call colorbar
set tick_marks = array range length classes
call xticks tick_marks classes rotation=90
call yticks tick_marks classes
set fmt = i... | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Matriz de Confusion',
cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tic... | Python | nomic_cornstack_python_v1 |
string Collection of various sequential layers in keras. Many of these models are directly copied from keras examples
import keras
from keras.models import Sequential
from keras.layers import Dense , Activation , Dropout , Conv2D , Flatten , MaxPooling2D , ConvLSTM2D , Conv3D , LSTM , BatchNormalization
from keras.cons... | """
Collection of various sequential layers in keras. Many of these models
are directly copied from keras examples
"""
import keras
from keras.models import Sequential
from keras.layers import (Dense,
Activation,
Dropout,
Conv2D,
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.