code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Queue begin function pop self begin pass end function function push self n begin pass end function function size self begin pass end function end class class MinHeap extends Queue begin function __init__ self k begin set _size = 0 set _k = k set _seq = list end function function pop self begin if _size > 0 begin...
class Queue: def pop(self): pass def push(self, n): pass def size(self): pass class MinHeap(Queue): def __init__(self, k): self._size = 0 self._k = k self._seq = [] def pop(self): if self._size > 0: self._seq[0], self._seq[self...
Python
zaydzuhri_stack_edu_python
function monge2test begin set i = 0 set s = string 123456 set m = 1 set n = s while i < m begin set i = i + 1 comment les character de pos -1 en pos -2 set n = n at slice - 2 : : - 2 + n at slice 1 : : 2 print n end end function call monge2test
def monge2test(): i=0 s='123456' m = 1 n=s while i < m : i=i+1 n=n[-2::-2]+n[1::2]#les character de pos -1 en pos -2 print(n) monge2test()
Python
zaydzuhri_stack_edu_python
function internal_server_error exception begin set response = call jsonify dict string status 500 ; string error string internal server error ; string message args at 0 set status_code = 500 return response end function
def internal_server_error(exception): response = jsonify({'status': 500, 'error': 'internal server error', 'message': exception.args[0]}) response.status_code = 500 return response
Python
nomic_cornstack_python_v1
class Node begin function __init__ self value begin set value = value set next = none end function end class function deleteOccurrences head k begin comment Handle case where the first few nodes contain k while head is not none and value == k begin set head = next end set prev = none set curr = head while curr is not n...
class Node: def __init__(self, value): self.value = value self.next = None def deleteOccurrences(head, k): # Handle case where the first few nodes contain k while head is not None and head.value == k: head = head.next prev = None curr = head while curr is not None: ...
Python
greatdarklord_python_dataset
import pygame as pg import sys from os import path from inventory_clem import * import random class Shop begin function __init__ self begin set rect = tuple 900 400 set fond = call Surface rect call fill tuple 0 0 0 255 set name = string shop set inv = call Inventory name set pos_x = pos_x + 500 for case in inventory b...
import pygame as pg import sys from os import path from inventory_clem import * import random class Shop(): def __init__(self): self.rect = (900, 400) self.fond = pg.Surface(self.rect) self.fond.fill((0, 0, 0, 255)) self.name = "shop" self.inv = Inventory(self.name) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jan 16 21:04:02 2020 @author: DELL function isYearLeap year begin comment print(n) comment for i in n: if year % 4 != 0 begin return Fasle end else if year % 100 != 0 begin return false end else if year % 400 != 0 begin return false end else begin return true end end ...
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 21:04:02 2020 @author: DELL """ def isYearLeap(year): #print(n) #for i in n: if year%4 !=0: return Fasle elif year%100!=0: return False elif year%400!=0: return False ...
Python
zaydzuhri_stack_edu_python
function __set_remaining_params self downloaded current_hash begin set __downloaded = downloaded set __db_hash = current_hash end function
def __set_remaining_params(self, downloaded, current_hash): self.__downloaded = downloaded self.__db_hash = current_hash
Python
nomic_cornstack_python_v1
function send_fds sock remote_read remote_write remote_event begin comment We want the transport to handle the handshake. call sendmsg list NEED_HANDSHAKE_MESSAGE list tuple SOL_SOCKET SCM_RIGHTS array string i list remote_read remote_write remote_event end function comment Send over socket. comment Payload is file-des...
def send_fds(sock, remote_read, remote_write, remote_event): sock.sendmsg([NEED_HANDSHAKE_MESSAGE], # We want the transport to handle the handshake. [(socket.SOL_SOCKET, # Send over socket. socket.SCM_RIGHTS, # Payload is file-descriptor array array.array('i', [remo...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string Module of file_storage class import json class FileStorage begin string Define FileStorage class to serialize and deserialize instances to a JSON file and from a JSON file. set __file_path = string file.json set __objects = dict function all self begin string Method to return the dicti...
#!/usr/bin/python3 """ Module of file_storage class """ import json class FileStorage(): """ Define FileStorage class to serialize and deserialize instances to a JSON file and from a JSON file. """ __file_path = "file.json" __objects = {} def all(self): """ ...
Python
zaydzuhri_stack_edu_python
comment c-style strings set l = list string A string B string C string D set i = 0 while i < length l begin print l at i set i = i + 1 end comment for-in or foreach type loop for i in l begin print i end comment enumerate for tuple i x in enumerate l begin print x end comment this also works for enumerate for x in enum...
#c-style strings l = ['A','B','C','D'] i = 0 while i < len(l): print(l[i]) i += 1 #for-in or foreach type loop for i in l: print(i) #enumerate for i, x in enumerate(l): print(x) #this also works for enumerate for x in enumerate(l): print(x[0], x[1]) #return value of enumerate print(enumerate(l)...
Python
zaydzuhri_stack_edu_python
function convolve self X begin if shape at slice 1 : - 1 : < _axes_shape begin set X = call _zero_pad X _axes_shape end set FX = call _fftn X set Fy = call _sum FX * _Fkernel set correlation = call _ifftn Fy return call fftshift correlation axes=_axes end function
def convolve(self, X): if X.shape[1:-1] < self.basis._axes_shape: X = self._zero_pad(X, self.basis._axes_shape) FX = self.basis._fftn(X) Fy = self._sum(FX * self._Fkernel) correlation = self.basis._ifftn(Fy) return np.fft.fftshift(correlation, axes=self.basis._axes)
Python
nomic_cornstack_python_v1
function delete_cluster_annotation h5_path sap_nr cluster_nr annotation_nr label=string latest begin with call SharedH5File h5_path string r+ as file begin if string clustering in file begin set clustering_group = file at string clustering if label in clustering_group begin set algo_group = clustering_group at label se...
def delete_cluster_annotation(h5_path, sap_nr, cluster_nr, annotation_nr, label='latest'): with SharedH5File(h5_path, "r+") as file: if 'clustering' in file: clustering_group = file['clustering'] if label in clustering_group: algo_group = clustering_group[label] ...
Python
nomic_cornstack_python_v1
comment rows for i in range 10 begin comment colum for j in range 10 begin comment +1 for each print i + 1 * j + 1 end=string end print end
#rows for i in range(10): #colum for j in range(10): #+1 for each print((i+1)*(j+1), end="\t") print()
Python
zaydzuhri_stack_edu_python
from concept_list import ConceptList , bound_concept_list from Concept import Symbol decorator call bound_concept_list isWords=false class SymbolList extends ConceptList begin string Represents a list of symbols to quiz set entry_model = Symbol function __repr__ self begin string Return the string representation return...
from .concept_list import ConceptList, bound_concept_list from ..Concept import Symbol @bound_concept_list(isWords=False) class SymbolList(ConceptList): """ Represents a list of symbols to quiz """ entry_model = Symbol def __repr__(self): """ Return the string representation """ ...
Python
zaydzuhri_stack_edu_python
function test_can_retrieve_sample_item self begin set url = reverse string download-sample args=set literal md5 set response = get client url keyword headers assert equal status_code HTTP_200_OK end function
def test_can_retrieve_sample_item(self): url = reverse('download-sample', args={self.sample.md5}) response = self.client.get(url, **self.headers) self.assertEqual(response.status_code, status.HTTP_200_OK)
Python
nomic_cornstack_python_v1
function show self subparser begin call set_defaults func=cmd_show end function
def show(self, subparser): subparser.set_defaults(func=self.cmd_show)
Python
nomic_cornstack_python_v1
comment Author is Duncan, created on June 13 2020 print string python is easy!! comment comments string this is a long comment Data types 1) none type 2) numeric types -- int, float, complex 3) sequences -- str, bytes, bytearray, list, tuple, range 4) sets 5) mappings
#Author is Duncan, created on June 13 2020 print('python is easy!!') #comments """ this is a long comment Data types 1) none type 2) numeric types -- int, float, complex 3) sequences -- str, bytes, bytearray, list, tuple, range 4) sets 5) mappings """
Python
zaydzuhri_stack_edu_python
function _enumerate self dind recurse home begin call _enum_out dict string input string enum.in ; string outfile string enum.out ; string seed if expression ran_seed is none then ran_seed else ran_seed + dind + recurse ; string lattice string lattice.in ; string distribution list string all string nconfigs ; string su...
def _enumerate(self,dind,recurse,home): _enum_out({"input":"enum.in","outfile":"enum.out", "seed":self.ran_seed if self.ran_seed is None else self.ran_seed+dind+recurse, "lattice":"lattice.in","distribution":["all",str(self.nconfigs)], "super":self.keep_s...
Python
nomic_cornstack_python_v1
import pygame import sys import time from math import * set PI_ = 3.1415 set data = list set window = 0 function arch_spiral begin set a = 0.0 set b = 0.05 for coreNb in range 0 64 begin set theta = coreNb / 64.0 * 7.5 * 3.1415 set x = a + b * theta * cos theta set y = a + b * theta * sin theta append data list x y en...
import pygame import sys import time from math import * PI_ = 3.1415 data = [] window = 0 def arch_spiral(): a = 0.0 b = 0.05 for coreNb in range(0, 64): theta = (coreNb / 64.0) * 7.5 * 3.1415 x = (a+b*theta)*cos(theta) y = (a+b*theta)*sin(theta) data.append([x,y]) def homog_disk(): global d...
Python
zaydzuhri_stack_edu_python
import random class Animal begin function __init__ self name begin set name = name set health = 100 end function function sleep self begin set decrease = random integer 5 15 set health = health - decrease print string { name } is sleeping. Health decreased by { decrease } . end function function eat self begin set incr...
import random class Animal: def __init__(self, name): self.name = name self.health = 100 def sleep(self): decrease = random.randint(5, 15) self.health -= decrease print(f"{self.name} is sleeping. Health decreased by {decrease}.") def eat(self): increase = r...
Python
jtatman_500k
function zip_sorted a b begin comment sorted by a set tuple a b = zip *sorted(zip(a, b)) comment sorted by b sorted zip a b key=lambda x -> x at 1 return tuple a b end function import sys set input = readline set I = lambda -> list map int split input set S = lambda -> list map str input set tuple t = call I for t1 i...
def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input())) t,=I() for t1 in range(t): a = I() if sum(a)%9==0: if min(...
Python
jtatman_500k
function disable_forging begin if not get __pillar__ string secret begin return string No secret set in pillar data end else begin set secret = strip get __pillar__ string secret set payload = dict string secret secret return call delegates string disable_forging payload end end function
def disable_forging(): if not __pillar__.get('secret'): return "No secret set in pillar data" else: secret = __pillar__.get('secret').strip() payload = {'secret': secret} return _get_api().delegates('disable_forging', payload)
Python
nomic_cornstack_python_v1
function convert_grammar grammar begin comment Remove all the productions of the type A -> X B C or A -> B a. global RULE_DICT set tuple unit_productions result = tuple list list set res_append = append set index = 0 for rule in grammar begin set new_rules = list if length rule == 2 and rule at 1 at 0 != string ' be...
def convert_grammar(grammar): # Remove all the productions of the type A -> X B C or A -> B a. global RULE_DICT unit_productions, result = [], [] res_append = result.append index = 0 for rule in grammar: new_rules = [] if len(rule) == 2 and rule[1][0] != "'": # Rule...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from Tkinter import * from Application import Application string main file, starts up the whole shabang function main begin set root = call Tk title root string Illumination Project comment Width x Height call geometry string 850x750 set app = call Application root end function
# -*- coding: utf-8 -*- from Tkinter import * from Application import Application """ main file, starts up the whole shabang """ def main(): root = Tk() root.title('Illumination Project') root.geometry('850x750') # Width x Height app = Application(root)
Python
zaydzuhri_stack_edu_python
comment 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. comment Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. function f_def_named ai ab begin if ab != 0 begin set def_val = ai / ab return def_val end else begin return string деление ...
# 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def f_def_named(ai, ab): if ab != 0: def_val = ai / ab return def_val else: return "деление на ноль" ...
Python
zaydzuhri_stack_edu_python
function is_float_array val begin return call is_np_array val and is subclass type floating end function
def is_float_array(val): return is_np_array(val) and issubclass(val.dtype.type, np.floating)
Python
nomic_cornstack_python_v1
comment SESSDSA18课程上机作业 comment 【H5】栈与队列编程作业 comment 说明:为方便批改作业,请同学们在完成作业时注意并遵守下面规则: comment (1)直接在本文件中的函数体内编写代码,每个题目的函数后有调用语句用于检验, comment 上交作业时提交本文件,命名为h5_学号_姓名.py,如h5_1700000012_张三.py comment (2)如果作业中对相关类有明确命名/参数/返回值要求的,请严格按照要求执行 comment (3)有些习题会对代码的编写进行特殊限制,请注意这些限制并遵守 comment (4)作业在4月3日23:59之前提交到教学网 comment by TYY ...
# SESSDSA18课程上机作业 # 【H5】栈与队列编程作业 # # 说明:为方便批改作业,请同学们在完成作业时注意并遵守下面规则: # (1)直接在本文件中的函数体内编写代码,每个题目的函数后有调用语句用于检验, # 上交作业时提交本文件,命名为h5_学号_姓名.py,如h5_1700000012_张三.py # (2)如果作业中对相关类有明确命名/参数/返回值要求的,请严格按照要求执行 # (3)有些习题会对代码的编写进行特殊限制,请注意这些限制并遵守 # (4)作业在4月3日23:59之前提交到教学网 # # # by TYY # 2018.3.21 # ======= 1 中缀表达式求值 ======= # 通过把“...
Python
zaydzuhri_stack_edu_python
function getySize self begin return ySize end function
def getySize(self): return self.ySize
Python
nomic_cornstack_python_v1
function parse_file file_path begin with open file_path as f begin return parse call XmlPropertyListParser f end end function
def parse_file(file_path): with open(file_path) as f: return XmlPropertyListParser().parse(f)
Python
nomic_cornstack_python_v1
import os import requests from bs4 import BeautifulSoup from datetime import datetime function check_dir dir begin if not is directory path dir begin make directory os dir print string create folder: dir end end function comment 定義網址 set base_url = string https://tw.news.yahoo.com set url = string https://tw.news.yahoo...
import os import requests from bs4 import BeautifulSoup from datetime import datetime def check_dir(dir): if not os.path.isdir(dir): os.mkdir(dir) print('create folder:', dir) #定義網址 base_url = "https://tw.news.yahoo.com" url = "https://tw.news.yahoo.com/sports/archive/" ''' 向網址要回網頁原始碼,並透過 Beautif...
Python
zaydzuhri_stack_edu_python
function reasonable self begin set tuple examples_accepted examples_rejected = call test_random_words self REASONABILITY_SAMPLE_SIZE comment (we store these as properties because we'll need them later if we use this rule) set num_accepted = length examples_accepted set num_rejected = length examples_rejected if length ...
def reasonable(self): self.examples_accepted, self.examples_rejected = test_random_words(self, REASONABILITY_SAMPLE_SIZE) # (we store these as properties because we'll need them later if we use this rule) num_accepted = len(self.examples_accepted) num_rejected = len(self.examples_rej...
Python
nomic_cornstack_python_v1
function is_anonymous self begin return false end function
def is_anonymous(self): return False
Python
nomic_cornstack_python_v1
comment [17] Letter Combinations of a Phone Number comment https://leetcode.com/problems/letter-combinations-of-a-phone-number comment Medium (34.04%) comment Total Accepted: comment Total Submissions: comment Testcase Example: '""' comment Given a digit string, return all possible letter combinations that the number c...
# # [17] Letter Combinations of a Phone Number # # https://leetcode.com/problems/letter-combinations-of-a-phone-number # # Medium (34.04%) # Total Accepted: # Total Submissions: # Testcase Example: '""' # # Given a digit string, return all possible letter combinations that the number # could represent....
Python
zaydzuhri_stack_edu_python
comment 身份选择 comment 欢迎信息 欢迎 XXX 进入游戏! comment 请选择身份 : comment 1 : comment 2 : set playerName = string 唐僧 set bossName = string 白骨精 print string 欢迎光临 《 { playerName } 大战 { bossName } 》 游戏 ! set a = input string 请选择你的身份: 1 : { playerName } 2 : { bossName } 请选择 : comment print(a) comment 根据用户选择身份来分配身份(显示不同的信息) if a == st...
# 身份选择 # 欢迎信息 欢迎 XXX 进入游戏! # 请选择身份 : # 1 : # 2 : playerName = "唐僧" bossName = "白骨精" print(f"欢迎光临 《{playerName}大战{bossName}》 游戏 !") a = input(f"请选择你的身份: \n 1 : {playerName} \n 2 : {bossName} \n 请选择 : ") # print(a) # 根据用户选择身份来分配身份(显示不同的信息) if a == '1': print(f"当前已选择用户 --> {playerName} <-- ")...
Python
zaydzuhri_stack_edu_python
function do_buildfile self args begin set usage = string Usage: buildfile [--altsrc=<altsrc>] filename hostname try begin set tuple opts alist = call gnu_getopt split args string list string altsrc= end except any begin print usage return end set altsrc = none for opt in opts begin if opt at 0 == string --altsrc begin...
def do_buildfile(self, args): usage = 'Usage: buildfile [--altsrc=<altsrc>] filename hostname' try: opts, alist = getopt.gnu_getopt(args.split(), '', ['altsrc=']) except: print(usage) return altsrc = None for opt in opts: if opt[0] ...
Python
nomic_cornstack_python_v1
function test_domain self client mocker begin patch string app.helpers.producer.kafka_producer patch string app.helpers.producer.send set headers = dict string X-Api-Key string 123 comment create user set data = dict string email string first@company.com set post_res = post string /api/user/add data=data headers=header...
def test_domain(self, client, mocker): mocker.patch("app.helpers.producer.kafka_producer") mocker.patch("app.helpers.producer.send") headers = {"X-Api-Key": "123"} # create user data = {"email": "first@company.com"} post_res = client.post("/api/user/add", data=data, head...
Python
nomic_cornstack_python_v1
import time function stopwatch begin set start = input string Press enter to start the timer print string the timer has started set begin = time set endtimer = input string Press enter to stop the timer set end = time set elapsed = end - begin set elapsed = integer elapsed print string The time elapsed is elapsed end f...
import time def stopwatch(): start = input("Press enter to start the timer") print("the timer has started") begin = time.time() endtimer = input("Press enter to stop the timer") end = time.time() elapsed = end - begin elapsed = int(elapsed) print("The time elapsed is", elapsed,)
Python
zaydzuhri_stack_edu_python
function from_yaml_map_list cls path_list add_default_src=true begin comment Make sure that all modules from LISA are loaded, so that comment get_subclasses will be accurate. call import_all_submodules lisa set conf_cls_set = set call get_subclasses cls only_leaves=true set conf_list = list for conf_path in path_list ...
def from_yaml_map_list(cls, path_list, add_default_src=True): # Make sure that all modules from LISA are loaded, so that # get_subclasses will be accurate. import_all_submodules(lisa) conf_cls_set = set(get_subclasses(cls, only_leaves=True)) conf_list = [] for conf_path ...
Python
nomic_cornstack_python_v1
comment Алфавит (Все допустимые символы(остальные удаляются)) set alphabet = list string а string б string в string г string д string е string ё string ж string з string и string й string к string л string м string н string о string п string р string с string т string у string ф string х string ц string ч string ш stri...
# Алфавит (Все допустимые символы(остальные удаляются)) alphabet = ['а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ь','э','ю','я','ы', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',...
Python
zaydzuhri_stack_edu_python
set n = integer input set l = list comprehension integer x for x in split input sort l set m = length l // 2 print l at m
n=int(input()) l=[int(x) for x in input().split()] l.sort() m=len(l)//2 print(l[m])
Python
zaydzuhri_stack_edu_python
class UndergroundSystem begin function __init__ self begin comment {(start, end): [times]} set time = dict comment {id: {time: t, station: s}} set check_in = dict end function function checkIn self id stationName t begin set check_in at id = dict string time t ; string station stationName end function function checkO...
class UndergroundSystem: def __init__(self): self.time = {} # {(start, end): [times]} self.check_in = {} # {id: {time: t, station: s}} def checkIn(self, id: int, stationName: str, t: int) -> None: self.check_in[id] = {'time': t, 'station': stationName} def checkOut(self, i...
Python
zaydzuhri_stack_edu_python
function __init__ self track_schedule verbose=false begin set _track_schedule = track_schedule set _verbose = verbose set output = default dictionary dict end function
def __init__(self, track_schedule, verbose=False): self._track_schedule = track_schedule self._verbose = verbose self.output = defaultdict(dict)
Python
nomic_cornstack_python_v1
comment Question 7: Return the number of times that the string “Emma” appears anywhere in the given string function count_emma str begin set substring = string mere set mere_count = count str substring return mere_count end function function count_ema2 str begin set list_words = split str set count_mere = count list_wo...
# Question 7: Return the number of times that the string “Emma” appears anywhere in the given string def count_emma(str): substring = 'mere' mere_count = str.count(substring) return mere_count def count_ema2(str): list_words = str.split() count_mere = list_words.count('mere') return count_mere...
Python
zaydzuhri_stack_edu_python
function entrepreneursIncubated dateFrom=none dateTo=none begin set queryset = objects set output = dict string queryset none ; string fields list ; string values list ; string fieldLabels list comment check for duplicated set queryset = filter stage_type=string IN set projects = filter id__in=values queryset string...
def entrepreneursIncubated(dateFrom=None, dateTo=None): queryset = Stage.objects output = { 'queryset': None, 'fields': [], 'values': [], 'fieldLabels': [], } queryset = queryset.filter(stage_type="IN") # check for duplicated projects = Project.objects.filter(id__in=...
Python
nomic_cornstack_python_v1
import fileinput import itertools set s2i = lambda xs -> list comprehension integer x for x in xs function comb ds begin set result = set for i in call xrange length ds begin set result = result ? set list comprehension sum x for x in call combinations ds i + 1 end return result end function function solve c v ds begin...
import fileinput import itertools s2i = lambda xs : [int(x) for x in xs] def comb(ds): result = set() for i in xrange(len(ds)): result |= set([sum(x) for x in itertools.combinations(ds, i + 1)]) return result def solve(c, v, ds): total = set(range(1, v + 1)) left = total - comb(ds) re...
Python
zaydzuhri_stack_edu_python
for i in range length moves begin if moves at i == string R begin set posx = posx + 1 end else if moves at i == string L begin set posx = posx - 1 end else if moves at i == string U begin set posy = posy + 1 end else if moves at i == string D begin set posy = posy - 1 end if posx == x and posy == y begin print string P...
for i in range(len(moves)): if moves[i] == 'R': posx += 1 elif moves[i] == 'L': posx -= 1 elif moves[i] == 'U': posy += 1 elif moves[i] == 'D': posy -= 1 if posx == x and posy == y: print('Passed') exit() print('Missed')
Python
zaydzuhri_stack_edu_python
function run self begin while true begin set tuple datagram addr = call recvfrom 1024 call _handle_datagram datagram end end function
def run(self): while True: datagram, addr = self.sock.recvfrom(1024) self._handle_datagram(datagram)
Python
nomic_cornstack_python_v1
comment 5 [0, 1, 1, 0, 1, 1, 0, 0] set pipe_numbers = list 5 4 5 set pipe_numbers_clear = list set pipe_numbers set a = length state set res = list set position_loader = list comprehension 0 for i in range a set temp = list comprehension 0 for i in range a for i in pipe_numbers_clear begin set position_loader at i = 1...
# 5 [0, 1, 1, 0, 1, 1, 0, 0] pipe_numbers = [5, 4, 5] pipe_numbers_clear = list(set(pipe_numbers)) a = len(state) res = [] position_loader = [0 for i in range(a)] temp = [0 for i in range(a)] for i in pipe_numbers_clear: position_loader[i] = 1 for r in range(a): sss = 1 for i in range(a): temp...
Python
zaydzuhri_stack_edu_python
function __init__ self **kwargs begin call __init__ self keyword kwargs set length = absolute start - end set pos = tuple start end set pos = round min pos + 2.0 * length / 3.0 set q = 2 * size / length end function
def __init__(self, **kwargs): DistLoad.__init__(self, **kwargs) length = abs(self.start - self.end) pos = (self.start, self.end) self.pos = round(min(pos)) + 2.0 * length / 3.0 self.q = 2 * self.size / length
Python
nomic_cornstack_python_v1
function label_and_sample_proposals self proposals targets begin comment Augment proposals with ground-truth boxes. comment In the case of learned proposals (e.g., RPN), when training starts comment the proposals will be low quality due to random initialization. comment It's possible that none of these initial comment ...
def label_and_sample_proposals( self, proposals: List[Instances], targets: List[Instances] ) -> List[Instances]: # Augment proposals with ground-truth boxes. # In the case of learned proposals (e.g., RPN), when training starts # the proposals will be low quality due to random initial...
Python
nomic_cornstack_python_v1
function test_validate_aws_config begin set cfg = config parser set cfg at CFG_BLAST = dict CFG_BLAST_PROGRAM string blastp ; CFG_BLAST_RESULTS string s3://test-results ; CFG_BLAST_DB string test-db ; CFG_BLAST_QUERY string test-queries set valid_aws_provider = dict CFG_CP_AWS_REGION string correct-Region-1 ; CFG_CP_AW...
def test_validate_aws_config(): cfg = configparser.ConfigParser() cfg[CFG_BLAST] = {CFG_BLAST_PROGRAM: 'blastp', CFG_BLAST_RESULTS: 's3://test-results', CFG_BLAST_DB: 'test-db', CFG_BLAST_QUERY: 'test-queries'} valid_aws_provider = { ...
Python
nomic_cornstack_python_v1
function get_opponent self team begin if is instance team Team begin return if expression team_host == team then team_visitor else team_host end else begin raise call IntegrityError string Only Team model is allowed... end end function
def get_opponent(self, team): if isinstance(team, Team): return self.team_visitor if self.team_host == team else self.team_host else: raise IntegrityError("Only Team model is allowed...")
Python
nomic_cornstack_python_v1
function build target_assigner_config bv_range box_coder begin if not is instance target_assigner_config TargetAssigner begin raise call ValueError string input_reader_config not of type input_reader_pb2.InputReader. end set classes_cfg = class_settings set anchor_generators = list set classes = list set feature_map_...
def build(target_assigner_config, bv_range, box_coder): if not isinstance(target_assigner_config, (target_pb2.TargetAssigner)): raise ValueError('input_reader_config not of type ' 'input_reader_pb2.InputReader.') classes_cfg = target_assigner_config.class_settings anchor_gen...
Python
nomic_cornstack_python_v1
import math import sys import matplotlib.pyplot as plt set filename = argv at 1 set outFileName = argv at 2 class MSMCresult begin string Simple class to read a MSMC result file. Constructor takes filename of MSMC result file function __init__ self filename begin set f = open filename string r set times_left = list se...
import math import sys import matplotlib.pyplot as plt filename = sys.argv[1] outFileName = sys.argv[2] class MSMCresult: """ Simple class to read a MSMC result file. Constructor takes filename of MSMC result file """ def __init__(self, filename): f = open(filename, "r") self.times_le...
Python
zaydzuhri_stack_edu_python
function list self request begin set games = all set game_objects = list set serializer = call GameSerializer games many=true context=dict string request request set game_array = data for od in game_array begin append game_objects dictionary od end for game in game_objects begin set category = filter gamecategory__gam...
def list(self, request): games = Game.objects.all() game_objects = [] serializer = GameSerializer( games, many=True, context={'request': request}) game_array = serializer.data for od in game_array: game_objects.append(dict(od)) for game...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from numpy.random import randn , randint , uniform , multivariate_normal from numpy.linalg import eigvals , eigvalsh , inv from numpy import log , exp , sqrt , zeros , ones , eye , linspace , arange , dot , outer , sign , diag import networkx as nx import timeit from i...
import numpy as np import matplotlib.pyplot as plt from numpy.random import randn, randint, uniform, multivariate_normal from numpy.linalg import eigvals, eigvalsh, inv from numpy import (log, exp, sqrt, zeros, ones, eye, linspace, arange, dot, outer, sign,diag) import networkx as nx import timeit ...
Python
zaydzuhri_stack_edu_python
function send_email self receiver_email subject=string message_body=string attachments=list begin set msg = call get_msg receiver_email subject message_body attachments set text = call as_string try begin set server = call SMTP_SSL server_address 465 call ehlo call login sender_email __password call sendmail sender_e...
def send_email(self, receiver_email, subject="", message_body="", attachments=[]): msg = self.get_msg(receiver_email, subject, message_body, attachments) text = msg.as_string() try: server = smtplib.SMTP_SSL(self.server_address,465) server.ehlo() serv...
Python
nomic_cornstack_python_v1
function seed args begin set seed_flag = seed at 0 if upper seed_flag == string Y begin set seeder = call DataSeeder set db_flag = seed if db_flag begin print string { colors at 6 } { colors at 4 } Data Seeded Successfully { colors at 0 } end else begin print string { colors at 6 } { colors at 5 } Data Seed Failed. Ple...
def seed(args) -> None: seed_flag = args.seed[0] if seed_flag.upper() == 'Y': seeder = DataSeeder() db_flag = seeder.seed() if db_flag: print(f"{colors[6]}{colors[4]}Data Seeded Successfully{colors[0]}") else: print(f"{color...
Python
nomic_cornstack_python_v1
function deallocateAllFlags self pluginName begin pass end function
def deallocateAllFlags(self, pluginName): pass
Python
nomic_cornstack_python_v1
function get_transaction_details transaction_hash coin_symbol=string btc begin return call get_transaction_details transaction_hash coin_symbol=coin_symbol end function
def get_transaction_details(transaction_hash, coin_symbol="btc"): return blockcypher.get_transaction_details( transaction_hash, coin_symbol=coin_symbol )
Python
nomic_cornstack_python_v1
from copy import copy from day22_1 import decks_from_file , play_game , score_deck set game_number = 0 function play_recursive_game d1 d2 begin global game_number set game_number = game_number + 1 set this_game_number = game_number print string === Game { this_game_number } === set played_rounds = set set turn = 0 whil...
from copy import copy from day22_1 import decks_from_file, play_game, score_deck game_number = 0 def play_recursive_game(d1, d2): global game_number game_number += 1 this_game_number = game_number print(f'=== Game {this_game_number} ===') played_rounds = set() turn = 0 while d1 and d2: ...
Python
zaydzuhri_stack_edu_python
function event_on_reply_to_call_trigger self diagnostics=none context=none begin raise call NotImplementedError string operation event_on_reply_to_call_trigger(...) not yet implemented end function
def event_on_reply_to_call_trigger(self, diagnostics=None, context=None): raise NotImplementedError( 'operation event_on_reply_to_call_trigger(...) not yet implemented')
Python
nomic_cornstack_python_v1
function filesizeformat bytes sep=string begin string Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 B, 2.3 GB etc). Grabbed from Django (http://www.djangoproject.com), slightly modified. :param bytes: size in bytes (as integer) :param sep: string separator between number and abbreviation ...
def filesizeformat(bytes, sep=' '): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 B, 2.3 GB etc). Grabbed from Django (http://www.djangoproject.com), slightly modified. :param bytes: size in bytes (as integer) :param sep: string separator between number and a...
Python
zaydzuhri_stack_edu_python
function get_conn self begin if postgres_pool is none begin raise exception string Cannot get db connection before connecting to database end set conn : RealDictConnection = call getconn if conn is none begin raise exception string Failed to get connection from Postgres connection pool end yield conn call putconn conn ...
def get_conn(self) -> Iterator[RealDictConnection]: if self.postgres_pool is None: raise Exception( "Cannot get db connection before connecting to database") conn: RealDictConnection = self.postgres_pool.getconn() if conn is None: raise Exception( ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3.8 import random import requests import socket import base64 import traceback from bs4 import BeautifulSoup function get_flight_state_bytes token x y flight_id label license finished begin if length flight_id != 16 or length label != 15 or length token != 32 or length license != 32 begin ra...
#!/usr/bin/env python3.8 import random import requests import socket import base64 import traceback from bs4 import BeautifulSoup def get_flight_state_bytes(token: str, x: int, y: int, flight_id: bytes, label: str, license: str, finished: bool) -> bytes: if le...
Python
zaydzuhri_stack_edu_python
async function prefix ctx begin if invoked_subcommand is none begin await call say string Usage: j.prefix [user/server] [subcommand] [parameters]. + string The following subcommands are available: get, set. end end function
async def prefix(ctx): if ctx.invoked_subcommand is None: await bot.say( "Usage: j.prefix [user/server] [subcommand] [parameters]." + "\nThe following subcommands are available: get, set.")
Python
nomic_cornstack_python_v1
import networkx as nx import numpy as np import pandas as pd from tqdm import tqdm from networkx.algorithms.link_analysis.pagerank_alg import pagerank , pagerank_numpy function load_dataset csv_file begin set df_edges = read csv csv_file set G = call Graph for row in call tqdm call iterrows begin set row = row at 1 cal...
import networkx as nx import numpy as np import pandas as pd from tqdm import tqdm from networkx.algorithms.link_analysis.pagerank_alg import pagerank, pagerank_numpy def load_dataset(csv_file): df_edges = pd.read_csv(csv_file) G = nx.Graph() for row in tqdm(df_edges.iterrows()): row = row[1] ...
Python
zaydzuhri_stack_edu_python
import HorarioFinal import Datos class Poblacion begin function __init__ self tamPob=0 datos=call Datos begin set tamPob = tamPob set datos = datos set listaHorariosFinales = list for i in range 0 tamPob begin append listaHorariosFinales call inicializarHF end end function function ordenarFitness self begin sort lista...
import HorarioFinal import Datos class Poblacion: def __init__(self, tamPob = 0, datos = Datos.Datos()): self.tamPob = tamPob self.datos = datos self.listaHorariosFinales = [] for i in range(0, self.tamPob): self.listaHorariosFinales.append(HorarioFinal.HorarioFinal(datos = self.datos).inicializarHF()) ...
Python
zaydzuhri_stack_edu_python
for i in range M begin set K = integer input if K >= card at turn begin set turn = ? turn end end print card at turn
for i in range(M): K = int(input()) if K >= card[turn]: turn = ~turn print(card[turn])
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import getopt import sys from coapthon.server.coap import CoAP from resources import BasicResource , BasicTemperatureResource , TemperatureResource , Hello , DoorResource , HelloPost , AdvancedResource class CoAPServer extends CoAP begin function __init__ self host port multicast=false begi...
#!/usr/bin/env python import getopt import sys from coapthon.server.coap import CoAP from resources import BasicResource, BasicTemperatureResource, TemperatureResource, Hello, DoorResource, \ HelloPost, AdvancedResource class CoAPServer(CoAP): def __init__(self, host, port, multicast=False): CoAP.__i...
Python
zaydzuhri_stack_edu_python
function ping begin set user_input = loads decode data string UTF-8 if string nodes not in user_input begin set ret_obj = dict string success false ; string message string Missing nodes parameter in post data. set ret = dumps ret_obj indent=2 return tuple ret 200 dict string Content-length length ret ; string Content-t...
def ping(): user_input = json.loads(request.data.decode('UTF-8')) if 'nodes' not in user_input: ret_obj = {'success': False, "message": "Missing nodes parameter in post data."} ret = json.dumps(ret_obj, indent=2) return (ret, 200, {'Content-length': len(ret), 'Content-type': 'application...
Python
nomic_cornstack_python_v1
function LotkaVolterra_Dynamics self begin comment (nF, nR) set LV_c = call toConceptual state set LV_c = call mul 1 - LV_c + call mm LV_c set LV_s = call toNeural LV_c return tuple LV_c LV_s end function
def LotkaVolterra_Dynamics(self): LV_c = self.toConceptual(self.state) # (nF, nR) LV_c = LV_c.mul((1 - LV_c) + self.LV_inhM.mm(LV_c)) LV_s = self.toNeural(LV_c) return LV_c, LV_s
Python
nomic_cornstack_python_v1
function _receive_check self length begin set data = call _receive length return data at slice : - 1 : end function
def _receive_check(self, length): data = self._receive(length) return data[:-1]
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.support.ui import Select import math import time set link = string http://suninjuly.github.io/selects1.html try begin set browser = call Chrome string D:/Courses/drivers/chromedriver.exe get browser link set x = text set y = text set num1 = integer x set num2 = int...
from selenium import webdriver from selenium.webdriver.support.ui import Select import math import time link = "http://suninjuly.github.io/selects1.html" try: browser = webdriver.Chrome("D:/Courses/drivers/chromedriver.exe") browser.get(link) x = browser.find_element_by_id("num1").text y = browser.fi...
Python
zaydzuhri_stack_edu_python
function align_spectral_cube spectral_cube oversampling=10 smooth_size=1 ref_trace=string median compensate=true begin comment Define reference if not given, if ref_trace is none begin comment This is first observation, first trace (Qp), flux, and the whole vector set ref_trace = spectral_cube at tuple 0 0 1 slice : ...
def align_spectral_cube(spectral_cube, oversampling = 10, smooth_size = 1, ref_trace = 'median', compensate=True): #Define reference if not given, if ref_trace is None: ref_trace = spectral_cube[0,0,1,:] #This is first observation, first trace (Qp), flux, and the whole vector elif type(ref_trace) ==...
Python
nomic_cornstack_python_v1
function tiling_not_inf self begin return call from_string string 1234_2341 end function
def tiling_not_inf(self): return Tiling.from_string("1234_2341")
Python
nomic_cornstack_python_v1
function serialnumber self begin set r = call _send_cmd b'X' set _serialnumber = r at slice 1 : : return _serialnumber end function
def serialnumber(self): r = self._send_cmd(b'X') self._serialnumber = r[1:] return self._serialnumber
Python
nomic_cornstack_python_v1
function unpack endian fmt data begin string Unpack a byte string to the given format. If the byte string contains more bytes than required for the given format, the function returns a tuple of values. if fmt == string s begin comment read data as an array of chars set val = call unpack join string list endian string ...
def unpack(endian, fmt, data): """Unpack a byte string to the given format. If the byte string contains more bytes than required for the given format, the function returns a tuple of values. """ if fmt == 's': # read data as an array of chars val = struct.unpack(''.join([endian, str(...
Python
jtatman_500k
function save_tree save_path=string { PROJECT_DIR } /outputs/tree/tree.txt begin call make_dir_if_not_exist directory name path save_path call save2file save_path end function
def save_tree(save_path=f"{PROJECT_DIR}/outputs/tree/tree.txt"): make_dir_if_not_exist(os.path.dirname(save_path)) tree.save2file(save_path)
Python
nomic_cornstack_python_v1
function handle self *args **options begin set base_url_lut = dict string local string http://localhost:8000/api ; string staging string https://staging.artofvisuals.com/api ; string production string https://data.artofvisuals.com/api set profile_method_lut = dict string classification run_classification_profile ; stri...
def handle(self, *args, **options): base_url_lut = { "local": "http://localhost:8000/api", "staging": "https://staging.artofvisuals.com/api", "production": "https://data.artofvisuals.com/api" } profile_method_lut = { "classification": run_classif...
Python
nomic_cornstack_python_v1
comment EXAMPLE 002 comment basic program to compute factorial comment compute factorial recursively function factorial n begin if n == 0 begin return 1 end else begin return n * call factorial n - 1 end end function
# EXAMPLE 002 # basic program to compute factorial # # compute factorial recursively # def factorial(n): if(n == 0): return 1; else: return n*factorial(n-1)
Python
zaydzuhri_stack_edu_python
function get_short_name self begin return name end function
def get_short_name(self): return self.name
Python
nomic_cornstack_python_v1
comment Function Decorator comment Example 1 function decor fun begin function inner begin print string Inner Function: Before enhancing Function call fun print string Inner Function: After enhancing Function end function return inner end function function num begin print string We will use this function print string a...
# Function Decorator # Example 1 def decor(fun): def inner(): print("Inner Function: Before enhancing Function") fun() print("Inner Function: After enhancing Function") return inner def num(): print("We will use this function") print("and will enhance this in decorator") result_fun = decor(nu...
Python
zaydzuhri_stack_edu_python
function process_incomplete_checkpoints self directories begin call send_json list string keys set checkpointed_files = list call recv_json set n_checkpointed = length checkpointed_files info string Processing %d incomplete checkpoints. % n_checkpointed for f in checkpointed_files begin info string Sending process requ...
def process_incomplete_checkpoints(self, directories): self.checkpoint_socket.send_json(['keys']) checkpointed_files = list(self.checkpoint_socket.recv_json()) n_checkpointed = len(checkpointed_files) logging.info('Processing %d incomplete checkpoints.' % n_checkpointed) for f in...
Python
nomic_cornstack_python_v1
function get_weights self begin return deep copy kernel_layers end function
def get_weights(self): return copy.deepcopy(self.kernel_layers)
Python
nomic_cornstack_python_v1
function y self begin comment update the top phase chemical formula and density set tuple newtopchem newtopden = call updatePhaseInfo topchem topden string Top comment update the bottom phase chemical formula and density set tuple newbotchem newbotden = call updatePhaseInfo botchem botden string Bottom comment wave vec...
def y(self): newtopchem, newtopden = self.updatePhaseInfo(self.topchem, self.topden, 'Top') # update the top phase chemical formula and density newbotchem, newbotden = self.updatePhaseInfo(self.botchem, self.botden, 'Bottom') # update the bottom phase chemical formula and density k0 = 2 * np....
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python from sys import stdin function solve num_rows num_cols lawn begin set rows = lawn set cols = list comprehension list comprehension lawn at r at c for r in call xrange num_rows for c in call xrange num_cols set row_max = list comprehension max row for row in rows set col_max = list comprehe...
#! /usr/bin/env python from sys import stdin def solve(num_rows, num_cols, lawn): rows = lawn cols = [[lawn[r][c] for r in xrange(num_rows)] for c in xrange(num_cols)] row_max = [max(row) for row in rows] col_max = [max(col) for col in cols] for i in xrange(num_rows): for j in xrange(nu...
Python
zaydzuhri_stack_edu_python
function change_key_name dict_ key with_ begin set dictionnary = copy dict_ if key in dictionnary begin set dictionnary at with_ = dictionnary at key del dictionnary at key end return dictionnary end function
def change_key_name(dict_, key, with_): dictionnary = dict_.copy() if key in dictionnary: dictionnary[with_] = dictionnary[key] del dictionnary[key] return dictionnary
Python
nomic_cornstack_python_v1
function test_class_block_usage assert_errors parse_ast_tree class_statement context variable_name default_options begin set code = format context format class_statement variable_name format string print({0}) variable_name set tree = call parse_ast_tree code set visitor = call BlockVariableVisitor default_options tree=...
def test_class_block_usage( assert_errors, parse_ast_tree, class_statement, context, variable_name, default_options, ): code = context.format( class_statement.format(variable_name), 'print({0})'.format(variable_name), ) tree = parse_ast_tree(code) visitor = Block...
Python
nomic_cornstack_python_v1
comment 2、给出一个无序的列表(至少包含一个元素),求出其最大连续子列表的和? comment 举例:输入[−2,1,−3,4,−1,2,1,−5,4],那么连续子列表[4,−1,2,1]有最大值,相加是 6 function max_sub_array_sum array begin set length = length array set max_so_far = array at 0 set current_max = array at 0 for i in range 1 length begin set current_max = max array at i current_max + array at i s...
# 2、给出一个无序的列表(至少包含一个元素),求出其最大连续子列表的和? # 举例:输入[−2,1,−3,4,−1,2,1,−5,4],那么连续子列表[4,−1,2,1]有最大值,相加是 6 def max_sub_array_sum(array): length = len(array) max_so_far = array[0] current_max = array[0] for i in range(1, length): current_max = max(array[i], current_max + array[i]) max_so_far = m...
Python
zaydzuhri_stack_edu_python
function freeze_ctc_prefix_beam_decoder encoder_out ctc_final_layer beam_size blank_id begin set batch_size = shape at 0 comment For CTC prefix beam search, we only support batch_size=1 comment Let's assume B = batch_size and N = beam_size comment 1. Encoder forward and get CTC score set maxlen = shape at 1 comment (1,...
def freeze_ctc_prefix_beam_decoder( encoder_out: tf.Tensor, ctc_final_layer: tf.keras.layers.Dense, beam_size: int, blank_id: int, ) -> Tuple[List[Tuple[tuple, float]], tf.Tensor]: batch_size = encoder_out.shape[0] # For CTC prefix beam search, we only support batch_size=1 # ...
Python
nomic_cornstack_python_v1
function pc_work_time_var self begin return call hdlc_deframer_sptr_pc_work_time_var self end function
def pc_work_time_var(self): return _spacegrant_swig.hdlc_deframer_sptr_pc_work_time_var(self)
Python
nomic_cornstack_python_v1
import pygame import os import math comment import Ball set tuple WIDTH HEIGHT = tuple 1200 700 set WIN = call set_mode tuple WIDTH HEIGHT call set_caption string FIRST Physics! set WHITE = tuple 255 255 255 set FPS = 60 set GRAVITY = 1 set ACCELERATION = call Vector2 0 GRAVITY set BALL_ONE_IMG = load image join path s...
import pygame import os import math #import Ball WIDTH, HEIGHT = 1200, 700 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("FIRST Physics!") WHITE = (255, 255, 255) FPS = 60 GRAVITY = 1 ACCELERATION = pygame.math.Vector2(0, GRAVITY) BALL_ONE_IMG = pygame.image.load(os.path.join('Assets'...
Python
zaydzuhri_stack_edu_python
comment This file contains single class with constants used in the project. class Config begin comment train / valid / test set train_ = 0.75 set validation = 0.0 set test = 0.25 comment training parameters set batch_size = 50 set char_embedding_size = 100 set word_embedding_size = 100 set num_epochs = 200 comment drop...
# This file contains single class with constants used in the project. class Config(): # train / valid / test train_= 0.75 validation = 0.0 test = 0.25 # training parameters batch_size = 50 char_embedding_size = 100 word_embedding_size = 100 num_epochs = 200 keep_prob = 0.5 # dro...
Python
zaydzuhri_stack_edu_python
function visualize **images begin set n = length images figure figsize=tuple 16 5 for tuple i tuple name image in enumerate items images begin subplot 1 n i + 1 call xticks list call yticks list title plt title join string split name string _ image show image end show end function
def visualize(**images): n = len(images) plt.figure(figsize=(16, 5)) for i, (name, image) in enumerate(images.items()): plt.subplot(1, n, i + 1) plt.xticks([]) plt.yticks([]) plt.title(' '.join(name.split('_')).title()) plt.imshow(image) plt.show()
Python
nomic_cornstack_python_v1
function calculate_mse nn x y begin comment TODO set mse = call mean_squared_error y predict nn x return mse end function
def calculate_mse(nn, x, y): ## TODO mse = mean_squared_error(y, nn.predict(x)) return mse
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np comment validasi set np = string jhonsmith set yo = 20 set is_new_pasien = true print string Nama Pasien: np string age: yo string pasien baru: is_new_pasien comment input sederhana set name = input string siapa lu? print name + string Hai set umur = input string tahun berapa lu l...
import pandas as pd import numpy as np #validasi np="jhonsmith" yo=20 is_new_pasien=True print("Nama Pasien: \n",np,"age: \n",yo,"pasien baru: \n",is_new_pasien) #input sederhana name = input("siapa lu?") print(name+ "Hai") umur=input("tahun berapa lu lahir? ") age = 2020 - int(umur) print (age) #i...
Python
zaydzuhri_stack_edu_python
function showCatalogHome begin set session = call dbconnect set categories = all set latest_items = call order_by call desc id at slice 0 : 10 : close session return call render_template string catalog_homepage.html categories=categories latest_items=latest_items end function
def showCatalogHome(): session = dbconnect() categories = session.query(Category).all() latest_items = session.query(Item).order_by(desc(Item.id))[0:10] session.close() return render_template('catalog_homepage.html', categories=categories, latest...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from keras.preprocessing.sequence import skipgrams , make_sampling_table from keras.layers.core import TimeDistributedDense , Dense , Dropout , Activation from keras.layers.embeddings import Embedding from keras.layers.recurrent import SimpleRNN from keras.models import Sequential import nu...
#!/usr/bin/env python from keras.preprocessing.sequence import skipgrams, make_sampling_table from keras.layers.core import TimeDistributedDense, Dense, Dropout, Activation from keras.layers.embeddings import Embedding from keras.layers.recurrent import SimpleRNN from keras.models import Sequential import numpy as np ...
Python
zaydzuhri_stack_edu_python
function edad nu begin set result = 2018 - nu return result end function print string su edad es: call edad nu
def edad(nu): result=2018-nu return result print("su edad es:",edad(nu))
Python
zaydzuhri_stack_edu_python