code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_api_v1_projects_post self
begin
pass
end function | def test_api_v1_projects_post(self):
pass | Python | nomic_cornstack_python_v1 |
function fake_lidar_file tmpdir_factory
begin
set file_name = join call mktemp string data string radar_file.nc
with call Dataset file_name string w format=string NETCDF4_CLASSIC as root_grp
begin
set tuple n_time n_height = tuple 4 4
call createDimension string time n_time
call createDimension string height n_height
s... | def fake_lidar_file(tmpdir_factory):
file_name = tmpdir_factory.mktemp("data").join("radar_file.nc")
with netCDF4.Dataset(file_name, "w", format="NETCDF4_CLASSIC") as root_grp:
n_time, n_height = 4, 4
root_grp.createDimension("time", n_time)
root_grp.createDimension("height", n_height)
... | Python | nomic_cornstack_python_v1 |
function files self pattern=none
begin
if pattern is none
begin
return list
end
return glob glob pattern
end function | def files (
self,
pattern = None
) :
if pattern is None : return [ ]
return glob.glob( pattern ) | Python | nomic_cornstack_python_v1 |
if n == 3
begin
pass
end
else
begin
print n
end | if n==3:
pass
else :
print(n)
| Python | zaydzuhri_stack_edu_python |
from decimal import *
import math
set prec = 102
set low = 2
set high = 99
set result = 0
for n in range low high + 1
begin
set i = integer square root n
if i * i == n
begin
continue
end
set decStr = string square root at slice : 101 :
for digit in decStr
begin
if digit != string .
begin
set result = result + integer... | from decimal import *
import math
getcontext().prec = 102
low = 2
high = 99
result = 0
for n in range(low, high + 1):
i = int(math.sqrt(n))
if (i * i == n):
continue
decStr = (str(Decimal(n).sqrt()))[:101]
for digit in decStr:
if (digit != '.'):
result += int(digit)
| Python | zaydzuhri_stack_edu_python |
function _config_cluster_kubernetes cluster cluster_template cfg_dir force=false certs=none use_keystone=false direct_output=false
begin
set cfg_file = string %s/config % cfg_dir
if tls_disabled or certs is none
begin
set cfg = string apiVersion: v1 clusters: - cluster: server: %(api_address)s name: %(name)s contexts: ... | def _config_cluster_kubernetes(cluster, cluster_template, cfg_dir,
force=False, certs=None, use_keystone=False,
direct_output=False):
cfg_file = "%s/config" % cfg_dir
if cluster_template.tls_disabled or certs is None:
cfg = ("apiVersion: v1\n... | Python | nomic_cornstack_python_v1 |
function share_nans self
begin
string Share not-a-numbers between all channels. If any channel is nan at a given index, all channels will be nan at that index after this operation. Uses the share_nans method found in wt.kit.
function f _ s channels
begin
set outs = call share_nans *[c[s] for c in channels]
for tuple c ... | def share_nans(self):
"""Share not-a-numbers between all channels.
If any channel is nan at a given index, all channels will be nan
at that index after this operation.
Uses the share_nans method found in wt.kit.
"""
def f(_, s, channels):
outs = wt_kit.shar... | Python | jtatman_500k |
for tuple username user_info in items users
begin
print string Username: + username
set full_name = user_info at string first + string + user_info at string last
set location = user_info at string location
print string Full name: + title full_name
print string Location: + title location
end | for username, user_info in users.items():
print('\nUsername:' + username)
full_name = user_info['first'] + ' ' + user_info['last']
location = user_info['location']
print('\tFull name:' + full_name.title())
print('\tLocation:' + location.title()) | Python | zaydzuhri_stack_edu_python |
function load_experience_replay_from_file self path
begin
set experience_replay_pool = load pickle open path string rb
end function | def load_experience_replay_from_file(self, path):
self.experience_replay_pool = pickle.load(open(path, 'rb')) | Python | nomic_cornstack_python_v1 |
function tab_menu_complete
begin
return get env string COMPLETION_MODE == string menu-complete
end function | def tab_menu_complete():
return XSH.env.get("COMPLETION_MODE") == "menu-complete" | Python | nomic_cornstack_python_v1 |
function new_restaurant_image_pair restaurant_id
begin
comment Don't proceed unless the user is logged in
if call handle_login login_session is false
begin
return call redirect string /login
end
if method == string POST
begin
comment Create an entry in the database for the image, and save the file
comment If image exis... | def new_restaurant_image_pair(restaurant_id):
# Don't proceed unless the user is logged in
if helper.handle_login(login_session) is False:
return redirect('/login')
if request.method == 'POST':
# Create an entry in the database for the image, and save the file
# If image exists, img... | Python | nomic_cornstack_python_v1 |
function adjust self *sizes repeat=false
begin
if not sizes
begin
set sizes = tuple MAX_WIDTH
end
set validated_sizes = map _validate_size sizes
set sizes_iter = if expression repeat then call repeat_all validated_sizes else call repeat_last validated_sizes
set size = next sizes_iter
set markup = list
set row : List a... | def adjust(self, *sizes: int, repeat: bool = False) -> "KeyboardBuilder[ButtonType]":
if not sizes:
sizes = (MAX_WIDTH,)
validated_sizes = map(self._validate_size, sizes)
sizes_iter = repeat_all(validated_sizes) if repeat else repeat_last(validated_sizes)
size = next(sizes_i... | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__
function descriptorRead self QLowEnergyDescriptor Union QByteArray=none bytes=none bytearray=none
begin
pass
end function | def descriptorRead(self, QLowEnergyDescriptor, Union, QByteArray=None, bytes=None, bytearray=None): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
function test_multi_exclude_functionality self
begin
set exclude_opts = list _opfields
remove exclude_opts string az
remove exclude_opts string instance_type
remove exclude_opts string storage_type
for ex_opt in exclude_opts
begin
comment noqa: E501
set base_url = string ?group_by[ { ex_opt } ]=*&filter[time_scope_unit... | def test_multi_exclude_functionality(self):
exclude_opts = list(OCPAWSExcludeSerializer._opfields)
exclude_opts.remove("az")
exclude_opts.remove("instance_type")
exclude_opts.remove("storage_type")
for ex_opt in exclude_opts:
base_url = f"?group_by[{ex_opt}]=*&filter[... | Python | nomic_cornstack_python_v1 |
function largestComponentSize A
begin
if length A <= 1
begin
return length A
end
set cal = list
set flagp = dict
set flaga = list comprehension - 1 for i in range length A
set prime = list 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 17... | def largestComponentSize(A):
if len(A) <= 1:
return len(A)
cal = []
flagp = {}
flaga = [-1 for i in range(len(A))]
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139, 149, 151, 157,... | Python | zaydzuhri_stack_edu_python |
comment Python Program to Count the Number of Lines in a Text File
set line_cnt = 0
with open call raw_input string Enter a filename: string r as fobj
begin
for line in fobj
begin
set line_cnt = line_cnt + 1
end
end
print format string Line count: {} line_cnt | # Python Program to Count the Number of Lines in a Text File
line_cnt = 0
with open(raw_input("Enter a filename:"),'r') as fobj:
for line in fobj:
line_cnt += 1
print ("Line count: {}".format(line_cnt))
| Python | zaydzuhri_stack_edu_python |
from ClasseCao import Cao
from ClasseGato import Gato
from ClasseElefante import Elefante
from ClasseCavalo import Cavalo
from ClasseAndorinha import Andorinha
from ClassePato import Pato
from ClasseGalinha import Galinha
class Iniciar extends object
begin
function __init__ self
begin
pass
end function
comment Iniciand... | from ClasseCao import Cao
from ClasseGato import Gato
from ClasseElefante import Elefante
from ClasseCavalo import Cavalo
from ClasseAndorinha import Andorinha
from ClassePato import Pato
from ClasseGalinha import Galinha
class Iniciar(object):
def __init__(self):
pass
#Iniciando Mamiferos
def iniciarCao(self... | Python | zaydzuhri_stack_edu_python |
function compute_glcm_textures polarisations kinds radii
begin
set progress = call tqdm total=length CASE_STUDIES * length polarisations * length kinds * length radii
for city in CASE_STUDIES
begin
set output_dir = join path DATA_DIR string processed string sentinel-1 id string textures
make directories output_dir exis... | def compute_glcm_textures(polarisations, kinds, radii):
progress = tqdm(total=(
len(CASE_STUDIES) * len(polarisations) * len(kinds) * len(radii)))
for city in CASE_STUDIES:
output_dir = os.path.join(
DATA_DIR, 'processed', 'sentinel-1', city.id, 'textures')
os.makedirs(outp... | Python | nomic_cornstack_python_v1 |
function get_timestamp_list client video_id
begin
set vtime_regex = compile string [\d\s\w]{0,1}\d:\d\d
set comments = call get_yt_comments client=client video_id=video_id
set times = list
for comment in comments
begin
set cur_times = find all comment
set clean_times = list comprehension call trim_str_num t for t in c... | def get_timestamp_list(client, video_id):
vtime_regex = re.compile(u'[\d\s\w]{0,1}\d:\d\d')
comments = get_yt_comments(client=client, video_id=video_id)
times = []
for comment in comments:
cur_times = vtime_regex.findall(comment)
clean_times = [trim_str_num(t) for t in cur_times]
... | Python | nomic_cornstack_python_v1 |
function setModoConsultar self mostrarBttNuevo=false dicValoresCompleto=none dicCondiciones=none
begin
set resp = call setModoConsultar self mostrarBttNuevo dicValoresCompleto dicCondiciones
set featureId = get dicValoresCompleto string gid
return resp
end function | def setModoConsultar(self, mostrarBttNuevo=False, dicValoresCompleto=None, dicCondiciones=None):
resp=ctrIntrodDatos.setModoConsultar(self, mostrarBttNuevo, dicValoresCompleto, dicCondiciones)
self.featureId=self.dicValoresCompleto.get("gid")
return resp | Python | nomic_cornstack_python_v1 |
function FastaLength FileName
begin
set sequence_length_list = list
set flush_n = 1
print string Reading fasta file
set FileHandle = open FileName string r
for sequence in parse SeqIO FileHandle string fasta
begin
write stdout string flush_n + string -
flush stdout
append sequence_length_list length sequence
set flush... | def FastaLength(FileName):
sequence_length_list = []
flush_n=1
print("Reading fasta file")
FileHandle = open(FileName, "r")
for sequence in SeqIO.parse(FileHandle, "fasta"):
sys.stdout.write(str(flush_n) + "-")
sys.stdout.flush()
sequence_length_list.append(len(sequen... | Python | nomic_cornstack_python_v1 |
function assertSameArray self a b
begin
if not call array_equal a b
begin
raise call AssertionError format string {} is not {} a b
end
end function | def assertSameArray(self, a, b):
if not np.array_equal(a, b):
raise AssertionError("{} is not {}".format(a, b)) | Python | nomic_cornstack_python_v1 |
function get_stone_tests
begin
set stone_tests = list
for rotation in call possible_rotations
begin
for sm in call possible_stone_maps
begin
append stone_tests tuple list comprehension tuple call unalign call apply_inverse l rotation l for l in call possible_latent_stones to_stone_unity_properties partial from_stone_u... | def get_stone_tests():
stone_tests = []
for rotation in stones_and_potions.possible_rotations():
for sm in stones_and_potions.possible_stone_maps():
stone_tests.append(
([(stones_and_potions.unalign(sm.apply_inverse(l), rotation), l)
for l in stones_and_potions.possible_latent_stones... | Python | nomic_cornstack_python_v1 |
from barbados.text import DisplayName
from barbados.serializers import ObjectSerializer
class SpecComponent
begin
string Someday the direct name part might be able to go away.
function __init__ self slug display_name=none quantity=none unit=none notes=none
begin
if not display_name
begin
set display_name = call Display... | from barbados.text import DisplayName
from barbados.serializers import ObjectSerializer
class SpecComponent:
"""
Someday the direct name part might be able to go away.
"""
def __init__(self, slug, display_name=None, quantity=None, unit=None, notes=None):
if not display_name:
displa... | Python | zaydzuhri_stack_edu_python |
function enable_hotkeys self
begin
if _hotkeys_enabled
begin
error string Hotkeys already enabled.
return
end
info string Enabling hotkey listener
for tuple k v in items _hotkeys
begin
set tuple func args kwargs = v
debug string Adding hotkey "%s" with function "%s" (args="%s", kwargs="%s") k __name__ args kwargs
call ... | def enable_hotkeys(self):
if self._hotkeys_enabled:
self.logger.error('Hotkeys already enabled.')
return
self.logger.info('Enabling hotkey listener')
for k, v in self._hotkeys.items():
func, args, kwargs = v
self.logger.debug('Adding hotkey "%s" w... | Python | nomic_cornstack_python_v1 |
import random
import string
set names = list
function get_name
begin
global names
while true
begin
set name = random choice uppercase
set name = name + random choice uppercase
set name = name + random choice uppercase
set name = name + random choice digits
set name = name + random choice digits
set name = name + random... | import random
import string
names = list()
def get_name():
global names
while True:
name = random.choice(string.uppercase)
name += random.choice(string.uppercase)
name += random.choice(string.uppercase)
name += random.choice(string.digits)
name += random.choice(stri... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
set N = 10
set tags = dictionary
for line in stdin
begin
set data_mapped = split strip line string
if length data_mapped != 2
begin
continue
end
set tuple tag occurrences = data_mapped
if tag in tags
begin
set tags at tag = tags at tag + integer occurrences
end
else
begin
set tags at... | #!/usr/bin/python
import sys
N = 10
tags = dict()
for line in sys.stdin:
data_mapped = line.strip().split("\t")
if len(data_mapped) != 2:
continue
tag, occurrences = data_mapped
if tag in tags:
tags[tag] += int(occurrences)
else:
tags[tag] = int(occurrences)
tags = sort... | Python | zaydzuhri_stack_edu_python |
function LCS arr1 arr2
begin
set result = list comprehension list comprehension 0 for i in range length arr2 + 1 for j in range length arr1 + 1
set dp = list comprehension list comprehension none for i in range length arr2 + 1 for j in range length arr1 + 1
for i in range length arr1
begin
for j in range length arr2
be... | def LCS(arr1, arr2):
result = [[0 for i in range(len(arr2)+1)] for j in range(len(arr1) + 1)]
dp = [[None for i in range(len(arr2)+1)] for j in range(len(arr1) + 1)]
for i in range(len(arr1)):
for j in range(len(arr2)):
if arr1[i] == arr2[j]:
result[i+1][j+1] = result[i][... | Python | zaydzuhri_stack_edu_python |
function test_get_alignments
begin
set al_bis = call get_alignments
assert length al_bis == 2
assert call get_sseqid == call get_sseqid
end function | def test_get_alignments():
al_bis = cds_list[0].get_alignments()
assert len(al_bis) == 2
assert al1.get_sseqid() == al_bis[0].get_sseqid() | Python | nomic_cornstack_python_v1 |
from ProGANVanilla import *
from Perceptual_loss_VGG import PROG_PL_VGG19
from util import *
import tensorflow as tf
import tensorflow_datasets as tfds
import os
from datetime import datetime
import matplotlib.pyplot as plt
import functools
string Training Progressive GAN,
comment HYPERPARAMS ###
set batch_size = 16
co... | from ProGANVanilla import *
from Perceptual_loss_VGG import PROG_PL_VGG19
from util import *
import tensorflow as tf
import tensorflow_datasets as tfds
import os
from datetime import datetime
import matplotlib.pyplot as plt
import functools
"""
Training Progressive GAN,
"""
### HYPERPARAMS ###
batch_size = 16
epochs ... | Python | zaydzuhri_stack_edu_python |
import fractions
set tuple N M = map int split input
set S = input
set T = input
set G = N * M // call gcd N M
set slist = list comprehension i * G // N for i in range N
set mlist = list comprehension i * G // M for i in range M
set sm = set slist ? set mlist
for i in sm
begin
set si = index slist i
set mi = index mlis... | import fractions
N, M = map(int, input().split())
S = input()
T = input()
G = N * M // fractions.gcd(N, M)
slist = [i*(G//N) for i in range(N)]
mlist = [i*(G//M) for i in range(M)]
sm = set(slist) & set(mlist)
for i in sm:
si = slist.index(i)
mi = mlist.index(i)
if S[si] != T[mi]:
print(-1)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string @author: Jennifer Nguyen
import time
import RPi.GPIO as gpio
comment light switch class
class lightSwitch
begin
function __init__ self pin
begin
call setmode BOARD
set pin = pin
setup gpio pin OUT
set dn = 5
set md = 7
set up = 20
set pwm = call PWM pin 50
start pwm md
end function
... | #!/usr/bin/env python3
"""
@author: Jennifer Nguyen
"""
import time
import RPi.GPIO as gpio
# light switch class
class lightSwitch():
def __init__(self, pin):
gpio.setmode(gpio.BOARD)
self.pin = pin
gpio.setup(self.pin, gpio.OUT)
self.dn = 5
self.md = 7
self.up = 20... | Python | zaydzuhri_stack_edu_python |
function upload ctx input media multimount
begin
set uuid = call upload_drive_image input
set drive = call find_drive uuid
call output call modify_drive drive at string uuid drive_name media multimount none
end function | def upload(ctx, input, media, multimount):
uuid = ctx.obj.upload_drive_image(input)
drive = ctx.obj.find_drive(uuid)
output(ctx.obj.modify_drive(drive['uuid'], ctx.obj.drive_name, media, multimount, None)) | Python | nomic_cornstack_python_v1 |
string Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer.
from functools import cmp_to_key
class Solution
begin
f... | """
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
"""
from functools import cmp_to_key
class... | Python | zaydzuhri_stack_edu_python |
function _load_json self photon_package
begin
if photon_package == string CustomElements
begin
set folder = custom_elements_folder
if not folder
begin
return dict
end
end
else
begin
set folder = directory name path absolute path path call getfile call currentframe + string /registry/
end
set file_name = join path fold... | def _load_json(self, photon_package: str):
if photon_package == "CustomElements":
folder = self.custom_elements_folder
if not folder:
return {}
else:
folder = (
os.path.dirname(
os.path.abspath(inspect.getfile(inspe... | Python | nomic_cornstack_python_v1 |
function abs_path self filename
begin
return join path tmp_dir filename
end function | def abs_path(self, filename):
return os.path.join(self.tmp_dir, filename) | Python | nomic_cornstack_python_v1 |
function _plain_labels self
begin
set trans = call maketrans string string string $\
return dictionary comprehension k : call translate trans for tuple k v in items labels
end function | def _plain_labels(self):
trans = str.maketrans('', '', '$\\')
return {k: v.translate(trans) for k, v in self.labels.items()} | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import json
import yfinance as yf
from flask import Flask , render_template , request
import locale
call setlocale LC_ALL string
comment Set global "Current Stock" variable to keep up with what is being
comment looked at between functions
set global_current_stock = string
comment Set global v... | #!/usr/bin/python3
import json
import yfinance as yf
from flask import Flask, render_template, request
import locale
locale.setlocale(locale.LC_ALL, '')
# Set global "Current Stock" variable to keep up with what is being
# looked at between functions
global_current_stock = ""
# Set global variable to track status o... | Python | zaydzuhri_stack_edu_python |
function disconnect self
begin
for c in _RemoteSL__components
begin
call disconnect
end
call send_midi GOOD_BYE_SYSEX_MESSAGE
end function | def disconnect(self):
for c in self._RemoteSL__components:
c.disconnect()
self.send_midi(GOOD_BYE_SYSEX_MESSAGE) | Python | nomic_cornstack_python_v1 |
function interpolate i j i_max j_max img fill_intensity
begin
comment Check if input pixel is the desired pixel.
if floor i == i and floor j == j
begin
set tuple i j = tuple integer i integer j
end
else
begin
comment Interpolate in x direction.
if absolute i - floor i < absolute i - ceil i
begin
comment Set pixel x loc... | def interpolate(i, j, i_max, j_max, img, fill_intensity):
# Check if input pixel is the desired pixel.
if np.floor(i) == i and np.floor(j) == j:
i, j = int(i), int(j)
else:
# Interpolate in x direction.
if np.abs(i - np.floor(i)) < np.abs(i - np.ceil(i)):
# Set p... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
function plot_loss_values train_loss eval_loss model_name
begin
figure figsize=tuple 10 5
plot train_loss label=string Train loss
plot eval_loss label=string Validation loss
title plt model_name
y label string Loss Value
x label string Epoch
legend
call ylim list 0 1
end function | import matplotlib.pyplot as plt
def plot_loss_values(train_loss, eval_loss, model_name):
plt.figure(figsize=(10, 5))
plt.plot(train_loss, label='Train loss')
plt.plot(eval_loss, label='Validation loss')
plt.title(model_name)
plt.ylabel('Loss Value')
plt.xlabel('Epoch')
plt.legend()
pl... | Python | zaydzuhri_stack_edu_python |
function proj_pt_2_line point paxe vaxe
begin
set vpaxe2point = call subs3 point paxe
set dist = dot vaxe vpaxe2point / dot vaxe vaxe
return call add3 paxe call mult3 vaxe dist
end function | def proj_pt_2_line(point, paxe, vaxe):
vpaxe2point = subs3(point, paxe)
dist = dot(vaxe, vpaxe2point) / dot(vaxe, vaxe)
return add3(paxe, mult3(vaxe, dist)) | Python | nomic_cornstack_python_v1 |
function verifica c d
begin
while c > d
begin
print string decrementando
set c = c - 1
end
return c
end function
set a = 10
set b = 3
set y = 8
set y = call verifica a b
print y | def verifica(c, d):
while c > d:
print("decrementando\n")
c = c - 1
return c
a = 10
b = 3
y = 8
y = verifica(a, b)
print(y)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import re
import nltk
from tensorflow.python.ops.gen_logging_ops import Print
call download string stopwords
call download string wordnet
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
set stop_words = set call words string english
from nltk.stem.wordnet import Wo... | import pandas as pd
import numpy as np
import re
import nltk
from tensorflow.python.ops.gen_logging_ops import Print
nltk.download('stopwords')
nltk.download('wordnet')
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
from nltk.stem.wordnet import WordNetLemma... | Python | zaydzuhri_stack_edu_python |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems openapi_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
function init_model engine
begin
set sm = call sessionmaker autoflush=true transactional=true bind=engine
set engine = engine
set Session = call scoped_session sm
end function | def init_model(engine):
sm = sessionmaker(autoflush=True, transactional=True, bind=engine)
meta.engine = engine
meta.Session = scoped_session(sm) | Python | nomic_cornstack_python_v1 |
from datetime import datetime
class Employee
begin
function __init__ self first_name last_name gender work_email salary join_date trial_passed=false phone_number=none leave_date=none
begin
set name = first_name
set surname = last_name
set gender = gender
set email = work_email
set salary = salary
set join = join_date
s... | from datetime import datetime
class Employee:
def __init__(self, first_name, last_name, gender, work_email, salary, join_date,
trial_passed=False, phone_number=None, leave_date=None):
self.name = first_name
self.surname = last_name
self.gender = gender
self.email =... | Python | zaydzuhri_stack_edu_python |
function minor_xvals self
begin
return prepStrs
end function | def minor_xvals(self):
return self.prepStrs | Python | nomic_cornstack_python_v1 |
function get_readonly_fields self request obj=none
begin
if obj
begin
return readonly_fields
end
return tuple
end function | def get_readonly_fields(self, request, obj=None):
if obj:
return self.readonly_fields
return () | Python | nomic_cornstack_python_v1 |
comment !/bin/python3
comment -*- coding: utf-8 -*-
from dataclasses import asdict
comment Базовый класс, от которого будут наследоваться все классы
class MainClass
begin
function to_string self
begin
string Форматирование вывода в удобочитаемом виде class ( elem = value, ... ) :return: Отформатированный класс для печа... | #!/bin/python3
# -*- coding: utf-8 -*-
from dataclasses import asdict
# Базовый класс, от которого будут наследоваться все классы
class MainClass:
def to_string(self):
'''
Форматирование вывода в удобочитаемом виде
class (
elem = value,
...
)
:return... | Python | zaydzuhri_stack_edu_python |
while number
begin
print n * n + 1 * 2 * n + 1 / 6
set number = integer call raw_input
end | while (number):
print (n*(n+1)*((2*n)+1))/6
number = int(raw_input())
| Python | zaydzuhri_stack_edu_python |
function postloop self
begin
pass
end function | def postloop(self):
pass | Python | nomic_cornstack_python_v1 |
function _get_backrefs_for_obj self obj
begin
set backrefs = list
set intid = call getId call aq_inner obj
for rel in call findRelations dict string to_id intid
begin
set obj = from_object
if obj is none
begin
continue
end
if call checkPermission string zope2.View obj
begin
append backrefs call BackReference call pret... | def _get_backrefs_for_obj(self, obj):
backrefs = []
intid = self.intids.getId(aq_inner(obj))
for rel in self.ref_catalog.findRelations({'to_id': intid}):
obj = rel.from_object
if obj is None:
continue
if checkPermission('zope2.View', obj):
... | Python | nomic_cornstack_python_v1 |
import app.utilities as util
comment Readability test
function return_readability_score text
begin
set readability_score = call return_readability_score text
set flesch_readability_score = split readability_score at string Flesch_Kincaide string ,
if call __len__ > 1
begin
set grade_level = flesch_readability_score at ... | import app.utilities as util
# Readability test
def return_readability_score(text):
readability_score = util.return_readability_score(text)
flesch_readability_score = readability_score['Flesch_Kincaide'].split(',')
if flesch_readability_score.__len__() > 1:
grade_level = flesch_readability_score[0... | Python | zaydzuhri_stack_edu_python |
function eggholderfcn x
begin
assert shape at 1 == 2 msg string The Eggholder function is only defined on a 2D space.
set X = x at tuple slice : : 0
set Y = x at tuple slice : : 1
set sin1component = sin square root absolute X / 2 + Y + 47
set sin2component = sin square root absolute X - Y + 47
set scores = - Y +... | def eggholderfcn(x: np.ndarray) -> np.ndarray:
assert (
x.shape[1] == 2
), "The Eggholder function is only defined on a 2D space."
X = x[:, 0]
Y = x[:, 1]
sin1component = np.sin(np.sqrt(np.abs((X / 2) + Y + 47)))
sin2component = np.sin(np.sqrt(np.abs(X - Y + 47)))
scores = -(Y + 4... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
function read path missing_na=list string NA string NaN
begin
set df = read csv path na_values=missing_na
call drop_duplicates inplace=true
set count_na = sum
print df
print string NaN in columns:
print count_na string
return df
end function
function noisy data_frame obj col
begin... | import pandas as pd
import numpy as np
def read(path, missing_na=['NA', 'NaN']):
df = pd.read_csv(path, na_values=missing_na, )
df.drop_duplicates(inplace=True)
count_na = df.isna().sum()
print(df)
print("\nNaN in columns: ")
print(count_na, '\n')
return df
def noisy(data_frame, obj, co... | Python | zaydzuhri_stack_edu_python |
string [1, 3, 11, 15, 23, 28, 37, 52, 85, 100] 와 같은 리스트 객체가 주어졌을 때 다음의 결과를 출력하는 짝수만 항목으로 가지는 리스트 객체를 생성하는 코드를 작성하십시오.
set data = list 1 3 11 15 23 28 37 52 85 100
set new_data = list comprehension num for num in data if num % 2 == 0
print new_data | '''
[1, 3, 11, 15, 23, 28, 37, 52, 85, 100] 와 같은 리스트 객체가 주어졌을 때
다음의 결과를 출력하는 짝수만 항목으로 가지는 리스트 객체를 생성하는
코드를 작성하십시오.
'''
data = [1, 3, 11, 15, 23, 28, 37, 52, 85, 100]
new_data = [num for num in data if num % 2 == 0]
print(new_data)
| Python | zaydzuhri_stack_edu_python |
function test_stream_publish self
begin
pass
end function | def test_stream_publish(self):
pass | Python | nomic_cornstack_python_v1 |
comment written by Niamh McCann
comment 2019
comment this program takes a text file of training data and separates it into input/output pairs for supervised learning
comment An LSTM model is then trained on this data for 50 epochs (approximately 12 hours)
comment A MIDI input is received and encoded into the duration a... | #written by Niamh McCann
#2019
#this program takes a text file of training data and separates it into input/output pairs for supervised learning
#An LSTM model is then trained on this data for 50 epochs (approximately 12 hours)
#A MIDI input is received and encoded into the duration and offset encoding methods
#The sy... | Python | zaydzuhri_stack_edu_python |
function ready self
begin
from apps.group.models import Group
call connect receiver=create_group_admin sender=Group
call connect receiver=remove_group_and_memberships sender=Group
end function | def ready(self):
from apps.group.models import Group
group_created.connect(receiver=create_group_admin, sender=Group)
group_and_membership_remove.connect(receiver=remove_group_and_memberships, sender=Group) | Python | nomic_cornstack_python_v1 |
import requests
from requests.auth import HTTPBasicAuth
import uuid
import json
class BaseTest
begin
set base_url = string https://demoqa.com
function name_test self name
begin
print name
end function
function generate_username_password self
begin
string This method generates a random username and password and returns ... | import requests
from requests.auth import HTTPBasicAuth
import uuid
import json
class BaseTest:
base_url = "https://demoqa.com"
def name_test(self, name):
print(name)
def generate_username_password(self):
"""This method generates a random username and password and returns the data as a ... | Python | zaydzuhri_stack_edu_python |
from django.db import models
from event import Event
from lens_model import LensModel
class PhotoshootHasGear extends Model
begin
string Purpose: The PhotoshootHasGear model defines the structure of an event's gear. (ie: A wedding has lenses associated.) This model allows a user to make a list of gear for specific even... | from django.db import models
from .event import Event
from .lens_model import LensModel
class PhotoshootHasGear(models.Model):
'''
Purpose:
The PhotoshootHasGear model defines the structure of an event's gear. (ie: A wedding has lenses associated.) This model allows a user to make a list of gear for specific eve... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import random
import sys
function isSorted arr
begin
set length = length arr
for tuple i number in enumerate arr
begin
try
begin
if number > arr at i + 1
begin
return false
end
else
begin
pass
end
end
except any
begin
if i == length - 1
begin
return true
end
end
end
return true
end function
co... | #!/usr/bin/python3
import random
import sys
def isSorted(arr):
length = len(arr)
for i, number in enumerate(arr):
try:
if number > arr[i+1]:
return False
else:
pass
except:
if i == length - 1:
return Tr... | Python | zaydzuhri_stack_edu_python |
comment from pyrobot.brain import Brain
import math
import cv2
from matplotlib import pyplot as plt
import numpy as np
import config
import datasetGenerator
import clasificadorEuc
import imutils
comment Autores:
comment Luciano Garcia Giordano - 150245
comment Gonzalo Florez Arias - 150048
comment Salvador Gonzalez Ger... | # from pyrobot.brain import Brain
import math
import cv2
from matplotlib import pyplot as plt
import numpy as np
import config
import datasetGenerator
import clasificadorEuc
import imutils
# Autores:
# Luciano Garcia Giordano - 150245
# Gonzalo Florez Arias - 150048
# Salvador Gonzalez Gerpe - 150044
class Brain... | Python | zaydzuhri_stack_edu_python |
from sys import stdin , stdout
set key = bytearray read open string key3 string rb
set mesg = bytearray read buffer
for i in range 0 length mesg
begin
set temp = bytes list mesg at i ? key at i % length key
write buffer temp
end | from sys import stdin, stdout
key = bytearray(open("key3","rb").read())
mesg = bytearray(stdin.buffer.read())
for i in range(0,len(mesg)):
temp = bytes([mesg[i]^key[i%len(key)]])
stdout.buffer.write(temp)
| Python | zaydzuhri_stack_edu_python |
function git_clone url path
begin
set cmd = string git clone %s %s % tuple url path
run cmd
end function | def git_clone(url, path):
cmd = 'git clone %s %s' % (url, path)
run(cmd) | Python | nomic_cornstack_python_v1 |
import sys
append path string /home/abhineet/workspace/
from NoobAutograd.tensor import *
function tensor_sum_test
begin
set t = tensor list 1 2 3 4 requires_grad=true
set s = sum
backward s tensor 1.0
assert data == 10
assert data == 1 and all
end function
function tensor_add_test
begin
set t1 = tensor list 1 2 3 requ... | import sys
sys.path.append('/home/abhineet/workspace/')
from NoobAutograd.tensor import *
def tensor_sum_test():
t = Tensor([1,2,3,4], requires_grad=True)
s = t.sum()
s.backward(Tensor(1.))
assert s.data == 10
assert s.grad.data==1 and t.grad.data.all()
def tensor_add_test():
t1 = Tensor([1... | Python | zaydzuhri_stack_edu_python |
string 给定一个数组,数组里有一个数组有且只有一个最大数,判断这个最大数是否是其他数的两倍或更大。如果存在这个数,则返回其index,否则返回-1。
function largest_twice nums
begin
set second_max = decimal string -inf
set first_max = decimal string -inf
set index = 0
for tuple n i in enumerate nums
begin
if i > first_max
begin
set tuple second_max first_max = tuple first_max i
set index... | """
给定一个数组,数组里有一个数组有且只有一个最大数,判断这个最大数是否是其他数的两倍或更大。如果存在这个数,则返回其index,否则返回-1。
"""
def largest_twice(nums):
second_max=first_max=float("-inf")
index=0
for n,i in enumerate(nums):
if i>first_max:
second_max,first_max=first_max,i
index=n
elif i>second_max: # i比first_max小,比s... | Python | zaydzuhri_stack_edu_python |
from socket import socket , gethostbyname , AF_INET , SOCK_STREAM , gethostname , SOCK_DGRAM
import pickle
import sys
comment THIS FILE SHOULD BE RUN WHEN MULTIPLAYER IS DESIRED. ONLY ONE PLAYER NEEDS TO RUN THIS FILE TO HOST MULTIPLAYER
comment Written based off of Documentation of Sockets Example 18.1.15 https://docs... | from socket import socket, gethostbyname, AF_INET, SOCK_STREAM, gethostname, SOCK_DGRAM
import pickle
import sys
#THIS FILE SHOULD BE RUN WHEN MULTIPLAYER IS DESIRED. ONLY ONE PLAYER NEEDS TO RUN THIS FILE TO HOST MULTIPLAYER
#Written based off of Documentation of Sockets Example 18.1.15 https://docs.python.org/3/lib... | Python | zaydzuhri_stack_edu_python |
comment create Tic-tac-toe game
set board = list none * 9
function draw_board
begin
set row1 = format string |{}|{}|{}| board at 0 board at 1 board at 2
set row2 = format string |{}|{}|{}| board at 3 board at 4 board at 5
set row3 = format string |{}|{}|{}| board at 6 board at 7 board at 8
print
print row1
print row2
p... | # create Tic-tac-toe game
board = [None] * 9
def draw_board():
row1 = "|{}|{}|{}|".format(board[0], board[1], board[2])
row2 = "|{}|{}|{}|".format(board[3], board[4], board[5])
row3 = "|{}|{}|{}|".format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def get_row_... | Python | jtatman_500k |
from sklearn.datasets import load_digits as ld
from sklearn.model_selection import train_test_split as tts
import xgboost as xgb
import matplotlib.pyplot as plt
from xgboost import plot_importance
from numpy import *
function classify
begin
set data = call ld
set X = data
set y = target
set tuple X_train X_test y_train... | from sklearn.datasets import load_digits as ld
from sklearn.model_selection import train_test_split as tts
import xgboost as xgb
import matplotlib.pyplot as plt
from xgboost import plot_importance
from numpy import *
def classify():
data = ld()
X=data.data; y=data.target
X_train, X_test, y_t... | Python | zaydzuhri_stack_edu_python |
function data_received self data
begin
set _incoming_buffer = _incoming_buffer + data
while length _incoming_buffer >= 2
begin
set block_length_bytes = _incoming_buffer at slice : 2 :
set block_length = call from_bytes block_length_bytes string little
set exp_length = block_length + 18
if length _incoming_buffer < ex... | def data_received(self, data):
self._incoming_buffer += data
while len(self._incoming_buffer) >= 2:
block_length_bytes = self._incoming_buffer[:2]
block_length = int.from_bytes(block_length_bytes, "little")
exp_length = block_length + 18
if len(self._in... | Python | nomic_cornstack_python_v1 |
function execute self
begin
raise NotImplementedError
end function | def execute(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function errorPrompt
begin
print string Opps! You've printed an invalid format. Please try again.
call prompt
end function | def errorPrompt():
print("Opps! You've printed an invalid format. Please try again.")
prompt() | Python | nomic_cornstack_python_v1 |
string 如果不用loop/recursion,就是数学解法. 这种题就是写出大量的case,然后找规律 注意: 0还有9的倍数-->corner case Time: O(1) Space: O(1)
class Solution extends object
begin
function addDigits self num
begin
string :type num: int :rtype: int
if not num
begin
return 0
end
return if expression num % 9 then num % 9 else 9
end function
end class | """
如果不用loop/recursion,就是数学解法.
这种题就是写出大量的case,然后找规律
注意: 0还有9的倍数-->corner case
Time: O(1)
Space: O(1)
"""
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if not num:
return 0
return num % 9 if num ... | Python | zaydzuhri_stack_edu_python |
string Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário. I'm trying but I keep falling down I cry out bu... | """
Escreva um programa para aprovar
o empréstimo bancário para a compra
de uma casa. O programa vai perguntar
o valor da casa, o salário do comprador
e em quantos anos ele vai pagar.
Calcule o valor da prestação mensal,
sabendo que ela não pode exceder 30%
do salário.
I'm trying b... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment @Author :wangliangguo
comment @time : 20-12-22 下午5:59
class Solution
begin
comment 递归调用
comment def preorder(self, root: 'Node') -> List[int]:
comment ans=[]
comment def pre(root):
comment if root:
comment ans.append(root.val)
comment for child in root.chi... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#@Author :wangliangguo
#@time : 20-12-22 下午5:59
class Solution:
# 递归调用
# def preorder(self, root: 'Node') -> List[int]:
# ans=[]
# def pre(root):
# if root:
# ans.append(root.val)
# for child in root.children... | Python | zaydzuhri_stack_edu_python |
function get_contents self
begin
with call closing open as handle
begin
return read handle
end
end function | def get_contents(self):
with closing(self.open()) as handle:
return handle.read() | Python | nomic_cornstack_python_v1 |
function get_x self index
begin
return index // nyz
end function | def get_x(self,index):
return index // self.nyz | Python | nomic_cornstack_python_v1 |
function gdisconnect
begin
set access_token = get session string access_token
if not access_token
begin
return call redirect string /
end
if access_token is none
begin
set response = call make_response dumps string Current user not connected. 401
set headers at string Content-Type = string application/json
return respo... | def gdisconnect():
access_token = flask.session.get('access_token')
if not access_token:
return flask.redirect('/')
if access_token is None:
response = flask.make_response(json.dumps('Current user not connected.'), 401)
response.headers['Content-Type'] = 'application/json'
re... | Python | nomic_cornstack_python_v1 |
function export_pem ring_signature
begin
set der = encode encoder decode decoder dict string key_image bytes data ; string public_keys list comprehension bytes data for public_key in public_keys ; string r list comprehension bytes data for r in r ; string c list comprehension bytes data for c in c asn1Spec=call RingSig... | def export_pem(ring_signature: RingSignature) -> str:
der = pyasn1.codec.der.encoder.encode(
pyasn1.codec.native.decoder.decode(
{
"key_image": bytes(ring_signature.key_image.data),
"public_keys": [
bytes(public_key.data) for public_key in ring... | Python | nomic_cornstack_python_v1 |
comment 36. Valid Sudoku (Medium)
comment https://leetcode.com/problems/valid-sudoku/
comment Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
comment Each row must contain the digits 1-9 without repetition.
comment Each column must contain the digit... | # 36. Valid Sudoku (Medium)
# https://leetcode.com/problems/valid-sudoku/
# Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
# Each row must contain the digits 1-9 without repetition.
# Each column must contain the digits 1-9 without repetition.
# E... | Python | zaydzuhri_stack_edu_python |
function shape self
begin
return shape
end function | def shape(self):
return self.neuron.shape | Python | nomic_cornstack_python_v1 |
function testDeleteDuplicateTaskNames self
begin
set task_names = list string T1 string T2 string T1
assert raises DuplicateTaskNameError DeleteTasksByName queue string default task_names
end function | def testDeleteDuplicateTaskNames(self):
task_names = ['T1', 'T2', 'T1']
self.assertRaises(taskqueue.DuplicateTaskNameError,
self.DeleteTasksByName,
Queue('default'),
task_names) | Python | nomic_cornstack_python_v1 |
function genScripts self skip
begin
for project in values projects
begin
call genScripts skip
end
end function | def genScripts(self, skip):
for project in self.projects.values():
project.genScripts(skip) | Python | nomic_cornstack_python_v1 |
function test_update self
begin
update datasource dict string __selected true list 1
comment ^^ update row with id 1
set rows = load datasource
assert equal data at 0 1
end function | def test_update(self):
self.datasource.update({'__selected': True}, [1])
# ^^ update row with id 1
rows = self.datasource.load()
self.assertEqual(rows[0].data[0], 1) | Python | nomic_cornstack_python_v1 |
function sum_of_array arr
begin
set result = 0
for x in arr
begin
set result = result + x
end
return result
end function
set sum = call sum_of_array list 3 5 6
print sum | def sum_of_array(arr):
result = 0
for x in arr:
result += x
return result
sum = sum_of_array([3, 5, 6])
print(sum) | Python | iamtarun_python_18k_alpaca |
function is_prime num
begin
if num < 2
begin
return false
end
for i in range 2 integer num ^ 0.5 + 1
begin
if num % i == 0
begin
return false
end
end
return true
end function
function is_palindrome num
begin
return string num == string num at slice : : - 1
end function
set primes = list
comment Start with the first ... | def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def is_palindrome(num):
return str(num) == str(num)[::-1]
primes = []
num = 10001 # Start with the first 5-digit number
while len(primes) < 50:
... | Python | jtatman_500k |
import numpy as np
function part1 numbers boards
begin
set called_numbers = list
for n in numbers
begin
append called_numbers n
for b in boards
begin
set col_condition = max
set row_condition = max
if row_condition >= 5 or col_condition >= 5
begin
return sum * n
end
end
end
end function
function part2 numbers boards
b... | import numpy as np
def part1(numbers, boards):
called_numbers = []
for n in numbers:
called_numbers.append(n)
for b in boards:
col_condition = np.isin(b, called_numbers).astype(int).sum(axis=1).max()
row_condition = np.isin(b, called_numbers).astype(int).sum(axis=0).max... | Python | zaydzuhri_stack_edu_python |
string Reversing a string. This is a variety of different functions to reverse a string. Some will print the reversed string, others will return the value.
function rev_print string
begin
string Prints a string in reverse (with spaces between characters), using a for loop. >>> rev_print('hello') o l l e h
end function | """Reversing a string.
This is a variety of different functions to reverse a string. Some will print
the reversed string, others will return the value.
"""
def rev_print(string):
"""Prints a string in reverse (with spaces between characters), using a for loop.
>>> rev_print('hello')
o l l e h
... | Python | zaydzuhri_stack_edu_python |
import collections
function ladderLength beginWord endWord wordList
begin
string :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
if beginWord == endWord
begin
return 0
end
if beginWord not in wordList
begin
append wordList beginWord
end
set d = default dictionary list
set q = deque
for w i... | import collections
def ladderLength(beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if beginWord == endWord:
return 0
if beginWord not in wordList:
wordList.append(beginWord)
d = ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Shashank This model provides claim prediction to help business if there is probability of policy holder to raise claim
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
comment Get the data for analysis
set ins_df = read csv string insurance.csv
set ins... | # -*- coding: utf-8 -*-
"""
@author: Shashank
This model provides claim prediction to help business if there
is probability of policy holder to raise claim
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Get the data for analysis
ins_df=pd.read_csv('insurance.csv')
ins_df_x... | Python | zaydzuhri_stack_edu_python |
import time
class Gesture extends object
begin
function __init__ self
begin
set idle = true
set state1 = false
set statefinal = false
end function
function update self data
begin
pass
end function
end class
class Swiperight extends Gesture
begin
function __init__ self
begin
comment three states going left
call __init__... | import time
class Gesture(object):
def __init__ (self):
self.idle = True
self.state1 = False
self.statefinal = False
def update (self, data):
pass
class Swiperight (Gesture):
def __init__ (self):
#three states going left
super().__init__(self)
self.s... | Python | zaydzuhri_stack_edu_python |
function contextMenuEvent self event
begin
set menu = call QMenu parent=self
for tuple i header_label in enumerate call section_labels at slice 1 : : start=1
begin
set act = call addAction header_label
call setCheckable true
set val = not call isSectionHidden i
call setChecked val
call setSectionHidden i val
call emi... | def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(parent=self)
for i, header_label in enumerate(self.section_labels()[1:], start=1):
act = menu.addAction(header_label)
act.setCheckable(True)
val = not self.isSectionHidden(i)
act.setChecked(val)
... | Python | nomic_cornstack_python_v1 |
import pypsa
import numpy as np
from sklearn.preprocessing import MinMaxScaler
comment REFERENCE WEBSITE: https://pypsa.org/doc/quick_start.html #########
set network = call Network
for i in range 5
begin
add network string Bus format string mybus{} i + 1
end | import pypsa
import numpy as np
from sklearn.preprocessing import MinMaxScaler
##### REFERENCE WEBSITE: https://pypsa.org/doc/quick_start.html #########
network=pypsa.Network()
for i in range(5):
network.add("Bus","mybus{}".format(i+1))
| Python | zaydzuhri_stack_edu_python |
function buildIfIndexToPhysicalIndexMap ip credentials=none
begin
if credentials == none
begin
set credentials = call CommunityData string public
end
set items = walk ip list OID_ENT_ALIAS_MAPPING_IDENTIFIER credentials
set phyMap = dict
for item in items
begin
for tuple k v in items item
begin
if starts with k OID_EN... | def buildIfIndexToPhysicalIndexMap(ip, credentials=None):
if credentials == None:
credentials = hlapi.CommunityData('public')
items = walk(ip, [OID_ENT_ALIAS_MAPPING_IDENTIFIER], credentials)
phyMap = {}
for item in items:
for k, v in item.items():
if k.startswith(OID_ENT_ALI... | Python | nomic_cornstack_python_v1 |
function get_auth self
begin
set auth_resp = call get_with_retry cerberus_url + string /v2/auth/user auth=tuple username password headers=HEADERS
if status_code != 200
begin
call throw_if_bad_response auth_resp
end
return json auth_resp
end function | def get_auth(self):
auth_resp = get_with_retry(self.cerberus_url + '/v2/auth/user',
auth=(self.username, self.password),
headers=self.HEADERS)
if auth_resp.status_code != 200:
throw_if_bad_response(auth_resp)
ret... | Python | nomic_cornstack_python_v1 |
import sqlite3
import os
class SqlCommands
begin
string SQLCommands : This class is setup to house all sql queries for the sqlite database that is used in this script. Only use optDB, variable and this function if ABSOLUTLY NEEDED. IT MUST USE THE SAME TABLE LAYOUT AS Data/TestDB!!!
function __init__ self optDB=string
... | import sqlite3
import os
class SqlCommands:
'''
SQLCommands : This class is setup to house all sql queries for the sqlite database
that is used in this script.
Only use optDB, variable and this function if ABSOLUTLY NEEDED.
IT MUST USE THE SAME TABLE LAYOUT AS Data/TestDB!!!
'''
def __init... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Dec 25 21:25:26 2018 @author: satyake
class RBM extends object
begin
function __init__ self nv nh
begin
set W = randn nh nv
set a = randn 1 nh
set b = randn 1 nv
end function
function sample_h self x
begin
set wx = call mm x t dist
set ac... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 25 21:25:26 2018
@author: satyake
"""
class RBM(object):
def __init__(self, nv, nh):
self.W = torch.randn(nh, nv)
self.a = torch.randn(1, nh)
self.b = torch.randn(1, nv)
def sample_h(self, x):
wx = torch.mm(x... | Python | zaydzuhri_stack_edu_python |
function read_secure_cookie self name
begin
set cookie_val = get cookies name
return cookie_val and call check_secure_val cookie_val
end function | def read_secure_cookie(self, name):
cookie_val = self.request.cookies.get(name)
return cookie_val and check_secure_val(cookie_val) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.