code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock?
comment The program should print two numbers: the numbers: the number of hours (between 0 and 23) and the number of minutes(between 0 and 59).
comment For example, if N=... | #Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock?
#The program should print two numbers: the numbers: the number of hours (between 0 and 23) and the number of minutes(between 0 and 59).
#For example, if N=150, then 150 minutes... | Python | zaydzuhri_stack_edu_python |
import shutil , os , sys
set usage = string All names should be passed without extensions. All input names will have *.py extension added. Entry point output name will have *.pyw extension added. Usage: > python build.py name_in name_out builds name_in as an main entry point and gives it name_out name > python build.py... | import shutil, os, sys
usage = """
All names should be passed without extensions.
All input names will have *.py extension added.
Entry point output name will have *.pyw extension added.
Usage:
> python build.py name_in name_out
builds name_in as an main entry... | Python | zaydzuhri_stack_edu_python |
function customise_image self image
begin
set new_image = call create_network_image image networks c_mode=c_mode * IMAGE_MAX
return as type new_image string uint8
end function | def customise_image(self, image):
new_image = create_network_image(
image,
self.networks,
c_mode=self.c_mode) * IMAGE_MAX
return new_image.astype('uint8') | Python | nomic_cornstack_python_v1 |
function get self path
begin
return cache at path
end function | def get(self, path):
return self.cache[path] | Python | nomic_cornstack_python_v1 |
function _get_run_information_from_experiments projection experiment_ids selection=none filter_string=string tracking_uri=none client=none
begin
comment Normalize input
if not is instance experiment_ids tuple list tuple
begin
set experiment_ids = list experiment_ids
end
set experiment_ids = list experiment_ids
if none... | def _get_run_information_from_experiments(
*,
projection: Callable[[mlflow.entities.Run], T],
experiment_ids: Union[int, Collection[int]],
selection: Optional[Callable[[mlflow.entities.Run], bool]] = None,
filter_string: Optional[str] = "",
tracking_uri: Optional[str] = None,
client: Optiona... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import os
set path = string /usr | #!/usr/bin/env python
import os
path = "/usr"
| Python | jtatman_500k |
comment -*- coding: utf-8 -*-
from redis import Redis as Redis_ , ConnectionPool
from redis.connection import UnixDomainSocketConnection
class Redis extends Redis_
begin
string This class is used for the intergration of Redis to a Flask application. There are two usage modes which work very similar. One if binding the ... | # -*- coding: utf-8 -*-
from redis import Redis as Redis_, ConnectionPool
from redis.connection import UnixDomainSocketConnection
class Redis(Redis_):
"""This class is used for the intergration of Redis to a Flask
application.
There are two usage modes which work very similar. One if binding
the inst... | Python | zaydzuhri_stack_edu_python |
function set_state_independent_trials self independent_trials
begin
set independent_trials = array independent_trials
if length independent_trials != dimensions or not all independent_trials < trials and all independent_trials >= 0
begin
raise exception format string independent_trials must be a list of {} indices, num... | def set_state_independent_trials(self, independent_trials):
independent_trials = np.array(independent_trials)
if len(independent_trials) != self.dimensions or not (
np.all(independent_trials < self.trials) and np.all(
independent_trials >= 0)):
raise Exception(
... | Python | nomic_cornstack_python_v1 |
function fileCompare a b
begin
if a at string file_first_event > b at string file_first_event
begin
return 1
end
if a at string file_first_event == b at string file_first_event
begin
return 0
end
else
begin
return - 1
end
end function | def fileCompare(a, b):
if a["file_first_event"] > b["file_first_event"]:
return 1
if a["file_first_event"] == b["file_first_event"]:
return 0
else:
return -1 | Python | nomic_cornstack_python_v1 |
import numpy as np
from itertools import count
import copy
import random
comment import pydot
comment from PIL import Image
function simulateOneSeq seqLength numRefs numCuts mutationRate
begin
set refs = list comprehension join string random choice list string A string C string G string T size=seqLength for _ in range... | import numpy as np
from itertools import count
import copy
import random
#import pydot
#from PIL import Image
def simulateOneSeq(seqLength, numRefs, numCuts, mutationRate):
refs = [ "".join( np.random.choice(['A','C','G','T'], size = seqLength) ) for _ in range(numRefs) ]
cutIndices = [0] + sorted( np.ran... | Python | zaydzuhri_stack_edu_python |
import time
set start = time
function gen_factorials target
begin
set factorials = list comprehension 1 for x in range 0 target + 1
for x in range 1 length factorials
begin
set factorials at x = x * factorials at x - 1
end
return factorials
end function
set factorials = call gen_factorials 100
set the_ans = 0
for x in ... | import time
start=time.time()
def gen_factorials(target):
factorials=[1 for x in range(0,target+1)]
for x in range(1,len(factorials)):
factorials[x]=x*factorials[x-1]
return factorials
factorials=gen_factorials(100)
the_ans=0
for x in range(1,101):
for y in range(x,0,-1):
if factorials[x]/(factorials[y]*fact... | Python | zaydzuhri_stack_edu_python |
function process_list puzzle
begin
set nodes = list
for line in puzzle
begin
set tuple cord size used avail perc = split strip line
set xi = index cord string x
set yi = index cord string y
set x = integer cord at slice xi + 1 : yi - 1 :
set y = integer cord at slice yi + 1 : :
set items = tuple size used avail perc
... | def process_list(puzzle):
nodes = []
for line in puzzle:
cord, size, used, avail, perc = line.strip().split()
xi = cord.index('x')
yi = cord.index('y')
x = int(cord[xi + 1:yi - 1])
y = int(cord[yi + 1:])
items = (size, used, avail, perc)
size, used, ava... | Python | zaydzuhri_stack_edu_python |
function gagne self
begin
call setlv lv + 1
call reinit
end function | def gagne(self):
self.setlv(self.lv+1)
self.reinit() | Python | nomic_cornstack_python_v1 |
function environment_created self
begin
pass
end function | def environment_created(self):
pass | Python | nomic_cornstack_python_v1 |
function update self *args **kwargs
begin
set list = list string id string width string height string x string y
set count = 0
if args
begin
for arg in args
begin
set count = count + 1
if count == 1
begin
set id = arg
end
else
if count == 2
begin
set width = arg
end
else
if count == 3
begin
set height = arg
end
else
if... | def update(self, *args, **kwargs):
list = ["id", "width", "height", "x", "y"]
count = 0
if args:
for arg in args:
count += 1
if count == 1:
self.id = arg
elif count == 2:
self.width = arg
... | Python | nomic_cornstack_python_v1 |
comment String ve listelerin indekslenmesi ###
comment Stringlerin İndekslenmesi
set merhabaStringi = string MERHABA
comment M E R H A B A
comment 0 1 2 3 4 5 6
print merhabaStringi at - 1
comment Listelerin indekslenmesi
set liste1 = list 0 1 2 3 4 5 6
comment listeler 0'dan indekslenmeye başlar,
comment yani ilk elem... | ### String ve listelerin indekslenmesi ###
# Stringlerin İndekslenmesi
merhabaStringi = "MERHABA"
# M E R H A B A
# 0 1 2 3 4 5 6
print(merhabaStringi[-1])
# Listelerin indekslenmesi
liste1 = [0,1,2,3,4,5,6]
# listeler 0'dan indekslenmeye başlar,
# yani ilk elemanın indeks değeri 0'dır.
ilkEleman = liste1[... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment Atcoder necoak answer
comment https://atcoder.jp/contests/dp/tasks/dp_a
set N = integer input
set h = list map int split input
set min_cost = list 10 ^ 4 * N
set min_cost at 0 = 0
set min_cost at 1 = absolute h at 0 - h at 1
for i in range 2 N 1
begin
set min_cost at i = min min_co... | #!/usr/bin/env python3
# Atcoder necoak answer
# https://atcoder.jp/contests/dp/tasks/dp_a
N = int(input())
h = list(map(int, input().split()))
min_cost = [10**4] * N
min_cost[0] = 0
min_cost[1] = abs(h[0]-h[1])
for i in range(2, N, 1):
min_cost[i] = min(
min_cost[i-1]+abs(h[i]-h[i-1]),
min_cost... | Python | zaydzuhri_stack_edu_python |
import cv2
import os
import numpy as np
from natsort import natsorted
function xywh2xyxy bbox
begin
set tuple x y w h = bbox
set x_min = integer x - w / 2
set y_min = integer y - h / 2
set x_max = integer x + w / 2
set y_max = integer y + h / 2
return tuple x_min y_min x_max y_max
end function
set seg_mask_dir = string... | import cv2
import os
import numpy as np
from natsort import natsorted
def xywh2xyxy(bbox):
x, y, w, h = bbox
x_min = int(x - (w/2))
y_min = int(y - (h/2))
x_max = int(x + (w/2))
y_max = int(y + (h/2))
return x_min, y_min, x_max, y_max
seg_mask_dir = f'./JPG'
label_dir = f'./labels'
segmask_... | Python | zaydzuhri_stack_edu_python |
function metadata self
begin
return get pulumi self string metadata
end function | def metadata(self) -> Optional[pulumi.Input['SyntheticsPrivateLocationMetadataArgs']]:
return pulumi.get(self, "metadata") | Python | nomic_cornstack_python_v1 |
function create_sparse_matrix self matrix_df
begin
print string creating sparse matrix...
set sparse_seg_tmp_df = reset index mean group by matrix_df list string segment_id string day_of_week string time_idx at args at string cluster_variable
set sparse_rt_tmp_df = reset index mean group by matrix_df list string road_t... | def create_sparse_matrix(self, matrix_df):
print('creating sparse matrix...')
sparse_seg_tmp_df = matrix_df.groupby(['segment_id','day_of_week','time_idx'])[self.args['cluster_variable']].mean().reset_index()
sparse_rt_tmp_df = matrix_df.groupby(['road_type','day_of_week','time_idx'])[self.args... | Python | nomic_cornstack_python_v1 |
function is_output obj
begin
return _output_type is not none and is instance obj _output_type
end function | def is_output(obj: Any) -> bool:
return _output_type is not None and isinstance(obj, _output_type) | Python | nomic_cornstack_python_v1 |
function modify_commandline_parameters parser is_train
begin
return parser
end function | def modify_commandline_parameters(parser, is_train):
return parser | Python | nomic_cornstack_python_v1 |
from bisect import bisect_left
set tuple N M = map int split input
set tuple X Y = map int split input
set A = list map int split input
set B = list map int split input
set tuple time cnt = tuple 0 0
while true
begin
set l_a = call bisect_left A time
if l_a == N
begin
break
end
set time = A at l_a + X
set l_b = call bi... | from bisect import bisect_left
N, M = map(int, input().split())
X, Y = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
time, cnt = 0, 0
while True:
l_a = bisect_left(A, time)
if l_a == N:
break
time = A[l_a] + X
l_b = bisect_left(B, time)
if... | Python | zaydzuhri_stack_edu_python |
function cast *args
begin
return call itkLabelShapeOpeningImageFilterIUS3_cast *args
end function | def cast(*args):
return _itkLabelShapeOpeningImageFilterPython.itkLabelShapeOpeningImageFilterIUS3_cast(*args) | Python | nomic_cornstack_python_v1 |
class Solution
begin
comment @param {integer} n
comment @return {string[]}
function generateParenthesisBack self initStr leftPSize rightPsize maxSize Res
begin
if leftPSize == maxSize and rightPsize == maxSize and call isValid initStr
begin
add Res initStr
end
else
if leftPSize > maxSize or rightPsize > maxSize or not ... | class Solution:
# @param {integer} n
# @return {string[]}
def generateParenthesisBack(self, initStr, leftPSize, rightPsize,maxSize, Res):
if leftPSize == maxSize and rightPsize==maxSize and self.isValid(initStr):
Res.add(initStr)
elif leftPSize>maxSize or rightPsize>maxSize or n... | Python | zaydzuhri_stack_edu_python |
function write_cache_ineligibility_reason self
begin
return _write_cache_ineligibility_reason
end function | def write_cache_ineligibility_reason(self):
return self._write_cache_ineligibility_reason | Python | nomic_cornstack_python_v1 |
function inter_matrix self form=string coo value_field=none
begin
if not uid_field or not iid_field
begin
raise call ValueError string dataset does not exist uid/iid, thus can not converted to sparse matrix.
end
return call _create_sparse_matrix inter_feat uid_field iid_field form value_field
end function | def inter_matrix(self, form="coo", value_field=None):
if not self.uid_field or not self.iid_field:
raise ValueError(
"dataset does not exist uid/iid, thus can not converted to sparse matrix."
)
return self._create_sparse_matrix(
self.inter_feat, self.u... | Python | nomic_cornstack_python_v1 |
if hrs <= 40
begin
set grosspay = hrs * rate
end
if hrs > 40
begin
set exhrs = hrs - 40
set exrate = rate * 1.5
set grosspay = 40 * rate + exhrs * exrate
end | if hrs <= 40:
grosspay= hrs*rate
if hrs >40:
exhrs=hrs-40
exrate=rate*1.5
grosspay= (40*rate) + (exhrs*exrate)
| Python | zaydzuhri_stack_edu_python |
function add_site_states self site states
begin
for state in states
begin
if state not in site_states at site
begin
append site_states at site state
end
end
end function | def add_site_states(self, site, states):
for state in states:
if state not in self.site_states[site]:
self.site_states[site].append(state) | Python | nomic_cornstack_python_v1 |
from nltk.tokenize import word_tokenize
set sentence = string This is a sample sentence.
print call word_tokenize sentence
comment Code executed. Sentence tokenized. | from nltk.tokenize import word_tokenize
sentence = 'This is a sample sentence.'
print(word_tokenize(sentence))
# Code executed. Sentence tokenized.
| Python | flytech_python_25k |
function add self obs_t action reward obs_tp1 done
begin
set data = tuple obs_t action reward obs_tp1 done
set priority = uniform 0 1
if length _storage < _maxsize
begin
call heappush _storage tuple priority data
end
else
if priority > _storage at 0 at 0
begin
call heapreplace _storage tuple priority data
end
end funct... | def add(self, obs_t, action, reward, obs_tp1, done):
data = (obs_t, action, reward, obs_tp1, done)
priority = random.uniform(0, 1)
if len(self._storage) < self._maxsize:
heapq.heappush(self._storage, (priority, data))
elif priority > self._storage[0][0]:
heapq.hea... | Python | nomic_cornstack_python_v1 |
import sys
append path string ../
import torch
import torch.autograd as autograd
from scipy.stats import truncnorm
from constants import FloatTensor , MEAN , VARIANCE , WEIGHT , BIAS , INIT_VARIANCE
set PARAMETER_TYPES = list WEIGHT BIAS
set STATISTICS = list MEAN VARIANCE
class ParametersDistribution
begin
function __... | import sys
sys.path.append('../')
import torch
import torch.autograd as autograd
from scipy.stats import truncnorm
from constants import FloatTensor, MEAN, VARIANCE, WEIGHT, BIAS, INIT_VARIANCE
PARAMETER_TYPES = [WEIGHT, BIAS]
STATISTICS = [MEAN, VARIANCE]
class ParametersDistribution:
def __init__(self, sharedW... | Python | zaydzuhri_stack_edu_python |
function test_repr post_factory
begin
set post = call post_factory
set expected = string Post(author_id= { call repr id } , slug= { call repr slug } )
assert call repr post == expected
end function | def test_repr(post_factory):
post = post_factory()
expected = (
f"Post(author_id={repr(post.author.id)}, slug={repr(post.slug)})"
)
assert repr(post) == expected | Python | nomic_cornstack_python_v1 |
function get_party party_uri
begin
set result = call query_db string SELECT * FROM PARTY WHERE URI = ? tuple party_uri one=true
if result is none
begin
raise call ValueError string Party with URI + party_uri + string not found.
end
return dictionary result
end function | def get_party(party_uri):
result = query_db('SELECT * FROM PARTY WHERE URI = ?', (party_uri,), one=True)
if result is None:
raise ValueError('Party with URI ' + party_uri + ' not found.')
return dict(result) | Python | nomic_cornstack_python_v1 |
function test_retrieve_workspace_view self
begin
comment Arrange:
set old_workspace_views_num = count objects
comment Act
set workspace_view = get objects pk=pk
comment Assert
set new_workspace_views_num = count objects
assert equal old_workspace_views_num new_workspace_views_num string The number of objects in the DB ... | def test_retrieve_workspace_view(self):
# Arrange:
self.old_workspace_views_num = WorkspaceView.objects.count()
# Act
self.workspace_view = WorkspaceView.objects.get(pk=self.workspace_view.pk)
# Assert
self.new_workspace_views_num = WorkspaceView.objects.count()
... | Python | nomic_cornstack_python_v1 |
async function get_user_projects_me self organization_id **kwargs
begin
set error_map = dict 401 ClientAuthenticationError ; 404 ResourceNotFoundError ; 409 ResourceExistsError
update error_map pop kwargs string error_map dict or dict
set _headers = pop kwargs string headers dict or dict
set _params = pop kwargs strin... | async def get_user_projects_me(
self,
organization_id: str,
**kwargs: Any
) -> Optional[Union[_models.ProjectListDataResult, _models.ErrorResult]]:
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_m... | Python | nomic_cornstack_python_v1 |
function findMinMax arr
begin
set min = arr at 0
set max = arr at 0
for i in range 1 length arr
begin
if arr at i < min
begin
set min = arr at i
end
else
if arr at i > max
begin
set max = arr at i
end
end
return tuple min max
end function
set arr = list 3 5 8 1 10
set tuple min_val max_val = call findMinMax arr
print m... | def findMinMax(arr):
min = arr[0]
max = arr[0]
for i in range(1, len(arr)):
if arr[i] < min:
min = arr[i]
elif arr[i] > max:
max = arr[i]
return min, max
arr = [3, 5, 8, 1, 10]
min_val, max_val = findMinMax(arr)
print(min_val, max_val) | Python | iamtarun_python_18k_alpaca |
comment -*- coding: utf-8 -*-
import sys
import pickle
import re
import operator
import random
function cmp c1 c2
begin
set tuple a b = c1
set tuple c d = c2
set s = b + d
set r = uniform 0 s
return if expression r > b then 1 else - 1
end function
comment dist. is a list of coulpes
function random_pull distribution
beg... | # -*- coding: utf-8 -*-
import sys
import pickle
import re
import operator
import random
def cmp(c1, c2):
a,b = c1
c,d = c2
s = b+d
r = random.uniform(0,s)
return 1 if r>b else -1
def random_pull(distribution): # dist. is a list of coulpes
if distribution :
sorted_couples = sorted(di... | Python | zaydzuhri_stack_edu_python |
import pyautogui
import time
while true
begin
comment moves mouse to X of 200, Y of 200.
call moveTo 200 200
sleep 1
comment moves mouse to X of 200, Y of 500.
call moveTo none 500
sleep 3
end
comment pyautogui.moveTo(600, None) # moves mouse to X of 600, Y of 500. | import pyautogui
import time
while True:
pyautogui.moveTo(200, 200) # moves mouse to X of 200, Y of 200.
time.sleep(1)
pyautogui.moveTo(None, 500) # moves mouse to X of 200, Y of 500.
time.sleep(3)
# pyautogui.moveTo(600, None) # moves mouse to X of 600, Y of 500. | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
comment 代码文件:chapter19/ch19.3.2-1.py
import wx
comment 创建应用程序对象
set app = call App
comment 创建窗口对象
set frm = call Frame none title=string 第一个GUI程序! size=tuple 400 300 pos=tuple 100 100
comment 显示窗口
show
comment 进入主事件循环
call MainLoop | # coding=utf-8
# 代码文件:chapter19/ch19.3.2-1.py
import wx
# 创建应用程序对象
app = wx.App()
# 创建窗口对象
frm = wx.Frame(None, title="第一个GUI程序!", size=(400, 300), pos=(100, 100))
frm.Show() # 显示窗口
app.MainLoop() # 进入主事件循环
| Python | zaydzuhri_stack_edu_python |
for i in range cases
begin
set num = input
print integer num at slice 0 : find num string : + integer num at slice find num string + 1 : length num :
end | for i in range(cases):
num = input()
print(int(num[0:num.find(' ')]) + int(num[num.find(' ')+1:len(num)])) | Python | zaydzuhri_stack_edu_python |
function getTemplate
begin
with open string /home/sevudan/Scripts/projects/topogen/template.cfg string r as file
begin
set data = read file
close file
end
return call Template data
end function | def getTemplate():
with open('/home/sevudan/Scripts/projects/topogen/template.cfg', 'r') as file:
data = file.read()
file.close()
return Template(data) | Python | nomic_cornstack_python_v1 |
function calculateLoadingTime self inputs
begin
set neededCharge = BATTERY_CAPACITY * 1 - call getAtt string current_soc inputs / 100
return integer neededCharge / NORM_VOLTAGE * CHARGE_SPEED * 60
end function | def calculateLoadingTime(self, inputs):
neededCharge = BATTERY_CAPACITY * (1 - (self.getAtt('current_soc', inputs) / 100))
return int((neededCharge / (NORM_VOLTAGE * CHARGE_SPEED)) * 60) | Python | nomic_cornstack_python_v1 |
comment Puzzle link: https://adventofcode.com/2020/day/15
set numdict = dict
set keys = keys numdict
function day15 startnums turns
begin
set spoken = startnums
set turn = 1
set x = length spoken
for i in spoken
begin
set numdict at i = list 1 turn turn
set turn = turn + 1
end
while x < turns
begin
set lastnum = spoke... | # Puzzle link: https://adventofcode.com/2020/day/15
numdict = {}
keys = numdict.keys()
def day15(startnums, turns):
spoken = startnums
turn = 1
x = len(spoken)
for i in spoken:
numdict[i] = [1, turn, turn]
turn += 1
while x < turns:
lastnum = spoken[-1]
... | Python | zaydzuhri_stack_edu_python |
from flask import *
from moviepy.editor import *
import os
from urllib.parse import unquote
from subprocess import call
from sys import argv
import threading
from random import choices , randint
import time
import json
set app = call Flask __name__ static_url_path=string /static root_path=string .
set videoPath = join ... | from flask import *
from moviepy.editor import *
import os
from urllib.parse import unquote
from subprocess import call
from sys import argv
import threading
from random import choices,randint
import time
import json
app=Flask(__name__,static_url_path='/static',root_path='.')
videoPath = os.path.join('./','static/','v... | Python | zaydzuhri_stack_edu_python |
string https://www.geeksforgeeks.org/maximize-the-profit-after-selling-the-tickets/?ref=leftbar-rightbar Maximize the profit after selling the tickets Given an array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the tick... | '''
https://www.geeksforgeeks.org/maximize-the-profit-after-selling-the-tickets/?ref=leftbar-rightbar
Maximize the profit after selling the tickets
Given an array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the ticket... | Python | zaydzuhri_stack_edu_python |
function search_videos self search_term
begin
print string search_videos needs implementation
comment Pass to Helper Function
call search_videos_general search_term lambda vid -> lower search_term in lower title
end function
comment print("search_videos needs implementation") | def search_videos(self, search_term):
print("search_videos needs implementation")
# Pass to Helper Function
self.search_videos_general(search_term, lambda vid: search_term.lower() in vid.title.lower())
# print("search_videos needs implementation") | Python | nomic_cornstack_python_v1 |
function lines self form level=0
begin
set account_obj = get pool string account.account
set period_obj = get pool string account.period
set fiscalyear_obj = get pool string account.fiscalyear
set wiz_rep = get pool string wizard.report
set afr_obj = get pool string afr
set show_earnings = false
set ids = list
set acc... | def lines(self, form, level=0):
account_obj = self.pool.get('account.account')
period_obj = self.pool.get('account.period')
fiscalyear_obj = self.pool.get('account.fiscalyear')
wiz_rep = self.pool.get('wizard.report')
afr_obj = self.pool.get('afr')
self.show_earnings = Fa... | Python | nomic_cornstack_python_v1 |
function rank_docs index query
begin
comment Initialize new list
set ranking = dict
for i in range 1 1401
begin
set ranking at i = 0
end
comment For each word in query
for word in call tokenize query
begin
comment If we have this word in our index
if word in keys index
begin
comment For each document in which we can f... | def rank_docs(index, query):
# Initialize new list
ranking = {}
for i in range(1, 1401):
ranking[i] = 0
# For each word in query
for word in tokenize(query):
# If we have this word in our index
if word in index.keys():
# For each document in which we can find the... | Python | nomic_cornstack_python_v1 |
class Account
begin
function __init__ self number total
begin
set number = number
set total = total
end function
end class
set alexandre = call Account 123 50.0
comment print(alexandre.saldo)
comment Função de deposito
function depositar self value
begin
set total = total + value
end function
comment Função de Sacar
fu... | class Account:
def __init__(self, number, total):
self.number = number
self.total = total
alexandre = Account(123, 50.00)
#print(alexandre.saldo)
def depositar(self, value): # Função de deposito
self.total+=value
def sacar(self, value): # Função de Sacar
self.total-=value
def get_total... | Python | zaydzuhri_stack_edu_python |
function transit_duration params
begin
set b = a * cos call radians inc
set duration = per / pi * call arcsin square root 1 - rp ^ 2 - b ^ 2 / a / sin call radians inc
return duration
end function | def transit_duration(params):
b = params.a * np.cos(np.radians(params.inc))
duration = (params.per / np.pi *
np.arcsin(np.sqrt((1-params.rp)**2 - b**2) / params.a /
np.sin(np.radians(params.inc))))
return duration | Python | nomic_cornstack_python_v1 |
import subprocess
import sublist3r
import shlex
import subprocess
from termcolor import colored
class ipWorker
begin
function __init__ self subdomainsList
begin
comment holds the list of subdomains domains
set subdomains = subdomainsList
comment holds the list of ips
set ips = list
comment maps the subdomain to the ip... | import subprocess
import sublist3r
import shlex
import subprocess
from termcolor import colored
class ipWorker:
def __init__(self, subdomainsList ):
self.subdomains = subdomainsList # holds the list of subdomains domains
self.ips = [] # holds the list of ips
self.dict = {} # maps the subdomain to ... | Python | zaydzuhri_stack_edu_python |
function solve n k string
begin
set chars = list string
comment 1st case
set b_starts = list
set i = 0
while i < n
begin
if i == 0 or chars at i - 1 == string A and chars at i == string B
begin
append b_starts i
end
set i = i + 1
end
comment 2nd case
set merges = dict
for i in b_starts
begin
set start_i = i
set diff_... | def solve(n, k, string):
chars = list(string)
# 1st case
b_starts = []
i = 0
while i < n:
if (i == 0 or chars[i - 1] == 'A') and chars[i] == 'B':
b_starts.append(i)
i += 1
# 2nd case
merges = {}
for i in b_starts:
start_i = i
diff_count = 0
... | Python | zaydzuhri_stack_edu_python |
function getname_firstany
begin
set result = call two_files string USCensusNamesFirstFemale.txt string USCensusNamesFirstMale.txt
print result
end function | def getname_firstany():
result = two_files ("USCensusNamesFirstFemale.txt", "USCensusNamesFirstMale.txt")
print (result) | Python | nomic_cornstack_python_v1 |
import math
function palindrome n
begin
return integer string n == integer string n at slice : : - 1
end function
function lychrel n
begin
for i in range 50
begin
set n = n + integer string n at slice : : - 1
if call palindrome n
begin
return false
end
end
return true
end function
set val = 0
for n in range 10000
b... | import math
def palindrome(n):
return int(str(n)) == int(str(n)[::-1])
def lychrel(n):
for i in range(50):
n = n + int(str(n)[::-1])
if palindrome(n):
return False
return True
val = 0
for n in range(10000):
if lychrel(n):
val += 1
print(val)
| Python | zaydzuhri_stack_edu_python |
comment You have a queue of integers, you need to retrieve the first unique integer in the queue.
comment Implement the FirstUnique class:
comment FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
comment int showFirstUnique() returns the value of the first unique integer of the queue, and r... | # You have a queue of integers, you need to retrieve the first unique integer in the queue.
#
# Implement the FirstUnique class:
# FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
# int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if
# ... | Python | zaydzuhri_stack_edu_python |
string sets are internally implemented as hashmaps dictionaries are also implemented similarly however, dictionaries have key-value pairs, while sets have just keys sets are maintained ordered
comment empty sets cannot be created by using {}
comment set removes duplicate elements
set s = set
set s = set literal 1 2 3
p... | '''
sets are internally implemented as hashmaps
dictionaries are also implemented similarly
however, dictionaries have key-value pairs,
while sets have just keys
sets are maintained ordered
'''
##empty sets cannot be created by using {}
##set removes duplicate elements
s = set()
s = {1, 2, 3}
print(s)
p... | Python | zaydzuhri_stack_edu_python |
function reader_main config=none mode=none
begin
assert mode in list string train string eval string test msg format string Nonsupport mode:{} mode
set global_params = config at string Global
if mode == string train
begin
set params = deep copy config at string TrainReader
end
else
if mode == string eval
begin
set para... | def reader_main(config=None, mode=None):
assert mode in ["train", "eval", "test"],\
"Nonsupport mode:{}".format(mode)
global_params = config['Global']
if mode == "train":
params = deepcopy(config['TrainReader'])
elif mode == "eval":
params = deepcopy(config['EvalReader'])
els... | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow as tf
import sys
import csv
set drive_path = string /content/drive/My Drive/ML2019Spring/
comment hyper parameters
set batch_size = 256
set epochs = 100
set lr = 0.001
set valid_rate = 0.2
set drop_rate = 0.5
function conv x filters
begin
return call conv 2d filters 3 padding=string... | import numpy as np
import tensorflow as tf
import sys
import csv
drive_path = "/content/drive/My Drive/ML2019Spring/"
# hyper parameters
batch_size = 256
epochs = 100
lr = 0.001
valid_rate = 0.2
drop_rate = 0.5
def conv(x, filters):
return tf.keras.layers.Conv2D(filters,3,padding='same',activation='relu')(x)
def m... | Python | zaydzuhri_stack_edu_python |
import re
import urllib
set url = string https://www.google.com/finance?q=
set z = call raw_input string Which company do you want to know the rates of the stock to???
set url_final = url + z
set data = read url open url_final
set data1 = decode data string utf-8
set m = search string meta itemprop="price" data1
set st... | import re
import urllib
url = "https://www.google.com/finance?q="
z=raw_input("Which company do you want to know the rates of the stock to???")
url_final = url + z
data = urllib.urlopen(url_final).read()
data1 = data.decode("utf-8")
m = re.search('meta itemprop="price"',data1)
start = m.start()
end = start... | Python | zaydzuhri_stack_edu_python |
function loudspeaker_model_adaptive
begin
set branches = 5
set filter_taps = 2 ^ 11
comment real world reference system, load input and output noise
set load_noise = call SignalFile filename=string C:/Users/diplomand.8/Desktop/nl_recordings/rec_4_db/Noise18.npz format=WAV_FLOAT
set output_noise = call GetOutput
set inp... | def loudspeaker_model_adaptive():
branches = 5
filter_taps = 2**11
# real world reference system, load input and output noise
load_noise = sumpf.modules.SignalFile(filename="C:/Users/diplomand.8/Desktop/nl_recordings/rec_4_db/Noise18.npz", format=sumpf.modules.SignalFile.WAV_FLOAT)
output_noise = s... | Python | nomic_cornstack_python_v1 |
function remove_repositories repo_names_to_remove
begin
for repo_name in repo_names_to_remove
begin
call run_ffx_command cmd=tuple string repository string remove repo_name check=true
end
end function | def remove_repositories(repo_names_to_remove):
for repo_name in repo_names_to_remove:
common.run_ffx_command(cmd=('repository', 'remove', repo_name), check=True) | Python | nomic_cornstack_python_v1 |
function html_replace exc
begin
if is instance exc tuple UnicodeEncodeError UnicodeTranslateError
begin
comment pylint: disable=invalid-name
set s = list comprehension string &%s; % codepoint2name at ordinal c for c in object at slice start : end :
return tuple join string s end
end
raise call TypeError string Can't ... | def html_replace(exc):
if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
# pylint: disable=invalid-name
s = ['&%s;' % entities.codepoint2name[ord(c)] for c in exc.object[exc.start:exc.end]]
return ''.join(s), exc.end
raise TypeError("Can't handle exception %s" % exc.__name... | Python | nomic_cornstack_python_v1 |
import re
import pandas as pd
import boto3
import pandas as pd
import numpy as np
import psycopg2
import string
string extract specified features from corpus of text documents
class FeatureExtraction extends object
begin
function __init__ self data
begin
string INPUT: - data = Path to data file as JSON string ATTRIBUTE... | import re
import pandas as pd
import boto3
import pandas as pd
import numpy as np
import psycopg2
import string
"""extract specified features from corpus of text documents"""
class FeatureExtraction(object):
def __init__(self, data):
"""
INPUT:
- data = Path to data file as JSON string
... | Python | zaydzuhri_stack_edu_python |
comment rubi
set s = integer input
set l = list map int split input
set s = list
for i in l
begin
append s count l i
end
set n = max s
for i in range 0 length s
begin
if s at i == n
begin
print l at i
break
end
end | #rubi
s=int(input())
l=list(map(int,input().split()))
s=[]
for i in l:
s.append(l.count(i))
n=max(s)
for i in range(0,len(s)):
if s[i]==n:
print(l[i])
break
| Python | zaydzuhri_stack_edu_python |
function num_ini_spaces strng
begin
set ini_spaces = match strng
if ini_spaces
begin
return call end
end
else
begin
return 0
end
end function | def num_ini_spaces(strng):
ini_spaces = ini_spaces_re.match(strng)
if ini_spaces:
return ini_spaces.end()
else:
return 0 | Python | nomic_cornstack_python_v1 |
from abc import ABC , abstractmethod
class VehicleStore extends ABC
begin
decorator abstractmethod
function create_vehicle self vehicle_type
begin
pass
end function
function order_vehicle self vehicle_type
begin
set vehicle = call create_vehicle vehicle_type
return vehicle
end function
end class | from abc import ABC, abstractmethod
class VehicleStore(ABC):
@abstractmethod
def create_vehicle(self, vehicle_type):
pass
def order_vehicle(self, vehicle_type):
vehicle = self.create_vehicle(vehicle_type)
return vehicle
| Python | zaydzuhri_stack_edu_python |
function log_return character deposit
begin
with open string history.txt string a as history
begin
set today = now
write history format string {}, {}, -{} character string format time today string %H:%M:%S deposit
end
end function | def log_return(character, deposit):
with open("history.txt", "a") as history:
today = datetime.now()
history.write('\n{}, {}, -{}'.format(character, today.strftime('%H:%M:%S'), deposit)) | Python | nomic_cornstack_python_v1 |
comment From http://gis.stackexchange.com/questions/115733/converting-json-to-geojson-or-csv
comment Convert json to geojson
function convert_json items
begin
import json
end function
return dumps dict string type string FeatureCollection ; string features list comprehension dict string type string Feature ; string geo... | # From http://gis.stackexchange.com/questions/115733/converting-json-to-geojson-or-csv
# Convert json to geojson
def convert_json(items):
import json
return json.dumps({
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
... | Python | zaydzuhri_stack_edu_python |
function buy_artifact_chest self chests_to_buy=none
begin
if not call open_artifact_store
begin
return error string Can't open Artifact Store.
end
call _drag_store_list_to_the_right
comment Wait for animations
call r_sleep 1
call _drag_store_list_to_the_right
for chest in chests_to_buy
begin
set chest_ui = call get_by_... | def buy_artifact_chest(self, chests_to_buy=None):
if not self.open_artifact_store():
return logger.error("Can't open Artifact Store.")
self._drag_store_list_to_the_right()
r_sleep(1) # Wait for animations
self._drag_store_list_to_the_right()
for chest in chests_to_bu... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env/ python
function sense p colors sensing_color sensor_right
begin
set result = list comprehension list for y in range length p
set pHit = sensor_right
set pMiss = 1 - sensor_right
for i in range length p
begin
for j in range length p at 0
begin
set hit = sensing_color == colors at i at j
append re... | #!/usr/bin/env/ python
def sense(p, colors, sensing_color, sensor_right):
result = [[] for y in range(len(p))]
pHit = sensor_right
pMiss = 1 - sensor_right
for i in range(len(p)):
for j in range(len(p[0])):
hit = (sensing_color == colors[i][j])
result[i].append(flo... | Python | zaydzuhri_stack_edu_python |
if name == string JOSEF
begin
print format string Hello,{name1}! The password is : w@12 name1=name
end
else
begin
print format string Hello AMINA! See you later name1=name
end | if name == "JOSEF":
print("Hello,{name1}! The password is : w@12".format(name1 = name))
else:
print("Hello AMINA! See you later".format(name1 = name))
| Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import pickle , time , re , json , os
from dateutil.parser import parse
set _DRIVER = call Chrome
class credentials
begin
function __init__ self
begin
set username = string
set passwor... | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import pickle, time, re, json, os
from dateutil.parser import parse
_DRIVER = webdriver.Chrome()
class credentials:
def __init__(self):
self.username = ""
... | Python | zaydzuhri_stack_edu_python |
function _vulns_ids_of_host self host
begin
return if expression host then list comprehension call getID for v in call getVulns else list
end function | def _vulns_ids_of_host(self, host):
return [v.getID() for v in host.getVulns()] if host else [] | Python | nomic_cornstack_python_v1 |
function refreshImages self
begin
set time0 = time
set imghashes = dict
if albumID is none
begin
return
end
set response = get requests string https://api.imgur.com/3/album/%s/images % albumID headers=dict string Authorization string Bearer %s % access_token verify=verify
if status_code != 200
begin
raise call ValueEr... | def refreshImages( self ):
time0 = time.time( )
self.imghashes = { }
if self.albumID is None: return
response = requests.get(
'https://api.imgur.com/3/album/%s/images' % self.albumID,
headers = { 'Authorization' : 'Bearer %s' % self.access_token },
ver... | Python | nomic_cornstack_python_v1 |
function suggest_label_name runtime_addr context move_id
begin
assert context is not none
set runtime_addr = call RuntimeAddr runtime_addr
comment if runtime_addr == 0x6a7:
comment print("BBB", hex(context), move_id)
comment Work out the best move_id to use for the label.
comment The basic idea is that if we can't assi... | def suggest_label_name(runtime_addr, context, move_id):
assert context is not None
runtime_addr = memorymanager.RuntimeAddr(runtime_addr)
#if runtime_addr == 0x6a7:
# print("BBB", hex(context), move_id)
# Work out the best move_id to use for the label.
#
# The basic idea is that if we c... | Python | nomic_cornstack_python_v1 |
function clean_df df
begin
set df = df at slice : - 3 :
drop df 10787 inplace=true
reset index df
set good_df = df at df at string Bouncing < 10549.66
set good_df = df
set ix at tuple slice : : string target = 1.0 * copy good_df at string Bouncing
set ix at tuple slice : : string Type = apply good_df at string ... | def clean_df(df):
df = df[:-3]
df.drop(10787, inplace=True)
df.reset_index()
good_df = df[df['Bouncing'] < 10549.66]
good_df = df
good_df.ix[:,'target'] = 1.0 * good_df['Bouncing'].copy()
good_df.ix[:,'Type'] = good_df['Type'].apply(lambda item: 'Downsize' if item == 'downsize' else item)
... | Python | nomic_cornstack_python_v1 |
function identify_movie_genre movie genre_list
begin
set movie_genre = none
for genre in genre_list
begin
set search_terms = split lower genre
if all generator expression term in lower movie for term in search_terms
begin
set movie_genre = genre
break
end
end
return movie_genre
end function
print call identify_movie_ge... | def identify_movie_genre(movie, genre_list):
movie_genre = None
for genre in genre_list:
search_terms = genre.lower().split()
if all(term in movie.lower() for term in search_terms):
movie_genre = genre
break
return movie_genre
print(identify_movie_genre(sampl... | Python | iamtarun_python_18k_alpaca |
function _insert_space self end_index string
begin
set string = string + string * end_index - length string
return string
end function | def _insert_space(self, end_index, string):
string += ' ' * (end_index - len(string))
return string | Python | nomic_cornstack_python_v1 |
function poseTransformPub self timestamp
begin
comment get state information
set state = call getState
comment create the message
set pt_msg = transform
set x = state at 0
set y = state at 1
set quat = call quaternion_from_euler 0.0 0.0 state at 2
set x = quat at 0
set y = quat at 1
set z = quat at 2
set w = quat at 3
... | def poseTransformPub(self, timestamp):
# get state information
state = self.rcs.getState()
# create the message
pt_msg = Transform()
pt_msg.translation.x = state[0]
pt_msg.translation.y = state[1]
quat = quaternion_from_euler(0.0, 0.0, state[2])
pt_msg.r... | Python | nomic_cornstack_python_v1 |
for w in words
begin
print string In the word { upper w } have end=string
for letter in w
begin
if lower letter in string aeiou
begin
print letter end=string
end
end
end | for w in words:
print(f'\nIn the word {w.upper()} have ', end='')
for letter in w:
if letter.lower() in 'aeiou':
print(letter, end=' ') | Python | zaydzuhri_stack_edu_python |
import yfinance as yf
import pandas as pd
from datetime import timedelta
set start = string 2000-01-02
set start_minus_1 = string 2000-01-01
comment Does not get data for the end day
set end = string 2020-03-02
set end_dt = call to_datetime end
function main
begin
set final_list = list
append final_list string volume,... | import yfinance as yf
import pandas as pd
from datetime import timedelta
start = "2000-01-02"
start_minus_1 = "2000-01-01"
end = "2020-03-02" # Does not get data for the end day
end_dt = pd.to_datetime(end)
def main():
final_list = []
final_list.append(
"volume,value_move_on_day,percent_move_on... | Python | zaydzuhri_stack_edu_python |
import argparse
import gym
import numpy as np
from temporal_difference.agents.qlearning_agent import qlearning_agent
from temporal_difference.agents.sarsa_agent import sarsa_agent
from function_approximation.agents.semigradient_q_agent import semigradient_q_agent
from function_approximation.agents.semigradient_sarsa_ag... | import argparse
import gym
import numpy as np
from temporal_difference.agents.qlearning_agent import qlearning_agent
from temporal_difference.agents.sarsa_agent import sarsa_agent
from function_approximation.agents.semigradient_q_agent import semigradient_q_agent
from function_approximation.agents.semigradient_sarsa_ag... | Python | zaydzuhri_stack_edu_python |
function path_prefix self
begin
return get pulumi self string path_prefix
end function | def path_prefix(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "path_prefix") | Python | nomic_cornstack_python_v1 |
comment for else文
comment for fruit in ['apple', 'banana', 'orange']:
comment print(fruit)
comment else:
comment print('I ate all!!')
for i in list 1 2 3 4 5
begin
if i == 4
begin
print string aaa
break
end
print i
end
for else
begin
print string complete!!
end | # for else文
# for fruit in ['apple', 'banana', 'orange']:
# print(fruit)
# else:
# print('I ate all!!')
for i in [1, 2, 3, 4, 5]:
if i == 4:
print('aaa')
break
print(i)
else:
print('complete!!')
| Python | zaydzuhri_stack_edu_python |
import requests
class CTDWrapper extends object
begin
function __init__ self
begin
set url = string https://ctdapi.renci.org/
end function
function gene2chem self gene_curie params=none
begin
set call = format string {0}CTD_chem_gene_ixns_GeneID/{1}/ url gene_curie
set results = get requests call params
return json res... | import requests
class CTDWrapper(object):
def __init__(self):
self.url = 'https://ctdapi.renci.org/'
def gene2chem(self, gene_curie, params=None):
call = '{0}CTD_chem_gene_ixns_GeneID/{1}/'.format(self.url, gene_curie)
results = requests.get(call, params)
return results.json()... | Python | zaydzuhri_stack_edu_python |
import os
from flask import Flask , render_template , request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session , sessionmaker
set app = call Flask __name__
set engine = call create_engine string postgresql://postgres:1234@localhost:5432/postgres
set db = call scoped_session call sessionmak... | import os
from flask import Flask , render_template , request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session , sessionmaker
app = Flask(__name__)
engine = create_engine("postgresql://postgres:1234@localhost:5432/postgres")
db = scoped_session(sessionmaker(bind = engine))
@app.route... | Python | zaydzuhri_stack_edu_python |
import requests
import re
import string
import sqlite3
import os
from bs4 import BeautifulSoup as bs
set dbpath = string C:\Users\resurrexi\Dropbox\databases
set letters = list ascii_uppercase
comment Init sqlite connection
set conn = call connect join path dbpath string mayo.db
set cur = call cursor
function val_check... | import requests
import re
import string
import sqlite3
import os
from bs4 import BeautifulSoup as bs
dbpath = r"C:\Users\resurrexi\Dropbox\databases"
letters = list(string.ascii_uppercase)
# Init sqlite connection
conn = sqlite3.connect(os.path.join(dbpath, 'mayo.db'))
cur = conn.cursor()
def val_check(tbl, col, va... | Python | zaydzuhri_stack_edu_python |
function prime_seive n
begin
set seive = list true * n
set seive at 0 = false
set seive at 1 = false
for i in range 2 integer square root n + 1
begin
set pointer = i * 2
while pointer < n
begin
set seive at pointer = false
set pointer = pointer + i
end
end
set prime = list
for i in range length seive
begin
if seive at... | def prime_seive(n):
seive = [True]*n
seive[0] = False
seive[1] = False
for i in range(2, int(sqrt(n)+1)):
pointer = i*2
while pointer<n:
seive[pointer] = False
pointer += i
prime = []
for i in range(len(seive)):
if seive[i]:
... | Python | nomic_cornstack_python_v1 |
for vowel in list
begin
print vowel
end | for vowel in list:
print(vowel) | Python | zaydzuhri_stack_edu_python |
function from_hex cls color
begin
set color = left strip color string #
if length color not in tuple 3 6
begin
raise call ValueError string Hex color # { color } is not of length 3 or 6
end
if length color == 3
begin
set color = join string list comprehension element * 2 for element in color
end
set tuple red green bl... | def from_hex(cls, color: str) -> TrueColor:
color = color.lstrip("#")
if len(color) not in (3, 6):
raise ValueError(f"Hex color #{color!s} is not of length 3 or 6")
if len(color) == 3:
color = "".join([element * 2 for element in color])
red, green, blue = [
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
if integer input > 6
begin
print string YES
end
else
begin
print string NO
end | #!/usr/bin/env python3
if int(input())>6:
print("YES")
else:
print("NO") | Python | zaydzuhri_stack_edu_python |
function _redirect_url request
begin
string Redirects to referring page, or CAS_REDIRECT_URL if no referrer is set. :param: request RequestObj
set next = get GET REDIRECT_FIELD_NAME
if not next
begin
if CAS_IGNORE_REFERER
begin
set next = CAS_REDIRECT_URL
end
else
begin
set next = get META string HTTP_REFERER CAS_REDIR... | def _redirect_url(request):
"""
Redirects to referring page, or CAS_REDIRECT_URL if no referrer is
set.
:param: request RequestObj
"""
next = request.GET.get(REDIRECT_FIELD_NAME)
if not next:
if settings.CAS_IGNORE_REFERER:
next = settings.CAS_REDIRECT_URL
els... | Python | jtatman_500k |
function serving_input_receiver_fn
begin
set csv_row = call placeholder shape=list none dtype=string
set tuple features _ = call call _make_input_parser with_target=false csv_row
return call ServingInputReceiver features dict string csv_row csv_row
end function | def serving_input_receiver_fn():
csv_row = tf.placeholder(shape=[None], dtype=tf.string)
features, _ = _make_input_parser(with_target=False)(csv_row)
return tf.estimator.export.ServingInputReceiver(features,
{'csv_row': csv_row}) | Python | nomic_cornstack_python_v1 |
class time
begin
function __init__ self hour min
begin
set hour = hour
set min = min
end function
end class
comment 9시 부턴 t분 간격으로 n번 운행하고 m명 이 탈 수 있다.
function plus_min _time t
begin
if min + t // 60 == 0
begin
set min = min + t
return _time
end
else
if min + t // 60 == 1
begin
set min = min + t - 60
set hour = hour + ... | class time:
def __init__(self, hour,min):
self.hour=hour
self.min = min
# 9시 부턴 t분 간격으로 n번 운행하고 m명 이 탈 수 있다.
def plus_min(_time, t):
if( (_time.min+t) //60 ==0 ):
_time.min+= t
return _time;
elif ( (_time.min+t) //60 ==1 ):
_time.min = _time.min+t-60
_time.ho... | Python | zaydzuhri_stack_edu_python |
function test_get_sensors_temperature self
begin
pass
end function | def test_get_sensors_temperature(self):
pass | Python | nomic_cornstack_python_v1 |
function test_no_payment self
begin
set data = valid_payload
del data at string payment_per_answer
call credentials HTTP_AUTHORIZATION=string Bearer EGsnU4Cz3Mx50UCuLrc20mup10s0Gz
set response = post reverse string specialists data=dumps valid_payload content_type=string application/json
assert equal status_code HTTP_4... | def test_no_payment(self):
data = self.valid_payload
del data['payment_per_answer']
self.client.credentials(
HTTP_AUTHORIZATION='Bearer EGsnU4Cz3Mx50UCuLrc20mup10s0Gz')
response = self.client.post(
reverse('specialists'),
data=json.dumps(self.valid_pay... | Python | nomic_cornstack_python_v1 |
function _compute_scores self emissions tags mask
begin
comment print(type(emissions.data[0]))
set tuple batch_size seq_length = shape
set scores = zeros batch_size
set scores = to scores device
comment save first and last tags to be used later
set first_tags = tags at tuple slice : : 0
set last_valid_idx = sum 1 - ... | def _compute_scores(self, emissions, tags, mask):
# print(type(emissions.data[0]))
batch_size, seq_length = tags.shape
scores = torch.zeros(batch_size)
scores = scores.to(self.device)
# save first and last tags to be used later
first_tags = tags[:, 0]
last_valid_i... | Python | nomic_cornstack_python_v1 |
function create_model self model_input vocab_size num_frames is_training=true **unused_params
begin
set iterations = iterations
set random_frames = sample_random_frames
set no_sample = no_sample
set num_frames = call cast call expand_dims num_frames 1 float32
set config = call from_json_file bert_config_file
set config... | def create_model(self, model_input, vocab_size, num_frames, is_training=True, **unused_params):
iterations = FLAGS.iterations
random_frames = FLAGS.sample_random_frames
no_sample = FLAGS.no_sample
num_frames = tf.cast(tf.expand_dims(num_frames, 1), tf.float32)
config = modeling... | Python | nomic_cornstack_python_v1 |
function anagram word1 word2
begin
set word1 = lower word1
set word2 = lower word2
return sorted word1 == sorted word2
end function
set n = integer input string Enter number of queries:
for a in range 0 n
begin
set ele1 = input string Enter first word:
set ele2 = input string Enter Second word:
print call anagram ele1 ... | def anagram(word1, word2):
word1 = word1.lower()
word2 = word2.lower()
return sorted(word1) == sorted(word2)
n = int(input("Enter number of queries: "))
for a in range(0, n):
ele1 = input("Enter first word: ")
ele2 = input("Enter Second word: ")
print(anagram(ele1,ele2))
#sample inp... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.