code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from preprocessing.common.preprocessor_graph.common.PreprocessorCheckAbstractClass import PreprocessorCheckAbstractClass
import numpy as np
import math
import re
class CheckString extends PreprocessorCheckAbstractClass
begin
function __init__ self
begin
set alphabet = compile string [A-Z]|[a-z]|\s
end function
function... | from preprocessing.common.preprocessor_graph.common.PreprocessorCheckAbstractClass import PreprocessorCheckAbstractClass
import numpy as np
import math
import re
class CheckString(PreprocessorCheckAbstractClass):
def __init__(self):
self.alphabet = re.compile('[A-Z]|[a-z]|\s')
def check(self, df_colu... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
import torchvision
class ConvNet extends Module
begin
function __init__ self num_classes=196
begin
call __init__
set conv1 = sequential conv 2d 3 32 kernel_size=3 relu
set conv2 = sequential conv 2d 32 32 kernel_size=3 relu call MaxPool2d kernel_size=2 call Dropout2d 0.25
set conv3 = ... | import torch
import torch.nn as nn
import torchvision
class ConvNet(nn.Module):
def __init__(self, num_classes=196):
super(ConvNet, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3),
nn.ReLU()
)
self.conv2 = nn.Sequential(
... | Python | zaydzuhri_stack_edu_python |
function n_ary func
begin
function wrapper x *args
begin
return if expression not args then x else call func x call wrapper *args
end function
return wrapper
end function | def n_ary(func):
def wrapper(x, *args):
return x if not args else func(x, wrapper(*args))
return wrapper | Python | nomic_cornstack_python_v1 |
function get_gradients image
begin
set tuple ix iy = tuple none none
comment TODO: YOUR IMAGE GRADIENTS CODE HERE #
comment define Sobel filter matrices
set Mx = array list list - 1.0 0.0 1.0 list - 2.0 0.0 2.0 list - 1.0 0.0 1.0
set My = array list list - 1.0 - 2.0 - 1.0 list 0.0 0.0 0.0 list 1.0 2.0 1.0
set ix = call... | def get_gradients(image):
ix, iy = None, None
#############################################################################
# TODO: YOUR IMAGE GRADIENTS CODE HERE #
#############################################################################
# define Sobel... | Python | nomic_cornstack_python_v1 |
function q1
begin
print string hello * 5
end function
function q2
begin
set tuple x y = tuple 4 5
set tuple y x = tuple x y
print x
print y
end function
function q3
begin
set z = 9
set lst = list 0 * z
print lst at slice : - 1 :
end function
function q4
begin
function help x
begin
return x % 2 == 0
end function
set ls... | def q1():
print("hello" * 5)
def q2():
x, y = 4, 5
y, x = x, y
print(x)
print(y)
def q3():
z = 9
lst = [0] * z
print(lst[:-1])
def q4():
def help(x):
return x % 2 == 0
lst = [i**2 for i in range(10)]
lst = filter(help, lst)
print(list(lst)[::2])
def q5():... | Python | zaydzuhri_stack_edu_python |
comment OOP
class bank
begin
set cid = 23
set current_balance = 2000
function funca self
begin
print string hello from funca in bank
end function
end class
set obja = call bank
set objb = call bank
print type objb | # OOP
class bank:
cid = 23
current_balance = 2000
def funca(self):
print("hello from funca in bank")
obja = bank()
objb = bank()
print(type(objb))
| Python | zaydzuhri_stack_edu_python |
if zero == 0
begin
print string NO
end
else
if zero == 1
begin
print if expression t at 0 == 0 and t at 1 == 3 and t at 2 == 2 or t at 1 == 0 and t at 2 == 1 and t at 0 == 3 or t at 2 == 0 and t at 0 == 2 and t at 1 == 1 then string NO else string YES
end
else
if zero >= 2
begin
print string YES
end | if zero == 0:
print("NO")
elif zero == 1:
print("NO" if ((t[0] == 0 and t[1] == 3 and t[2] == 2) or (t[1] == 0 and t[2] == 1 and t[0] == 3) or (t[2] == 0 and t[0] == 2 and t[1] == 1)) else "YES")
elif zero >= 2:
print("YES") | Python | zaydzuhri_stack_edu_python |
import matplotlib.pylab as plt
call rc string font family=string serif
comment # F1
comment metric = 'F1 score'
comment xlabel = 'classifiers'
comment ylabel = 'f1 score'
comment title = 'Impact of binning over ' + metric + ' for proposed NFs'
comment orderingList = ['Naive Bayes', 'SVM', 'ANN', 'Random Forest']
commen... | import matplotlib.pylab as plt
plt.rc('font', family='serif')
# # F1
# metric = 'F1 score'
# xlabel = 'classifiers'
# ylabel = 'f1 score'
# title = 'Impact of binning over ' + metric + ' for proposed NFs'
#
# orderingList = ['Naive Bayes', 'SVM', 'ANN', 'Random Forest']
# noBinningVal = [0.684286227, 0.6372947608, 0.... | Python | zaydzuhri_stack_edu_python |
function rho x
begin
return mean exp 2j * call deg2rad x
end function | def rho(x):
return np.exp(2j * np.deg2rad(x)).mean() | Python | nomic_cornstack_python_v1 |
function import_entities self
begin
comment Generate a "stub function" on-the-fly which will actually make
comment the request.
comment gRPC handles serialization and deserialization, so we just need
comment to pass in the functions for each.
if string import_entities not in _stubs
begin
set _stubs at string import_ent... | def import_entities(
self,
) -> Callable[
[datastore_admin.ImportEntitiesRequest], Awaitable[operations_pb2.Operation]
]:
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
... | Python | nomic_cornstack_python_v1 |
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session , sessionmaker
import csv
set engine = call create_engine call getenv string DATABASE_URL
set db = call scoped_session call sessionmaker bind=engine
set f = open string books.csv
set reader = reader f
execute db string CREATE TABLE... | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import csv
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
f = open("books.csv")
reader = csv.reader(f)
db.execute("CREATE TABLE IF NOT EXISTS books (\
... | Python | zaydzuhri_stack_edu_python |
function deserialize data events
begin
set calendar = call Calendar none none none none none
for attr in tuple string resourceType string name string url string changeToken string shared string sharedByMe
begin
set attribute calendar attr call u2str data at attr
end
set componentTypes = set map u2str data at string com... | def deserialize(data, events):
calendar = Calendar(None, None, None, None, None)
for attr in ("resourceType", "name", "url", "changeToken", "shared", "sharedByMe"):
setattr(calendar, attr, u2str(data[attr]))
calendar.componentTypes = set(map(u2str, data["componentTypes"]))
... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
comment 计算机组相关统计数据的函数···
comment 统计标准功率数据···
function calculate_normal_power normal_power_curve normal_power_splat
begin
for wind_cut in normal_power_curve
begin
for real_wind_id in range length normal_power_splat at string wind_list
begin
if normal_power_splat at string wind_list at real_wind_id -... | #coding=utf-8
#计算机组相关统计数据的函数···
#统计标准功率数据···
def calculate_normal_power(normal_power_curve,normal_power_splat):
for wind_cut in normal_power_curve:
for real_wind_id in range(len(normal_power_splat['wind_list'])):
if normal_power_splat['wind_list'][real_wind_id]-wind_cut>=0:
... | Python | zaydzuhri_stack_edu_python |
import sqlite3
import constants
import api
import json
set DATABASE = string database.db
function add_language user_id language vocab_proficiency grammar_proficiency db_path=DATABASE
begin
comment if not grammar_proficiency.keys() == constants.LANGUAGES[language]:
comment raise ValueError("grammar_proficiency doesn't m... | import sqlite3
import constants
import api
import json
DATABASE = "database.db"
def add_language(user_id, language, vocab_proficiency, grammar_proficiency, db_path=DATABASE):
# if not grammar_proficiency.keys() == constants.LANGUAGES[language]:
# raise ValueError("grammar_proficiency doesn't match the lan... | Python | zaydzuhri_stack_edu_python |
comment print n
function addx n
begin
set temp = 0
while n > 0
begin
set temp = temp + 9 * 10 ^ n - 2 * n - 1
set n = n - 1
end
comment print n
return temp
end function
comment print int(addx(3))
set x = n - 10 ^ len - 1 - 1 * len + integer call addx len | #print n
def addx(n):
temp = 0
while n > 0:
temp = temp + 9*(10**(n-2))*(n-1)
n = n - 1
#print n
return temp
#print int(addx(3))
x = ((n - (10**(len-1)-1))*len) + int(addx(len)) | Python | zaydzuhri_stack_edu_python |
class Profile extends object
begin
function __init__ self alignment score_matrix
begin
set profile = dict
for ac in list keys score_matrix
begin
set profile at ac = list
for i in range length alignment at 0
begin
set count = 0
for j in range length alignment
begin
if alignment at j at i == ac
begin
set count = count ... | class Profile(object):
def __init__(self, alignment, score_matrix):
self.profile = {}
for ac in list(score_matrix.keys()):
self.profile[ac] = []
for i in range(len(alignment[0])):
count = 0
for j in range(len(alignment)):
if... | Python | zaydzuhri_stack_edu_python |
comment (linear / tail-recursive) Recursive version
function binary_search_rec arr value low high
begin
if low > high
begin
return false
end
set mid = low + high // 2
if value == arr at mid
begin
return true
end
else
if value < arr at mid
begin
return call binary_search_rec arr value low mid - 1
end
else
begin
return c... | # (linear / tail-recursive) Recursive version
def binary_search_rec(arr, value, low, high):
if low > high:
return False
mid = (low + high) // 2
if value == arr[mid]:
return True
elif value < arr[mid]:
return binary_search_rec(arr, value, low, mid - 1)
else:
return b... | Python | zaydzuhri_stack_edu_python |
function test_recipients_with_muted_review_requests self
begin
set dopey = get objects username=string dopey
set admin = get objects username=string admin
set group = call create name=string group
add users admin
save
set review_request = call create_review_request summary=string My test review request public=true
add ... | def test_recipients_with_muted_review_requests(self):
dopey = User.objects.get(username='dopey')
admin = User.objects.get(username='admin')
group = Group.objects.create(name='group')
group.users.add(admin)
group.save()
review_request = self.create_review_request(
... | Python | nomic_cornstack_python_v1 |
comment 주민번호는 반드시 14자리이어야 한다.
comment 6번째 항목은 반드시 '-' 이어야 함
comment 2번째 항목은 '0' 또는 '1'이어야 함
comment 7번째 항목은 '1','2','3','4' 이어야 함
function findSsn juminno
begin
if length juminno != 14
begin
return false
end
if juminno at 6 != string -
begin
return false
end
if not juminno at 2 in list string 0 string 1
begin
comment i... | # 주민번호는 반드시 14자리이어야 한다.
# 6번째 항목은 반드시 '-' 이어야 함
# 2번째 항목은 '0' 또는 '1'이어야 함
# 7번째 항목은 '1','2','3','4' 이어야 함
def findSsn(juminno):
if len(juminno) != 14:
return False
if juminno[6] != '-':
return False
if not juminno[2] in ['0','1']:
#if juminno[2] !=0 or juminno[2] != 1:
return Fal... | Python | zaydzuhri_stack_edu_python |
function version_prefix self
begin
return _version_prefix
end function | def version_prefix(self) -> str:
return self._version_prefix | Python | nomic_cornstack_python_v1 |
function slack_app_id self
begin
return get pulumi self string slack_app_id
end function | def slack_app_id(self) -> pulumi.Output[str]:
return pulumi.get(self, "slack_app_id") | Python | nomic_cornstack_python_v1 |
function read_3_images filename order=string row
begin
comment Checking whether the C extension is correctly built.
if _pyflct is none
begin
raise call ImportError string C extension for flct is missing, please rebuild.
end
if lower order not in list string row string column
begin
raise call ValueError string The order... | def read_3_images(filename, order="row"):
# Checking whether the C extension is correctly built.
if _pyflct is None:
raise ImportError("C extension for flct is missing, please rebuild.")
if order.lower() not in ["row", "column"]:
raise ValueError(
"The order of the arrays is no... | Python | nomic_cornstack_python_v1 |
function pytest_addoption parser
begin
set group = call getgroup string doctest_custom HELP at string plugin
call addoption string --doctest-repr default=none help=HELP at string repr
end function | def pytest_addoption(parser):
group = parser.getgroup("doctest_custom", HELP["plugin"])
group.addoption("--doctest-repr", default=None, help=HELP["repr"]) | Python | nomic_cornstack_python_v1 |
from tkinter import *
import random
import time
comment We use these counter
set counter = 0
set counter1 = 0
set tk = call Tk
title tk string Pong!
comment Cannot resize window because it would mess up the game size.
call resizable 0 0
call wm_attributes string -topmost 1
set canvas = call Canvas tk width=500 height=4... | from tkinter import *
import random
import time
counter = 0 #We use these counter
counter1 = 0
tk = Tk()
tk.title("Pong!")
tk.resizable(0,0) #Cannot resize window because it would mess up the game size.
tk.wm_attributes("-topmost", 1) #
canvas = Canvas(tk, width = 500, height = 400, bd = 0, highlightthickn... | Python | zaydzuhri_stack_edu_python |
import sys , os
append path pardir
import numpy as np
from dataset.mnist import load_mnist
set hint_ms_error = string
set hint_ce_error = string Cross entropy error is as follow def entropy_error(y, t): delta = 1e-7 return -np.sum(t * np.log(y + delta)) And check your define function as follow. checkCeError()
set hint... | import sys, os
sys.path.append(os.pardir)
import numpy as np
from dataset.mnist import load_mnist
hint_ms_error = ""
hint_ce_error = """Cross entropy error is as follow
def entropy_error(y, t):
delta = 1e-7
return -np.sum(t * np.log(y + delta))
And check your define function as follow.
checkCeError()
"""
h... | Python | zaydzuhri_stack_edu_python |
from caesar_cipher.caesar_cipher import encrypt , decrypt , crack
function test_encrypt_one
begin
set actual = call encrypt string Omar zoubi 6
print actual
set expected = string Usgx fuaho
assert actual == expected
end function
function test_encrypt_ones
begin
set actual = call encrypt string I live in Ramtha 13
print... | from caesar_cipher.caesar_cipher import encrypt,decrypt, crack
def test_encrypt_one():
actual = encrypt('Omar zoubi',6)
print(actual)
expected = 'Usgx fuaho'
assert actual == expected
def test_encrypt_ones():
actual = encrypt('I live in Ramtha',13)
print(actual)
expected = 'V yvir va En... | Python | zaydzuhri_stack_edu_python |
import random
function main
begin
set hats = dictionary comprehension key : list 1 2 3 for key in range 1 101
comment hats[1].remove(2) vs hats[1].append(2)
comment does not have to be set-up dynamically with num of sticks
comment because it is a sliding scale against a max of 100 + 1.
print string Welcome to the Game ... | import random
def main():
hats = {key: [1, 2, 3] for key in range(1, 101)}
# hats[1].remove(2) vs hats[1].append(2)
# does not have to be set-up dynamically with num of sticks
# because it is a sliding scale against a max of 100 + 1.
print ("Welcome to the Game of Sticks!")
while True:
... | Python | zaydzuhri_stack_edu_python |
function on_off_to_boolean value
begin
debug string converting value %s to bool call repr value
if not is instance value str
begin
raise call ValueError string The value { call __repr__ } is not a string.
end
if lower value in tuple string on string true string yes string 1
begin
return true
end
if lower value in tuple... | def on_off_to_boolean(value: str) -> bool:
logger.debug("converting value %s to bool", repr(value))
if not isinstance(value, str):
raise ValueError(f"The value {value.__repr__()} is not a string.")
if value.lower() in ("on", "true", "yes", "1"):
return True
if value.lower() in ("off", "f... | Python | nomic_cornstack_python_v1 |
function call_at self t func *args
begin
raise call NotImplementedError
end function | def call_at(self, t, func, *args):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function update_status self proxy_id connect_times fail_times
begin
call update_data dict string connect_times connect_times ; string fail_times fail_times list dict string proxy_id dict string judge string = ; string value proxy_id
end function | def update_status(self, proxy_id, connect_times, fail_times):
self.update_data({"connect_times": connect_times, "fail_times": fail_times},
[{"proxy_id": {"judge": "=", "value": proxy_id}}]) | Python | nomic_cornstack_python_v1 |
function cluster_master_phase self
begin
return get pulumi self string cluster_master_phase
end function | def cluster_master_phase(self) -> Optional[str]:
return pulumi.get(self, "cluster_master_phase") | Python | nomic_cornstack_python_v1 |
function initial_alcohol_percentage
begin
comment Given values
comment liters
set initial_volume = 6
comment liters
set added_alcohol = 3.6
comment 50% alcohol
set final_concentration = 0.5
comment Calculate final volume of the solution
set final_volume = initial_volume + added_alcohol
comment Calculate total volume of... | def initial_alcohol_percentage():
# Given values
initial_volume = 6 # liters
added_alcohol = 3.6 # liters
final_concentration = 0.5 # 50% alcohol
# Calculate final volume of the solution
final_volume = initial_volume + added_alcohol
# Calculate total volume of alcohol in the final solut... | Python | dbands_pythonMath |
import unittest
from main import run
from unittest.mock import MagicMock , patch
from unittest.mock import call
class TestMain extends TestCase
begin
function test_run self
begin
set all_directories = list string /foo string /bar string /baz string /a/b/c
with patch string main.parseFile as parseFileMock
begin
with pat... | import unittest
from main import run
from unittest.mock import MagicMock, patch
from unittest.mock import call
class TestMain(unittest.TestCase):
def test_run(self):
all_directories = ['/foo', '/bar', '/baz', '/a/b/c']
with patch('main.parseFile') as parseFileMock:
with patch('main.pro... | Python | zaydzuhri_stack_edu_python |
string User Mutations
from graphene import Mutation
from src.models.user import User
from src.serializers import UserGrapheneInputModel , UserGrapheneModel
class CreateUser extends Mutation
begin
string Mutation for Creating a User
class Arguments
begin
string Endpoint Arguments for Mutation
set user_details = call Use... | """ User Mutations """
from graphene import Mutation
from src.models.user import User
from src.serializers import UserGrapheneInputModel, UserGrapheneModel
class CreateUser(Mutation):
"""Mutation for Creating a User"""
class Arguments:
"""Endpoint Arguments for Mutation"""
user_details = U... | Python | zaydzuhri_stack_edu_python |
function rmse df w
begin
return square root mean squared error df w
end function | def rmse(df, w):
return np.sqrt(mse(df, w)) | Python | nomic_cornstack_python_v1 |
function members self
begin
from members.members_request_builder import MembersRequestBuilder
return call MembersRequestBuilder request_adapter path_parameters
end function | def members(self) -> MembersRequestBuilder:
from .members.members_request_builder import MembersRequestBuilder
return MembersRequestBuilder(self.request_adapter, self.path_parameters) | Python | nomic_cornstack_python_v1 |
function bestSum targetSum numbers memo=dict
begin
if targetSum in keys memo
begin
return memo at targetSum
end
if targetSum == 0
begin
return list
end
if targetSum < 0
begin
return none
end
set myShortestCombination = none
for num in numbers
begin
set remainder = targetSum - num
set reamainderCombination = call bestS... | def bestSum(targetSum,numbers,memo={}):
if targetSum in memo.keys():
return memo[targetSum]
if targetSum == 0:
return []
if targetSum<0:
return None
myShortestCombination = None
for num in numbers:
remainder = targetSum - num
reamainderCombination = bestSum(re... | Python | zaydzuhri_stack_edu_python |
import math
from math import sqrt
comment from math import * - Don't use this
from math import sqrt as squareroot
import math as m
function main
begin
comment uses import math
print square root 9
comment uses from math import sqrt
print square root 16
comment uses from math import sqrt as squareroot
print call squarero... | import math
from math import sqrt
# from math import * - Don't use this
from math import sqrt as squareroot
import math as m
def main():
print(math.sqrt(9)) # uses import math
print(sqrt(16)) # uses from math import sqrt
print(squareroot(25)) # uses from math import sqrt as squareroot
print(m.sqr... | Python | zaydzuhri_stack_edu_python |
function interpolate_and_plot x y num_points=1000
begin
set univ_spline = univariate spline x y
set wavelength_line = linear space x at 0 x at - 1 num_points
plot x y string ro ms=5
plot wavelength_line call univ_spline wavelength_line string g lw=3
call set_smoothing_factor 0
set QuantumEfficiency = call univ_spline w... | def interpolate_and_plot(
x,y,
num_points=1000):
univ_spline = UnivariateSpline(
x, y)
wavelength_line = np.linspace(x[0], x[-1], num_points)
plt.plot(x, y, 'ro', ms=5)
plt.plot(wavelength_line, univ_spline(wavelength_line), 'g', lw=3)
univ_spline.set_smoothing_... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Projection the semantic image to the world frame Author: Henry Zhang Date:February 18, 2020
comment module
import cv2
import numpy as np
from utils import dehomogenize
comment parameters
comment classes
comment functions
function generate_homography im_src pts_src pts_dst vis=false
b... | #!/usr/bin/env python
""" Projection the semantic image to the world frame
Author: Henry Zhang
Date:February 18, 2020
"""
# module
import cv2
import numpy as np
from utils import dehomogenize
# parameters
# classes
# functions
def generate_homography(im_src, pts_src, pts_dst, vis=False):
"""
https://ww... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
string @param A: a list of integers @return an integer
comment [1,1,1,2,2,3]
function removeDuplicates self A
begin
if not A
begin
return 0
end
comment curt is the last valid index
set tuple curt count = tuple 0 1
for i in range 1 length A
begin
if A at curt == A at i
begin
if count >= 2
begin
cont... | class Solution:
"""
@param A: a list of integers
@return an integer
"""
# [1,1,1,2,2,3]
def removeDuplicates(self, A):
if not A:
return 0
# curt is the last valid index
curt, count = 0, 1
for i in range(1, len(A)):
if A[curt] == A[i]:
... | Python | zaydzuhri_stack_edu_python |
function push self x
begin
append ls1 x
end function | def push(self, x: 'int') -> 'None':
self.ls1.append(x) | Python | nomic_cornstack_python_v1 |
string #print("Você Está Grávida ? Aperte 1 para SIM ou 2 para NÃO: ") #if 1 == True: # print("Você está GráVida por isto não podera usar nosso brinquedo") #else 2 == False: # print("Não Gravida!!!!")
set gravida = integer input string Você está Gravida ? digite 1 para SIM ou 2 para NÃO:
if gravida == 1
begin
print str... | """
#print("Você Está Grávida ? Aperte 1 para SIM ou 2 para NÃO: ")
#if 1 == True:
# print("Você está GráVida por isto não podera usar nosso brinquedo")
#else 2 == False:
# print("Não Gravida!!!!")
"""
gravida = int(input('Você está Gravida ? digite 1 para SIM ou 2 para NÃO: ') )
if gravida == 1:
print('Você está ... | Python | zaydzuhri_stack_edu_python |
function show_frameDelta self cont
begin
set frame = frames at cont
comment Displays either "Ready" or "Insert stimuli" based on experiment type
call gettext
call tkraise
end function | def show_frameDelta(self, cont):
frame = self.frames[cont]
frame.gettext() #Displays either "Ready" or "Insert stimuli" based on experiment type
frame.tkraise() | Python | nomic_cornstack_python_v1 |
function test_getClientIP_XForwardedFor self
begin
set request = call createRequestWithIPs
set clientIP = call getClientIP request useForwardedHeader=true
assert equal clientIP string 2.2.2.2
end function | def test_getClientIP_XForwardedFor(self):
request = self.createRequestWithIPs()
clientIP = server.getClientIP(request, useForwardedHeader=True)
self.assertEqual(clientIP, '2.2.2.2') | Python | nomic_cornstack_python_v1 |
function load_properties self meta
begin
comment doctype properties
for prop in doctype_properties
begin
set prop get meta prop
end
for d in get meta string fields
begin
set new_d = dict string fieldname fieldname ; string is_custom_field get d string is_custom_field ; string is_system_generated get d string is_system_... | def load_properties(self, meta):
# doctype properties
for prop in doctype_properties:
self.set(prop, meta.get(prop))
for d in meta.get("fields"):
new_d = {
"fieldname": d.fieldname,
"is_custom_field": d.get("is_custom_field"),
"is_system_generated": d.get("is_system_generated"),
"name": d.n... | Python | nomic_cornstack_python_v1 |
comment A stateful recurrent model is one for which the internal states (memories) obtained
comment after processing a batch of samples are reused as initial states for the samples of the next batch.
comment This allows to process longer sequences while keeping computational complexity manageable.
import keras
from ker... | # A stateful recurrent model is one for which the internal states (memories) obtained
# after processing a batch of samples are reused as initial states for the samples of the next batch.
# This allows to process longer sequences while keeping computational complexity manageable.
import keras
from keras.models impor... | Python | zaydzuhri_stack_edu_python |
function recall true_positives false_negatives
begin
try
begin
return true_positives / true_positives + false_negatives
end
except ZeroDivisionError
begin
return nan
end
end function | def recall(true_positives, false_negatives):
try:
return true_positives / (true_positives + false_negatives)
except ZeroDivisionError:
return np.nan | Python | nomic_cornstack_python_v1 |
function count f
begin
function counted *args
begin
set call_count = call_count + 1
return f dist *args
end function
set call_count = 0
return counted
end function
decorator count
function divides k n
begin
return n % k == 0
end function
function factors n
begin
set total = 0
for k in range 1 n + 1
begin
if call divide... | def count(f):
def counted(*args):
counted.call_count += 1
return f(*args)
counted.call_count = 0
return counted
@count
def divides(k, n):
return n % k == 0
def factors(n):
total = 0
for k in range(1, n + 1):
if divides(k, n):
total += 1
return total
from math import sqrt
def factors_fast(n):
total ... | Python | zaydzuhri_stack_edu_python |
function _check_bounds_values lower_value upper_value
begin
set types_ = set literal type lower_value type upper_value
try
begin
comment remove None to simplify further checking
remove types_ type none
set has_None = true
end
except KeyError
begin
set has_None = false
end
if tuple types_ not in tuple tuple int tuple fl... | def _check_bounds_values(lower_value, upper_value):
types_ = {type(lower_value), type(upper_value)}
try:
# remove None to simplify further checking
types_.remove(type(None))
has_None = True
except KeyError:
has_None = False
if tuple(types_... | Python | nomic_cornstack_python_v1 |
function update self namespace=none name=call generate_random_name **kwargs
begin
set namespace = if expression namespace is none then namespace else namespace
set deployment = get deployment namespace name
set data = dict string min get kwargs string min 2 ; string max get kwargs string max 4 ; string cpu_percent 45 ;... | def update(self, namespace=None, name=generate_random_name(), **kwargs):
namespace = self.namespace if namespace is None else namespace
deployment = self.scheduler.deployment.get(namespace, name)
data = {
'min': kwargs.get('min', 2),
'max': kwargs.get('max', 4),
... | Python | nomic_cornstack_python_v1 |
function bcb_s2s_fixedtime_shooter meoe0 meoef A B dt shooterInfo
begin
comment -----------------------------------------------------------
comment Initial Integration ##
comment Getting segement initial conditions
set N = 3
set segment_type = list 1 0 1
set segICs = list horizontal stack tuple meoe0 shooterInfo at str... | def bcb_s2s_fixedtime_shooter(meoe0, meoef, A, B, dt, shooterInfo):
# -----------------------------------------------------------
## Initial Integration ##
# Getting segement initial conditions
N = 3; segment_type = [1, 0, 1]
segICs = [np.hstack((meoe0, shooterInfo['m0']))]
for i in ra... | Python | nomic_cornstack_python_v1 |
import torch
import numpy as np
function rgb2yuv images channel_dimension=1
begin
set rgb_to_yuv_matrix = array list list 0.299 0.587 0.114 list - 0.147 - 0.289 0.436 list 0.615 - 0.515 - 0.1
set new_images = clone images
if channel_dimension == 1
begin
set new_images at tuple slice : : 0 slice : : slice : : =... | import torch
import numpy as np
def rgb2yuv(images, channel_dimension=1):
rgb_to_yuv_matrix = np.array(
[[0.299, 0.587, 0.114], [-0.147, -0.289, 0.436], [0.615, -0.515, -0.1]])
new_images = images.clone()
if channel_dimension == 1:
new_images[:, 0, :, :] = rgb_to_yuv_matrix[0, 0] * images[... | Python | zaydzuhri_stack_edu_python |
function add_node self node_group_name hostname=none headers=none payload=none active_validation=true **query_parameters
begin
call check_type headers dict
if headers is not none
begin
pass
end
set with_custom_headers = false
set _headers = headers or dict
if headers
begin
update _headers call dict_of_str headers
set ... | def add_node(self,
node_group_name,
hostname=None,
headers=None,
payload=None,
active_validation=True,
**query_parameters):
check_type(headers, dict)
if headers is not None:
pass
w... | Python | nomic_cornstack_python_v1 |
function partition ar
begin
set p = ar at 0
set left = list
comment equal=[]
set right = list
for char in ar
begin
if char < p
begin
append left char
end
else
comment elif char==p:
comment equal.append(char)
if char > p
begin
append right char
end
end
comment string=' '.join(str(x) for x in left)+' '+' '.join(str(x) ... | def partition(ar):
p=ar[0]
left=[]
#equal=[]
right=[]
for char in ar:
if char<p:
left.append(char)
#elif char==p:
#equal.append(char)
elif char>p:
right.append(char)
#string=' '.join(str(x) for x in left)+' '+' '.join(str(x) for x ... | Python | zaydzuhri_stack_edu_python |
function get_taken_fields request
begin
set app_pk = get POST string app_pk or 0
set taken_list = call values_list string field_name flat=true
return call HttpResponse dumps list taken_list
end function | def get_taken_fields(request):
app_pk = request.POST.get('app_pk') or 0
taken_list = MembershipAppField.objects.filter(
Q(field_name__startswith='ud'), (Q(display=True) | Q(admin_only=True))).exclude(
membership_app=app_pk).values_list(
'field_name', flat=True)
return Ht... | Python | nomic_cornstack_python_v1 |
function integer_string x
begin
set integer_list = list
for a in range 1 x + 1
begin
for b in string a
begin
append integer_list b
end
end
return join string integer_list
end function
set x = call integer_string 1000000
print integer x at 0 * integer x at 9 * integer x at 99 * integer x at 999 * integer x at 9999 * i... | def integer_string(x):
integer_list = []
for a in range(1,x + 1):
for b in str(a):
integer_list.append(b)
return ''.join(integer_list)
x = integer_string(1000000)
print(int(x[0]) * int(x[9]) * int(x[99]) * int(x[999]) * int(x[9999]) * int(x[99999]) * int(x[999999]))
| Python | zaydzuhri_stack_edu_python |
function draw_plot_func dictionary n_classes window_title plot_title x_label output_path to_show plot_color true_p_bar
begin
comment sort the dictionary by decreasing value, into a list of tuples
set sorted_dic_by_value = sorted items dictionary key=call itemgetter 1
comment unpacking the list of tuples into two lists
... | def draw_plot_func(dictionary, n_classes, window_title, plot_title, x_label, output_path, to_show, plot_color, true_p_bar):
# sort the dictionary by decreasing value, into a list of tuples
sorted_dic_by_value = sorted(dictionary.items(), key=operator.itemgetter(1))
# unpacking the list of tuples into two li... | Python | nomic_cornstack_python_v1 |
import nltk
function extract_pnp text
begin
set tokens = call word_tokenize text
set tagged = call pos_tag tokens
set pnp = list
set blanks = list
for tuple word tag in tagged
begin
if string NNP in tag
begin
append pnp word
append blanks string ___
end
else
begin
append blanks word
end
end
return tuple blanks pnp
en... | import nltk
def extract_pnp(text):
tokens = nltk.word_tokenize(text)
tagged = nltk.pos_tag(tokens)
pnp = []
blanks = []
for (word, tag) in tagged:
if "NNP" in tag:
pnp.append(word)
blanks.append('___')
else:
blanks.append(word)
return (blanks, pnp) | Python | zaydzuhri_stack_edu_python |
from Connections import CONNECTIONS
class Features extends CONNECTIONS
begin
function fetch_questions self
begin
set ques_dict = dict
set query = string Select QuesNo,Questions,Options from tbl_quizquestions
set fetched_data = call fetch_data query
for data in fetched_data
begin
set tuple ques_no question options = da... | from Connections import CONNECTIONS
class Features(CONNECTIONS):
def fetch_questions(self):
ques_dict = {}
query = 'Select QuesNo,Questions,Options from tbl_quizquestions'
fetched_data = self.fetch_data(query)
for data in fetched_data:
ques_no, question, opti... | Python | zaydzuhri_stack_edu_python |
function test_delayms delayms
begin
set n_tests = list 1000 1000 1000 1000 100 40 10 4 2 1
set tests = list 0 0.1 0.5 1 10 50 100 500 1000 5000
comment Uncomment to test a 1 minute delay:
comment tests.append(60000); n_tests.append(1)
set total_error = 0.0
set time_no_delay = 0
for i in range length n_tests
begin
set t... | def test_delayms(delayms):
n_tests = [1000, 1000, 1000, 1000, 100, 40, 10, 4, 2, 1]
tests = [ 0, 0.1, 0.5, 1, 10, 50, 100, 500, 1000, 5000]
# Uncomment to test a 1 minute delay:
#tests.append(60000); n_tests.append(1)
total_error = 0.0
time_no_delay = 0
for i in range(len(n_tes... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment In[1]:
comment define rooms and items
comment All Objects (furniture)
set career_hack_chairs = dict string name string career_hack_chairs ; string type string furniture
set dish_washer = dict string name string dish_washer ; string type string furniture
set eating_seats = dict stri... | # -*- coding: utf-8 -*-
# In[1]:
# define rooms and items
# All Objects (furniture)
career_hack_chairs = {
"name": "career_hack_chairs",
"type": "furniture",
}
dish_washer = {
"name": "dish_washer",
"type": "furniture",
}
eating_seats = {
"name": "eating_seats",
"type": "furniture",
}
toi... | Python | zaydzuhri_stack_edu_python |
function page_not_found error
begin
set error_response = dict string error string Not found
return call make_response call jsonify error_response 404
end function | def page_not_found(error):
error_response = {"error": "Not found"}
return make_response(jsonify(error_response), 404) | Python | nomic_cornstack_python_v1 |
import collections
import uuid
import unittest
from ab import ab
class ABTestCase extends TestCase
begin
function test_calc_none_bucket self
begin
with call assertRaisesRegex ABTestError string saw <class 'NoneType'>
begin
call calc none buckets=2
end
end function
function test_calc_negative_bucket self
begin
with call... | import collections
import uuid
import unittest
from ab import ab
class ABTestCase(unittest.TestCase):
def test_calc_none_bucket(self):
with self.assertRaisesRegex(ab.ABTestError, "saw <class 'NoneType'>"):
ab.calc(None, buckets=2)
def test_calc_negative_bucket(self):
with self.a... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function _get_ip self
begin
return __ip
end function | def _get_ip(self):
return self.__ip | Python | nomic_cornstack_python_v1 |
function test_amin_general_function_06 self
begin
set result = call amin maxvaltest maxlen=5
assert equal result min maxvaltest at slice : 5 :
end function | def test_amin_general_function_06(self):
result = arrayfunc.amin(self.maxvaltest, maxlen=5 )
self.assertEqual(result, min(self.maxvaltest[:5])) | Python | nomic_cornstack_python_v1 |
function get_service api_name api_version scope key_file_location service_account_email
begin
set credentials = call from_p12_keyfile service_account_email key_file_location scopes=scope
set http = call authorize call Http
comment Build the service object.
set service = call build api_name api_version http=http
return ... | def get_service(api_name, api_version, scope, key_file_location, service_account_email):
credentials = ServiceAccountCredentials.from_p12_keyfile(service_account_email, key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = api.discovery.b... | Python | nomic_cornstack_python_v1 |
import hashlib
set data = input
set output = sha256 encode data
print hex digest output | import hashlib
data = input()
output = hashlib.sha256(data.encode())
print(output.hexdigest())
| Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function isPowerOfThree self n
begin
string :type n: int :rtype: bool
if n <= 0
begin
return false
end
while n > 1
begin
set d = n % 3
if d
begin
return false
end
set n = n / 3
end
return true
end function
end class | class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if(n <= 0):
return False
while( n> 1):
d = n % 3
if(d):
return False
n = n/3
return True
| Python | zaydzuhri_stack_edu_python |
comment Problem 66: Write a regular expression to validate a phone number.
import re
function isPhoneNum instring
begin
set pattern = match string \+?\d{1,3}\(?\d{1,3}\)?\s?\d{3}-?\d{2}-?\d{2} instring
comment re.match() returns None if no matches are found
if pattern is not none and call group 0 == instring
begin
retu... | # Problem 66: Write a regular expression to validate a phone number.
import re
def isPhoneNum(instring):
pattern = re.match(r'\+?\d{1,3}\(?\d{1,3}\)?\s?\d{3}-?\d{2}-?\d{2}', instring)
if pattern is not None and pattern.group(0) == instring: # re.match() returns None if no matches are found
return Tr... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
string SSL 证书验证 Requests 提供了证书验证的功能,当发送 HTTP 请求的时候,它会检查 SSL 证书, 我们可以使用 verify 这个参数来控制是否检查此证书,其实如果不加的话默认是 True, 会自动验证。
import requests
comment response = requests.get('https://www.12306.cn', verify=False)
comment print(response.status_code)
comment import loggin... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
""" SSL 证书验证
Requests 提供了证书验证的功能,当发送 HTTP 请求的时候,它会检查 SSL 证书,
我们可以使用 verify 这个参数来控制是否检查此证书,其实如果不加的话默认是 True,
会自动验证。
"""
import requests
# response = requests.get('https://www.12306.cn', verify=False)
# print(response.status_code)
# import logging
#
# logging.captureWarn... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment http://qiita.com/okappy/items/e12ce8fb39dfd4ed1a44
import matplotlib.pyplot as plt
from matplotlib import animation
import networkx as nx
import random
comment ネットワーク
set g = call Graph
function get_fig node_number
begin
call add_node node_number Position=tuple call randrange 0 100... | # -*- coding: utf-8 -*-
# http://qiita.com/okappy/items/e12ce8fb39dfd4ed1a44
import matplotlib.pyplot as plt
from matplotlib import animation
import networkx as nx
import random
# ネットワーク
g = nx.Graph()
def get_fig(node_number):
g.add_node(node_number, Position=(
random.randrange(0, 100), random.randrange... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment Copyright 2009-2017 BHG http://bw.org/
print string There are three additional controls:
print string -Continue [Short-cut a loop and start it again]
print string -Break [Break out of a loop prematurely]
print string -Else [Executes only if loop ends normally or an if condition is ... | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
print("There are three additional controls:")
print("\t-Continue\t[Short-cut a loop and start it again]")
print("\t-Break\t\t[Break out of a loop prematurely]")
print("\t-Else\t\t[Executes only if loop ends normally or an if condition is not met]")
... | Python | zaydzuhri_stack_edu_python |
comment Program Soal3
comment Menentukan KPK dari tiga buah bilangan
comment KAMUS
comment a,b,c: integer
function fpb a b
begin
comment Menentukan faktor persekutuan terbesar dari dua buah bilangan
comment KAMUS LOKAL
comment mini,a,b: integer
comment ALGORITMA
comment Mini menyimpan angka yang lebih kecil dari a
set ... | # Program Soal3
# Menentukan KPK dari tiga buah bilangan
# KAMUS
# a,b,c: integer
def fpb(a,b):
# Menentukan faktor persekutuan terbesar dari dua buah bilangan
# KAMUS LOKAL
# mini,a,b: integer
# ALGORITMA
mini=a # Mini menyimpan angka yang lebih kecil dari a
if (b<mini):
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Aug 22 10:27:31 2018 @author: eirikh
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import time
import random
import socket
function make_checksum msg
begin
string Make a NMEA 0183 checksum on a string. Skips leading ! or $ and stops at * It igno... | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 10:27:31 2018
@author: eirikh
"""
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import time
import random
import socket
def make_checksum( msg ):
"""
Make a NMEA 0183 checksum on a string. Skips leading ! or $ and stops
at *
It ... | Python | zaydzuhri_stack_edu_python |
comment compare two integers
set int1 = 1
set int2 = 2
if int1 > int2
begin
print string int1 is greater than int2
end
else
if int2 > int1
begin
print string int2 is greater than int1
end
else
begin
print string int1 and int2 are equal
end | # compare two integers
int1=1
int2=2
if int1 > int2:
print("int1 is greater than int2")
elif int2 > int1:
print("int2 is greater than int1")
else:
print("int1 and int2 are equal")
| Python | flytech_python_25k |
function setName self name createNamespace=string False
begin
pass
end function | def setName(self, name, createNamespace='False'):
pass | Python | nomic_cornstack_python_v1 |
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
string These are the only functions in the app that interface with the Citibike API JSON Information about the stations is obtained from these links "feeds":[ { "name":"station_information", "u... | from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
""" These are the only functions in the app that interface with the Citibike API
JSON Information about the stations is obtained from these links
"feeds":[
{
"name":"station_in... | Python | zaydzuhri_stack_edu_python |
function save_load_result func
begin
string Saves and/or loads func output (must be picklable).
decorator wraps func
function wrapper *args **kwargs
begin
string Default behavior is no saving and loading. Specify save_name to save and load. Parameters ---------- save_name: str, optional File name including directory an... | def save_load_result(func):
"""Saves and/or loads func output (must be picklable)."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Default behavior is no saving and loading. Specify save_name to save
and load.
Parameters
----------
save_name: str,... | Python | jtatman_500k |
function repos_raw self
begin
return call RepositoryGroup chain source_repos_raw installed_repos_raw
end function | def repos_raw(self):
return RepositoryGroup(chain(self.source_repos_raw, self.installed_repos_raw)) | Python | nomic_cornstack_python_v1 |
function parse_args
begin
set parser = call ArgumentParser description=string Create timezone info JSON file from tzdata files
call add_argument string -v string --vzic dest=string vzic_path required=true help=string Path to the `vzic` executable. This must be downloaded from https://code.google.com/p/tzurl/ and compil... | def parse_args():
parser = argparse.ArgumentParser(
description="Create timezone info JSON file from tzdata files"
)
parser.add_argument(
"-v",
"--vzic",
dest="vzic_path",
required=True,
help="""Path to the `vzic` executable. This must be
... | Python | nomic_cornstack_python_v1 |
comment Import the class
from PassRetrievalTool import PassRetrievalTool
class PassRetrievalTool_test
begin
function __init__ self
begin
comment Call the static method get_wifi_password_dictionary() and save it
set wifi_password_dictionary = call get_all_wifi_password_dictionary
comment Print them or do whatever you wa... | from PassRetrievalTool import PassRetrievalTool # Import the class
class PassRetrievalTool_test:
def __init__(self):
wifi_password_dictionary = PassRetrievalTool.get_all_wifi_password_dictionary() # Call the static method get_wifi_password_dictionary() and save it
PassRetrievalTool.print_password... | Python | zaydzuhri_stack_edu_python |
function plot self fmt=string - linewidth=2
begin
call plot_fuzzyvariable universe=universe memberships=list comprehension sets at k for k in keys sets labels=list keys sets title=name fmt=fmt linewidth=linewidth view_xaxis=true view_yaxis=true
end function | def plot(self, fmt="-", linewidth=2):
plot_fuzzyvariable(
universe=self.universe,
memberships=[self.sets[k] for k in self.sets.keys()],
labels=list(self.sets.keys()),
title=self.name,
fmt=fmt,
linewidth=linewidth,
view_xaxis=Tru... | Python | nomic_cornstack_python_v1 |
function cat_splits_lin_e cat cols=none mask=none p=none
begin
if p is not none
begin
set jobs = list
set p = pool processes=get cfg string proc 32 maxtasksperchild=get cfg string task none
end
set mask = call check_mask coadd mask p=p
if cols is none
begin
set cols = call get_cat_colnames cat
end
call heading string ... | def cat_splits_lin_e(cat,cols=None,mask=None,p=None):
if p is not None:
jobs=[]
p=multiprocessing.Pool(processes=config.cfg.get('proc',32),maxtasksperchild=config.cfg.get('task',None))
mask=catalog.CatalogMethods.check_mask(cat.coadd,mask,p=p)
if cols is None:
cols=catalog.CatalogMethods... | Python | nomic_cornstack_python_v1 |
string Capture Regions on Board ======================== Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. Input Format: First and only argument is a N x M character matrix A Output Format: make changes to the t... | """
Capture Regions on Board
========================
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Input Format:
First and only argument is a N x M character matrix A
Output Format:
make change... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
import glob
import subprocess
from collections import Counter
function run_child cmd exe=string /bin/bash
begin
string use subrocess.check_output to run an external program with arguments
try
begin
set output = check output cmd universal_newlines=true shell=true executable=exe st... | #!/usr/bin/env python
import sys
import glob
import subprocess
from collections import Counter
def run_child(cmd, exe='/bin/bash'):
'''use subrocess.check_output to run an external program with arguments'''
try:
output = subprocess.check_output(cmd, universal_newlines=True,
shell=True, executa... | Python | zaydzuhri_stack_edu_python |
function getEditPoints self **kwargs
begin
pass
end function | def getEditPoints(self, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
function test_concept_drift_for_single_task task_branch shear_degree_max shear_degree_increments split num_samples_to_check=100
begin
print string *** Testing how task relativity changes with concept drift: task_name
comment initialise variables
set shear_degree_increment_num = round shear_degree_max / shear_degree_inc... | def test_concept_drift_for_single_task(task_branch, shear_degree_max,shear_degree_increments, split, num_samples_to_check=100):
print("*** Testing how task relativity changes with concept drift: ", task_branch.task_name)
# initialise variables
shear_degree_increment_num = round(shear_degree_m... | Python | nomic_cornstack_python_v1 |
function singleton cls
begin
set instance = none
function wrapper *args **kwargs
begin
nonlocal instance
if not instance
begin
set instance = call cls *args keyword kwargs
end
return instance
end function
return wrapper
end function
class JsonParser
begin
function parse self obj
begin
return string json: { string obj }... | def singleton(cls):
instance = None
def wrapper(*args, **kwargs):
nonlocal instance
if not instance:
instance = cls(*args, **kwargs)
return instance
return wrapper
class JsonParser:
def parse(self, obj):
return f'json: {str(obj)}'
@singleton
class JsonPa... | Python | zaydzuhri_stack_edu_python |
import json
from predict.predict import main
if __name__ == string __main__
begin
with open string ../data/data.json string r as fr
begin
set result = load json fr encoding=string utf-8 at string data
end
set count = 0
for x in result
begin
set x = x at string paragraphs
set count = count + length x at 0 at string qas
... | import json
from predict.predict import main
if __name__ == '__main__':
with open("../data/data.json", 'r') as fr:
result = json.load(fr, encoding="utf-8")['data']
count = 0
for x in result:
x = x["paragraphs"]
count += len(x[0]['qas'])
print(count)
# for r in r... | Python | zaydzuhri_stack_edu_python |
function cv_multiclass_fold Y num_fold
begin
set tuple K N = shape
set indices = dictionary
set Nk = dictionary
for k in range K
begin
comment select indices belonging to class k
set indices at k = list call nonzero at 0
shuffle rand indices at k
set Nk at k = length indices at k / num_fold
end
set Sidx = list
for k i... | def cv_multiclass_fold(Y,num_fold):
(K,N) = Y.shape
indices = dict(); Nk = dict()
for k in range(K):
# select indices belonging to class k
indices[k] = list((Y[k,:]==1).nonzero()[0])
rand.shuffle(indices[k])
Nk[k] = len(indices[k])/num_fold
Sidx = []
for k in range(K):
for i in range(num_fold-1):
... | Python | nomic_cornstack_python_v1 |
function width self
begin
return 0
end function | def width (self):
return 0 | Python | nomic_cornstack_python_v1 |
string Leia um vetor com 20 números inteiros. Escreva os elementos do vetor eliminando elementos repetidos.
set vetor = list
while length vetor < 20
begin
set num = integer input string Digite um número inteiro:
append vetor num
end
set vetor_filtro = set vetor
set vetor_final = list vetor_filtro
print vetor
print vet... | '''
Leia um vetor com 20 números inteiros. Escreva os elementos do vetor eliminando elementos repetidos.
'''
vetor = []
while len(vetor) < 20:
num = int(input('Digite um número inteiro: '))
vetor.append(num)
vetor_filtro = set(vetor)
vetor_final = list(vetor_filtro)
print(vetor)
print(vetor_final) | Python | zaydzuhri_stack_edu_python |
function __iter__ self
begin
for child in children
begin
yield child
end
end function | def __iter__(self):
for child in self.children:
yield child | Python | nomic_cornstack_python_v1 |
function _interpret_as_minutes sval mdict
begin
string Times like "1:22" are ambiguous; do they represent minutes and seconds or hours and minutes? By default, timeparse assumes the latter. Call this function after parsing out a dictionary to change that assumption. >>> import pprint >>> pprint.pprint(_interpret_as_min... | def _interpret_as_minutes(sval, mdict):
"""
Times like "1:22" are ambiguous; do they represent minutes and seconds
or hours and minutes? By default, timeparse assumes the latter. Call
this function after parsing out a dictionary to change that assumption.
>>> import pprint
>>> pprint.ppri... | Python | jtatman_500k |
function make_new_column self title
begin
set column_titles = call get_column_titles
if title not in column_titles
begin
try
begin
set max_column = max_column
set value = title
end
except any
begin
print format string Something went wrong with building column {} title
end
end
else
begin
print format string Column title... | def make_new_column(self, title):
column_titles = self.get_column_titles()
if title not in column_titles:
try:
max_column = self.sheet.max_column
self.sheet.cell(row=1, column=max_column+1).value = title
except:
print("Someth... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
comment import random
call setmode BCM
class Sensor extends object
begin
function __init__ self gpio_trigger gpio_echo
begin
comment GPIO Pins zuweisen
set __GPIO_TRIGGER = gpio_trigger
set __GPIO_ECHO = gpio_echo
comment Richtung der GPIO-Pins festlegen... | # -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
#import random
GPIO.setmode(GPIO.BCM)
class Sensor(object):
def __init__(self, gpio_trigger, gpio_echo):
#GPIO Pins zuweisen
self.__GPIO_TRIGGER = gpio_trigger
self.__GPIO_ECHO = gpio_echo
#Richtung der GPIO-Pins festleg... | Python | zaydzuhri_stack_edu_python |
function link
begin
function bin_file c
begin
return BUILD_PATH + c + string .bin
end function
function method contract strings addresses
begin
string Replaces library stubs with addresses @param strings - List of strings to replace in the bytecode @param addresses - List of addresses to insert
set binary = read open c... | def link():
def bin_file(c):
return BUILD_PATH + c + ".bin"
def method(contract, strings, addresses):
"""
Replaces library stubs with addresses
@param strings - List of strings to replace in the bytecode
@param addresses - List of addresses to insert
"""
... | Python | nomic_cornstack_python_v1 |
function delete_many self uris
begin
set cache_keys = generator expression call _build_cache_key uri for uri in uris
call _delete_many cache_keys
end function | def delete_many(self, uris):
cache_keys = (self._build_cache_key(uri) for uri in uris)
self._delete_many(cache_keys) | 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.