code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function print_items items begin for item in items begin print item end end function
def print_items(items): for item in items: print (item)
Python
nomic_cornstack_python_v1
function get_counters self id begin set tbl = state_machine_table set res = execute db select list state_counters state_machine_id_column == id return loads call singleton res or string {} end function
def get_counters(self, id): tbl = self.state_machine_table res = self.db.execute(select([tbl.c.state_counters], self.state_machine_id_column==id)) return json.loads(self.singleton(res) or '{}')
Python
nomic_cornstack_python_v1
function check m begin return channel == channel_mentions at 0 and author == author end function
def check(m): return m.channel == ctx.message.channel_mentions[0] and m.author == ctx.author
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter.ttk import * import pandas as pd from pandastable import Table from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import numpy as np comment The main window with a resolution of 700x600 set master = call Tk call geometry string 700x600 func...
from tkinter import * from tkinter.ttk import * import pandas as pd from pandastable import Table from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import numpy as np #The main window with a resolution of 700x600 master = Tk() master.geometry("700x600") def op...
Python
zaydzuhri_stack_edu_python
function test_user_fk_add_popup self begin set response = get client reverse string admin:admin_views_album_add call assertContains response reverse string admin:auth_user_add call assertContains response string class="related-widget-wrapper-link add-related" id="add_id_owner" set response = get client reverse string a...
def test_user_fk_add_popup(self): response = self.client.get(reverse('admin:admin_views_album_add')) self.assertContains(response, reverse('admin:auth_user_add')) self.assertContains(response, 'class="related-widget-wrapper-link add-related" id="add_id_owner"') response = self.client.get...
Python
nomic_cornstack_python_v1
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
function dequote_yaml_string input begin comment Double-quoted? set result = match string ^\s*"(.*) input if result begin set escape = false set in_suffix = false set hexleft = 0 set output = string set suffix = string for character in call group 1 begin if in_suffix begin set suffix = suffix + character continue end...
def dequote_yaml_string(input): # Double-quoted? result = re.match(r'^\s*"(.*)', input) if result: escape = False in_suffix = False hexleft = 0 output = '' suffix = '' for character in result.group(1): if in_suffix: suffix += charac...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from hex.player import Player from hex.game import Game from convert_to_game_state import row_to_features import random import numpy as np class ModelPlayer extends Player begin function __init__ self hex_model relative=false begin string Create a model based player, with a given model set ...
#!/usr/bin/env python from hex.player import Player from hex.game import Game from convert_to_game_state import row_to_features import random import numpy as np class ModelPlayer(Player): def __init__(self, hex_model, relative=False): """Create a model based player, with a given model""" se...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import pandas as pd import numpy as np comment ### 类别数据 comment ![tupian](img/categorical_methods.png) comment #### 类别数据基础 comment 类别数据的元素是不可变类型 comment In[3]: set fruits = list string apple string orange string apple string orange * 2 set N = length fru...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np # ### 类别数据 # ![tupian](img/categorical_methods.png) # #### 类别数据基础 # 类别数据的元素是不可变类型 # In[3]: fruits = ['apple', 'orange', 'apple', 'orange'] * 2 N = len(fruits) df = pd.DataFrame({ 'fruit':fruits, 'basket_id': np.arang...
Python
zaydzuhri_stack_edu_python
import sys set MOD = 10 ^ 9 + 7 set tuple n k *ab = map int split read stdin set ab = zip *[iter(ab)] * 2 set g = list comprehension list for _ in range n + 1 for tuple a b in ab begin append g at a b append g at b a end function main begin set stack = list 1 set coloring = list none * n + 1 set coloring at 1 = k set ...
import sys MOD = 10**9 + 7 n, k, *ab = map(int, sys.stdin.read().split()) ab = zip(*[iter(ab)] * 2) g = [[] for _ in range(n+1)] for a, b in ab: g[a].append(b) g[b].append(a) def main(): stack = [1] coloring = [None] * (n + 1); coloring[1] = k par = [None] * (n + 1) while stack: u = s...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun May 12 14:07:51 2019 @author: snama import random import itertools function poker hands begin string Returns a list of winning hands return call allmax hands key=hand_rank end function function allmax iterable key=none begin string Return a list of all winning hands. ...
# -*- coding: utf-8 -*- """ Created on Sun May 12 14:07:51 2019 @author: snama """ import random import itertools def poker(hands): "Returns a list of winning hands" return allmax(hands,key=hand_rank) def allmax(iterable,key=None): "Return a list of all winning hands. Accounts for ties" ...
Python
zaydzuhri_stack_edu_python
function replace self name newobject begin if name in self begin del self at name end set self at name = newobject end function
def replace(self, name, newobject): if name in self: del self[name] self[name] = newobject
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Jul 8 22:03:32 2018 @author: rajar class Queue2 begin comment Constructor function __init__ self begin set queue = list set maxSize = 8 set head = 0 set tail = 0 end function comment Adding elements function enqueue self data begin comment Checking if the queue is ful...
# -*- coding: utf-8 -*- """ Created on Sun Jul 8 22:03:32 2018 @author: rajar """ class Queue2: # Constructor def __init__(self): self.queue = list() self.maxSize = 8 self.head = 0 self.tail = 0 # Adding elements def enqueue(self, data): ...
Python
zaydzuhri_stack_edu_python
import random from collections import Counter function get_random_odd_occurrence string max_occurrences begin comment Count the occurrences of each uppercase letter in the string set occurrences = counter filter isupper string comment Filter the letters that occur an odd number of times up to the maximum occurrences se...
import random from collections import Counter def get_random_odd_occurrence(string, max_occurrences): # Count the occurrences of each uppercase letter in the string occurrences = Counter(filter(str.isupper, string)) # Filter the letters that occur an odd number of times up to the maximum occurrences ...
Python
jtatman_500k
import sys set input = readline set N = integer input set Max_DP = list map int split input set Min_DP = list for d in Max_DP begin append Min_DP d end for _ in range N - 1 begin set tuple a b c = map int split input set tuple Max_DP at 0 Max_DP at 1 Max_DP at 2 = tuple max Max_DP at 0 Max_DP at 1 + a max Max_DP at 0 ...
import sys input = sys.stdin.readline N = int(input()) Max_DP = list(map(int,input().split())) Min_DP = [] for d in Max_DP: Min_DP.append(d) for _ in range(N-1): a,b,c = map(int,input().split()) Max_DP[0],Max_DP[1],Max_DP[2] = max(Max_DP[0],Max_DP[1])+a,max(Max_DP[0],Max_DP[1],Max_DP[2])+b,max(Max_...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution begin function tree2str self t begin set stack = list function fun node begin if node begin append stack string val if left begin appe...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def tree2str(self, t: TreeNode) -> str: stack = [] def fun(node): if node: stack.append(str(n...
Python
zaydzuhri_stack_edu_python
function find_in_path filename begin comment Force cwd to be searched regardless of envvars set paths = list string . + split get environ string PYPATH string pathsep + split get environ string PATH string pathsep + path for path in paths begin set path = call unicode path try begin set files = list directory path end ...
def find_in_path(filename): paths = (["."] # Force cwd to be searched regardless of envvars + os.environ.get("PYPATH", "").split(os.pathsep) + os.environ.get("PATH", "").split(os.pathsep) + sys.path) for path in paths: path = unicode(path) try: f...
Python
nomic_cornstack_python_v1
function render_attr key value attr_format=string {key}="{value}" begin if not key or string in key begin raise call InvalidAttribute format string Invalid name "{}" key end if value begin if type value is RawNode begin set value = string value end else begin set value = call escape string value end return format attr...
def render_attr(key, value, attr_format='{key}="{value}"'): if not key or ' ' in key: raise InvalidAttribute('Invalid name "{}"'.format(key)) if value: if type(value) is RawNode: value = str(value) else: value = html.escape(str(value)) return attr_forma...
Python
nomic_cornstack_python_v1
for x in list string Morning string Afternoon string Evening string Night begin print string Good x end
for x in ['Morning', 'Afternoon', 'Evening', 'Night']: print('Good', x)
Python
zaydzuhri_stack_edu_python
async function test_device_registry_config_entry_1 hass target_domain begin set device_registry = call async_get hass set entity_registry = call async_get hass set switch_config_entry = call MockConfigEntry set device_entry = call async_get_or_create config_entry_id=entry_id connections=set literal tuple CONNECTION_NET...
async def test_device_registry_config_entry_1(hass: HomeAssistant, target_domain): device_registry = dr.async_get(hass) entity_registry = er.async_get(hass) switch_config_entry = MockConfigEntry() device_entry = device_registry.async_get_or_create( config_entry_id=switch_config_entry.entry_id,...
Python
nomic_cornstack_python_v1
import preprocess from preprocess import Process import sklearn from sklearn import neural_network import pandas as pd import numpy as np import tensorflow as tf set model = sequential list flatten layers input_shape=tuple 2 79 dense 128 activation=string relu dense 96 activation=string relu dense 64 activation=string ...
import preprocess from preprocess import Process import sklearn from sklearn import neural_network import pandas as pd import numpy as np import tensorflow as tf model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(2, 79)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Den...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys from collections import deque if length argv != 4 begin print string linepoem2cards beforelen afterlen poemfile exit 1 end set beforelen = integer argv at 1 set afterlen = integer argv at 2 set f = open argv at 3 string r set lines = list for l in f begin append lines strip l e...
#!/usr/bin/env python3 import sys from collections import deque if len(sys.argv)!=4: print('linepoem2cards beforelen afterlen poemfile') exit(1) beforelen=int(sys.argv[1]) afterlen=int(sys.argv[2]) f=open(sys.argv[3], 'r') lines=[] for l in f: lines.append(l.strip()) ll=len(lines) for i in range(0, ll): pri...
Python
zaydzuhri_stack_edu_python
comment Implementação machine chatbot in python import random comment from speech import * from pip._vendor.distlib.compat import raw_input set CONVERSING = true set memory = list set greetings = list string ola string olar string inicio string start set questions = list string Como você está? string Esta bem? string ...
#Implementação machine chatbot in python import random # from speech import * from pip._vendor.distlib.compat import raw_input CONVERSING = True memory = [] greetings = ['ola', 'olar', 'inicio', 'start'] questions = ['Como você está?', 'Esta bem?', 'Está tudo bem?'] responses = ['Ok!', 'Estou bem'] validations = ['Si...
Python
zaydzuhri_stack_edu_python
from subprocess import * call tuple string pypy3 string -c string import sys def input(): return sys.stdin.readline().rstrip() # 単位元とseg_funcを設定する from fractions import gcd class seg(): def __init__(self,init_val): self.n=len(init_val) self.ide_ele=0 #単位元 self.num=2**(self.n-1).bit_length() #n以上の最小の2のべき乗 self.seg=[self...
from subprocess import * call(('pypy3','-c',""" import sys def input(): return sys.stdin.readline().rstrip() # 単位元とseg_funcを設定する from fractions import gcd class seg(): def __init__(self,init_val): self.n=len(init_val) self.ide_ele=0 #単位元 self.num=2**(self.n-1).bit_length() #n以上の最小の2のべき乗 ...
Python
zaydzuhri_stack_edu_python
set x = integer input print if expression x then 0 else 1
x = int(input()) print(0 if x else 1)
Python
zaydzuhri_stack_edu_python
function consume_reservation_type self begin return get pulumi self string consume_reservation_type end function
def consume_reservation_type(self) -> Optional[pulumi.Input['ReservationAffinityConsumeReservationType']]: return pulumi.get(self, "consume_reservation_type")
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- import sys import sender set argc = length argv if argc < 3 begin print string usage: + __file__ + string 79161111111 your message exit - 1 end set phone = argv at 1 if phone at 0 == string + begin set phone = phone at slice 1 : : end if not is digit phone begin...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import sender argc = len(sys.argv) if argc < 3: print('usage: ' + __file__ + " 79161111111 your message") sys.exit(-1) phone = sys.argv[1] if phone[0] == "+": phone = phone[1:] if not phone.isdigit(): print("Invalid phone number") sys.exit(-1) me...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import torch import torch.nn as nn from torch.nn.functional import F class HNetLoss extends loss begin string HNet Loss function __init__ self gt_pts transformation_coefficient name usegpu=true begin string :param gt_pts: [x, y, 1] :param transformation_coeffcient: [[a, b, c], [0, d, e], [...
#!/usr/bin/env python3 import torch import torch.nn as nn from torch.nn.functional import F class HNetLoss(nn.modules.loss): """ HNet Loss """ def __init__( self, gt_pts, transformation_coefficient, name, usegpu=True ) -> None: """ :param g...
Python
zaydzuhri_stack_edu_python
string 继承: 创建一个父类--汽车类 品牌,价格 一个子类--电动车类 电瓶容量,充电功率 class Car begin function __init__ self brand price begin set brand = brand set price = price end function end class class Electric_car extends Car begin function __init__ self brand price capacity charging_power begin call __init__ brand price set capacity = capacity se...
""" 继承: 创建一个父类--汽车类 品牌,价格 一个子类--电动车类 电瓶容量,充电功率 """ class Car: def __init__(self, brand, price): self.brand = brand self.price = price class Electric_car(Car): def __init__(self, brand, price, capacity, charging_power): s...
Python
zaydzuhri_stack_edu_python
for i in range 26 begin set s = s + character i + 97 + string + string i + 1 + string end print s print print string Decode print set sentance = string is a 2016 british experimental protest film that was produced directed and shot set n = random integer 1 15 set s = string for i in range length sentance begin if se...
for i in range(26): s+= chr(i+97)+' '+str(i+1)+' ' print(s) print() print('Decode') print() sentance='is a 2016 british experimental protest film that was produced directed and shot' n=random.randint(1,15) s='' for i in range(len(sentance)): if(sentance[i]==' '): s+=' ' else: s+=str(ord(sentance[i])-96+...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import requests from datetime import datetime from classes.Competition import Competition function readPWCA begin set now = now set competitions = list for year in range 2000 year + 1 begin set url = string http://www.pwca.org/view/tour/ + string year set page_response = get requests url ...
from bs4 import BeautifulSoup import requests from datetime import datetime from classes.Competition import Competition def readPWCA(): now = datetime.now() competitions = [] for year in range(2000, now.year + 1): url = 'http://www.pwca.org/view/tour/' + str(year) page_response = requ...
Python
zaydzuhri_stack_edu_python
function convert_vertex match begin set x = call format_number call groups at 0 set y = call format_number call groups at 1 set bulge_str = call groups at 3 if bulge_str begin set bulge_deg = call atan decimal bulge_str * 4 / pi set bulge = call format_number bulge_deg * 9 return format string {},{},{} x y bulge end el...
def convert_vertex(match): x = format_number(match.groups()[0]) y = format_number(match.groups()[1]) bulge_str = match.groups()[3] if bulge_str: bulge_deg = math.atan(float(bulge_str)) * 4 / math.pi bulge = format_number(bulge_deg * 9) return '{},{},{}'.format(x, y, bulge) el...
Python
nomic_cornstack_python_v1
function get_altruist_fitness self begin return altruist_fitness end function
def get_altruist_fitness(self): return self.altruist_fitness
Python
nomic_cornstack_python_v1
comment install nltk - nlp toolkit comment sudo pip3 install nltk comment go to python console comment $ python3 comment run the below commands to download all the libraries comment >> import nltk comment >> nltk.download() comment choose 'all' from nltk.corpus import brown from nltk.tokenize import RegexpTokenizer fro...
# install nltk - nlp toolkit # sudo pip3 install nltk # go to python console # $ python3 # run the below commands to download all the libraries # >> import nltk # >> nltk.download() # choose 'all' from nltk.corpus import brown from nltk.tokenize import RegexpTokenizer from nltk.tokenize import sent_tokenize # test pri...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys import math function boards blanks mines clicks begin if blanks > 0 begin for b in call boards blanks - 1 mines clicks begin yield list string + b end end if mines > 0 begin for b in call boards blanks mines - 1 clicks begin yield list string * + b end end if clicks > 0 begin for b ...
#!/usr/bin/python import sys import math def boards(blanks,mines,clicks): if(blanks>0): for b in boards(blanks-1,mines,clicks): yield [' ']+b if(mines>0): for b in boards(blanks,mines-1,clicks): yield ['*']+b if(clicks>0): for b in boards(blanks,mines,clicks-...
Python
zaydzuhri_stack_edu_python
function find self task_id begin for task_obj in queue begin if starts with id task_id begin return task_obj end end raise call LookupError format string No such task in queue: '{}' task_id end function
def find(self, task_id): for task_obj in self.queue: if task_obj.id.startswith(task_id): return task_obj raise LookupError("No such task in queue: '{}'".format(task_id))
Python
nomic_cornstack_python_v1
set msg = input set msg = set msg print length msg - 2
msg = input() msg = set(msg) print(len(msg)-2)
Python
zaydzuhri_stack_edu_python
function get_features self begin call _prepare_features comment get absolute features for tuple index row in call iterrows begin call _get_dur_features index row call _get_int_features index row call _get_pitch_features index row call _get_spect_features index row end comment get normalized features call _norm_dur_feat...
def get_features(self) -> pd.DataFrame: self._prepare_features() # get absolute features for index, row in self.features.iterrows(): self._get_dur_features(index, row) self._get_int_features(index, row) self._get_pitch_features(index, row) self._g...
Python
nomic_cornstack_python_v1
function predict self X_s begin set Kern = call kernel X X_s set Kern_s = call kernel X_s X_s set Kerninv = call inv K set mul = dot Y set mul = reshape np mul - 1 set cov = Kern_s - dot Kern set cov = call diagonal return tuple mul cov end function
def predict(self, X_s): Kern = self.kernel(self.X, X_s) Kern_s = self.kernel(X_s, X_s) Kerninv = np.linalg.inv(self.K) mul = Kern.T.dot(Kerninv).dot(self.Y) mul = np.reshape(mul, -1) cov = Kern_s - Kern.T.dot(Kerninv).dot(Kern) cov = cov.diagonal() return ...
Python
nomic_cornstack_python_v1
string 파이썬은 기본적으로 public으로 설정되어 있다 private __name class Car begin function __init__ self model=string sm5 color=string black speed=50 maker=string 삼성 begin print string ===생성자 호출=== set model = model set color = color set speed = speed set __maker = maker end function function output self begin print string 모델 : model ...
''' 파이썬은 기본적으로 public으로 설정되어 있다 private __name ''' class Car : def __init__(self, model='sm5', color='black', speed=50, maker='삼성') : print('===생성자 호출===') self.model = model self.color = color self.speed = speed self.__maker = maker def output(se...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string SI Pool ======== Modified: 2021-11 This module stores and performs operations on a set of neuron objects to extract correlational data. Dependancies ------------ >>> import logging.config >>> from threading import Thread >>> from ecp.memory.matrix_memory import MatrixMap >>> from ec...
# -*- coding: utf-8 -*- """ SI Pool ======== Modified: 2021-11 This module stores and performs operations on a set of neuron objects to extract correlational data. Dependancies ------------ >>> import logging.config >>> from threading import Thread >>> from ecp.memory.matrix_memory import MatrixMap >>> f...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 set tuple = tuple string abcd 123 2.123 string runoob 23.2 set tinytuple = tuple 1231 string sfadf comment 输出完整元组 print tuple comment 输出元组的第一个元素 print tuple at 0 comment 输出从第二个元素开始到第三个元素 print tuple at slice 1 : 3 : comment 输出从第三个元素开始的所有元素 print tuple at slice 2 : : comment 输出两次元组 print tinyt...
#!/usr/bin/python3 tuple =('abcd',123,2.123,'runoob',23.2) tinytuple=(1231,'sfadf') print (tuple) # 输出完整元组 print (tuple[0]) # 输出元组的第一个元素 print (tuple[1:3]) # 输出从第二个元素开始到第三个元素 print (tuple[2:]) # 输出从第三个元素开始的所有元素 print (tinytuple * 2) # 输出两次元组 print (tuple + tinytuple) # 连接元组
Python
zaydzuhri_stack_edu_python
import math function rightangleup numrows begin for i in range 1 numrows + 1 begin print string * * i end end function function rightangledown numrows begin set x = string * for i in range numrows begin print string * * numrows - i end end function function diamnd numrows begin set halfrange = ceil numrows / 2 for i in...
import math def rightangleup(numrows): for i in range(1, numrows + 1): print("* " * i) def rightangledown(numrows): x = '*' for i in range(numrows): print('* ' * (numrows - i)) def diamnd(numrows): halfrange = math.ceil(numrows / 2) for i in range(1,halfrange+1): print(...
Python
zaydzuhri_stack_edu_python
function longestDigitsPrefix inputString begin set result = list for char in inputString begin if not call isnumeric begin break end else begin append result char end end return join string result end function if __name__ == string __main__ begin print call longestDigitsPrefix string 123aa1 end
def longestDigitsPrefix(inputString): result = [] for char in inputString: if not char.isnumeric(): break else: result.append(char) return ''.join(result) if __name__ == "__main__": print(longestDigitsPrefix('123aa1'))
Python
zaydzuhri_stack_edu_python
comment for now i'm going with a joos style dummy AST, so I can start comment writing and testing the parser comment should probably add a baseclass later with linenos class Service extends object begin function __init__ self htmls schemas variables functions sessions begin set htmls = htmls set schemas = schemas set v...
# for now i'm going with a joos style dummy AST, so I can start # writing and testing the parser # should probably add a baseclass later with linenos class Service(object) : def __init__(self, htmls, schemas, variables, functions, sessions) : self.htmls = htmls self.schemas = schemas ...
Python
zaydzuhri_stack_edu_python
function test_exec_js_field_sub self begin class Comment extends EmbeddedDocument begin set content = call StringField db_field=string body end class class BlogPost extends Document begin set name = call StringField db_field=string doc-name set comments = call ListField call EmbeddedDocumentField Comment db_field=strin...
def test_exec_js_field_sub(self): class Comment(EmbeddedDocument): content = StringField(db_field="body") class BlogPost(Document): name = StringField(db_field="doc-name") comments = ListField(EmbeddedDocumentField(Comment), db_field="cmnts") BlogPost.drop_...
Python
nomic_cornstack_python_v1
function find_ts uh_t begin set input_interval = uh_t at 1 - uh_t at 0 debug string Input Timestep = %i seconds % input_interval return input_interval end function
def find_ts(uh_t): input_interval = uh_t[1]-uh_t[0] log.debug('Input Timestep = %i seconds' % input_interval) return input_interval
Python
nomic_cornstack_python_v1
function memoize fn begin set cache = dict function inner x begin if x not in cache begin set cache at x = call fn x end return cache at x end function return inner end function decorator memoize function fib n begin print string number of times running { n } if n < 2 begin return n end else begin return call fib n - ...
def memoize(fn): cache = {} def inner(x): if x not in cache: cache[x] = fn(x) return cache[x] return inner @memoize def fib(n): print(f'number of times running {n}') if n < 2: return n else: return fib(n-1) + fib(n-2) if __name__ == '__main__': ...
Python
zaydzuhri_stack_edu_python
while cnt <= 51 begin set i = 2 ^ cnt append dp i set cnt = cnt + 1 end for _ in range t begin set n = integer input if n not in dp begin print string YES end else begin print string NO end end
while cnt <= 51: i = 2**cnt dp.append(i) cnt+=1 for _ in range(t): n = int(input()) if n not in dp: print("YES") else: print("NO")
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from bs4 import BeautifulSoup import re import requests import time import csv from selenium.common.exceptions import TimeoutException function url_crawler driver project project_folder_name begin get driver string https://seekingalpha.com/symbol/ { project } /transcripts sleep 2 for i in...
from selenium import webdriver from bs4 import BeautifulSoup import re import requests import time import csv from selenium.common.exceptions import TimeoutException def url_crawler(driver,project,project_folder_name): driver.get(f'https://seekingalpha.com/symbol/{project}/transcripts') time.sleep(2) for i...
Python
zaydzuhri_stack_edu_python
function convert_x_to_bbox x score=none begin set w = square root x at 2 * x at 3 set h = x at 2 / w if w == 0.0 begin print string Stop: x end if score is none begin return reshape array list x at 0 - w / 2.0 x at 1 - h / 2.0 x at 0 + w / 2.0 x at 1 + h / 2.0 dtype=float32 tuple 1 4 end else begin return reshape array...
def convert_x_to_bbox(x, score=None): w = np.sqrt(x[2] * x[3]) h = x[2] / w if w == 0.0: print('Stop: ', x) if score is None: return np.array([x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2.], dtype=np.float32).reshape((1, 4)) else: return np.array([x[0] - w / 2., ...
Python
nomic_cornstack_python_v1
function _parse_init_http self line begin set v = call _parse_init line if not v begin return none end set tuple method url httpversion = v if not call isascii url begin return none end if not starts with url string / or url == string * begin return none end return tuple method url httpversion end function
def _parse_init_http(self, line): v = self._parse_init(line) if not v: return None method, url, httpversion = v if not utils.isascii(url): return None if not (url.startswith("/") or url == "*"): return None return method, url, httpversi...
Python
nomic_cornstack_python_v1
from time import time import tflearn from tensorflow.examples.tutorials.mnist.input_data import read_data_sets from tflearn.layers.conv import conv_2d , max_pool_2d from tflearn.layers.core import dropout , fully_connected , input_data from tflearn.layers.estimator import regression comment defines path to TensorBoard ...
from time import time import tflearn from tensorflow.examples.tutorials.mnist.input_data import read_data_sets from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import dropout, fully_connected, input_data from tflearn.layers.estimator import regression # defines path to TensorBoard log fi...
Python
zaydzuhri_stack_edu_python
import operator import math from pos_tag import * class IRModel begin set _total = 0 set posTagFrequencies = dict string N 0 ; string V 0 ; string R 0 ; string J 0 ; string P 0 ; string I 0 function __init__ self begin set N = 0 set _termList = list set _docLists = list set _docLength = list set _queryLength = 0.0 e...
import operator import math from pos_tag import * class IRModel: _total = 0 posTagFrequencies = {"N": 0, "V": 0, "R": 0, "J": 0, "P": 0, "I": 0} def __init__(self): self.N = 0 self._termList = [] self._docLists = [] self._docLength = [] self._queryLength = 0.0 ...
Python
zaydzuhri_stack_edu_python
function main begin comment Get's info on the user's name than greets them set first_name = input string What is your first name?: set last_name = input string What is your last name?: print string Hello, %s %s! % tuple first_name last_name print comment Lists the foods avaliable set food = list string Cookie string St...
def main(): #Get's info on the user's name than greets them first_name = input("What is your first name?: ") last_name = input("What is your last name?: ") print("Hello, %s %s!"%(first_name,last_name)) print() #Lists the foods avaliable food = ['Cookie', 'Steak', 'Ice cream', 'Apples'] ...
Python
zaydzuhri_stack_edu_python
function sign self message privkey secret begin string sign the message using private key and sign secret for signsecret k, message m, privatekey x return (G*k, (m+x*r)/k) set m = call value message set x = call value privkey set k = call value secret set R = G * k set r = call value x set s = m + x * r / k return tupl...
def sign(self, message, privkey, secret): """ sign the message using private key and sign secret for signsecret k, message m, privatekey x return (G*k, (m+x*r)/k) """ m = self.GFn.value(message) x = self.GFn.value(privkey) k = self.GFn.value(secret) ...
Python
jtatman_500k
function _get_library gi sample_info config begin string Retrieve the appropriate data library for the current user. set galaxy_lib = get sample_info string galaxy_library get config string galaxy_library set role = get sample_info string galaxy_role get config string galaxy_role if galaxy_lib begin return call _get_li...
def _get_library(gi, sample_info, config): """Retrieve the appropriate data library for the current user. """ galaxy_lib = sample_info.get("galaxy_library", config.get("galaxy_library")) role = sample_info.get("galaxy_role", config.get("galaxy_...
Python
jtatman_500k
function getId self begin return call SimpleSpeciesReference_getId self end function
def getId(self): return _libsbml.SimpleSpeciesReference_getId(self)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding=utf-8 -*- comment Using GPL v2 comment Author: ihipop@gmail.com comment 2010-10-27 22:07 string Usage: Just A Template from __future__ import division import sys , time set j = string # set N = 15 if __name__ == string __main__ begin for n in range 15 begin write stdout s...
#!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2 #Author: ihipop@gmail.com ##2010-10-27 22:07 """ Usage: Just A Template """ from __future__ import division import sys,time j = '#' N=15 if __name__ == '__main__': for n in range(15): sys.stdout.write('\r') sys.stdout.write(' ' * (N+len(st...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from django.test import TestCase from sz.core.morphology import stemmers from sz.core import models , morphology from sz.core.services import morphology as services class MorphUtilsTest extends TestCase begin function test_extract_words_ru self begin set text = string съешь ещё этих мягких...
# -*- coding: utf-8 -*- from django.test import TestCase from sz.core.morphology import stemmers from sz.core import models, morphology from sz.core.services import morphology as services class MorphUtilsTest(TestCase): def test_extract_words_ru(self): text = u'съешь ещё этих мягких французских булочек с ...
Python
zaydzuhri_stack_edu_python
function accuracy output target topk=tuple 1 begin set maxk = max topk set batch_size = size target 0 set tuple _ pred = call topk maxk 1 true true set pred = t dist set correct = call eq call expand_as pred set res = list for k in topk begin set correct_k = sum 0 append res call mul_ 100.0 / batch_size end return res...
def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res...
Python
nomic_cornstack_python_v1
function always_bls fn begin function entry *args **kw begin comment override bls setting set kw at string bls_active = true return call call bls_switch fn *args keyword kw end function return call call with_meta_tags dict string bls_setting 1 entry end function
def always_bls(fn): def entry(*args, **kw): # override bls setting kw['bls_active'] = True return bls_switch(fn)(*args, **kw) return with_meta_tags({'bls_setting': 1})(entry)
Python
nomic_cornstack_python_v1
comment 传统方法################ comment 创建一个文件对象 set f = open string ./1.text string w comment 向文件写内容 try begin write f string hello flask end except Exception begin pass end finally begin comment 关闭文件 close f end comment with方法############# with open string ./2.text string w as f begin write f string hello django,hello f...
####传统方法################ #创建一个文件对象 f = open("./1.text","w") # 向文件写内容 try: f.write("hello flask") except Exception: pass finally: #关闭文件 f.close() #########with方法############# with open('./2.text',"w") as f: f.write("hello django,hello flask,hello tornado") """ with称为上下文管理器, """ class Foo(): def ...
Python
zaydzuhri_stack_edu_python
string vending.py Name: Kaiqin Huang Date: 1/18/2017 A module of class VendingMachine. class VendingMachine begin comment __init__(): constructor function __init__ self initial_chocolates begin string Gives the number of chocolates in the vending machine Args: initial_chocolates: number of chocolates left in this vendi...
""" vending.py Name: Kaiqin Huang Date: 1/18/2017 A module of class VendingMachine. """ class VendingMachine: def __init__(self, initial_chocolates): # __init__(): constructor '''Gives the number of chocolates in the vending machine Args: initial_chocolates: number of ...
Python
zaydzuhri_stack_edu_python
function media_image_hash self begin return _media_image_hash end function
def media_image_hash(self): return self._media_image_hash
Python
nomic_cornstack_python_v1
comment This will import math module import math comment Mathematical Functions comment abs print string abs(-45) : absolute - 45 print string abs(100.12) : absolute 100.12 comment ceil print string math.ceil(-45.17) : ceil - 45.17 print string math.ceil(100.12) : ceil 100.12 print string math.ceil(100.72) : ceil 100.7...
import math # This will import math module ## Mathematical Functions ## abs print ("abs(-45) : ", abs(-45)) print ("abs(100.12) : ", abs(100.12)) ## ceil print ("math.ceil(-45.17) : ", math.ceil(-45.17)) print ("math.ceil(100.12) : ", math.ceil(100.12)) print ("math.ceil(100.72) : ", math.ceil(100.72)) print ("ma...
Python
zaydzuhri_stack_edu_python
from ipycanvas import MultiCanvas import math from ipywidgets import Color from sidecar import Sidecar class TurtleScreen begin function __init__ self width=400 height=400 begin set multicanvas = call MultiCanvas 4 width=width height=height set turtleCanvas = multicanvas at 3 set sc = call Sidecar title=string Turtle S...
from ipycanvas import MultiCanvas import math from ipywidgets import Color from sidecar import Sidecar class TurtleScreen(): def __init__(self, width=400, height=400): self.multicanvas = MultiCanvas(4, width=width, height=height) self.turtleCanvas = self.multicanvas[3] self.sc = Sidecar(ti...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- set __author__ = string hannibal from urllib import request import json from datetime import datetime , timedelta import time import cx_Oracle import sys import io import pymysql import re set stdout = call TextIOWrapper buffer encoding=string utf8 comment 获取数据 function get_data url begin ...
# -*- coding: utf-8 -*- __author__ = 'hannibal' from urllib import request import json from datetime import datetime, timedelta import time import cx_Oracle import sys import io import pymysql import re sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') # 获取数据 def get_data(url): headers = { ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 from models import storage from models.state import State from flask import Flask , render_template string This module import data from storage set app = call Flask __name__ decorator teardown_appcontext function close arg begin string Close the session close storage end function decorator cal...
#!/usr/bin/python3 from models import storage from models.state import State from flask import Flask, render_template """ This module import data from storage """ app = Flask(__name__) @app.teardown_appcontext def close(arg): """ Close the session """ storage.close() @app.route('/states_list', strict_slash...
Python
zaydzuhri_stack_edu_python
import re import hashlib comment Secure database storage mechanism class Database begin function __init__ self begin set users = list end function function add_user self user begin append users user end function function check_email_unique self email begin for user in users begin if email == email begin return false e...
import re import hashlib # Secure database storage mechanism class Database: def __init__(self): self.users = [] def add_user(self, user): self.users.append(user) def check_email_unique(self, email): for user in self.users: if user.email == email: retur...
Python
greatdarklord_python_dataset
for i in range n begin set tuple T at i A at i = map int split input end set votes = list T at 0 A at 0 for i in range 1 n begin set m = max - - votes at 0 // T at i - - votes at 1 // A at i set votes at 0 = m * T at i set votes at 1 = m * A at i end print votes at 0 + votes at 1 comment floatで正確に表示できるのは15桁程度
for i in range(n): T[i],A[i] = map(int,input().split()) votes = [T[0],A[0]] for i in range(1,n): m = max(-(-votes[0]//T[i]),-(-votes[1]//A[i])) votes[0] = m*T[i] votes[1] = m*A[i] print(votes[0]+votes[1]) #floatで正確に表示できるのは15桁程度
Python
zaydzuhri_stack_edu_python
function connect_via self begin return get pulumi self string connect_via end function
def connect_via(self) -> Optional['outputs.IntegrationRuntimeReferenceResponse']: return pulumi.get(self, "connect_via")
Python
nomic_cornstack_python_v1
function popPendingWires self errorOnEmpty=true begin if errorOnEmpty and not pendingWires begin raise call ValueError string No pending wires present end set out = pendingWires set pendingWires = list return out end function
def popPendingWires(self, errorOnEmpty: bool = True) -> List[Wire]: if errorOnEmpty and not self.pendingWires: raise ValueError("No pending wires present") out = self.pendingWires self.pendingWires = [] return out
Python
nomic_cornstack_python_v1
function __init__ self sys t_t k begin call __init__ sys t_t set k = k end function
def __init__(self, sys, t_t, k): super().__init__(sys, t_t) self.k = k
Python
nomic_cornstack_python_v1
function random_strings n max_string_size=6 begin return list comprehension call random_string random integer 1 max_string_size for i in range n end function
def random_strings(n, max_string_size=6): return [random_string(random.randint(1, max_string_size)) for i in range(n)]
Python
nomic_cornstack_python_v1
function shuffle_set self begin set shuffler = random sample call xrange length questions length questions for i in shuffler begin append questions pop questions i append answers pop answers i append q_from pop q_from i end call set_card end function
def shuffle_set(self): shuffler = random.sample(xrange(len(self.questions)), len(self.questions)) for i in shuffler: self.questions.append(self.questions.pop(i)) self.answers.append(self.answers.pop(i)) self.q_from.append(self.q_from.pop(i)) self.set_card()
Python
nomic_cornstack_python_v1
function __init__ self saved_artifacts_info begin set saved_artifacts_info = saved_artifacts_info end function
def __init__(self, saved_artifacts_info): self.saved_artifacts_info = saved_artifacts_info
Python
nomic_cornstack_python_v1
comment https://codeup.kr/problem.php?id=1295 comment readline을 사용하기 위해 import합니다. from sys import stdin comment 한 줄의 공백없는 문장을 입력합니다. comment 최대 길이는 1000입니다. comment 맨 끝의 \n은 떼어줍니다. set string = right strip read line stdin comment 입력한 문장의 대소문자를 서로 변환한 결과를 출력합니다. print call swapcase
# https://codeup.kr/problem.php?id=1295 # readline을 사용하기 위해 import합니다. from sys import stdin # 한 줄의 공백없는 문장을 입력합니다. # 최대 길이는 1000입니다. # 맨 끝의 \n은 떼어줍니다. string = stdin.readline().rstrip() # 입력한 문장의 대소문자를 서로 변환한 결과를 출력합니다. print(string.swapcase())
Python
zaydzuhri_stack_edu_python
string 03/12/2020 Asier Blazquez Make a program that asks a number and says if it is odd or not. set n = integer input string Sartu zenbaki bat bakoitia edo bikoitia den jakiteko: if n % 2 == 0 begin print n string Bikoitia da end else begin print n string Bakoitia da end
''' 03/12/2020 Asier Blazquez Make a program that asks a number and says if it is odd or not. ''' n= int(input("Sartu zenbaki bat bakoitia edo bikoitia den jakiteko: ")) if(n%2==0): print(n,"Bikoitia da") else: print(n,"Bakoitia da")
Python
zaydzuhri_stack_edu_python
function modified_time self begin return get pulumi self string modified_time end function
def modified_time(self) -> Optional[str]: return pulumi.get(self, "modified_time")
Python
nomic_cornstack_python_v1
import random from environment import Agent , Environment from planner import RoutePlanner from simulator import Simulator import numpy as np import pandas as pd class LearningAgent extends Agent begin string An agent that learns to drive in the smartcab world. function __init__ self env learning_rate discount_factor g...
import random from environment import Agent, Environment from planner import RoutePlanner from simulator import Simulator import numpy as np import pandas as pd class LearningAgent(Agent): """An agent that learns to drive in the smartcab world.""" def __init__(self, env, learning_rate, discount_factor, greedy...
Python
zaydzuhri_stack_edu_python
function patch_apps_v1alpha1_namespaced_stateful_set_with_http_info self name namespace body **kwargs begin set all_params = list string name string namespace string body string pretty append all_params string callback append all_params string _return_http_data_only set params = locals for tuple key val in call iterite...
def patch_apps_v1alpha1_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs): all_params = ['name', 'namespace', 'body', 'pretty'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(para...
Python
nomic_cornstack_python_v1
function figure7C_plot cv_scores AUC_raw_data begin comment fig, ax = plt.subplots(1, 1, figsize=(10, 10)) set tuple fig ax = call subplots 1 1 set colors = dict string Full Panel string #e34b34 ; string Sparse Panel string #8dba41 for tuple i name in enumerate AUC_raw_data begin set tuple y_real y_proba = AUC_raw_data...
def figure7C_plot(cv_scores, AUC_raw_data): #fig, ax = plt.subplots(1, 1, figsize=(10, 10)) fig, ax = plt.subplots(1, 1) colors = {'Full Panel': '#e34b34', 'Sparse Panel': '#8dba41'} for i, name in enumerate(AUC_raw_data): y_real, y_proba = AUC_raw_data[name] y...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri Feb 15 19:29:57 2019 @author: amogh import cv2 import numpy as np import os from PIL import * set recognizer = call LBPHFaceRecognizer_create comment Path of the folder where the Training Images are stored set path = string Dataset functi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 15 19:29:57 2019 @author: amogh """ import cv2 import numpy as np import os from PIL import * recognizer = cv2.face.LBPHFaceRecognizer_create() path='Dataset' #Path of the folder where the Training Images are stored def getIDsandImages(path): ...
Python
zaydzuhri_stack_edu_python
function setup self begin set background = call load_texture string assets/overworld/overworld_deadly.png set ui_manager = call UIManager call add_ui_element call MenuButton self call add_ui_element call QuitButton end function
def setup(self) -> None: self.background = arcade.load_texture("assets/overworld/overworld_deadly.png") self.ui_manager = UIManager() self.ui_manager.add_ui_element(MenuButton(self)) self.ui_manager.add_ui_element(QuitButton())
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Apr 17 11:23:26 2020 @author: Rajesh
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 11:23:26 2020 @author: Rajesh """
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.model_selection import train_test_split from keras.models import Model from keras.layers import Conv1D , MaxPooling1D , Embedding , Dropout , Dense , concatenate , Flatten , Input from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from k...
import numpy as np from sklearn.model_selection import train_test_split from keras.models import Model from keras.layers import Conv1D, MaxPooling1D, Embedding, Dropout, Dense, concatenate, Flatten, Input from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.ut...
Python
zaydzuhri_stack_edu_python
string Homework 5, Exercise 4 William Morris 3/04/19 This program uses regular expressions to make sure the password string is a strong password where there is at least 8 characters long, contains both upper and lowercase characters, and has at least 1 digit. import re set passwordRegex = compile string ^(?=.*?[A-Z])(?...
""" Homework 5, Exercise 4 William Morris 3/04/19 This program uses regular expressions to make sure the password string is a strong password where there is at least 8 characters long, contains both upper and lowercase characters, and has at least 1 digit. """ import re passwordRegex = re.compile( r"^(?=.*?[A-Z])(...
Python
zaydzuhri_stack_edu_python
function new_item self line begin set newItem = call QTreeWidgetItem set _widgets = list for i in range maxColors / rows begin set index = i + maxColors / rows * line append _widgets call new_button i index newItem end return newItem end function
def new_item(self, line): newItem = QtGui.QTreeWidgetItem() newItem._widgets = [] for i in range(self.maxColors / self.rows): index = i + ((self.maxColors / self.rows) * line) newItem._widgets.append(self.new_button(i, index, newItem)) return newItem
Python
nomic_cornstack_python_v1
comment Python内建的filter()函数用于过滤序列 comment 和map()类似,filter()也接收一个函数和一个序列 comment 它把传入的函数依次作用于每个元素,根据返回值是True/False决定保留/丢弃该元素。 comment 例如,在一个list中,删掉偶数,只保留奇数,可以这么写 function is_Odd n begin return n % 2 == 1 end function print list filter is_Odd list 1 2 3 4 5 6 comment 把一个序列中的空字符串删掉 function not_Empty s begin return s and...
#Python内建的filter()函数用于过滤序列 #和map()类似,filter()也接收一个函数和一个序列 #它把传入的函数依次作用于每个元素,根据返回值是True/False决定保留/丢弃该元素。 #例如,在一个list中,删掉偶数,只保留奇数,可以这么写 def is_Odd(n): return n%2==1 print(list(filter(is_Odd, [1, 2, 3, 4, 5, 6]))) #把一个序列中的空字符串删掉 def not_Empty(s): return s and s.strip() print(list(filter(not_Empty, ['A', '', 'B', None,...
Python
zaydzuhri_stack_edu_python
function get_filename_from_cd cd begin if not cd begin return none end set fname = find all string filename=(.+) cd if length fname == 0 begin return none end return fname at 0 end function
def get_filename_from_cd(cd): if not cd: return None fname = re.findall('filename=(.+)', cd) if len(fname) == 0: return None return fname[0]
Python
nomic_cornstack_python_v1
for i in range 1 n + 1 begin for j in range 1 i begin print string end=string end for k in range 0 p begin print string * end=string end print string set p = n - i end
for i in range(1,n+1): for j in range(1,i): print(" ",end="") for k in range(0,p): print("*",end="") print("") p=n-i
Python
zaydzuhri_stack_edu_python
comment @lc app=leetcode.cn id=130 lang=python3 comment [130] 被围绕的区域 from typing import List comment @lc code=start class Solution begin function solve self board begin string Do not return anything, modify board in-place instead. if length board == 0 begin return end set DELTA = tuple tuple - 1 0 tuple 0 1 tuple 1 0 t...
# # @lc app=leetcode.cn id=130 lang=python3 # # [130] 被围绕的区域 # from typing import List # @lc code=start class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if len(board) == 0: return DEL...
Python
zaydzuhri_stack_edu_python
function __str__ self begin comment add a dagger symbol to the class name if needed set temp = call __str__ if dagger begin set temp = temp + string .H end return temp end function
def __str__(self): # add a dagger symbol to the class name if needed temp = super().__str__() if self.dagger: temp += ".H" return temp
Python
nomic_cornstack_python_v1
function pack filename source_dir begin raise NotImplemented end function
def pack(filename: Union[str, Path], source_dir: Union[str, Path]) -> None: raise NotImplemented
Python
nomic_cornstack_python_v1
function grad w f noise begin set f = f - mean f comment standardize the rewards to be N(0,1) gaussian set f = f / standard deviation f set g = dot f noise return g end function
def grad(w, f, noise): f -= f.mean() f /= f.std() # standardize the rewards to be N(0,1) gaussian g = np.dot(f, noise) return g
Python
nomic_cornstack_python_v1
function contact request begin if method == string POST begin set form = call ContactForm POST if call is_valid begin set name = cleaned_data at string name set sender = cleaned_data at string email set subject = cleaned_data at string subject set message = cleaned_data at string message set recipients = list EMAIL_HOS...
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] sender = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] ...
Python
nomic_cornstack_python_v1
string Contains functions to create model objects from json data import datetime from dateutil import parser from paranuara.models import Company , Person , PersonTag , Food function get_timestamp_prefix begin string Unique prefix for data index :return: string in format: 1549846344.44- return string timestamp now + st...
""" Contains functions to create model objects from json data """ import datetime from dateutil import parser from paranuara.models import Company, Person, PersonTag, Food def get_timestamp_prefix(): """ Unique prefix for data index :return: string in format: 1549846344.44- """ return str(datetime...
Python
zaydzuhri_stack_edu_python
import os import tensorflow as tf comment From: https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py import inception_resnet_v2 comment From: https://github.com/tensorflow/models/blob/master/slim/preprocessing/inception_preprocessing.py import inception_preprocessing from tensorflow.contrib...
import os import tensorflow as tf import inception_resnet_v2 #From: https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py import inception_preprocessing # From: https://github.com/tensorflow/models/blob/master/slim/preprocessing/inception_preprocessing.py from tensorflow.contrib import slim...
Python
zaydzuhri_stack_edu_python
class Solution begin function repeatedSubstringPattern self s begin set length = 1 set flag = false while not flag and length <= length s / 2 begin while length s % length != 0 and length <= length s / 2 begin set length = length + 1 end if length s % length != 0 begin break end set pat = s at slice : length : set fl...
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: length = 1 flag = False while not flag and length <= len(s) / 2: while len(s) % length != 0 and length <= len(s) / 2: length += 1 if len(s) % length != 0: break ...
Python
zaydzuhri_stack_edu_python