code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function restart name
begin
string Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name>
set cmd = format string /usr/sbin/svcadm restart {0} name
if not call cmd python_shell=false
begin
comment calling restart doesn't clear maintenance
comment or tell us that the service ... | def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear mainten... | Python | jtatman_500k |
comment python program to remove odd characters using user defined functions
function remove_odd_characters
begin
set input_string = input string enter the input string :
set string2 = string
for x in range 1 length input_string + 1
begin
if x % 2 == 0
begin
set string2 = string2 + input_string at x
end
end
print stri... | #python program to remove odd characters using user defined functions
def remove_odd_characters():
input_string=input("enter the input string :")
string2=""
for x in range (1,len(input_string)+1):
if (x%2==0):
string2=string2+input_string[x]
print(string2)
remove_odd_characters()
| Python | zaydzuhri_stack_edu_python |
from requests import get
import json
import matplotlib.pyplot as plt
from dateutil import parser
from pprint import pprint
from haversine import haversine
set stations = string https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallstations
set weather = string https://apex.oracle.com/pls/apex/raspberrypi/we... | from requests import get
import json
import matplotlib.pyplot as plt
from dateutil import parser
from pprint import pprint
from haversine import haversine
stations = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallstations'
weather = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getla... | Python | zaydzuhri_stack_edu_python |
import tables
import sys
from time import time
import numpy as np
import cv2
function remove_inactives hdf_in hdf_out inac
begin
comment Open an existing hdf5 file
set h5file_in = call openFile hdf_in mode=string r
set h5array_in = call getNode string / string denseFeat
end function | import tables
import sys
from time import time
import numpy as np
import cv2
def remove_inactives(hdf_in, hdf_out, inac):
# Open an existing hdf5 file
h5file_in = tables.openFile(hdf_in, mode="r")
h5array_in = h5file_in.getNode('/', "denseFeat") | Python | zaydzuhri_stack_edu_python |
function collect_coordinate_derivatives self comm discipline scenarios root=0
begin
if discipline == string aerodynamic or discipline == string flow or discipline == string aero
begin
set all_aero_ids = gather comm aero_id root=root
comment append struct shapes for each scenario
set full_aero_shape_term = list
for sce... | def collect_coordinate_derivatives(self, comm, discipline, scenarios, root=0):
if discipline == "aerodynamic" or discipline == "flow" or discipline == "aero":
all_aero_ids = comm.gather(self.aero_id, root=root)
# append struct shapes for each scenario
full_aero_shape_term =... | Python | nomic_cornstack_python_v1 |
function plot_corr_matrix dataset
begin
print string Generating correlation matrix
set style=string white
set matrix = call corr method=string pearson
set mask = zeros like matrix dtype=bool
set mask at call triu_indices_from mask = true
call subplots figsize=tuple 7 7
set cmap = call diverging_palette 220 10 as_cmap=t... | def plot_corr_matrix(dataset):
print("\tGenerating correlation matrix")
sns.set(style="white")
matrix = dataset.corr(method="pearson")
mask = np.zeros_like(matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
plt.subplots(figsize=(7, 7))
cmap = sns.diverging_palette(220, 10, as_cmap=True)
sns.heat... | Python | nomic_cornstack_python_v1 |
import time
import os
set environ at string KIVY_GL_BACKEND = string gl
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager , Screen
from kivy.config import Config
from kivy.properties import ObjectProperty
set string graphics string width string 1024
set string graph... | import time
import os
os.environ['KIVY_GL_BACKEND'] = 'gl'
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.config import Config
from kivy.properties import ObjectProperty
Config.set('graphics', 'width', '1024')
Config.set('graphics', 'height', '... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment "Database code" for the Logs Analysis Project
string db architecture - authors: name | bio | id articles: author-id | title | slug | lead | body | time | article-id log: path | ip | method | status | time | id Report1: What are the most popular three articles of all time? * Sum the... | #! /usr/bin/env python
# "Database code" for the Logs Analysis Project
'''
db architecture
-
authors: name | bio | id
articles: author-id | title | slug | lead | body | time | article-id
log: path | ip | method | status | time | id
Report1:
What are the most popular three articles of all time?
* Sum the views in log... | Python | zaydzuhri_stack_edu_python |
comment 025 문자열 인덱싱
comment letters가 바인딩하는 문자열에서 첫번째와 세번째 문자를 출력하라.
comment >>> letters = "python"
comment 실행 예
comment p
comment t
set letters = string python
print letters at 0
print letters at 2 | # 025 문자열 인덱싱
#
# letters가 바인딩하는 문자열에서 첫번째와 세번째 문자를 출력하라.
#
# >>> letters = "python"
#
# 실행 예
# p
# t
letters = "python"
print(letters[0])
print(letters[2]) | Python | zaydzuhri_stack_edu_python |
function DFS_DE self
begin
set rev_dir = dict string n string s ; string w string e ; string s string n ; string e string w
while true
begin
set exits = call get_exits current_room
comment If we've explored all exits, return.
if all list comprehension world at current_room at string to_ { exit_ } is not none for exit_ ... | def DFS_DE(self) -> None:
rev_dir = {'n': 's', 'w': 'e', 's': 'n', 'e': 'w'}
while True:
exits = self.get_exits(self.current_room)
# If we've explored all exits, return.
if all([self.world[self.current_room][f'to_{exit_}'] is not None for exit_ in exits]):
... | Python | nomic_cornstack_python_v1 |
function ping_pong lst win
begin
set pingpong = list
set eyes = length lst - 1
set counter = 0
if win == false
begin
for x in lst
begin
if counter == eyes
begin
append pingpong x
end
else
begin
set counter = counter + 1
append pingpong x
append pingpong string Pong!
end
end
return pingpong
end
else
begin
for x in lst
... | def ping_pong(lst, win):
pingpong=[]
eyes=len(lst)-1
counter=0
if win == False:
for x in lst:
if counter == eyes:
pingpong.append(x)
else:
counter+=1
pingpong.append(x)
pingpong.append("Pong!")
return pingpong
else:
for x in lst:
pingpong.append(x)... | Python | zaydzuhri_stack_edu_python |
function config_edge_trunk_on_interface device interface
begin
try
begin
call configure list format string interface {interface} interface=interface string spanning portf edge trunk
end
except SubCommandFailure as e
begin
raise call SubCommandFailure format string Couldn't configure spanning portf edge trunk on interfa... | def config_edge_trunk_on_interface(device, interface):
try:
device.configure(
[
"interface {interface}".format(interface=interface),
"spanning portf edge trunk"
]
)
except SubCommandFailure as e:
raise SubCommandFailure(
... | Python | nomic_cornstack_python_v1 |
function validate_role_assignment_id ns
begin
if role_assignment_id is not none
begin
set role_assignment_id = call _parse_resource_path role_assignment_id false string sqlRoleAssignments
end
else
begin
set role_assignment_id = call _gen_guid
end
end function | def validate_role_assignment_id(ns):
if ns.role_assignment_id is not None:
ns.role_assignment_id = _parse_resource_path(ns.role_assignment_id, False, "sqlRoleAssignments")
else:
ns.role_assignment_id = _gen_guid() | Python | nomic_cornstack_python_v1 |
function winning_display self
begin
if call get_end_game_status == PLAYER_1
begin
return PLAYER_1_WIN_MSG
end
else
if call get_end_game_status == PLAYER_2
begin
return PLAYER_2_WIN_MSG
end
else
begin
return TIE_MSG
end
end function | def winning_display(self):
if self.game.get_end_game_status() == PLAYER_1:
return PLAYER_1_WIN_MSG
elif self.game.get_end_game_status() == PLAYER_2:
return PLAYER_2_WIN_MSG
else:
return TIE_MSG | Python | nomic_cornstack_python_v1 |
function pattern_match arr x
begin
for string in arr
begin
if is lower string at 0 and is upper string at slice 1 : - 1 : and is digit string at - 1
begin
if x == string
begin
return true
end
end
end
return false
end function | def pattern_match(arr, x):
for string in arr:
if string[0].islower() and string[1:-1].isupper() and string[-1].isdigit():
if x == string:
return True
return False
| Python | jtatman_500k |
string Generate many stat blocks to try to find average stat block
import random
function roll_stat
begin
return sum generator expression random integer 1 6 for _ in range 3
end function
function roll_stats
begin
set stats = list comprehension call roll_stat for _ in range 7
return sorted stats reverse=true at slice :... | """
Generate many stat blocks to try to find average stat block
"""
import random
def roll_stat():
return sum(random.randint(1, 6) for _ in range(3))
def roll_stats():
stats = [roll_stat() for _ in range(7)]
return sorted(stats, reverse=True)[:-1]
def main():
roll_count = 1000000
stats_sum = ... | Python | zaydzuhri_stack_edu_python |
string input_case:1 4258 output_case:1 1 input_case:2 541236 output_case:2 3
import math
set n = integer input
set a = list
set odd = 0
set even = 0
set y = n
for _ in range 100
begin
set y = y / 10
append a y % 10
if y == 0
begin
break
end
end
reverse a
for i in range length a
begin
if i % 2 == 0
begin
set odd = odd ... | ''' input_case:1
4258
output_case:1
1
input_case:2
541236
output_case:2
3
'''
import math
n=int(input())
a=[]
odd=0
even=0
y=n
for _ in range(100):
y=y/10
a.append(y%10)
if(y==0):
break
a.reverse()
for i in range(len(a)):
if(i%2==0):
odd+=a[i]
else:
... | Python | zaydzuhri_stack_edu_python |
string ============================================================== Garante que o software funcione para aquilo que foi testado. BDD - Behavior Driven Development (criar um teste do ponto de vista do usuário) Cenário: garante uma visão estável e conhecida do sistema - Dado um estado do sistema ->visão estável e conhe... | ''' ==============================================================
Garante que o software funcione para aquilo que foi testado.
BDD - Behavior Driven Development (criar um teste do ponto de vista do usuário)
Cenário: garante uma visão estável e conhecida do sistema
- Dado um estado do sistema ->visão estável e conhe... | Python | zaydzuhri_stack_edu_python |
from itertools import product
from collections import defaultdict
function run_amp raw_program
begin
set relative_base = 0
set program = default dictionary int
for tuple i cmd in enumerate raw_program
begin
set program at i = cmd
end
set curr_pos = 0
set get = list lambda pos -> program at program at pos lambda pos -> ... | from itertools import product
from collections import defaultdict
def run_amp(raw_program):
relative_base = 0
program = defaultdict(int)
for i,cmd in enumerate(raw_program):
program[i]=cmd
curr_pos = 0
get = [lambda pos: program[program[pos]],lambda pos: program[pos], lambda pos: program[po... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
set tuple N K = list map int split input
set A = list map int split input
set mod = integer 1000000000.0 + 7
set cnt1 = 0
for i in range N
begin
for j in range i + 1 N
begin
if A at i > A at j
begin
set cnt1 = cnt1 + 1
end
end
end
set cnt2 = 0
for i in range N
begin
for j in range N
begi... | from collections import Counter
N,K = list(map(int, input().split()))
A = list(map(int, input().split()))
mod = int(1e9+7)
cnt1 = 0
for i in range(N):
for j in range(i+1,N):
if A[i] > A[j]:
cnt1 += 1
cnt2 = 0
for i in range(N):
for j in range(N):
if A[i] > A[j]:
cnt2 += 1
print((cnt1 * K ... | Python | zaydzuhri_stack_edu_python |
function getNewError self
begin
return call getAttribute string new_error == string True and true or false
end function | def getNewError(self):
return self._domInstance.getAttribute('new_error') == \
'True' and True or False | Python | nomic_cornstack_python_v1 |
function write_users_to_csv_file args users
begin
info string write_users_to_csv_file function started running.
import csv
with open output_directory + string users/in/users- + string integer time + string .csv string w encoding=string utf8 newline=string as csvfile
begin
set user_csv_writer = writer csvfile delimiter=... | def write_users_to_csv_file(args, users):
logger.info("write_users_to_csv_file function started running.")
import csv
with open(args.output_directory + 'users/in/users-' + str(int(time.time())) + '.csv', 'w', encoding='utf8', newline='') as csvfile:
user_csv_writer = csv.writer(csvfile, delimiter='|... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import logging
from max.performance import Performance
set logger = call getLogger __name__
class Backtester extends object
begin
string Backtester class @member strategy: Strategy object, to be backtested @member dc: DataCenter object @member start_date, end_date: string, backtest start and end dat... | import pandas as pd
import logging
from max.performance import Performance
logger = logging.getLogger(__name__)
class Backtester(object):
"""Backtester class
@member strategy: Strategy object, to be backtested
@member dc: DataCenter object
@member start_date, end_date: string, backtest start and en... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import machine
import time
import untplib
set __all__ = list string synchronize
function synchronize ntp_url=string us.pool.ntp.org
begin
set response = call request ntp_url
comment utime.localtime has format:
comment (year, month, day, hour, minute, second, weekday, yearday)
set tuple yea... | # -*- coding: utf-8 -*-
import machine
import time
import untplib
__all__ = ['synchronize']
def synchronize(ntp_url: str = 'us.pool.ntp.org') -> None:
response = untplib.request(ntp_url)
# utime.localtime has format:
# (year, month, day, hour, minute, second, weekday, yearday)
year, month, day, ho... | Python | zaydzuhri_stack_edu_python |
function __init__ self data
begin
set data = data
set DT = data at string DT
set N_T = integer data at string N_T
set xr = as type data at string XR at 0 string float32
set yr = as type data at string YR at 0 string float32
set S_gen = as type data at string S_gen string float32
set Var = as type data at string Var at ... | def __init__(self, data):
self.data = data
self.DT = self.data['DT']
self.N_T = int(self.data['N_T'])
self.xr = self.data['XR'][0].astype('float32')
self.yr = self.data['YR'][0].astype('float32')
self.S_gen = self.data['S_gen'].astype('float32')
self.Var = self.... | Python | nomic_cornstack_python_v1 |
function callChecking self method *args **kwargs
begin
comment the connection is already dead and a reconnect is underway
if connectionIsDead
begin
return call fail call ConnectionDead
end
comment call the method and check if the connection died
set d = call maybeDeferred method *args keyword kwargs
return call addErrb... | def callChecking(self, method, *args, **kwargs):
# the connection is already dead and a reconnect is underway
if self.connectionIsDead:
return defer.fail(ConnectionDead())
# call the method and check if the connection died
d = defer.maybeDeferred(method, *args, **kwarg... | Python | nomic_cornstack_python_v1 |
function get_best_move self move
begin
return call best_strategy move
end function | def get_best_move(self, move):
return self.root.best_strategy(move) | Python | nomic_cornstack_python_v1 |
function solution A B K
begin
if A == 0
begin
set s = 0
end
else
if K > A
begin
set s = K
end
else
begin
set s = A + A % K
end
if K > B or B == 0
begin
set e = 0
end
else
begin
set e = B - B % K
end
if s > e
begin
return 0
end
else
begin
return e - s / K + 1
end
end function | def solution(A, B, K):
if A == 0:
s = 0
elif K > A:
s = K
else:
s = A + A % K
if K > B or B == 0:
e = 0
else:
e = B - B % K
if s > e:
return 0
else:
return (e - s) / K + 1
| Python | zaydzuhri_stack_edu_python |
function loss_D self L_minus L_plus
begin
return - L_minus + L_plus
end function | def loss_D(self, L_minus, L_plus):
return - L_minus + L_plus | Python | nomic_cornstack_python_v1 |
function createContact tx query pId1 pId2 hour date
begin
run query pId1=pId1 pId2=pId2 hour=hour date=date
end function | def createContact(tx, query, pId1, pId2, hour, date):
tx.run(query, pId1=pId1, pId2=pId2, hour=hour, date=date) | Python | nomic_cornstack_python_v1 |
from flask import Flask , escape , request , make_response , redirect
import requests
import os
import random
import base64
set client_id = get environ string SPOTIFY_CLIENT_ID
set client_secret = get environ string SPOTIFY_CLIENT_SECRET
set redirect_uri = string http://localhost:3000/callback
function generate_random_... | from flask import Flask, escape, request, make_response, redirect
import requests
import os
import random
import base64
client_id = os.environ.get('SPOTIFY_CLIENT_ID')
client_secret = os.environ.get('SPOTIFY_CLIENT_SECRET')
redirect_uri = 'http://localhost:3000/callback'
def generate_random_string(length):
text =... | Python | zaydzuhri_stack_edu_python |
function is_ogh v
begin
try
begin
call _validate v prefixes=list b'o'
end
except tuple ValueError TypeError
begin
return false
end
return true
end function | def is_ogh(v) -> bool:
try:
_validate(v, prefixes=[b'o'])
except (ValueError, TypeError):
return False
return True | Python | nomic_cornstack_python_v1 |
import sys
from collections import Counter
with open argv at 1 string r as input
begin
set test_cases = call splitlines
end
for test in test_cases
begin
set array = split test string ; at 1
set array = split array string ,
end | import sys
from collections import Counter
with open(sys.argv[1], 'r') as input:
test_cases = input.read().strip().splitlines()
for test in test_cases:
array = test.split(";")[1]
array = array.split(',')
| Python | zaydzuhri_stack_edu_python |
function _is_skyserve ip_port
begin
set tuple ip skyserve_port = ip_port
set url = format string http://{ip}:{skyserve_port}/discover ip=ip skyserve_port=DEFAULT_SKYSERVE_PORT
try
begin
set resp = json get requests url timeout=1.5
if get resp string success
begin
return ip
end
end
comment noqa: E722
except any
begin
re... | def _is_skyserve(ip_port):
ip, skyserve_port = ip_port
url = 'http://{ip}:{skyserve_port}/discover'.format(ip=ip, skyserve_port=DEFAULT_SKYSERVE_PORT)
try:
resp = requests.get(url, timeout=1.5).json()
if resp.get('success'):
return ip
except: # noqa: E722
return | Python | nomic_cornstack_python_v1 |
function resume_routine_resnet config weights_path verbose=tuple 2 2 nb_epoch_finetune=15 nb_epoch_after=50 stiefel_observed=none stiefel_lr=0.01 by_name=false
begin
set image_gen = call ImageDataGeneratorAdvanced TARGET_SIZE RESCALE_SMALL true horizontal_flip=true
call resume_model_with_config ResNet50_o2 config weigh... | def resume_routine_resnet(config, weights_path,
verbose=(2,2), nb_epoch_finetune=15, nb_epoch_after=50,
stiefel_observed=None, stiefel_lr=0.01,
by_name=False):
image_gen = ImageDataGeneratorAdvanced(TARGET_SIZE, RESCALE_SMALL, True,
... | Python | nomic_cornstack_python_v1 |
function getting_biggest_group session
begin
set graql_query = string compute cluster in [character, allies, marriage, parental], using connected-component;
with read call transaction as transaction
begin
comment exicute the query and getting the clusters
set iterator = query transaction graql_query
set result = list c... | def getting_biggest_group(session):
graql_query = f'compute cluster in [character, allies, marriage, parental], ' \
f'using connected-component;'
with session.transaction().read() as transaction:
# exicute the query and getting the clusters
iterator = transaction.query(graql_qu... | Python | nomic_cornstack_python_v1 |
from pyspark.sql import SparkSession
from graphframes import *
from pyspark.sql.functions import col , concat , lit
import pyspark as ps
import warnings
from pyspark.sql import SQLContext
try
begin
comment create SparkContext on all CPUs available: in my case I have 4 CPUs on my laptop
set sc = call SparkContext string... | from pyspark.sql import SparkSession
from graphframes import *
from pyspark.sql.functions import col, concat, lit
import pyspark as ps
import warnings
from pyspark.sql import SQLContext
try:
# create SparkContext on all CPUs available: in my case I have 4 CPUs on my laptop
sc = ps.SparkContext('local[4]')
... | Python | zaydzuhri_stack_edu_python |
comment Space Invaders by Eclizanto #
import pygame , sys
from random import choice , randint
from player import Player
from barriers import Block , shape
from aliens import Alien , Ship
from laser import Laser
class Game
begin
comment Declara Grupos de Sprites e Configurações
function __init__ self
begin
comment Playe... | # Space Invaders by Eclizanto #
import pygame, sys
from random import choice, randint
from player import Player
from barriers import Block, shape
from aliens import Alien, Ship
from laser import Laser
class Game:
def __init__(self): # Declara Grupos de Sprites e... | Python | zaydzuhri_stack_edu_python |
function distinct self *columns
begin
set _distinct = columns
return self
end function | def distinct(self, *columns):
self._distinct = columns
return self | Python | nomic_cornstack_python_v1 |
function getIdentifier self length
begin
return call _getStr length
end function | def getIdentifier(self, length):
return self._getStr(length) | Python | nomic_cornstack_python_v1 |
function __generate_resource_modules self
begin
set res_modules = read select string Type_Features where=list list string Type_ID string = type_id
set modules = call fetchone
set module_names = list
set full_feature_list = call read_column_names string Type_Features where=string Features at 0 at 1
if type modules at s... | def __generate_resource_modules(self):
res_modules = self.resource.select.read("Type_Features",
where=[["Type_ID", "=", self.resource.type_id]]
)
modules = res_modules.fetchone()
module_names = []
full_feature... | Python | nomic_cornstack_python_v1 |
function unsigned n
begin
return n ? 4294967295
end function
while true
begin
try
begin
set linha = input
set i = find linha string
set n1 = call unsigned integer linha at slice : i :
set n2 = call unsigned integer linha at slice i + 1 : :
set sum = n1 ? n2
print sum
end
except EOFError
begin
break
end
end | def unsigned(n):
return n & 0xFFFFFFFF
while True:
try:
linha = input()
i = linha.find(' ')
n1 = unsigned(int(linha[:i]))
n2 = unsigned(int(linha[i+1:]))
sum = n1 ^ n2
print(sum)
except EOFError:
break;
| Python | zaydzuhri_stack_edu_python |
function parse self
begin
try
begin
call validate
end
except Exception as e
begin
raise call AssetmapError e
end
set tree = parse ET path
set root = get root tree
comment ElementTree prepends the namespace to all elements, so we need to extract
comment it so that we can perform sensible searching on elements.
set asset... | def parse(self):
try:
self.validate()
except Exception as e:
raise AssetmapError(e)
tree = ET.parse(self.path)
root = tree.getroot()
# ElementTree prepends the namespace to all elements, so we need to extract
# it so that we can perform sensible s... | Python | nomic_cornstack_python_v1 |
function test_step_constructors ndraw=1000 burnin=200
begin
set cls = step
for tuple const_info rand in product zip list gaussian_instance logistic_instance poisson_instance list gaussian logistic poisson list string gaussian string logistic string laplace
begin
set tuple inst const = const_info
set tuple X Y = call in... | def test_step_constructors(ndraw=1000, burnin=200):
cls = step
for const_info, rand in product(zip([gaussian_instance,
logistic_instance,
poisson_instance],
[cls.gaussian,
... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
import pprint
import numpy as np
import random as rd
class Environment
begin
function __init__ self state transitions reward start end
begin
set state = state
set transitions = transitions
set reward = reward
end function
function outputInfo self
begin
print string 状態遷移
call pprint transitions
prin... | # coding:utf-8
import pprint
import numpy as np
import random as rd
class Environment:
def __init__(self, state, transitions, reward, start, end):
self.state = state
self.transitions = transitions
self.reward = reward
def outputInfo(self):
print('状態遷移')
pprint.pprint(s... | Python | zaydzuhri_stack_edu_python |
function generate_index self
begin
set tuple begin_o end_o begin_a end_a = tuple 0 0 0 0
for tuple obs_space act_space in zip observation_space action_space
begin
set end_o = end_o + shape at 0
if is instance act_space Box
begin
set end_a = shape at 0
end
else
begin
set end_a = n
end
set range_o = tuple begin_o end_o
s... | def generate_index(self):
begin_o, end_o, begin_a, end_a = 0, 0, 0, 0
for obs_space, act_space in zip(self.env.observation_space, self.env.action_space):
end_o = end_o + obs_space.shape[0]
if isinstance(act_space, Box):
end_a = act_space.shape[0]
else:... | Python | nomic_cornstack_python_v1 |
from Crypto import Random
from Crypto.Cipher import AES
from lab1.lab1_task1_task2 import padding_str , checking_padding
import re
comment вход: три байт-строки
comment выход: байт-строка, полученная в результате соединения входных строк в соответсвующем порядке(причем, из средней удалены символы ; и =
function padding... | from Crypto import Random
from Crypto.Cipher import AES
from lab1.lab1_task1_task2 import padding_str, checking_padding
import re
#вход: три байт-строки
#выход: байт-строка, полученная в результате соединения входных строк в соответсвующем порядке(причем, из средней удалены символы ; и =
def padding_begin_and_end(inpu... | Python | zaydzuhri_stack_edu_python |
if x == 1
begin
print x string is not prime no.
end
else
begin
while i < x
begin
if x % i == 0
begin
print x string is not a prime no
break
end
set i = i + 1
end
while else
begin
print x string is a prime no
end
end | if x == 1:
print(x, "is not prime no.")
else:
while i < x:
if x % i == 0:
print(x, "is not a prime no")
break
i = i + 1
else:
print(x,"is a prime no") | Python | zaydzuhri_stack_edu_python |
function copy self
begin
set folder = selected_folder
set tuple args kwargs = call _copy_args
set new_conn = call __class__ *args keyword kwargs
if folder
begin
select new_conn folder
end
return new_conn
end function | def copy(self):
folder = self.selected_folder
args, kwargs = self._copy_args()
new_conn = self.__class__(*args, **kwargs)
if folder:
new_conn.select(folder)
return new_conn | Python | nomic_cornstack_python_v1 |
function _checkpointed self *args use_checkpointing=true **checkpoint_kwargs
begin
if use_checkpointing
begin
return call checkpoint _wrapped_with_dummy_arg _dummy_arg *args keyword checkpoint_kwargs
end
return call wrapped_module *args
end function | def _checkpointed(self, *args, use_checkpointing=True, **checkpoint_kwargs):
if use_checkpointing:
return checkpoint(self._wrapped_with_dummy_arg, self._dummy_arg, *args, **checkpoint_kwargs)
return self.wrapped_module(*args) | Python | nomic_cornstack_python_v1 |
function collect self
begin
string Collect interrupt data
if not call access PROC R_OK
begin
return false
end
comment Open PROC file
set file = open PROC string r
comment Get data
set cpuCount = none
for line in file
begin
if not cpuCount
begin
set cpuCount = length split line
end
else
begin
set data = split strip line... | def collect(self):
"""
Collect interrupt data
"""
if not os.access(self.PROC, os.R_OK):
return False
# Open PROC file
file = open(self.PROC, 'r')
# Get data
cpuCount = None
for line in file:
if not cpuCount:
... | Python | jtatman_500k |
function extract_wavelet self freq num_cyc=3 mode=string complex ignore_sessions=false
begin
set wav = call wavelet freq sampling_freq=sampling_freq num_cyc=num_cyc
if sessions is none or ignore_sessions
begin
set convolved = call __class__ call DataFrame dictionary comprehension x : convolve y wav mode=string same for... | def extract_wavelet(self, freq, num_cyc=3, mode="complex", ignore_sessions=False):
wav = wavelet(freq, sampling_freq=self.sampling_freq, num_cyc=num_cyc)
if self.sessions is None or ignore_sessions:
convolved = self.__class__(
pd.DataFrame(
{x: convolve(y,... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function le_calibration_func etr kc ts
begin
return etr * kc * 2.501 - 0.002361 * ts - 273 * 2500 / 9
end function | def le_calibration_func(etr, kc, ts):
return etr * kc * (2.501 - 2.361E-3 * (ts - 273)) * 2500 / 9 | Python | nomic_cornstack_python_v1 |
import csv
import math
import time
import operator
import numbers
import pandas as pd
class Question
begin
function __init__ self column value
begin
set column = column
set operator = operator
set value = value
end function
function ask_question self
begin
if call is_numeric value
begin
print string is + string column ... | import csv
import math
import time
import operator
import numbers
import pandas as pd
class Question:
def __init__(self, column, value):
self.column = column
self.operator = operator
self.value = value
def ask_question(self):
if is_numeric(self.value):
print('is ' ... | Python | zaydzuhri_stack_edu_python |
function do_stop self line
begin
set _kwargs = call _parse_stop line
if _kwargs
begin
call stop_service _kwargs at string name
end
end function | def do_stop(self, line):
_kwargs = self._parse_stop(line)
if _kwargs:
self.cloud.stop_service(_kwargs["name"]) | Python | nomic_cornstack_python_v1 |
from progressbar import progress
from manga import download_manga
from pdfconverter import convertFolder , fit_images_by_folder , isDuplicate
from consts import BASE_DIR
from pathdir import PathDir
from decorators import extension
import os
function parseCap capnumber
begin
if length split capnumber string _ == 1
begin... | from progressbar import progress
from manga import download_manga
from pdfconverter import convertFolder, fit_images_by_folder, isDuplicate
from consts import BASE_DIR
from pathdir import PathDir
from decorators import extension
import os
def parseCap(capnumber: str):
if len(capnumber.split('_')) == 1:
if... | Python | zaydzuhri_stack_edu_python |
function __levenshtein a b
begin
set tuple n m = tuple length a length b
if n > m
begin
comment Make sure n <= m, to use O(min(n,m)) space
set tuple a b = tuple b a
set tuple n m = tuple m n
end
set current = list range n + 1
for i in range 1 m + 1
begin
set tuple previous current = tuple current list i + list 0 * n
fo... | def __levenshtein(a, b):
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a, b = b, a
n, m = m, n
current = list(range(n + 1))
for i in range(1, m + 1):
previous, current = current, [i] + [0] * n
for j in range(1, n + 1):
... | Python | nomic_cornstack_python_v1 |
class Action extends object
begin
function __init__ self name position states
begin
set name = name
set position = position
set states = states
set probability = list comprehension list 0 * length states at 0 for _ in range length states
set possibleSubAcions_n = borders_n at slice : :
set borders_n = borders_n at s... | class Action(object):
def __init__(self,name,position,states):
self.name = name
self.position = position
self.states = states
self.probability = [ [0] * len(states[0]) for _ in range(len(states))]
self.possibleSubAcions_n = self.states[position[0]][position[1]].borders_n[... | Python | zaydzuhri_stack_edu_python |
function prince_options self
begin
return _prince_options
end function | def prince_options(self):
return self._prince_options | Python | nomic_cornstack_python_v1 |
class Solution
begin
function maxChunksToSorted self arr
begin
string :type arr: List[int] :rtype: int
set max_ = 0
set result = 0
set max_count = 0
set sort = sorted arr at slice : :
for tuple i n in enumerate arr
begin
if n > max_
begin
set max_ = n
set max_count = 1
end
else
if n == max_
begin
set max_count = max_... | class Solution:
def maxChunksToSorted(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
max_ = 0
result = 0
max_count = 0
sort = sorted(arr[:])
for i, n in enumerate(arr):
if n > max_:
max_ = n
max... | Python | zaydzuhri_stack_edu_python |
comment Задача «Больше предыдущего»
comment Условие
comment Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента.
set A = list comprehension integer s for s in split input
for i in range length A - 1
begin
if A at i < A at i + 1
begin
print A at i + 1 end=string
end
end | #Задача «Больше предыдущего»
#Условие
#Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента.
A = [int(s) for s in input().split()]
for i in range(len(A)-1):
if A[i] < A[i+1]:
print(A[i+1], end=' ') | Python | zaydzuhri_stack_edu_python |
from sqlalchemy import Column , Integer , String , DateTime
from datetime import datetime as dtm
from app.model.Base import Base
from sqlalchemy.orm import relationship
class CalendarEntry extends Base
begin
set __tablename__ = string calendar_entry
set id = call Column Integer primary_key=true
set currency = call Colu... | from sqlalchemy import Column, Integer, String, DateTime
from datetime import datetime as dtm
from app.model.Base import Base
from sqlalchemy.orm import relationship
class CalendarEntry(Base):
__tablename__ = 'calendar_entry'
id = Column(Integer, primary_key=True)
currency = Column(String(3), n... | Python | zaydzuhri_stack_edu_python |
function generate_characteristics characteristics_filename dim dataset
begin
set project_directory = get current directory
set path_to_save = join path project_directory string Data string characteristics
set path_to_data = join path project_directory string Data string datasets dataset
if not exists path path_to_save
... | def generate_characteristics(characteristics_filename, dim, dataset):
project_directory = os.getcwd()
path_to_save = os.path.join(project_directory,"Data", "characteristics")
path_to_data = os.path.join(project_directory, "Data","datasets", dataset)
if not os.path.exists(path_to_save):
os... | Python | nomic_cornstack_python_v1 |
function ComputeKinematicParameters marker_data
begin
comment Sort values per timestamp ascending
set marker_data = sort values marker_data string timestamp ascending=true
comment Compute for displacement
set marker_data at string displacement = absolute marker_data at string meas - call shift
comment Compute for the t... | def ComputeKinematicParameters(marker_data):
#### Sort values per timestamp ascending
marker_data = marker_data.sort_values('timestamp',ascending = True)
#### Compute for displacement
marker_data['displacement'] = np.abs(marker_data['meas'] - marker_data['meas'].shift())
#### Compute ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import random
import collections
import numpy as np
import pandas as pd
import csv
set letters = tuple string I string E string N string S string T string F string P string J
set df = read csv string mbti_1.csv
set train = default dictionary list
set test = default dictionary list
set set_t... | #!/usr/bin/env python
import random
import collections
import numpy as np
import pandas as pd
import csv
letters = ('I', 'E', 'N', 'S', 'T', 'F', 'P', 'J')
df = pd.read_csv('mbti_1.csv')
train = collections.defaultdict(list)
test = collections.defaultdict(list)
set_types = {'train': train, 'test': test}
### make 8... | Python | zaydzuhri_stack_edu_python |
from defines import *
from myparser import *
class Scope
begin
set paren = string
set prev_was_string = false
set prev_was_real = false
end class
class CodeGen extends object
begin
function __init__ self tree
begin
set error_flag = false
set tree = tree
set current_token = none
set stack = list
set scope_stack = list... | from defines import *
from myparser import *
class Scope:
paren = ''
prev_was_string = False
prev_was_real = False
class CodeGen(object):
def __init__(self, tree):
self.error_flag = False
self.tree = tree
self.current_token = None
self.stack = []
self.scope_st... | Python | zaydzuhri_stack_edu_python |
function users_get
begin
set all_users : list = call get_users
if all_users is none
begin
set response = call jsonify dict string self string /v2/users ; string users none ; string error string an unexpected error occurred retrieving users
set status_code = 500
return response
end
set user_dicts = list
for user_data i... | def users_get() -> Response:
all_users: list = UserDao.get_users()
if all_users is None:
response = jsonify(
{
"self": "/v2/users",
"users": None,
"error": "an unexpected error occurred retrieving users",
}
)
respon... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
import glob
from Thresholds import Thresholds
from process import ProcessStep
class Filter extends ProcessStep
begin
function __init__ self
begin
call __init__
print string Filter created ...
set threshold = call Thresholds
set image = none
set d... | import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
import glob
from Thresholds import Thresholds
from process import ProcessStep
class Filter(ProcessStep):
def __init__(self):
super().__init__()
print('Filter created ...')
self.threshold = Thresholds()
self.image = None
self.data = ... | Python | zaydzuhri_stack_edu_python |
function change_username self name
begin
set username = name
end function | def change_username(self, name):
self.username = name | Python | nomic_cornstack_python_v1 |
import unittest
from unittest.mock import patch
function get_words_from_file file
begin
set words = list
with open file as f
begin
for line in f
begin
extend words split line
end
end
return words
end function
function filter_long_words *words file_input=none min_length=0
begin
if file_input
begin
set words = call get_... | import unittest
from unittest.mock import patch
def get_words_from_file(file):
words = []
with open(file) as f:
for line in f:
words.extend(line.split())
return words
def filter_long_words(*words, file_input=None, min_length=0):
if file_input:
words = get_words_from_file(... | Python | zaydzuhri_stack_edu_python |
function readGenes y geneFile=gffFile
begin
debug string readGenes: y. + string y + string g. + geneFile
set geneInfo = dictionary
set geneFile = open geneFile mode=string r
for line in geneFile
begin
if string exon in line
begin
set line = split line
if line at 0 not in geneInfo
begin
set geneInfo at line at 0 = call ... | def readGenes(y, geneFile=Main.gffFile):
Main.logger.debug("readGenes: y." + str(y) + " g." + geneFile)
geneInfo = dict()
geneFile = open(geneFile, mode="r")
for line in geneFile:
if "exon" in line:
line = line.split()
if line[0] not in geneInf... | Python | nomic_cornstack_python_v1 |
function pose2mat R p
begin
set p0 = call ravel
set H = call block list list R p0 at tuple slice : : newaxis list zeros 3 1
return H
end function | def pose2mat(R, p):
p0 = p.ravel()
H = np.block([
[R, p0[:, np.newaxis]],
[np.zeros(3), 1]
])
return H | Python | nomic_cornstack_python_v1 |
import numpy as np
class Activation extends object
begin
function forward self x
begin
raise NotImplementedError
end function
function backward self z
begin
raise NotImplementedError
end function
end class
class Sigmoid extends Activation
begin
function forward self x
begin
return 1 / 1 + exp - x
end function
function ... | import numpy as np
class Activation(object):
def forward(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
def backward(self, z: np.ndarray) -> np.ndarray:
raise NotImplementedError
class Sigmoid(Activation):
def forward(self, x: np.ndarray) -> np.ndarray:
return 1... | Python | zaydzuhri_stack_edu_python |
function __init__ self lat lon grid api
begin
set lat = lat
set lon = lon
set city = grid at string city
set county = grid at string county
set village = grid at string village
set api = api
set result = dict
end function | def __init__(self, lat, lon, grid, api):
self.lat = lat
self.lon = lon
self.city = grid['city']
self.county = grid['county']
self.village = grid['village']
self.api = api
self.result = {} | Python | nomic_cornstack_python_v1 |
function parse_gprecoverseg_line filename lineno line fslist
begin
set groups = length split line
if groups not in list 1 2
begin
set msg = string only one or two groups of fields delimited by a space, not %d % groups
raise call ExceptionNoStackTraceNeeded string %s:%s:%s LINE >>%s %s % tuple filename lineno call calle... | def parse_gprecoverseg_line(filename, lineno, line, fslist):
groups = len(line.split())
if groups not in [1, 2]:
msg = "only one or two groups of fields delimited by a space, not %d" % groups
raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg))
... | Python | nomic_cornstack_python_v1 |
function line_plot slice_spec pix plot_type steps plot_offset map_axis hduname ax
begin
debug string slice_spec: %s slice_spec
debug string shape(pix[slice_spec])=%s call shape pix at slice_spec
comment transform region to a row or column (average, median, ...)
debug string plot_type=%s plot_type
if not plot_type
begin... | def line_plot(slice_spec, pix, plot_type, steps,
plot_offset, map_axis, hduname, ax):
logging.debug('slice_spec: %s', slice_spec)
logging.debug('shape(pix[slice_spec])=%s', np.shape(pix[slice_spec]))
# transform region to a row or column (average, median, ...)
logging.debug('plot_type=%s... | Python | nomic_cornstack_python_v1 |
import numpy as np
import simulacra as si
import simulacra.units as u
from import utils , exceptions
from import potential
class ImaginaryGaussianRing extends PotentialEnergy
begin
function __init__ self center=20 * bohr_radius width=2 * bohr_radius decay_time=100 * asec
begin
string Construct a RadialImaginary poten... | import numpy as np
import simulacra as si
import simulacra.units as u
from .. import utils, exceptions
from . import potential
class ImaginaryGaussianRing(potential.PotentialEnergy):
def __init__(
self,
center: float = 20 * u.bohr_radius,
width: float = 2 * u.bohr_radius,
decay_t... | Python | zaydzuhri_stack_edu_python |
function get_visit_svn_rev src
begin
set svnrev = string <Unknown>
set proc = popen string svn info %s % src shell=true universal_newlines=true stdout=PIPE
set result = communicate proc at 0
set res = search result
if not res is none
begin
set svnrev = strip split result at slice start res : call end : at 1
end
return ... | def get_visit_svn_rev(src):
svnrev = "<Unknown>"
proc = subprocess.Popen('svn info %s' % src,
shell=True,
universal_newlines = True,
stdout=subprocess.PIPE)
result = proc.communicate()[0]
res = re.compile(r'Revision:\s[0... | Python | nomic_cornstack_python_v1 |
comment 20'
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
function getIntersectionNode self headA headB
begin
comment init
set res = none
comment special case
comment * 注意优先级
if not headA or headB
begi... | # 20'
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
# init
res = None
# special case
#* 注意优先级
if not (headA or headB):
retu... | Python | zaydzuhri_stack_edu_python |
comment There are comments with the names of
comment the required functions to build.
comment Please paste your solution underneath
comment the appropriate comment.
comment search
function search array query
begin
comment base case
print array
if array == list
begin
return false
end
if array at 0 == query
begin
return... | # There are comments with the names of
# the required functions to build.
# Please paste your solution underneath
# the appropriate comment.
# search
def search(array,query):
#base case
print(array)
if array == []:
return False
if array[0] == query:
return True
... | Python | zaydzuhri_stack_edu_python |
comment taking two inputs at a time
comment x, y = input("Enter a two values: ").split()
comment print("Number of boys: ", x)
comment print("Numner of girls: ", y)
comment print() | # taking two inputs at a time
# x, y = input("Enter a two values: ").split()
# print("Number of boys: ", x)
# print("Numner of girls: ", y)
# print() | Python | zaydzuhri_stack_edu_python |
comment Copyright 2021 Google LLC. All Rights Reserved.
comment Licensed under the Apache License, Version 2.0 (the "License");
comment you may not use this file except in compliance with the License.
comment You may obtain a copy of the License at
comment http://www.apache.org/licenses/LICENSE-2.0
comment Unless requi... | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Python | jtatman_500k |
import socket
set s = call socket
set host = call gethostname
set port = 7777
call bind tuple host port
call listen 5
while true
begin
set tuple c addr = call accept
end | import socket
s=socket.socket()
host=socket.gethostname()
port=7777
s.bind((host,port))
s.listen(5)
while True:
c,addr=s.accept() | Python | zaydzuhri_stack_edu_python |
function get_projection id tree projection
begin
for child in tree at string children at id
begin
if child in projection
begin
comment cycle is or will be reported elsewhere
continue
end
add projection child
call get_projection child tree projection
end
return projection
end function | def get_projection(id, tree, projection):
for child in tree['children'][id]:
if child in projection:
continue # cycle is or will be reported elsewhere
projection.add(child)
get_projection(child, tree, projection)
return projection | Python | nomic_cornstack_python_v1 |
import re
import csv
import pickle
import nltk
import collections
import random
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
set common_words = set call words str... | import re
import csv
import pickle
import nltk
import collections
import random
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
common_words = set(stopwords.words('... | Python | zaydzuhri_stack_edu_python |
function add self element multiplicity=1
begin
string Adds an element to the multiset. >>> ms = Multiset() >>> ms.add('a') >>> sorted(ms) ['a'] An optional multiplicity can be specified to define how many of the element are added: >>> ms.add('b', 2) >>> sorted(ms) ['a', 'b', 'b'] This extends the :meth:`MutableSet.add`... | def add(self, element, multiplicity=1):
"""Adds an element to the multiset.
>>> ms = Multiset()
>>> ms.add('a')
>>> sorted(ms)
['a']
An optional multiplicity can be specified to define how many of the element are added:
>>> ms.add('b', 2)
>>> sorted(ms)... | Python | jtatman_500k |
function _batch_shuffle_ddp self x
begin
comment gather from all gpus
set batch_size_this = shape at 0
set x_gather = call concat_all_gather x
set batch_size_all = shape at 0
set num_gpus = batch_size_all // batch_size_this
comment random shuffle index
set idx_shuffle = cuda random permutation batch_size_all
comment br... | def _batch_shuffle_ddp(self, x):
# gather from all gpus
batch_size_this = x.shape[0]
x_gather = concat_all_gather(x)
batch_size_all = x_gather.shape[0]
num_gpus = batch_size_all // batch_size_this
# random shuffle index
idx_shuffle = torch.randperm(batch_size_al... | Python | nomic_cornstack_python_v1 |
string This program calls the main dictionary_search_main which internally calls dictionary api for fetching the word meaning. dictionary_search_main comprises of the DicitonarySearch class and provides all the required methods in order to achieve the desired result.
from assignment_2 import dictionary_search_main as d... | """
This program calls the main dictionary_search_main which internally calls dictionary api
for fetching the word meaning.
dictionary_search_main comprises of the DicitonarySearch class and provides all the required
methods in order to achieve the desired result.
"""
from assignment_2 import dictionary_search_main as ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from gpode.bayes import Parameter , HamiltonianMonteCarlo
from gpode.kernels import SEParameterCollection , Kernel
from scipy.stats import gamma , multivariate_normal
import scipy.special
from scipy.misc import derivative
import matplotlib.pyplot as plt
call set_printoptions precision=4
seed 11
set p... | import numpy as np
from gpode.bayes import Parameter, HamiltonianMonteCarlo
from gpode.kernels import SEParameterCollection, Kernel
from scipy.stats import gamma, multivariate_normal
import scipy.special
from scipy.misc import derivative
import matplotlib.pyplot as plt
np.set_printoptions(precision=4)
np.random.seed(1... | Python | zaydzuhri_stack_edu_python |
comment noqa: PR02
function searchsorted self **kwargs
begin
return call call register searchsorted self keyword kwargs
end function | def searchsorted(self, **kwargs): # noqa: PR02
return SeriesDefault.register(pandas.Series.searchsorted)(self, **kwargs) | Python | nomic_cornstack_python_v1 |
function shortest_path_distances a
begin
set res = copy np a
for k in range shape at 0
begin
for i in range shape at 0
begin
for j in range i + 1
begin
set res at tuple i j = min res at tuple i j res at tuple i k + res at tuple k j
set res at tuple j i = min res at tuple i j res at tuple i k + res at tuple k j
end
end
... | def shortest_path_distances(a):
res = np.copy(a)
for k in range(res.shape[0]):
for i in range(res.shape[0]):
for j in range(i+1):
res[i, j] = res[j, i] = min(res[i, j], res[i, k] + res[k, j])
return res | Python | nomic_cornstack_python_v1 |
function start_without_shipping_callback update context
begin
set chat_id = chat_id
set title = string Подписка на FriendZone
set description = string Подписка на 5 сезонов FriendZone
comment select a payload just for you to recognize its the donation from your bot
set payload = string Custom-Payload
set currency = str... | def start_without_shipping_callback(update: Update, context: CallbackContext) -> None:
chat_id = update.message.chat_id
title = "Подписка на FriendZone"
description = "Подписка на 5 сезонов FriendZone"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payl... | Python | nomic_cornstack_python_v1 |
function startsWith self prefix
begin
set level = trie
for c in prefix
begin
if c in level
begin
set level = level at c
end
else
begin
return false
end
end
return true
end function | def startsWith(self, prefix):
level = self.trie
for c in prefix:
if c in level:
level = level[c]
else:
return False
return True | Python | nomic_cornstack_python_v1 |
function sample self x
begin
set tuple g0 g = call log_potentials x
set V = call forward g0 g N K
while 1
begin
yield call backward_sample g V
end
end function | def sample(self, x):
(g0, g) = self.log_potentials(x)
V = self.forward(g0, g, x.N, self.K)
while 1:
yield self.backward_sample(g, V) | Python | nomic_cornstack_python_v1 |
function transfer_file_remote ssh_key un ip_address remotepath localpath
begin
set ssh = call SSHClient
call set_missing_host_key_policy call AutoAddPolicy
call connect ip_address username=un key_filename=ssh_key
comment Transfer Files to Server
set scp = call SCPClient call get_transport
put localpath recursive=true r... | def transfer_file_remote(ssh_key,un,ip_address,remotepath,localpath):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_address, username=un, key_filename=ssh_key)
# Transfer Files to Server
scp = SCPClient(ssh.get_transport())
scp.put(localpath, recursive=True, r... | Python | nomic_cornstack_python_v1 |
function get_app_module app
begin
set app_module = string join string . split __name__ string . at slice : - 1 :
return call __import__ app_module dict dict list string string
end function | def get_app_module(app):
app_module = str('.'.join(app.__name__.split('.')[:-1]))
return __import__(app_module, {}, {}, [str('')]) | Python | nomic_cornstack_python_v1 |
function get_dataloader opt split **kwargs
begin
set graph_parser = get kwargs string graph_parser
set embedder = get kwargs string embedder
set dataset = call get_dataset opt split graph_parser=graph_parser embedder=embedder
set shuffle = if expression split == string train then shuffle else 0
set loader = call ClevrQ... | def get_dataloader(opt, split, **kwargs):
graph_parser = kwargs.get('graph_parser')
embedder = kwargs.get('embedder')
dataset = get_dataset(opt, split, graph_parser=graph_parser, embedder=embedder)
shuffle = opt.shuffle if split == 'train' else 0
loader = ClevrQuestionDataLoader(dataset=dataset, bat... | Python | nomic_cornstack_python_v1 |
comment Copyright (C) 2017 Feedvay (Gagandeep Singh: singh.gagan144@gmail.com) - All Rights Reserved
comment Content in this document can not be copied and/or distributed without the express
comment permission of Gagandeep Singh.
from mongoengine.document import *
from mongoengine.fields import *
from mongoengine.base.... | # Copyright (C) 2017 Feedvay (Gagandeep Singh: singh.gagan144@gmail.com) - All Rights Reserved
# Content in this document can not be copied and/or distributed without the express
# permission of Gagandeep Singh.
from mongoengine.document import *
from mongoengine.fields import *
from mongoengine.base.fields import Base... | Python | zaydzuhri_stack_edu_python |
function data_variance df response
begin
info format string Running data variance for response {} response
call seterr invalid=string ignore
set cf = values
set n = values
if response == string lt_cf
begin
set gc_var = values
end
else
if response == string ln_rate
begin
set gc_var = values
end
else
begin
raise call Run... | def data_variance(df, response):
logger.info("Running data variance for response {}".format(response))
np.seterr(invalid='ignore')
cf = df.cf.values
n = df.sample_size.values
if response == "lt_cf":
gc_var = df.gc_var_lt_cf.values
elif response == "ln_rate":
gc_var = df.gc_var_ln... | 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.