code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function solution2 s
begin
set stack = list
for ele in s
begin
if length stack == 0
begin
append stack ele
end
else
if stack at - 1 == ele
begin
pop stack
end
else
begin
append stack ele
end
end
return if expression length stack == 0 then 1 else 0
end function
print call solution2 string baabaa
from collections import ... | def solution2(s):
stack = list()
for ele in s:
if len(stack) == 0:
stack.append(ele)
elif stack[-1] == ele:
stack.pop()
else:
stack.append(ele)
return 1 if len(stack) == 0 else 0
print(solution2("baabaa"))
from collections import deque
def solu... | Python | zaydzuhri_stack_edu_python |
function render node strict=false
begin
string Recipe to render a given FST node. The FST is composed of branch nodes which are either lists or dicts and of leaf nodes which are strings. Branch nodes can have other list, dict or leaf nodes as childs. To render a string, simply output it. To render a list, render each o... | def render(node, strict=False):
"""Recipe to render a given FST node.
The FST is composed of branch nodes which are either lists or dicts
and of leaf nodes which are strings. Branch nodes can have other
list, dict or leaf nodes as childs.
To render a string, simply output it. To render a list, ren... | Python | jtatman_500k |
import numpy as np
import skimage
import skimage.measure
import skimage.color
import skimage.restoration
import skimage.filters
import skimage.morphology
import skimage.segmentation
comment takes a color image
comment returns a list of bounding boxes and black_and_white image
function findLetters image
begin
set bboxes... | import numpy as np
import skimage
import skimage.measure
import skimage.color
import skimage.restoration
import skimage.filters
import skimage.morphology
import skimage.segmentation
# takes a color image
# returns a list of bounding boxes and black_and_white image
def findLetters(image):
bboxes = []
bw = None... | Python | zaydzuhri_stack_edu_python |
function by_id cls id
begin
with call DBSession as db
begin
return first filter id == id
end
end function | def by_id(cls, id: str) -> Any:
with DBSession() as db:
return db.query(cls).filter(cls.id == id).first() | Python | nomic_cornstack_python_v1 |
string Module contains file operation to pretty print files in json
import logging
import json
from json.decoder import JSONDecodeError
from logfile.operations.operation_base import OperationBase
comment pylint: disable=W1203
class PrettyJson extends OperationBase
begin
string This class is responseable for pretty prin... | """
Module contains file operation to pretty print files in json
"""
import logging
import json
from json.decoder import JSONDecodeError
from logfile.operations.operation_base import OperationBase
# pylint: disable=W1203
class PrettyJson(OperationBase):
"""
This class is responseable for pretty printing json... | Python | zaydzuhri_stack_edu_python |
function timeBase self num=none denom=none
begin
if num != none and denom != none
begin
set value = list integer num integer denom
end
else
begin
set value = none
end
set ret = call __getset_prop INT string timebase value
if ret == none
begin
return
end
return ret
end function | def timeBase(self, num=None, denom=None):
if num != None and denom != None: value = [int(num), int(denom)]
else: value = None
ret = self.__getset_prop(Type.INT, "timebase", value)
if ret == None: return
return ret | Python | nomic_cornstack_python_v1 |
import random
function answers
begin
comment number of answers for each response
return list 1 2 3
end function
function answers_responses responses answers
begin
return random choices answers list 2 3 1 k=responses
end function
function choices
begin
return list 0 1 2 3 4 5
end function
function response responses ans... | import random
def answers():
return [1, 2, 3] # number of answers for each response
def answers_responses(responses, answers):
return random.choices(answers, [2, 3, 1], k=responses)
def choices():
return [0, 1, 2, 3, 4, 5]
def response(responses, answers, choices):
response = []
for i in r... | Python | zaydzuhri_stack_edu_python |
function get_selection self
begin
set items = call selectedItems
set article_ids = set
for item in items
begin
add article_ids call text 0
end
return article_ids
end function | def get_selection(self):
items = self.tree.selectedItems()
article_ids = set()
for item in items:
article_ids.add(item.text(0))
return article_ids | Python | nomic_cornstack_python_v1 |
function detect_edges image_array
begin
comment Transform image into grayscale
set img = call rgb2gray image_array
comment Remove some noise from the image
set img = call denoise_tv_chambolle img weight=0.55
comment Apply canny
set edges = call canny img sigma=3.2
comment Clear the borders
call clear_border edges 15
co... | def detect_edges(image_array):
#Transform image into grayscale
img = rgb2gray(image_array)
#Remove some noise from the image
img = denoise_tv_chambolle(img, weight=0.55)
#Apply canny
edges = filter.canny(img, sigma=3.2)
#Clear the borders
clear_border(edges, 15)
#Dilate edges to make... | Python | nomic_cornstack_python_v1 |
function __init__ __self__ hand_size=none queue_length_limit=none queues=none
begin
if hand_size is not none
begin
set __self__ string hand_size hand_size
end
if queue_length_limit is not none
begin
set __self__ string queue_length_limit queue_length_limit
end
if queues is not none
begin
set __self__ string queues queu... | def __init__(__self__, *,
hand_size: Optional[int] = None,
queue_length_limit: Optional[int] = None,
queues: Optional[int] = None):
if hand_size is not None:
pulumi.set(__self__, "hand_size", hand_size)
if queue_length_limit is not None:
... | Python | nomic_cornstack_python_v1 |
function right_triangle a b c
begin
set tri = list a b c
sort tri
if tri at 0 ^ 2 + tri at 1 ^ 2 == tri at 2 ^ 2
begin
return true
end
return false
end function | def right_triangle(a, b, c):
tri = [a, b, c]
tri.sort()
if tri[0] ** 2 + tri[1] ** 2 == tri[2] ** 2:
return True
return False
| Python | zaydzuhri_stack_edu_python |
from unittest import TestCase
import TSPopt
import numpy
string TSP testing
class TSP0 extends TestCase
begin
function setUp self
begin
set segList1 = list tuple 0.0 1.0 tuple 0.0 2.0 tuple 0.0 3.0 tuple 0.0 4.0 tuple 0.0 5.0
end function
end class
class TSP0Test0 extends TSP0
begin
function runTest self
begin
set tupl... | from unittest import TestCase
import TSPopt
import numpy
''' TSP testing '''
class TSP0(TestCase):
def setUp(self):
self.segList1 = [(0., 1.), (0., 2.), (0., 3.), (0., 4.), (0., 5.)]
class TSP0Test0(TSP0):
def runTest(self):
delta, seglist2 = TSPopt.threeOptLoop(self.segList1)
self.a... | Python | zaydzuhri_stack_edu_python |
function get_suffix_lists cache urls cache_fetch_timeout fallback_to_snapshot
begin
return call run_and_cache func=_get_suffix_lists namespace=string publicsuffix.org-tlds kwargs=dict string cache cache ; string urls urls ; string cache_fetch_timeout cache_fetch_timeout ; string fallback_to_snapshot fallback_to_snapsho... | def get_suffix_lists(
cache: DiskCache,
urls: Sequence[str],
cache_fetch_timeout: float | int | None,
fallback_to_snapshot: bool,
) -> tuple[list[str], list[str]]:
return cache.run_and_cache(
func=_get_suffix_lists,
namespace="publicsuffix.org-tlds",
kwargs={
"cac... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import unirest
import json
from sunshine4py.sunshineexceptions import checkCode
class SunshineStats
begin
class SunshineStatsPlayer
begin
function __init__ self name data
begin
for tuple key value in items data
begin
set attribute self key value
end
end function
end class
function setStats ... | #!/usr/bin/env python
import unirest
import json
from sunshine4py.sunshineexceptions import checkCode
class SunshineStats:
class SunshineStatsPlayer:
def __init__(self, name, data):
for key, value in data.items():
setattr(self, key, value)
def setStats(self, stats_data):
... | Python | zaydzuhri_stack_edu_python |
function calculate_sum nums index
begin
if index == length nums - 1
begin
return nums at index
end
return nums at index + call calculate_sum nums index + 1
end function
function find_max_product nums
begin
set total_sum = call calculate_sum nums 0
set new_list = list comprehension nums at i * total_sum for i in range l... | def calculate_sum(nums, index):
if index == len(nums) - 1:
return nums[index]
return nums[index] + calculate_sum(nums, index + 1)
def find_max_product(nums):
total_sum = calculate_sum(nums, 0)
new_list = [nums[i] * total_sum for i in range(len(nums))]
return max(new_list)
nums = [1, 2, 3, ... | Python | jtatman_500k |
function clear_record dns_dict keys
begin
for k in keys
begin
if not is instance dns_dict at k list
begin
call clear_record dns_dict at k list keys dns_dict at k
end
else
begin
set r = dns_dict at k at 0
if integer time - r at string time >= r at string TTL
begin
del dns_dict at k
end
end
end
end function | def clear_record(dns_dict, keys):
for k in keys:
if not isinstance(dns_dict[k], list):
clear_record(dns_dict[k], list(dns_dict[k].keys()))
else:
r = dns_dict[k][0]
if int(time.time()) - r['time'] >= r['TTL']:
del dns_dict[k] | Python | nomic_cornstack_python_v1 |
function add_classifier self
begin
if rnn_gap
begin
set classifier = to call Classify 3 * hidden_dim hidden_dim y_len device
end
else
comment only for the average case
if backbone in tuple string resnet18 string vgg string squeeze string resnet34
begin
set classifier = to call Classify 3 * 512 hidden_dim y_len device
e... | def add_classifier(self):
if self.rnn_gap:
self.classifier = Classify(3 * self.hidden_dim, self.hidden_dim, self.y_len).to(self.device)
else:
# only for the average case
if self.backbone in ("resnet18", "vgg", "squeeze", "resnet34"):
self.classifier = ... | Python | nomic_cornstack_python_v1 |
function is_normal self channel=none
begin
return call get_state channel == 0
end function | def is_normal(self, channel=None):
return self.get_state(channel) == 0 | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Special logic for 8D -> 4D to find the best bases in human understandable way
import sys
import itertools
import math
import numpy as np
from scipy import random , array , dot , zeros
from scipy.linalg import orth , det
from scipy.optimize import minimize , basinhopping
set high_dim... | #!/usr/bin/env python
# Special logic for 8D -> 4D to find the best bases in human understandable way
import sys
import itertools
import math
import numpy as np
from scipy import random, array, dot, zeros
from scipy.linalg import orth, det
from scipy.optimize import minimize, basinhopping
high_dimension = 8
low_dimen... | Python | zaydzuhri_stack_edu_python |
comment m = map(int, raw_input().split())
comment a, b, c = map(int, raw_input().split())
comment s = raw_input()
comment l = raw_input().split()
set n = integer call raw_input
set m = list
for i in call xrange n
begin
append m call raw_input
end
sort m key=lambda x -> length x
set ans = string YES
for i in call xrang... | # m = map(int, raw_input().split())
# a, b, c = map(int, raw_input().split())
# s = raw_input()
# l = raw_input().split()
n = int(raw_input())
m = []
for i in xrange(n):
m.append(raw_input())
m.sort(key=lambda x: len(x))
ans = 'YES'
for i in xrange(n-1):
if m[i] not in m[i+1]:
ans = 'NO'
break | Python | zaydzuhri_stack_edu_python |
function 평to제곱미터 평
begin
return 평 * 3.3058
end function
function 제곱미터to평 제곱미터
begin
return 제곱미터 / 3.3058
end function | def 평to제곱미터(평):
return 평*3.3058
def 제곱미터to평(제곱미터):
return 제곱미터/3.3058
| Python | zaydzuhri_stack_edu_python |
function pascal_triangle n
begin
comment Two empty lists to store the previous and current row
set prev_row = list
set curr_row = list
comment Looping through the rows
for i in range n
begin
comment Reseting the curr_row for each row
set curr_row = list
comment Looping through columns
for j in range i + 1
begin
comm... | def pascal_triangle(n):
# Two empty lists to store the previous and current row
prev_row = []
curr_row = []
# Looping through the rows
for i in range(n):
# Reseting the curr_row for each row
curr_row = []
# Looping through columns
... | Python | jtatman_500k |
comment !/usr/bin/python
import re , math
from collections import Counter
import sys
import pickle
import nltk.stem
set stemmer_func = stem
function normalize_word word
begin
return call stemmer_func lower word
end function
set WORD = compile string \w+
set input_file = argv at 1
function text_to_vector text
begin
set ... | #!/usr/bin/python
import re, math
from collections import Counter
import sys
import pickle
import nltk.stem
stemmer_func = nltk.stem.snowball.EnglishStemmer().stem
def normalize_word(word):
return stemmer_func(word.lower())
WORD = re.compile(r'\w+')
input_file = sys.argv[1]
def text_to_vector(text):
words ... | Python | zaydzuhri_stack_edu_python |
function map_new_fields self obj data
begin
set position = data at string POSITION
set street_address = data at string STREET_ADDRESS at string fi
set street_address_fi = data at string STREET_ADDRESS at string fi
set street_address_sv = data at string STREET_ADDRESS at string sv
set email = data at string EMAIL
set te... | def map_new_fields(self, obj: Any, data: dict) -> None:
obj.position = data['POSITION']
obj.street_address = obj.street_address_fi = data['STREET_ADDRESS']['fi']
obj.street_address_sv = data['STREET_ADDRESS']['sv']
obj.email = data['EMAIL']
obj.telephone = data['TELEPHONE']
... | Python | nomic_cornstack_python_v1 |
function test_sparsity_detection ODE alg
begin
set stepper = call alg 0 dt_init q_init A
assert starts with __name__ string Sparse == call issparse I
end function | def test_sparsity_detection(ODE, alg):
stepper = alg(0, ODE.dt_init, ODE.q_init, ODE.A)
assert ODE.__name__.startswith('Sparse') == sp.issparse(stepper.I) | Python | nomic_cornstack_python_v1 |
function logistic weights data targets hyperparameters
begin
set y = call logistic_predict weights data
if hyperparameters at string weight_regularization is true
begin
set tuple f df = call logistic_pen weights data targets hyperparameters
end
else
begin
comment TODO: compute f and df without regularization
set tuple ... | def logistic(weights, data, targets, hyperparameters):
y = logistic_predict(weights, data)
if hyperparameters['weight_regularization'] is True:
f, df = logistic_pen(weights, data, targets, hyperparameters)
else:
# TODO: compute f and df without regularization
f,df = compute_base_lo... | Python | nomic_cornstack_python_v1 |
function test_solicitation_max_retry self
begin
set _solicitation_max_retry = 6
set waittime = _solicitation_timeout * 10
call start_process
set interest = call Interest call Name string /foo/bar
put list none interest
set deadline = call utcnow + time delta seconds=waittime
set tolower = list
while call utcnow < dead... | def test_solicitation_max_retry(self):
self.autoconflayer._solicitation_max_retry = 6
waittime = self.autoconflayer._solicitation_timeout * 10
self.autoconflayer.start_process()
interest = Interest(Name('/foo/bar'))
self.queue_from_higher.put([None, interest])
deadline =... | Python | nomic_cornstack_python_v1 |
function instance_url self
begin
return get pulumi self string instance_url
end function | def instance_url(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "instance_url") | Python | nomic_cornstack_python_v1 |
function test_allowed_values self
begin
set test_cell = tuple 2 2
set next_cell = tuple 3 3
set test_value = 2
set *test_cell test_value
assert equal set literal test_value call get_allowed_values *test_cell
assert true test_value in call get_allowed_values *test_cell
assert true test_value in call get_allowed_values *... | def test_allowed_values(self):
test_cell = (2, 2)
next_cell = (3, 3)
test_value = 2
self.p.set(*test_cell, test_value)
self.assertEqual({test_value}, self.p.get_allowed_values(*test_cell))
self.assertTrue(test_value in self.p.get_allowed_values(*test_cell))
self.... | Python | nomic_cornstack_python_v1 |
import pyfingerprint.find_port
import sys
import glob
import time
from pyfingerprint.pyfingerprint import PyFingerprint as p
from interruptingcow import timeout
class fingerprint
begin
function __init__ self
begin
try
begin
set f = call p string /dev/tty.SLAB_USBtoUART 57600 4294967295 0
if call verifyPassword == false... | import pyfingerprint.find_port
import sys
import glob
import time
from pyfingerprint.pyfingerprint import PyFingerprint as p
from interruptingcow import timeout
class fingerprint():
########################################################################################################################
def __ini... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 感谢 网易有道翻译 ;)
comment 从下面的地址申请 APIkey && keyfrom
comment http://fanyi.youdao.com/openapi?path=data-mode
comment 你的 APIkey
set APIkey = string 242349121
comment 你的 keyfrom
set keyfrom = string Tiandechi
set __author__ = string Tiande ( https://github.com... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 感谢 网易有道翻译 ;)
# 从下面的地址申请 APIkey && keyfrom
# http://fanyi.youdao.com/openapi?path=data-mode
APIkey = '242349121' # 你的 APIkey
keyfrom = 'Tiandechi' # 你的 keyfrom
__author__ = 'Tiande ( https://github.com/Tiande ) '
import urllib.request
import urllib.parse
import json
im... | Python | zaydzuhri_stack_edu_python |
function ReadSCRMpeg2 self buffer
begin
if length buffer < 6
begin
return none
end
set highbit = ordinal buffer at 0 ? 32 ? 5
set low4Bytes = call long ordinal buffer at 0 ? 24 ? 3 ? 30
set low4Bytes = low4Bytes ? ordinal buffer at 0 ? 3 ? 28
set low4Bytes = low4Bytes ? ordinal buffer at 1 ? 20
set low4Bytes = low4Byte... | def ReadSCRMpeg2(self, buffer):
if len(buffer) < 6:
return None
highbit = (ord(buffer[0])&0x20)>>5
low4Bytes= ((long(ord(buffer[0])) & 0x18) >> 3) << 30
low4Bytes |= (ord(buffer[0]) & 0x03) << 28
low4Bytes |= ord(buffer[1]) << 20
low4Bytes |= (ord(buffer[2])... | Python | nomic_cornstack_python_v1 |
comment def _FindAnagram(source):
comment source = source.rstrip("\n\r")
comment if len(source) <= 1:
comment return "Нет анаграммы"
comment number = ""
comment number_alp = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
comment for i in range(0, len(source)):
comment if '0' <= str(source[i]) <= '9':
comment number += source[i]
commen... | # def _FindAnagram(source):
# source = source.rstrip("\n\r")
# if len(source) <= 1:
# return "Нет анаграммы"
# number = ""
# number_alp = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# for i in range(0, len(source)):
# if '0' <= str(source[i]) <= '9':
# number += source[i]
# ... | Python | zaydzuhri_stack_edu_python |
comment vim: fdm=indent
string author: Fabio Zanini date: 21/05/19 content: Check reads mapped against VEEV with N cigars (intron)
import os
import sys
import numpy as np
import pandas as pd
import pysam
import matplotlib.pyplot as plt
if __name__ == string __main__
begin
set fdn = string ../data/dataset/
set fn_bam = ... | # vim: fdm=indent
'''
author: Fabio Zanini
date: 21/05/19
content: Check reads mapped against VEEV with N cigars (intron)
'''
import os
import sys
import numpy as np
import pandas as pd
import pysam
import matplotlib.pyplot as plt
if __name__ == '__main__':
fdn = '../data/dataset/'
fn_bam = fdn... | Python | zaydzuhri_stack_edu_python |
function sol n
begin
if n == 1
begin
return string FastestFinger
end
if n % 2 == 1 or n == 2
begin
return string Ashishgup
end
for i in range 3 integer n ^ 0.5 + 1
begin
if n % i == 0
begin
if i % 2 == 1 or n // i % 2 == 1
begin
return string Ashishgup
end
end
end
return string FastestFinger
end function
set t = intege... | def sol(n):
if n == 1:
return "FastestFinger"
if n % 2 == 1 or n == 2:
return "Ashishgup"
for i in range(3, int(n**0.5) + 1):
if n % i == 0:
if i % 2 == 1 or (n // i) % 2 == 1:
return "Ashishgup"
return "FastestFinger"
t = int(input())
for _ in range(t):
print(sol(int(input()))) | Python | zaydzuhri_stack_edu_python |
function _response self svc_name
begin
set endpoint = join path call geturl svc_name
set response = get requests endpoint
if ok
begin
try
begin
return json response at string service
end
except KeyError
begin
raise call HTTPError string Malformed JSON
end
end
raise call HTTPError string Bad Response [%d] % status_code
... | def _response(self, svc_name):
endpoint = os.path.join(self.url.geturl(), svc_name)
response = requests.get(endpoint)
if response.ok:
try:
return response.json()["service"]
except KeyError:
raise requests.HTTPError("Malformed JSON")
... | Python | nomic_cornstack_python_v1 |
import math
import string
comment Quiz 2
function isND n
begin
if n < 10 and n % 2 == 1
begin
return true
end
set n = string n
for i in range length string n 0 - 1
begin
if n at i % 2 == 0
begin
return false
end
else
if n at i <= n at i - 1
begin
return false
end
end
return true
end function
function nthND n
begin
set ... | import math
import string
## Quiz 2
def isND(n):
if n<10 and n%2==1:
return True
n= str(n)
for i in range(len(str(n)),0,-1):
if n[i]%2==0: return False
else:
if n[i]<= n[i-1]:
return False
return True
def nthND(n):
found=-1
guess=0
while... | Python | zaydzuhri_stack_edu_python |
function read_file filename
begin
with open filename as f
begin
set contents = read lines f
set contents = list comprehension strip x for x in contents
end
set gate_list = list comprehension split item string for item in contents
return gate_list
end function | def read_file(filename):
with open(filename) as f:
contents = f.readlines()
contents = [x.strip() for x in contents]
gate_list = [item.split(" ") for item in contents]
return gate_list | Python | nomic_cornstack_python_v1 |
function make_transformer_timing_signal inp min_timescale=1.0 max_timescale=10000.0 offset=0 inp_reverse=none
begin
with call name_scope string timing_signal
begin
set ninp = call shape inp at 1
set hid_size = call shape inp at 2
set position = call to_float range ninp at tuple none slice : :
if offset == string ran... | def make_transformer_timing_signal(inp, min_timescale=1.0, max_timescale=1e4, offset=0, inp_reverse=None):
with tf.name_scope("timing_signal"):
ninp = tf.shape(inp)[1]
hid_size = tf.shape(inp)[2]
position = tf.to_float(tf.range(ninp))[None, :]
if offset == 'random':
BIG... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Feb 16 14:33:14 2021 @author: yhkim
import numpy as np
import pandas as pd
from collections import Counter
import FunLib_stock as FL
import multiprocessing as mp
comment Load data (X & y) 2(permno, date) + 94(firm-level) + 74(sic_dummy)+ 752(interact) +1(y) = 923 colu... | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 14:33:14 2021
@author: yhkim
"""
import numpy as np
import pandas as pd
from collections import Counter
import FunLib_stock as FL
import multiprocessing as mp
# Load data (X & y) 2(permno, date) + 94(firm-level) + 74(sic_dummy)+ 752(interact) +1(y) = ... | Python | zaydzuhri_stack_edu_python |
import time
from subprocess import call
import os
set CLUTO_SCLUSTER_EXECUTABLE = string ./scluster
set CLUTO_VCLUSTER_EXECUTABLE = string ./vcluster
function cluto_cluster K matrixFileName
begin
set fileName = matrixFileName + string .clustering. + string K
if exists path fileName
begin
return fileName
end
print strin... | import time
from subprocess import call
import os
CLUTO_SCLUSTER_EXECUTABLE = "./scluster"
CLUTO_VCLUSTER_EXECUTABLE = "./vcluster"
def cluto_cluster(K, matrixFileName):
fileName = matrixFileName + ".clustering." + str(K)
if os.path.exists(fileName):
return fileName
print("STARTING CLUTO CL... | Python | zaydzuhri_stack_edu_python |
function squirrel_sources
begin
pass
end function | def squirrel_sources() -> List[Tuple[CatalogKey, Source]]:
pass | Python | nomic_cornstack_python_v1 |
function rename_client_tab self client given_name
begin
string Rename client's tab
set index = call get_client_index_from_id call id client
if given_name is not none
begin
set given_name = given_name
end
call setTabText index call get_name
end function | def rename_client_tab(self, client, given_name):
"""Rename client's tab"""
index = self.get_client_index_from_id(id(client))
if given_name is not None:
client.given_name = given_name
self.tabwidget.setTabText(index, client.get_name()) | Python | jtatman_500k |
function factorial n
begin
comment Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1
begin
return 1
end
else
begin
comment Recursive case: factorial of n is n multiplied by factorial of (n-1)
return n * call factorial n - 1
end
end function
print call factorial 5 | def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: factorial of n is n multiplied by factorial of (n-1)
else:
return n * factorial(n - 1)
print(factorial(5))
| Python | jtatman_500k |
import numpy as np
import gym
from gym import wrappers
from td3pg import agent
from utils import plot_learning_curve
comment Implementation of Addressing Function Approximation Error in Actor-Critic Methods
comment :https://arxiv.org/abs/1802.09477
if __name__ == string __main__
begin
comment Uncomment the env_name for... | import numpy as np
import gym
from gym import wrappers
from td3pg import agent
from utils import plot_learning_curve
# Implementation of Addressing Function Approximation Error in Actor-Critic Methods
# :https://arxiv.org/abs/1802.09477
if __name__ =="__main__":
#Uncomment the env_name for experimen... | Python | zaydzuhri_stack_edu_python |
for i in p
begin
if i <= a
begin
set A = A + 1
end
else
if i <= b
begin
set B = B + 1
end
else
begin
set C = C + 1
end
end
print min A B C | for i in p:
if i<=a:
A+=1
elif i<=b:
B+=1
else:
C+=1
print(min(A,B,C)) | Python | zaydzuhri_stack_edu_python |
import os
import numpy as np
import tensorflow as tf
function count_model_parameters
begin
set total_parameters = 0
for variable in call trainable_variables
begin
comment shape is an array of tf.Dimension
set shape = call get_shape
comment print(shape)
comment print(len(shape))
set variable_parameters = 1
for dim in sh... | import os
import numpy as np
import tensorflow as tf
def count_model_parameters():
total_parameters = 0
for variable in tf.trainable_variables():
# shape is an array of tf.Dimension
shape = variable.get_shape()
# print(shape)
# print(len(shape))
variable_parameters = 1
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 不同的二叉搜索树.py
string 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
string 思路:典型的动态规划问题。
set __author__ = string Aiyane
class Solution
begin
function start self l
begin
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 不同的二叉搜索树.py
"""
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 ... | Python | zaydzuhri_stack_edu_python |
function hellinger_distance_pmf p q
begin
return square root 1 - call bhattacharyya_coefficient_pmf p q
end function | def hellinger_distance_pmf(p, q):
return np.sqrt(1 - bhattacharyya_coefficient_pmf(p, q)) | Python | nomic_cornstack_python_v1 |
function test_context_manager self
begin
with call Timer as my_timer
begin
assert equal string my_timer string 0.00s
end
end function | def test_context_manager(self):
with etl.util.timer.Timer() as my_timer:
self.assertEqual(str(my_timer), "0.00s") | Python | nomic_cornstack_python_v1 |
function custom_time_zone_info_data self custom_time_zone_info_data
begin
set _custom_time_zone_info_data = custom_time_zone_info_data
end function | def custom_time_zone_info_data(self, custom_time_zone_info_data):
self._custom_time_zone_info_data = custom_time_zone_info_data | Python | nomic_cornstack_python_v1 |
if 주차시간 <= 15
begin
set 요금 = 0
end
else
if 15 < 주차시간 < 30
begin
set 요금 = 3000
end
else
begin
set 초과시간 = 주차시간 - 30 // 15
set 초과요금 = 초과시간 * 1000
set 요금 = 3000 + 초과요금
end
print string 주차시간 : %d분 % 주차시간
print string 주차요금 : %d원 % 요금 | if 주차시간<=15 :
요금 = 0
elif 15<주차시간 <30 :
요금 = 3000
else :
초과시간 = (주차시간 - 30) // 15
초과요금 = 초과시간*1000
요금 = 3000 + 초과요금
print(" 주차시간 : %d분" % 주차시간)
print(" 주차요금 : %d원" % 요금)
| Python | zaydzuhri_stack_edu_python |
string Hi,Mike
print string Hi string Mike sep=string , end=string .
string Hi,Mike Hi,Mike. | """
Hi,Mike
"""
print ('Hi', 'Mike', sep=',', end='.\n')
"""
Hi,Mike
Hi,Mike.
"""
| Python | zaydzuhri_stack_edu_python |
function get_application_by_name self name custom_headers=none raw=false **operation_config
begin
comment Construct URL
set url = string /v1/directory/applications/{name}
set path_format_arguments = dict string name call url string name name string str
set url = call format_url url keyword path_format_arguments
comment... | def get_application_by_name(
self, name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = '/v1/directory/applications/{name}'
path_format_arguments = {
'name': self._serialize.url("name", name, 'str')
}
url = self._client.format_u... | Python | nomic_cornstack_python_v1 |
class Person extends object
begin
function __init__ self firstname lastname
begin
set firstname = firstname
set lastname = lastname
end function
function full_name self
begin
print string Name is: %s %s % tuple firstname lastname
end function
end class
class Student extends Person
begin
function __init__ self firstname... | class Person(object):
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def full_name(self):
print("Name is: %s %s" % (self.firstname, self.lastname))
class Student(Person):
def __init__(self, firstname, lastname, subjectname):
... | Python | zaydzuhri_stack_edu_python |
import socket
comment 报文和传送内容 中间空行
set baowen = string HTTP/1.1 200 OK Server: nginx Date: Wed, 03 Apr 2019 08:11:46 GMT Content-Type: text/html; charset=UTF-8 hello wold
comment 创建套接字 默认ipv4 tcp协议
set ss = call socket
set addr = tuple string 0.0.0.0 9090
comment 绑定端口
call bind addr
call listen 5
while 1
begin
comment ... | import socket
# 报文和传送内容 中间空行
baowen = """
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 03 Apr 2019 08:11:46 GMT
Content-Type: text/html; charset=UTF-8
hello wold
"""
# 创建套接字 默认ipv4 tcp协议
ss = socket.socket()
addr = ('0.0.0.0',9090)
# 绑定端口
ss.bind(addr)
ss.listen(5)
while 1:
# 接受监听的信息
conn,addr =ss.accept()
... | Python | zaydzuhri_stack_edu_python |
function mounts self
begin
pass
end function | def mounts(self) -> Iterable:
pass | Python | nomic_cornstack_python_v1 |
function getBindingSite2 self
begin
return call InSpeciesTypeBond_getBindingSite2 self
end function | def getBindingSite2(self):
return _libsbml.InSpeciesTypeBond_getBindingSite2(self) | Python | nomic_cornstack_python_v1 |
comment BaseConnection
comment Overview:
comment Provides the base connection framework for specific DB connection objects.
from ResultStatus import ResultStatus
class BaseConnection
begin
function __init__ self user password host port database dbtype=string
begin
set User = user
set Password = password
set Host = host... | ###############################################################################
# BaseConnection
#
# Overview:
# Provides the base connection framework for specific DB connection objects.
#
###############################################################################
from ResultStatus import ResultStatus
class Bas... | Python | zaydzuhri_stack_edu_python |
function Level5
begin
global level1 canvas nivel5 nivel55 w x y m k f r contador m2 w2 r2 f2 g1 g11 g2 g22 g3 g33 g4 g44 g5 g55 g6 g66 gas equis ac gas2 ac2 ply1 ply2 puntoss puntoss2
set level1 = call Toplevel vt
call iconify
call geometry string 1200x1000
set canvas = call Canvas level1 width=1500 height=780 bg=strin... | def Level5():
global level1,canvas,nivel5,nivel55,w,x,y,m,k,f,r,contador,m2,w2,r2,f2,g1,g11,g2,g22,g3,g33,g4,g44,g5,g55,g6,g66,gas,equis,ac,gas2,ac2,ply1,ply2,puntoss,puntoss2
level1 = tkinter.Toplevel(vt)
vt.iconify()
level1.geometry("1200x1000")
canvas = tkinter.Canvas(level1, width=1500, height=7... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Nov 1 13:07:18 2019 @author: keyur
comment Association Rule Mining
comment Apriori
comment Data Preeprocessing
comment Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment Import Dataset
set dataset = read csv string Market_B... | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 1 13:07:18 2019
@author: keyur
"""
# Association Rule Mining
# Apriori
# Data Preeprocessing
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Dataset
dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = No... | Python | zaydzuhri_stack_edu_python |
import math
import VAO
import OpenGL.GL as gl
class Primitives extends object
begin
string This class allows the creation of primitive shapes and stores them as VAOs
comment A dictionary of VAOs mapped to names
set s_VAOs = dict
function __init__ self
begin
string The constructor
pass
end function
function draw self _... | import math
import VAO
import OpenGL.GL as gl
class Primitives(object):
"""This class allows the creation of primitive shapes and stores them as VAOs"""
# A dictionary of VAOs mapped to names
s_VAOs = {}
def __init__(self):
"""The constructor"""
pass
def draw(self, _name):
... | Python | zaydzuhri_stack_edu_python |
import pygame
from pygame.sprite import Sprite
class Alien extends Sprite
begin
string This is the Alien class for the DIY Alien Invasion.
function __init__ self ai_game
begin
call __init__
set screen = screen
set settings = settings
set image = load image string images/alien.bmp
set image = call rotate image - 90
set ... | import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""This is the Alien class for the DIY Alien Invasion."""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.image = pygame.image.load('images/a... | Python | zaydzuhri_stack_edu_python |
function triples self
begin
if length words < 3
begin
return
end
for i in range length words - 2
begin
yield tuple words at i words at i + 1 words at i + 2
end
end function | def triples(self):
if len(self.words) < 3:
return
for i in range(len(self.words) - 2):
yield (self.words[i], self.words[i + 1], self.words[i + 2]) | Python | nomic_cornstack_python_v1 |
function make_declare loop_orders dtypes sub
begin
set decl = string
for tuple i tuple loop_order dtype in enumerate zip loop_orders dtypes
begin
comment input name corresponding to ith loop variable
set var = sub at string lv%i % i
comment we declare an iteration variable
comment and an integer for the number of dime... | def make_declare(loop_orders, dtypes, sub):
decl = ""
for i, (loop_order, dtype) in enumerate(zip(loop_orders, dtypes)):
var = sub['lv%i' % i] # input name corresponding to ith loop variable
# we declare an iteration variable
# and an integer for the number of dimensions
... | Python | nomic_cornstack_python_v1 |
function __init__ self state_dict
begin
set _state = state_dict
end function | def __init__(self, state_dict):
self._state = state_dict | Python | nomic_cornstack_python_v1 |
import time
import board
import digitalio
from lcd.lcd import LCD
from lcd.i2c_pcf8574_interface import I2CPCF8574Interface
from lcd.lcd import CursorMode
set button_a = call DigitalInOut BUTTON_A
set direction = INPUT
set pull = DOWN
comment Talk to the LCD at I2C address 0x27.
comment The number of rows and columns d... | import time
import board
import digitalio
from lcd.lcd import LCD
from lcd.i2c_pcf8574_interface import I2CPCF8574Interface
from lcd.lcd import CursorMode
button_a = digitalio.DigitalInOut(board.BUTTON_A)
button_a.direction = digitalio.Direction.INPUT
button_a.pull = digitalio.Pull.DOWN
# Talk to the LCD at I2C add... | Python | zaydzuhri_stack_edu_python |
comment taken 1:1 from:
comment https://github.com/YuChenAmberLu/Options-Calculator/blob/master/Options%20Calculator%20with%20Black%20Scholes%20model.ipynb
comment import certain packages
from math import log , sqrt , pi , exp
from scipy.stats import norm
from datetime import datetime , date
import numpy as np
import p... | #taken 1:1 from:
#https://github.com/YuChenAmberLu/Options-Calculator/blob/master/Options%20Calculator%20with%20Black%20Scholes%20model.ipynb
## import certain packages
from math import log, sqrt, pi, exp
from scipy.stats import norm
from datetime import datetime, date
import numpy as np
import pandas as pd
from panda... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
for i in range 300 310 1
begin
set nShared = list 0 * 1000
set nShared_df = array read csv string C:/Users/Anni/Documents/Uni/Computer Science/Proj/CSVs and text files/nShared + string i + string .csv
set missing = 1000 - length nShared_df
set nShar... | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
for i in range(300,310,1):
nShared = [0] * 1000
nShared_df=np.array(pd.read_csv("C:/Users/Anni/Documents/Uni/Computer "
"Science/Proj/CSVs "
"and text files/nShared"+str(i)+".csv"))
... | Python | zaydzuhri_stack_edu_python |
import os
function get_all_topics input
begin
string Get all the topics' code and names (as queries) for BM25 Return queries(dict) - A dictionary of Topic code : topic title
set xmlFile = open input
set xmlContent = read xmlFile
set lines = split xmlContent string
close xmlFile
set topic_title = list
set topic_code = ... | import os
def get_all_topics(input):
"""Get all the topics' code and names (as queries) for BM25
Return
queries(dict) - A dictionary of Topic code : topic title
"""
xmlFile = open(input)
xmlContent = xmlFile.read()
lines = xmlContent.split('\n')
xmlFile.close()
topic_title = []
... | Python | zaydzuhri_stack_edu_python |
function __init__ self inOpts=none
begin
import argparse
set parser = call ArgumentParser description=string Process index fastq files.
call add_argument string inFile1 action=string store nargs=string + help=string i7 index input file name
call add_argument string inFile2 action=string store nargs=string + help=string... | def __init__(self, inOpts=None):
import argparse
self.parser = argparse.ArgumentParser(description="Process index fastq files.")
self.parser.add_argument("inFile1", action="store", nargs="+", help="i7 index input file name")
self.parser.add_argument("inFile2", action="store", nargs="+", ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
function safe_cast val to_type default=none
begin
try
begin
return call to_type val
end
except tuple ValueError TypeError
begin
return default
end
end function
set bi = read csv string supera-data-test\test.csv
set df = bi
set df at string pr_domreturn = df at string domgross_2013... | import pandas as pd
import numpy as np
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
bi = pd.read_csv(r'supera-data-test\test.csv')
df = bi
df['pr_domreturn'] = df['domgross_2013']/df['budget_2013']
df['pr_intreturn'] = df[... | Python | zaydzuhri_stack_edu_python |
function test_remove_pbc_unsegmented
begin
set ref_array = call load_structure join call data_dir string structure string 3o5r.mmtf
comment Center structure in box
set centroid = call centroid ref_array
set box_center = call diag box / 2
set ref_array = call translate ref_array box_center - centroid
comment Remove solv... | def test_remove_pbc_unsegmented():
ref_array = load_structure(join(data_dir("structure"), "3o5r.mmtf"))
# Center structure in box
centroid = struc.centroid(ref_array)
box_center = np.diag(ref_array.box) / 2
ref_array = struc.translate(ref_array, box_center-centroid)
# Remove solvent
ref_arra... | Python | nomic_cornstack_python_v1 |
comment Code template to create invidual market sets and label them by color
comment Distance between parallel actin filaments, Angstroms.
set lattice_spacing = 100
comment Actin length in Angstroms.
set actin_length = 1000
from math import sqrt
set plane_spacing = square root 3 / 2 * lattice_spacing
comment Radius of ... | #Code template to create invidual market sets and label them by color
lattice_spacing = 100 # Distance between parallel actin filaments, Angstroms.
actin_length = 1000 # Actin length in Angstroms.
from math import sqrt
plane_spacing = sqrt(3)/2 * lattice_spacing
radius = 30 # Radius of cylinder depicting actin fil... | Python | zaydzuhri_stack_edu_python |
from os.path import join
from optparse import OptionParser
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import matplotlib.pyplot as plt
from PIL import Image
from model import UNet
from resnet import resNet
from dataloader import DataLoader
function train_net net epochs=100 data_dir=string data ... | from os.path import join
from optparse import OptionParser
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import matplotlib.pyplot as plt
from PIL import Image
from model import UNet
from resnet import resNet
from dataloader import DataLoader
def train_net(net,
epochs=100,
... | Python | zaydzuhri_stack_edu_python |
function log_execution_time func
begin
decorator wraps func
function _func *args **kwargs
begin
set start_time = time
call func *args keyword kwargs
set execution_time = time - start_time
print format string Function {} took {:05.3f} seconds to run. __name__ execution_time
end function
return _func
end function | def log_execution_time(func):
@wraps(func)
def _func(*args, **kwargs):
start_time = time()
func(*args, **kwargs)
execution_time = time() - start_time
print('Function {} took {:05.3f} seconds to run.'.format(
func.__name__, execution_time))
return _func | Python | nomic_cornstack_python_v1 |
function which program
begin
function is_exe fpath
begin
return is file path fpath and call access fpath X_OK
end function
set tuple fpath fname = split path program
if fpath
begin
if call is_exe program
begin
return program
end
end
else
begin
for path in split environ at string PATH pathsep
begin
set path = strip path... | def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip(... | Python | nomic_cornstack_python_v1 |
function even_numbers limit
begin
return list range 0 limit + 1 2
end function
comment 1. Optimized the generation of even numbers using range with step.
comment Code fixed. # Executing code. | def even_numbers(limit):
return list(range(0, limit+1, 2))
# 1. Optimized the generation of even numbers using range with step.
# Code fixed. # Executing code.
| Python | flytech_python_25k |
function isPrintable self targetGrid
begin
set color_bounds = dict
set tuple m n = tuple length targetGrid length targetGrid at 0
for i in range m
begin
for j in range n
begin
set color = targetGrid at i at j
if color not in color_bounds
begin
set color_bounds at color = list i j i j
end
else
begin
set color_bounds at... | def isPrintable(self, targetGrid: List[List[int]]) -> bool:
color_bounds = {}
m, n = len(targetGrid), len(targetGrid[0])
for i in range(m):
for j in range(n):
color = targetGrid[i][j]
if color not in color_bounds:
color_bounds[color] = [i, j, i, j]
... | Python | jtatman_500k |
function _diag m
begin
return list comprehension m at j at j for j in range length m
end function | def _diag(m):
return [m[j][j] for j in range(len(m))] | Python | nomic_cornstack_python_v1 |
from typing import List
import geopy.distance
from common.primitives import Point
comment meters!
function distance_between_points point_a point_b
begin
return meters
end function
function remove_duplicates_by_key iterable key
begin
set mapping = dict
set duplicates = dict
for item in iterable
begin
if not get mappin... | from typing import List
import geopy.distance
from common.primitives import Point
def distance_between_points(point_a: Point, point_b: Point) -> float: # meters!
return geopy.distance.geodesic((point_a.lat, point_a.lon), (point_b.lat, point_b.lon)).meters
def remove_duplicates_by_key(iterable: List, key: str... | Python | zaydzuhri_stack_edu_python |
function reverse x
begin
string :type x: int :rtype: int
set maxInt32 = 2147483647
set minInt32 = - 2147483648
set num = 0
set neg = if expression x < 0 then true else false
if neg is true
begin
set x = - 1 * x
end
while x != 0
begin
set num = 10 * num + x % 10
set x = x // 10
end
if num > maxInt32 or num < minInt32
be... | def reverse(x):
"""
:type x: int
:rtype: int
"""
maxInt32 = 2147483647
minInt32 = -2147483648
num = 0
neg = True if x < 0 else False
if neg is True:
x = (-1) * x
while x != 0:
num = 10 * num + x % 10
x = x // 10
if num > maxInt32 or num < minInt32:
... | Python | zaydzuhri_stack_edu_python |
function sendMessage self payload isBinary=false fragmentSize=none sync=false doNotCompress=false
begin
set payload at string msg = msg
set msg = msg + 1
set data = dump payload
debug string Sent data: %s % data
if not call is_binary
begin
set data = encode data string utf-8
end
call sendMessage data call is_binary fra... | def sendMessage(self, payload, isBinary=False, fragmentSize=None, sync=False, doNotCompress=False):
payload["msg"] = self.msg
self.msg += 1
data = self.serializer.dump(payload)
self.logger.debug("Sent data: %s" % data)
if not self.serializer.is_binary():
data = data.e... | Python | nomic_cornstack_python_v1 |
comment Author: Kusha Maharshi
comment Email: kmaharsh@andrew.cmu.edu
import string
string BST Custom Features: Number if children (d) Implementation -> - Functional - Imperative Additional features: - Augment with reduced values - Balanced Functions: - Add - Delete - Insert at Rank - Search - Print (Inorder, Preorder,... | ##Author: Kusha Maharshi
##Email: kmaharsh@andrew.cmu.edu
import string
"""
BST
Custom Features:
Number if children (d)
Implementation ->
- Functional
- Imperative
Additional features:
- Augment with reduced values
- Balanced
Functions:
- Add
- Delete
- Insert at Rank
- Search
- Print (Inorder, Preorder, Postorder)
... | Python | zaydzuhri_stack_edu_python |
function setProperty self child key value
begin
comment First get the child's dictionary
set childDict = call getInfoDict child
if childDict
begin
set childDict at key = value
end
end function | def setProperty(self, child, key, value):
# First get the child's dictionary
childDict = self.getInfoDict(child)
if childDict:
childDict[key] = value | Python | nomic_cornstack_python_v1 |
string Created on 2013-5-5 @author: Administrator | '''
Created on 2013-5-5
@author: Administrator
''' | Python | zaydzuhri_stack_edu_python |
import re
function extract_domain_names url_list
begin
set domain_names = list
for url in url_list
begin
comment Extract the domain name using regex
set matches = find all string [a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+ url
if matches
begin
append domain_names matches at 0
end
end
comment Filter out domain names with less than t... | import re
def extract_domain_names(url_list):
domain_names = []
for url in url_list:
# Extract the domain name using regex
matches = re.findall(r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', url)
if matches:
domain_names.append(matches[0])
# Filter out domain names... | Python | jtatman_500k |
comment So read my comments. Its very pseudo-code. It will be best to read this and rewrite it as you want. There are going to be bugs for sure so just remember to think it out
comment through and fix them.
comment This is where you enter the game. You enter at the Enterance.
print string Game Begin/n
set exit_entrance... | # So read my comments. Its very pseudo-code. It will be best to read this and rewrite it as you want. There are going to be bugs for sure so just remember to think it out
# through and fix them.
# This is where you enter the game. You enter at the Enterance.
print("Game Begin/n");
exit_entrance_loop = 0
pantry... | Python | zaydzuhri_stack_edu_python |
function label_to_coco_label self label
begin
return coco_labels at label
end function | def label_to_coco_label(self, label):
return self.coco_labels[label] | Python | nomic_cornstack_python_v1 |
function test_mm_2019_sss_2_imported
begin
assert string mm_2019_sss_2 in modules
end function | def test_mm_2019_sss_2_imported():
assert "mm_2019_sss_2" in sys.modules | Python | nomic_cornstack_python_v1 |
function run_pyats_command self command
begin
set label = label
return call run_command label command
end function | def run_pyats_command(self, command):
label = self.label
return self.lab.pyats.run_command(label, command) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
set df_raw = read json string data.json
set data = df_raw at list string age string countGroups
set X = reshape array data at string age - 1 1
set y = reshape arra... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
df_raw = pd.read_json(r"data.json")
data = df_raw[['age','countGroups']]
X = np.array(data['age']).reshape(-1, 1)
y = np.array(data['countGroups']).reshape(-1... | Python | zaydzuhri_stack_edu_python |
for i in call xrange 2 501
begin
set length = length ans
set flag = 0
for j in call xrange length
begin
if ans at j == i
begin
set flag = 1
break
end
for k in call xrange j + 1 length
begin
if ans at k + ans at j == i
begin
set flag = 1
break
end
end
end
if flag == 0
begin
append ans i
end
end
comment print ans, len(an... | for i in xrange(2, 501):
length = len(ans)
flag = 0
for j in xrange(length):
if ans[j] == i:
flag = 1
break
for k in xrange(j+1, length):
if ans[k] + ans[j] == i:
flag = 1
break
if flag == 0:
ans.append(i)
# print ans, len(ans)
tt = int(raw_input())
for i in xrange(tt):
n = int(raw_inpu... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
class MagData extends object
begin
string Magnetic data set
function __init__ self fname=none
begin
call __init__
set df = call DataFrame columns=list string x string y string z string mag string uncert
set inc = none
set dec = none
set b0 = none
if fname is not none
begin
call re... | import pandas as pd
import numpy as np
class MagData(object):
"""Magnetic data set"""
def __init__(self, fname=None):
super(MagData, self).__init__()
self.df = pd.DataFrame(columns=['x', 'y', 'z', 'mag', 'uncert'])
self.inc = None
self.dec = None
self.b0 = None
... | Python | zaydzuhri_stack_edu_python |
async function test_user_adds_full_device hass full_device pairing
begin
set result = await call async_init DOMAIN context=dict string source SOURCE_USER
assert result at string type == RESULT_TYPE_FORM
assert result at string errors == dict
set result2 = await call async_configure result at string flow_id dict string... | async def test_user_adds_full_device(hass, full_device, pairing):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {}
result2 = await hass.config_... | Python | nomic_cornstack_python_v1 |
from itertools import combinations
while 1
begin
set nums = list map int split input
if nums at 0 == 0
begin
break
end
del nums at 0
sort nums
for x in list call combinations nums 6
begin
for j in x
begin
print j end=string
end
print
end
print
end | from itertools import combinations
while(1):
nums = list(map(int, input().split()))
if(nums[0] == 0):
break
del nums[0]
nums.sort()
for x in list(combinations(nums, 6)):
for j in x:
print(j, end=' ')
print()
print() | Python | zaydzuhri_stack_edu_python |
function add self new_node
begin
if not is instance new_node int
begin
raise TypeError
end
set new_node = call Node new_node
if tree_root is none
begin
set tree_root = new_node
end
comment значение, с которым будем сравнивать новое
set base_node = tree_root
while true
begin
if root < root
begin
comment если меньшего зн... | def add(self, new_node: int):
if not isinstance(new_node, int):
raise TypeError
new_node = Node(new_node)
if self.tree_root is None:
self.tree_root = new_node
base_node = self.tree_root # значение, с которым будем сравнивать новое
while True:
... | Python | nomic_cornstack_python_v1 |
import json
import numpy as np
import pandas as pd
from numpy import sqrt , square
from config import USER_COL , ITEM_COL , RATING_COL , SGD_HYPER_PARAMS , ALS_HYPER_PARAMS , TEST_OUT_SGD , TEST_OUT_ALS
from utils import get_data , get_test
class MatrixFactorization
begin
function __init__ self k=15 gamma_u=0.01 gamma_... | import json
import numpy as np
import pandas as pd
from numpy import sqrt, square
from config import USER_COL, ITEM_COL, RATING_COL, SGD_HYPER_PARAMS, \
ALS_HYPER_PARAMS, TEST_OUT_SGD, TEST_OUT_ALS
from utils import get_data, get_test
class MatrixFactorization:
def __init__(self, k=15, gamma_u=0.01, gamma_... | Python | zaydzuhri_stack_edu_python |
comment Kaizend 3: Python for Scripting - Exercises
comment Exercise: Products CSV Reader and Writer
comment The main objective of this project idea is to read a CSV with a list of
comment products for an ecommerce site. The application should be able to:
comment - Remove all products that don’t have categories
comment... | # Kaizend 3: Python for Scripting - Exercises
# Exercise: Products CSV Reader and Writer
# The main objective of this project idea is to read a CSV with a list of
# products for an ecommerce site. The application should be able to:
# - Remove all products that don’t have categories
# - Output a new CSV file that con... | Python | zaydzuhri_stack_edu_python |
function launch_template_id self
begin
return get pulumi self string launch_template_id
end function | def launch_template_id(self) -> pulumi.Input[str]:
return pulumi.get(self, "launch_template_id") | 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.