code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function read_fluxfile ifile begin comment Read in the pypeit reduction file info string Loading the fluxcalib file set lines = call _read_pypeit_file_lines ifile set is_config = ones length lines dtype=bool comment Parse the fluxing block set spec1dfiles = list set sensfiles_in = list set tuple s e = call _find_pype...
def read_fluxfile(ifile): # Read in the pypeit reduction file msgs.info('Loading the fluxcalib file') lines = par.util._read_pypeit_file_lines(ifile) is_config = np.ones(len(lines), dtype=bool) # Parse the fluxing block spec1dfiles = [] sensfiles_in = [] s, e = par.util._find_pypeit_bl...
Python
nomic_cornstack_python_v1
string Module responsible for generating the database structure specific to the Restaurant Chooser application and accessing its data. comment Built-in modules from os import remove comment User-defined modules from database import DatabaseAccessor from database._restaurant_chooser_init import CREATE_TABLES , INITIAL_V...
""" Module responsible for generating the database structure specific to the Restaurant Chooser application and accessing its data. """ # Built-in modules from os import remove # User-defined modules from database import DatabaseAccessor from database._restaurant_chooser_init import CREATE_TABLES, INITIAL_VALUE_INSER...
Python
zaydzuhri_stack_edu_python
while i < n begin set num = integer input append v num set aux = 1 set fatorial = 1 while aux <= num begin set fatorial = fatorial * aux set aux = aux + 1 end append w fatorial set i = i + 1 end set i = 0 while i <= n - 1 begin if i == n - 1 begin print format string {} v at i end else begin print format string {} v at...
while i < n: num = int(input()) v.append(num) aux = 1 fatorial = 1 while aux <= num: fatorial = fatorial * aux aux = aux + 1 w.append(fatorial) i = i+1 i = 0 while i <= n-1: if i == n-1: print("{}".format(v[i])) else: print("{}".format(v[i]),...
Python
zaydzuhri_stack_edu_python
comment Best Time to Buy and Sell Stock comment Say you have an array for which the ith element is the price comment of a given stock on day i. comment If you were only permitted to complete at most one transaction comment (ie, buy one and sell one share of the stock), comment design an algorithm to find the maximum pr...
##Best Time to Buy and Sell Stock ##Say you have an array for which the ith element is the price ##of a given stock on day i. ##If you were only permitted to complete at most one transaction ##(ie, buy one and sell one share of the stock), ##design an algorithm to find the maximum profit. ## ##2015年8月17日 09:24:19 AC ##...
Python
zaydzuhri_stack_edu_python
comment Min Substring comment Have the function min_substring(str_lst) take the list of strings stored in str_lst, comment which will contain only two strings, the first parameter being the container_string and the comment second parameter being the inside_string of some characters. comment Your goal is to determine th...
# Min Substring # Have the function min_substring(str_lst) take the list of strings stored in str_lst, # which will contain only two strings, the first parameter being the container_string and the # second parameter being the inside_string of some characters. # Your goal is to determine the smallest substring of the...
Python
zaydzuhri_stack_edu_python
comment S = 'spam' comment result = ?.fi.. 'pa' # Call the find method to look for 'pa' in string S comment print ?
# S = 'spam' # result = ?.fi.. 'pa' # Call the find method to look for 'pa' in string S # print ?
Python
zaydzuhri_stack_edu_python
function functions self begin return __functions end function
def functions(self): return self.__functions
Python
nomic_cornstack_python_v1
import pathlib class PathStorage begin function __init__ self sep begin set sep = sep set __storage = list string storage end function function add_path self path begin if string .. in path and length __storage != 1 begin pop __storage - 1 end else if string .. in path begin print string Вы хотите выйти за пределы песо...
import pathlib class PathStorage: def __init__(self, sep): self.sep = sep self.__storage = ["storage"] def add_path(self, path): if ".." in path and len(self.__storage) != 1: self.__storage.pop(-1) elif ".." in path: print("Вы хотите выйти...
Python
zaydzuhri_stack_edu_python
for x in e begin if d < k begin set d = k end set k = j set i = 0 set x = integer x while x >= 0 begin append z i set z at k = i set x = x - 1 set i = i + 1 set k = k + 1 end set j = j + 1 end if d < k begin set d = k end
for x in e: if d<k: d=k k=j i=0 x=int(x) while x>=0: z.append(i) z[k]=i x=x-1 i=i+1 k=k+1 j=j+1 if d<k: d=k
Python
zaydzuhri_stack_edu_python
string 765. Couples Holding Hands N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. The people and seats are represented by an inte...
""" 765. Couples Holding Hands N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. The people and seats are represented by an integ...
Python
zaydzuhri_stack_edu_python
function test_account_self_follow self begin set url = reverse string user-account-follow args=list username call token_login set request = post path=url content_type=string application/json keyword client_header assert equal status_code HTTP_403_FORBIDDEN end function
def test_account_self_follow(self): url = reverse('user-account-follow', args=[self.username]) self.token_login() request = self.c.post(path=url, content_type='application/json', **self.client_header) self.assertEqual(request.status_code, status.HTTP_403_FOR...
Python
nomic_cornstack_python_v1
string Generate data for function set __author__ = string Arthur Shaikhatarov set __copyright__ = string Copyright 2021 import pandas as pd import math from fractions import Fraction function frange start stop step begin set i = start while i < stop begin yield i set i = i + step end end function set columns = list str...
"""Generate data for function""" __author__ = "Arthur Shaikhatarov" __copyright__ = "Copyright 2021" import pandas as pd import math from fractions import Fraction def frange(start, stop, step): i = start while i < stop: yield i i += step columns=['x', 'y'] data = [] for x in fr...
Python
zaydzuhri_stack_edu_python
function get_webex_token webex_access_token begin return call WebexTeamsAPI webex_access_token end function
def get_webex_token(webex_access_token): return WebexTeamsAPI(webex_access_token)
Python
nomic_cornstack_python_v1
function filter_by_email func begin decorator wraps func function wrapper self event begin set incoming_emails = list if is instance event PatchSetCreated begin append incoming_emails email append incoming_emails email append incoming_emails email append incoming_emails email end if is instance event CommentAdded begi...
def filter_by_email(func): @six.wraps(func) def wrapper(self, event): incoming_emails = [] if isinstance(event, PatchSetCreated): incoming_emails.append(event.change.owner.email) incoming_emails.append(event.patch_set.author.email) incoming_emails.append(even...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from PIL import Image import numpy as np from colorama import Fore , Back , Style import argparse set parser = call ArgumentParser call add_argument string filePath help=string file path call add_argument string -i string --invert help=string invert the result action=string store_true call ...
#!/usr/bin/env python from PIL import Image import numpy as np from colorama import Fore, Back, Style import argparse parser = argparse.ArgumentParser() parser.add_argument("filePath", help="file path") parser.add_argument("-i","--invert", help="invert the result", action="store_true") parser.add_argument("-t", "--th...
Python
zaydzuhri_stack_edu_python
function get_overlay_data_start_offset self begin string Get the offset of data appended to the file and not contained within the area described in the headers. set highest_PointerToRawData = 0 set highest_SizeOfRawData = 0 for section in sections begin comment If a section seems to fall outside the boundaries of the f...
def get_overlay_data_start_offset(self): """Get the offset of data appended to the file and not contained within the area described in the headers.""" highest_PointerToRawData = 0 highest_SizeOfRawData = 0 for section in self.sections: # If a section seems to fa...
Python
jtatman_500k
function create_visibility_buttons self begin set view_graph_btn = call LayerButtonWidget description=string Graph tooltip=string View graph icon=string project-diagram layer_type=string graphs layer_subtype=string graph viewer=viewer set view_pgon_btn = call LayerButtonWidget description=string Polygons tooltip=string...
def create_visibility_buttons(self) -> widgets.Box: view_graph_btn = LayerButtonWidget( description="Graph", tooltip="View graph", icon="project-diagram", layer_type="graphs", layer_subtype="graph", viewer=self.viewer, ) vi...
Python
nomic_cornstack_python_v1
function fit theta var_prop prior_theta_kernel var_Lprop prior_ell kern p nu=none n_iter=500 verbose=false likelihood=none L=none begin if nu is none begin set nu = p + 1 end set K = call kern inverse_width=theta set umat = call sample_gp K nu=nu p=p if L is none begin set learn_ell = true set L = call tril randn p p e...
def fit( theta, var_prop, prior_theta_kernel, var_Lprop, prior_ell, kern, p, nu=None, n_iter=500, verbose=False, likelihood=None, L=None, ): if nu is None: nu = p + 1 K = kern(inverse_width=theta) umat = sample_gp(K, nu=nu, p=p) if L is None: ...
Python
nomic_cornstack_python_v1
comment characters class CharacterError extends Exception begin pass end class class Character extends object begin string Manages characters set HEALTH_STYLE_LAMBDA = 0 set HEALTH_STYLE_PC = 1 function __init__ self **kwargs begin string boop set id = get kwargs string id none set name = get kwargs string id none comm...
# characters class CharacterError(Exception): pass class Character(object): """Manages characters""" HEALTH_STYLE_LAMBDA = 0 HEALTH_STYLE_PC = 1 def __init__(self, **kwargs): """boop""" self.id = kwargs.get('id', None) self.name = kwargs.get('id', None) ...
Python
zaydzuhri_stack_edu_python
function grup d e begin set s = list set grup = call raw_input string Escriu el nom del grup: if call has_key grup == false begin set q = string S while q == string S begin set p = call raw_input string Escriu el nom de l'alumne que vols afegir al grup: set k = call raw_input string Escriu el cognom de l'alumne que vo...
def grup(d,e): s=[] grup=raw_input("Escriu el nom del grup: ") if e.has_key(grup)==False: q="S" while q=="S": p=raw_input("Escriu el nom de l'alumne que vols afegir al grup: ") k=raw_input("Escriu el cognom de l'alumne que vols afegir al grup: ")
Python
nomic_cornstack_python_v1
function test_view_recipe_not_found self begin comment registering recipe user call register_new_user name email test_username test_password set response = get test_client string /recipe/api/v1.0/category/recipes/ headers=call get_header_token content_type=string application/json assert equal status_code 404 end functi...
def test_view_recipe_not_found(self): #registering recipe user self.register_new_user(self.name, self.email, self.test_username, self.test_password) response = self.test_client.get('/recipe/api/v1.0/category/recipes/', headers=\ self.get_header_token(), content_type='application/json') ...
Python
nomic_cornstack_python_v1
comment set in orders print grocery_items reverse grocery_items comment set in opposite orders print grocery_items set grocery_items_sorted = sorted grocery_items comment same information but use sorted to reorder and save in grocery_items_sorted print grocery_items print length grocery_items comment count elements pri...
# set in orders print (grocery_items) grocery_items.reverse() # set in opposite orders print (grocery_items) grocery_items_sorted = sorted(grocery_items) # same information but use sorted to reorder and save in grocery_items_sorted print (grocery_items) print(len(grocery_items)) # count elements print(grocery_item...
Python
zaydzuhri_stack_edu_python
function to64 number begin if not type number is LongType or type number is IntType begin raise call TypeError string You must pass a long or an int end comment 00-09 translates to '0' - '9' if 0 <= number <= 9 begin return character number + 48 end if 10 <= number <= 35 begin comment 10-35 translates to 'A' - 'Z' retu...
def to64(number): if not (type(number) is types.LongType or type(number) is types.IntType): raise TypeError("You must pass a long or an int") if 0 <= number <= 9: #00-09 translates to '0' - '9' return chr(number + 48) if 10 <= number <= 35: return chr(number + 55) #...
Python
nomic_cornstack_python_v1
class Solution extends object begin function backspaceCompare self S T begin string :type S: str :type T: str :rtype: bool set new_S = call removebackspace S set new_T = call removebackspace T if new_S == new_T begin return true end else begin return false end end function function removebackspace self word begin set n...
class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ new_S= self.removebackspace(S) new_T = self.removebackspace(T) if new_S == new_T: return True else: return False ...
Python
zaydzuhri_stack_edu_python
function _check_privileges self begin if _verbosity begin print string # Checking users permission to perform consistency check. # end comment Check privileges for master. set master_priv = list tuple string SUPER string REPLICATION CLIENT tuple string LOCK TABLES tuple string SELECT set master_priv_str = string SUPER ...
def _check_privileges(self): if self._verbosity: print("# Checking users permission to perform consistency check.\n" "#") # Check privileges for master. master_priv = [('SUPER', 'REPLICATION CLIENT'), ('LOCK TABLES',), ('SELECT',)] ma...
Python
nomic_cornstack_python_v1
import codecs set fr_en_dict = dict set f = open string tinelex_FR_EN.dix_2 mode=string rb encoding=string cp1252 for line in read lines f begin set s = line while find s string ? != - 1 begin set pos_q = find s string ? set pos_q_ends = find s string : pos_q length s set pos_q_next = find s string ? pos_q_ends length...
import codecs fr_en_dict={} f=codecs.open('tinelex_FR_EN.dix_2',mode='rb',encoding='cp1252') for line in f.readlines(): s= line while s.find('?')!=-1: pos_q = s.find('?') pos_q_ends = s.find(':',pos_q,len(s)) pos_q_next = s.find('?',pos_q_ends,len(s)) fr_en_dict[s[pos_q+1:pos_q...
Python
zaydzuhri_stack_edu_python
function search self begin set W = zeros tuple shape at 0 for tuple i E in enumerate subsets begin comment set the nodes to their values call setV E set W at i = call computeW end set Ws = W end function
def search(self): W = np.zeros((self.subsets.shape[0],)) for i,E in enumerate(self.subsets): self.graph.setV(E) # set the nodes to their values W[i] = self.graph.computeW() self.Ws = W
Python
nomic_cornstack_python_v1
function peek self begin if capacity1 == 0 or capacity1 < 0 begin print string Capacity of Stack is 0 or less than 1. Can't use this Stack return end if size self == 0 begin print string Stack is empty return end return top1 end function
def peek(self): if self.capacity1==0 or self.capacity1<0: print("Capacity of Stack is 0 or less than 1. Can't use this Stack") return if self.size()==0 : print("Stack is empty") return return self.top1
Python
nomic_cornstack_python_v1
comment @lc app=leetcode id=33 lang=python comment [33] Search in Rotated Sorted Array class Solution extends object begin function search self nums target begin string :type nums: List[int] :type target: int :rtype: int comment here implement bisearch, the key mission is to find the part of sorted array, and use bisea...
# # @lc app=leetcode id=33 lang=python # # [33] Search in Rotated Sorted Array # class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ #here implement bisearch, the key mission...
Python
zaydzuhri_stack_edu_python
import socket import _thread as thread comment abrir uma nova thread comment thread.start_new_thread(funcao, argumentos) function processar_nova_conexao novoSocketDaConexao begin set linha = string while true begin comment 2000 bytwa na 1º retorna 1024, na 2º retorna os 976 dos dados. set data = call recv 1 set linha ...
import socket import _thread as thread #abrir uma nova thread #thread.start_new_thread(funcao, argumentos) def processar_nova_conexao(novoSocketDaConexao): linha = '' while True: data = novoSocketDaConexao.recv(1) ##2000 bytwa na 1º retorna 1024, na 2º retorna os 976 dos dados. linha += data....
Python
zaydzuhri_stack_edu_python
function run self test_file config system custom_args=none begin set test_path = root_dir / test_file set shard = get shards set cov_args = call cov_args config set stage_args = args + call shard_args shard config set file_args = call file_args test_file config set cmd = list string legate_path + stage_args + cov_args ...
def run( self, test_file: Path, config: Config, system: TestSystem, *, custom_args: ArgList | None = None, ) -> ProcessResult: test_path = config.root_dir / test_file shard = self.shards.get() cov_args = self.cov_args(config) stage_a...
Python
nomic_cornstack_python_v1
call NoGradient string Size
tf.NoGradient("Size")
Python
zaydzuhri_stack_edu_python
function _embed self begin comment with tf.device('/cpu:0'), tf.variable_scope('word_embedding'): with call variable_scope string word_embedding begin set word_embeddings = call get_variable string word_embeddings shape=tuple size vocab embed_dim initializer=call constant_initializer embeddings trainable=true set p_emb...
def _embed(self): #with tf.device('/cpu:0'), tf.variable_scope('word_embedding'): with tf.variable_scope('word_embedding'): self.word_embeddings = tf.get_variable( 'word_embeddings', shape=(self.vocab.size(), self.vocab.embed_dim), initializer=...
Python
nomic_cornstack_python_v1
import logging import boto3 from botocore.exceptions import ClientError function list_bucket_objects bucket_name begin set s3 = call client string s3 try begin set response = call list_objects_v2 Bucket=bucket_name end except ClientError as e begin comment AllAccessDisabled error == bucket not found error e return none...
import logging import boto3 from botocore.exceptions import ClientError def list_bucket_objects(bucket_name): s3 = boto3.client('s3') try: response = s3.list_objects_v2(Bucket=bucket_name) except ClientError as e: # AllAccessDisabled error == bucket not found logging.error...
Python
zaydzuhri_stack_edu_python
function append_generic_csv self sample_sheet_path begin set delimiter = string , with open sample_sheet_path string a as output_file begin set append = writer output_file delimiter=delimiter for row in seqid_rows begin write row append row end end end function
def append_generic_csv(self, sample_sheet_path): delimiter = ',' with open(sample_sheet_path, 'a') as output_file: append = csv.writer(output_file, delimiter=delimiter) for row in self.seqid_rows: append.writerow(row)
Python
nomic_cornstack_python_v1
comment 主函数:调用其他的类来完成整个流程 import jieba import jieba.posseg import re from Classifier import Question_classify from distribute import * class Question begin function __init__ self begin comment self.classify = Question_classify() # 问题分类 comment self.distribute = distribute() # 问题类型匹配分流到对应模版回答 comment self.location = '' ...
# 主函数:调用其他的类来完成整个流程 import jieba import jieba.posseg import re from Classifier import Question_classify from distribute import * class Question: def __init__(self): # self.classify = Question_classify() # 问题分类 # self.distribute = distribute() # 问题类型匹配分流到对应模版回答 # ...
Python
zaydzuhri_stack_edu_python
function Reset self *args begin return call ChFiDS_Stripe_Reset self *args end function
def Reset(self, *args): return _ChFiDS.ChFiDS_Stripe_Reset(self, *args)
Python
nomic_cornstack_python_v1
string @file : 003-keras实现QA版本2.py @author : xiaolu @time1 : 2019-05-31 from functools import reduce import numpy as np from keras.preprocessing.sequence import pad_sequences from keras.layers import Input , Embedding , Dropout from keras.layers import LSTM , RepeatVector , Add , Dense from keras.models import Sequenti...
""" @file : 003-keras实现QA版本2.py @author : xiaolu @time1 : 2019-05-31 """ from functools import reduce import numpy as np from keras.preprocessing.sequence import pad_sequences from keras.layers import Input, Embedding, Dropout from keras.layers import LSTM, RepeatVector, Add, Dense from keras.models import Seque...
Python
zaydzuhri_stack_edu_python
function load_sql sql test **kwargs begin set test_template = call get_template test return split sql_split_re right strip call render sql=sql keyword kwargs string ; end function
def load_sql(sql, test, **kwargs): test_template = env.get_template(test) return sql_split_re.split( test_template.render(sql=sql, **kwargs).rstrip(';'))
Python
nomic_cornstack_python_v1
import requests from selenium import webdriver set options = call ChromeOptions call add_argument string start-maximized call add_argument string disable-infobars set driver = call Chrome chrome_options=options executable_path=string C:\Windows\Chromedriver.exe get driver string https://google.co.in/ set links = call f...
import requests from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path="C:\Windows\Chromedriver.exe") driver.get('https://google.co.in/') links = driver.find_el...
Python
zaydzuhri_stack_edu_python
function add_post begin set t_id = insert survey question=question user_email=email user_name=call get_user_name_from_email email opt1=opt1 opt2=opt2 opt3=opt3 opt4=opt4 comment created_on_human = humanize.naturaltime(datetime.datetime.utcnow()), set t = call survey t_id return json response dictionary post=t end funct...
def add_post(): t_id = db.survey.insert( question = request.vars.question, user_email = request.vars.email, user_name = get_user_name_from_email(request.vars.email), opt1 = request.vars.opt1, opt2 = request.vars.opt2, opt3 = request.vars.opt3, opt4 = request.vars.opt4, #created_on_human = humanize.natu...
Python
nomic_cornstack_python_v1
for i in range 97 123 begin print character i end=string end
for i in range(97,123): print(chr(i),end=" ")
Python
zaydzuhri_stack_edu_python
function add_software_suggestions self name=none url=none begin append software_suggestions call SoftwareSuggestions name=name url=url end function
def add_software_suggestions( self, name: Optional[str] = None, url: Optional[str] = None, ): self.software_suggestions.append( SoftwareSuggestions( name=name, url=url ) )
Python
nomic_cornstack_python_v1
function _create_examples self lines set_type begin set examples = list for tuple i line in enumerate lines begin if i == 0 begin continue end set guid = string %s-%s % tuple set_type line at 0 set text_a = line at 8 set text_b = line at 9 if set_type != string test begin set label = line at - 1 end else begin set lab...
def _create_examples(self, lines, set_type): examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, line[0]) text_a = line[8] text_b = line[9] if set_type != 'test': ...
Python
nomic_cornstack_python_v1
comment def weight(item, extWeight): comment if type(item) == str: comment return extWeight comment else: comment return [weight(item[0], extWeight*2), weight(item[1], extWeight*3), extWeight] comment for _ in range(int(input())): comment postfix = input() comment position = 0 comment nested = [] comment for letter in ...
# def weight(item, extWeight): # if type(item) == str: # return extWeight # else: # return [weight(item[0], extWeight*2), weight(item[1], extWeight*3), extWeight] # # for _ in range(int(input())): # postfix = input() # position = 0 # nested = [] # for letter in postfix: # ...
Python
zaydzuhri_stack_edu_python
comment Written by Gerrit Schoettler, 2018 set f = open string all_critical_sample_input.txt string r set output = open string all_critical_sample_outputTEST.txt string w set input = readline set ans = 1 for cnum in range 1 integer input + 1 begin set p = split strip input set p = list map float p print p print string ...
# Written by Gerrit Schoettler, 2018 f = open("all_critical_sample_input.txt", 'r') output = open("all_critical_sample_outputTEST.txt", 'w') input = f.readline ans = 1 for cnum in range(1, int(input()) + 1): p = input().strip().split() p = list(map(float, p)) print(p) print("Case #%d: %d" % (cnum, ans...
Python
zaydzuhri_stack_edu_python
function shutdown self data=none begin call stop call publish string core dict string event string ShuttingDown call unload_extensions clear thread_events at string mudpi_running set state = not_running set _closed_threads = list comment First pass of threads to find out which ones are slower for tuple thread_name thr...
def shutdown(self, data=None): self.stop() self.events.publish('core', {'event': 'ShuttingDown'}) self.unload_extensions() self.thread_events['mudpi_running'].clear() self.state = CoreState.not_running _closed_threads = [] # First pass of threads to find out whic...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 import pygraphviz as pgv set A = call AGraph directed=true strict=true call add_edge 1 2 call add_edge 1 3 call add_edge 2 4 call add_edge 2 5 call add_edge 5 6 call add_edge 5 7 call add_edge 3 8 call add_edge 3 9 call add_edge 8 10 call add_edge 8 11 set graph_attr at...
#!/usr/bin/env python # coding=utf-8 import pygraphviz as pgv A=pgv.AGraph(directed=True,strict=True) A.add_edge(1,2) A.add_edge(1,3) A.add_edge(2,4) A.add_edge(2,5) A.add_edge(5,6) A.add_edge(5,7) A.add_edge(3,8) A.add_edge(3,9) A.add_edge(8,10) A.add_edge(8,11) A.graph_attr['epsilon']='0.01' A.write('fooOld.dot') A...
Python
zaydzuhri_stack_edu_python
function main begin set inp = string input string Please enter a file name with extension. read inp end function function read inp begin set readFile = open inp string r set data = read readFile call countWord data call countLines data call countCharacters data end function function countWord data begin set count = 0 s...
def main(): inp = str(input("Please enter a file name with extension. ")) read(inp) def read(inp): readFile = open(inp, 'r') data = readFile.read() countWord(data) countLines(data) countCharacters(data) def countWord(data): count = 0 words = data.split() for words in words: ...
Python
zaydzuhri_stack_edu_python
function info message colored=true begin if colored begin print format string {} message end else begin print message end end function
def info(message, colored=True): if colored: print('\033[96m{}\033[00m'.format(message)) else: print(message)
Python
nomic_cornstack_python_v1
comment Import of all the libraries we need to work import sys from altair.vegalite.v4.api import value insert path 0 string /home/apprenant/Documents/Brief-Emotion-Analysis-Text/ import pandas as pd import numpy as np import warnings filter warnings string ignore from sklearn.model_selection import train_test_split fr...
# Import of all the libraries we need to work import sys from altair.vegalite.v4.api import value sys.path.insert(0, "/home/apprenant/Documents/Brief-Emotion-Analysis-Text/") import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") from sklearn.model_selection import train_test_split fr...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment rje_seq - DNA/Protein sequence module comment Copyright (C) 2005 Richard J. Edwards <redwards@cabbagesofdoom.co.uk> comment This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License comment as published by the Free Software...
#!/usr/bin/python # rje_seq - DNA/Protein sequence module # Copyright (C) 2005 Richard J. Edwards <redwards@cabbagesofdoom.co.uk> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version ...
Python
zaydzuhri_stack_edu_python
function show_flashcard begin set random_key = random choice list glossary print string Define: random_key input string Press return to see the definition print glossary at random_key end function
def show_flashcard(): random_key = choice(list(glossary)) print('Define: ', random_key) input('Press return to see the definition') print(glossary[random_key])
Python
nomic_cornstack_python_v1
function predict_and_save images_path model results_folder begin comment Check if the folder exists and create it if necessary set _seg_path = call Path results_folder / string seg make directory _seg_path parents=true exist_ok=true comment Get the list of image file names set images_path_search = call Path images_path...
def predict_and_save(images_path: str, model: StarDist3DCustom, results_folder: str): # Check if the folder exists and create it if necessary _seg_path = Path(results_folder) / "seg" _seg_path.mkdir(parents=True, exist_ok=True) # Get the list of image file names images_path_search = Path(images_pat...
Python
nomic_cornstack_python_v1
function setGood self isGood begin set isGood = isGood if isGood begin call set_title title call set_color string black end else begin call set_title title + string ** dc call set_color string red end end function
def setGood(self, isGood): self.isGood = isGood if self.isGood: self.ax.set_title(self.title) self.ax.title.set_color('black') else: self.ax.set_title(self.title + ' ** dc') self.ax.title.set_color('red')
Python
nomic_cornstack_python_v1
import random from time import * function hangman begin global streak set streak = 0 function difficulty begin while true begin set diff = input string Choose your difficulty (E/M/H): if diff == string E or diff == string e begin return 10 end else if diff == string M or diff == string m begin return 6 end else if diff...
import random from time import * def hangman(): global streak streak = 0 def difficulty(): while True: diff = input('Choose your difficulty (E/M/H): ') if diff == 'E' or diff == 'e': return 10 elif diff == 'M' or diff == 'm': return 6 e...
Python
zaydzuhri_stack_edu_python
from models.models import ApiRequest from models.ciphertext import Ciphertext import models.helpers as helpers import models.funcs as funcs function get_vignere_table begin string Constructs a table of form: { [col index]: { [row index]: [element] ... } ... } set vignere_table = dict for col in call get_upper_alphabet...
from models.models import ApiRequest from models.ciphertext import Ciphertext import models.helpers as helpers import models.funcs as funcs def get_vignere_table(): """ Constructs a table of form: { [col index]: { [row index]: [element] ... } ... } """ vignere_table = {} for col in funcs.ge...
Python
zaydzuhri_stack_edu_python
comment LIST COMPREHENSION & GENERATOR EXPRESSION comment Q.1- Write a python program to print the cube of each value of a list using list comprehension. set l = list 2 3 4 set d = list comprehension o ^ 3 for o in l print d comment Q.2- Write a python program to get all the prime numbers in a specific range using list...
#LIST COMPREHENSION & GENERATOR EXPRESSION #Q.1- Write a python program to print the cube of each value of a list using list comprehension. l=[2,3,4] d=[o**3 for o in l] print(d) #Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension. p=[j for j in range (2,101)...
Python
zaydzuhri_stack_edu_python
function _deref ref begin return T end function
def _deref(ref): return mat[ref][:].T
Python
nomic_cornstack_python_v1
function alphabeta self game depth alpha=decimal string -inf beta=decimal string inf begin comment Checks that the time left is greater than the threshold. if call time_left < TIMER_THRESHOLD begin raise call SearchTimeout end comment Call to the alphabeta algorithm via the max value function. set tuple alpha bestMove ...
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")): # Checks that the time left is greater than the threshold. if self.time_left() < self.TIMER_THRESHOLD: raise SearchTimeout() # Call to the alphabeta algorithm via the max value function. alpha,...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python string linked_list.py Author: Joshua Nasiatka (2016) Description: Create and modify a singly linked list in Python Version: 2016.10.22.2 TO-DO: - Delete specific node - Insert at positon class node begin function __init__ self data=none next=none begin comment this contain the node data se...
#! /usr/bin/env python """ linked_list.py Author: Joshua Nasiatka (2016) Description: Create and modify a singly linked list in Python Version: 2016.10.22.2 TO-DO: - Delete specific node - Insert at positon """ class node: def __init__(self, data = None, next = None): self.data = data # this cont...
Python
zaydzuhri_stack_edu_python
function get_ohlc_data self pair interval=1 since=none ascending=false begin comment create data dictionary set data = dictionary comprehension arg : value for tuple arg value in items locals if arg != string self and value is not none comment query set res = call query_public string OHLC data=data comment check for er...
def get_ohlc_data(self, pair, interval=1, since=None, ascending=False): # create data dictionary data = {arg: value for arg, value in locals().items() if arg != 'self' and value is not None} # query res = self.api.query_public('OHLC', data=data) # check for err...
Python
nomic_cornstack_python_v1
function __repr__ self begin set r = string > set r = r + string depth= + string depth set r = r + string | + string self return r end function
def __repr__(self): r = '> ' r += 'depth= ' + str(self.depth) r += ' | ' + str(self) return r
Python
nomic_cornstack_python_v1
async function info self begin return await call send string miIO.info end function
async def info(self): return await self.send("miIO.info")
Python
nomic_cornstack_python_v1
from datetime import datetime , timezone import os import json import pymongo class Filter begin function __init__ self unique_field begin string Parameters: - unique_field - this field will be used to uniquely identify mongo document set field_name = unique_field set processed_values = set end function function is_pro...
from datetime import datetime, timezone import os import json import pymongo class Filter: def __init__(self, unique_field): """ Parameters: - unique_field - this field will be used to uniquely identify mongo document """ self.field_name = unique_field self.proces...
Python
zaydzuhri_stack_edu_python
import bisect class Autocomplete begin function __init__ self words begin set words = words comment map word to its frequency set word_frequencies = dict call populate_word_frequencies end function function populate_word_frequencies self begin for word in words begin set word_frequencies at word = get word_frequencies...
import bisect class Autocomplete: def __init__(self, words): self.words = words self.word_frequencies = {} # map word to its frequency self.populate_word_frequencies() def populate_word_frequencies(self): for word in self.words: self.word_frequencies[word] = self.w...
Python
jtatman_500k
function getActions board begin set actions = set for row_i in range length board begin for col_i in range length board at 0 begin if board at row_i at col_i == EMPTY begin add actions tuple row_i col_i end end end return actions end function
def getActions(board): actions = set() for row_i in range(len(board)): for col_i in range(len(board[0])): if board[row_i][col_i] == EMPTY: actions.add((row_i, col_i)) return actions
Python
nomic_cornstack_python_v1
function SetDirty self name begin append __dict__ at string __dirty name end function
def SetDirty(self, name): self.__dict__['__dirty'].append(name)
Python
nomic_cornstack_python_v1
import numpy as np from pandas import DataFrame , read_csv from dataProducer import * comment General syntax to import a library but no functions: comment import (library) as (give the library a nickname/alias) import matplotlib.pyplot as plt comment this is how I usually import pandas import pandas as pd comment only ...
import numpy as np from pandas import DataFrame, read_csv from dataProducer import * # General syntax to import a library but no functions: ##import (library) as (give the library a nickname/alias) import matplotlib.pyplot as plt import pandas as pd #this is how I usually import pandas import sys #only needed to det...
Python
zaydzuhri_stack_edu_python
from datetime import datetime import json from util.test import ANY set any_data = any function test_create_order client begin set data = dict string customer_id 1 ; string delivery_address string Calle 40 #20-40 ; string products list dict string id 10 ; string units 1 dict string id 15 ; string units 2 set response =...
from datetime import datetime import json from util.test import ANY any_data = ANY() def test_create_order(client): data = { "customer_id":1, "delivery_address": "Calle 40 #20-40", "products": [ { "id": 10, "units": 1 }, {...
Python
zaydzuhri_stack_edu_python
function _do_his pdbfile pid user_sel begin function add_his_hydrogen n c1 c2 name begin string Create histidine protons set h = deep copy n set d1 = 2.0 * xyz - xyz + xyz set ld1 = 1.03 set f = ld1 / square root sum d1 ^ 2 set d1 = d1 * f set xyz = xyz + d1 set x = x + d1 at 0 set y = y + d1 at 1 set z = z + d1 at 2 s...
def _do_his(pdbfile,pid,user_sel) : def add_his_hydrogen(n,c1,c2,name) : """ Create histidine protons """ h = copy.deepcopy(n) d1 = 2.00*n.xyz-(c1.xyz+c2.xyz) ld1 = 1.0300 f = ld1 / np.sqrt(np.sum(d1**2)) d1 = d1*f h.xyz = n.xyz+d1 h.x = n.x+d1[0] h.y = n.y+d1[1] h...
Python
nomic_cornstack_python_v1
function _light_cnn_block out filter_scale block_name strides=list 1 1 1 include_projection=false begin set conv_fn = partial Conv2D kernel_size=3 padding=string same use_bias=false activation=string relu set out = call call conv_fn filters=filter_scale strides=strides at 0 name=string %s_1_3x3 % block_name out set out...
def _light_cnn_block( out, filter_scale, block_name, strides=[1, 1, 1], include_projection=False): conv_fn = partial( Conv2D, kernel_size=3, padding='same', use_bias=False, activation='relu' ...
Python
nomic_cornstack_python_v1
function post request project_name begin set project = get objects name=project_name set comment = none set page = none set referrer = none set data = get POST string duat-data none if data begin set j = loads encode data string utf-8 set html = j at string html set comment = j at string comment set referrer = j at str...
def post(request, project_name): project = Project.objects.get(name=project_name) comment = page = referrer = None data = request.POST.get('duat-data',None) if data: j = json.loads(data.encode("utf-8")) html = j['html'] comment = j['comment'] referrer = j['referrer'] ...
Python
nomic_cornstack_python_v1
function add_front self item begin insert items 0 item end function
def add_front(self, item): self.items.insert(0, item)
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other UserPermissions begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, UserPermissions): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function gen_cone params coordinate cone_height=3.87 inverse_sqrt_cone_width=0.0032 perm=DEFAULT_PERMUTATION begin comment Many of the initialization parameters for forcing function and other comment functions should be encapsulated in a model specific param object. function gen_cone_fn xx yy zz lx ly lz coord begin de...
def gen_cone(params, coordinate, cone_height=3.87, inverse_sqrt_cone_width=0.0032, perm=DEFAULT_PERMUTATION): # Many of the initialization parameters for forcing function and other # functions should be encapsulated in a model specific param object. def gen_con...
Python
nomic_cornstack_python_v1
if number_of_nights > 7 begin set price_for_night = price_for_night * 0.95 end set total_money = number_of_nights * price_for_night + budget * percent_other_costs / 100 set difference = absolute budget - total_money if total_money <= budget begin print string Ivanovi will be left with { difference } leva after vacation...
if number_of_nights > 7: price_for_night *= 0.95 total_money = number_of_nights * price_for_night + budget * percent_other_costs / 100 difference = abs(budget - total_money) if total_money <= budget: print(f"Ivanovi will be left with {difference:.2f} leva after vacation.") else: print(f"{difference:.2f} lev...
Python
zaydzuhri_stack_edu_python
function get_num_of_characters inputStr begin set count = 0 for i in range 0 length inputStr begin set count = count + 1 end return count end function function output_without_whitespace inputStr begin set inputStr = replace inputStr string string return inputStr end function if __name__ == string __main__ begin set in...
def get_num_of_characters(inputStr): count = 0 for i in range(0,len(inputStr)): count+=1 return count def output_without_whitespace(inputStr): inputStr = inputStr.replace(' ', '') return inputStr if __name__ == '__main__': inputStr = input('Enter a sentence or phrase: ') print()...
Python
zaydzuhri_stack_edu_python
function GetParentFileEntry self begin set parent_location = none set location = get attribute path_spec string location none if location is not none begin set parent_location = call DirnamePath location if parent_location == string begin set parent_location = PATH_SEPARATOR end end set parent_path_spec = get attribut...
def GetParentFileEntry(self): parent_location = None location = getattr(self.path_spec, 'location', None) if location is not None: parent_location = self._file_system.DirnamePath(location) if parent_location == '': parent_location = self._file_system.PATH_SEPARATOR parent_path_spec...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Implement Laker model for follicular growth comment In[12]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.integrate import odeint comment In[54]: comment -----------------------------------------------...
#!/usr/bin/env python # coding: utf-8 # # Implement Laker model for follicular growth # In[12]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.integrate import odeint # In[54]: #-----------------------------------------------------------------------------...
Python
zaydzuhri_stack_edu_python
function __init__ self refstd radmax=1.5 fig=none rect=111 label=string _ begin from matplotlib.projections import PolarAxes import mpl_toolkits.axisartist.floating_axes as FA import mpl_toolkits.axisartist.grid_finder as GF comment Reference standard deviation set refstd = refstd set tr = call PolarTransform comment C...
def __init__(self, refstd, radmax=1.5, fig=None, rect=111, label='_'): from matplotlib.projections import PolarAxes import mpl_toolkits.axisartist.floating_axes as FA import mpl_toolkits.axisartist.grid_finder as GF self.refstd = refstd # Reference standard deviation ...
Python
nomic_cornstack_python_v1
comment Python3 code to demonstrate working of comment Convert String list to ascii values comment using list comprehension + ord() comment initialize list set test_list = list string RSA es muy importante comment printing original list print string The original list : + string test_list comment Convert String list to ...
# Python3 code to demonstrate working of # Convert String list to ascii values # using list comprehension + ord() # initialize list test_list = ['RSA es muy importante'] # printing original list print("The original list : " + str(test_list)) # Convert String list to ascii values # using list comprehensi...
Python
zaydzuhri_stack_edu_python
function get self page=0 page_size=100 begin return list comprehension item for item in find self page=page page_size=page_size end function
def get(self, page: int = 0, page_size: int = 100) -> list: return [item for item in self.find(page=page, page_size=page_size)]
Python
nomic_cornstack_python_v1
function test_nota self begin call nota_final __author_1__ __author_2__ end function
def test_nota(self): self.nota_final(__author_1__, __author_2__)
Python
nomic_cornstack_python_v1
from math import * function isPrime x begin set raiz = square root x for i in range 2 integer raiz + 1 begin if x % i == 0 begin return false end end return true end function set x = 600851475143 for i in range 2 integer square root x begin if call isPrime i begin while x % i == 0 begin comment print i set x = x / i se...
from math import * def isPrime(x): raiz=sqrt(x) for i in range(2, int(raiz)+1): if(x%i==0): return False return True x=600851475143 for i in range(2, int(sqrt(x))): if(isPrime(i)): while x%i==0: #print i x/=i aux=i
Python
zaydzuhri_stack_edu_python
string context-sensitive spelling correction import numpy as np from pca import PCA from vocab import Vocab from nltk import word_tokenize set embedding_directory = string /projects/csl/viswanath/data/hgong6/Preposition/data/prepositions_word_vector/ set vocabInputFile = string vocab.txt set vectorInputFile = string ve...
""" context-sensitive spelling correction """ import numpy as np from pca import PCA from vocab import Vocab from nltk import word_tokenize embedding_directory = "/projects/csl/viswanath/data/hgong6/Preposition/data/prepositions_word_vector/" vocabInputFile = "vocab.txt" vectorInputFile = "vectors.bin" def cosSim(ar...
Python
zaydzuhri_stack_edu_python
function update_persistent_boot self device_type=list mac=none begin comment Check if the input is valid for item in device_type begin if upper item not in DEVICE_COMMON_TO_RIS begin raise call IloInvalidInputError string Invalid input. Valid devices: NETWORK, HDD, ISCSI or CDROM. end end call _update_persistent_boot ...
def update_persistent_boot(self, device_type=[], mac=None): # Check if the input is valid for item in device_type: if item.upper() not in DEVICE_COMMON_TO_RIS: raise exception.IloInvalidInputError("Invalid input. Valid " "d...
Python
nomic_cornstack_python_v1
string Author: Carmen Wu import random from BaseAI import BaseAI from Grid import Grid import time import math set MAX_DEPTH = 3 set TIME_LIMIT = 0.195 set directionVectors = tuple tuple - 1 0 tuple 1 0 tuple 0 - 1 tuple 0 1 set tuple UP_VEC DOWN_VEC LEFT_VEC RIGHT_VEC = tuple tuple - 1 0 tuple 1 0 tuple 0 - 1 tuple 0 ...
""" Author: Carmen Wu """ import random from BaseAI import BaseAI from Grid import Grid import time import math MAX_DEPTH = 3 TIME_LIMIT = 0.195 directionVectors = (UP_VEC, DOWN_VEC, LEFT_VEC, RIGHT_VEC) = ((-1, 0), (1, 0), (0, -1), (0, 1)) directionMap = { 0: UP_VEC, 1: RIGHT_VEC, 2: DOWN_VEC, 3: LE...
Python
zaydzuhri_stack_edu_python
function CurveCurveValidate curveA curveB tolerance overlapTolerance multiple=false begin set url = string rhino/geometry/intersect/intersection/curvecurvevalidate-curve_curve_double_double_intarray_textlog if multiple begin set url = url + string ?multiple=true end set args = list curveA curveB tolerance overlapTolera...
def CurveCurveValidate(curveA, curveB, tolerance, overlapTolerance, multiple=False): url = "rhino/geometry/intersect/intersection/curvecurvevalidate-curve_curve_double_double_intarray_textlog" if multiple: url += "?multiple=true" args = [curveA, curveB, tolerance, overlapTolerance] if multiple: args = l...
Python
nomic_cornstack_python_v1
function __getstate__ self begin comment grab all the traits set traits = call traits comment filter out transient traits set traits = list comprehension trait for trait in traits if call get_metadata string transient in list none false comment build a dictionary comment TODO: use self.__dict__ instead of self._trait_v...
def __getstate__(self): # grab all the traits traits = self.traits() # filter out transient traits traits = [trait for trait in traits if traits[trait].get_metadata("transient") in [None, False]] # build a dictionary # TODO: use self.__dict__ instead of self._trait_valu...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Feb 03 22:27:36 2019 @author: Shiyan import arcpy import pandas as pd import os comment 1. Prepare raster and shapefiles set overwriteOutput = true comment Set environment settings and path set in_path = string D:/GWU/AdamJ/task6/mission set out_path = string D:/GWU/A...
# -*- coding: utf-8 -*- """ Created on Sun Feb 03 22:27:36 2019 @author: Shiyan """ import arcpy import pandas as pd import os # 1. Prepare raster and shapefiles arcpy.env.overwriteOutput = True # Set environment settings and path in_path = "D:/GWU/AdamJ/task6/mission" out_path = "D:/GWU/AdamJ/task6/mission/result/...
Python
zaydzuhri_stack_edu_python
for i in range n begin set list3 = split input for j in range integer list3 at 0 begin set list2 at integer list3 at j + 1 - 1 = 1 end end for i in range m begin if list2 at i == 0 begin print string NO set isR = false break end end if isR begin print string YES end
for i in range(n): list3=input().split() for j in range(int(list3[0])): list2[int(list3[j+1])-1]=1 for i in range(m): if list2[i]==0: print('NO') isR=False break if isR: print('YES')
Python
zaydzuhri_stack_edu_python
set vowels = string aeiou set string = input print list comprehension vowel for vowel in string if vowel in vowels
vowels = 'aeiou' string = input() print([vowel for vowel in string if vowel in vowels])
Python
zaydzuhri_stack_edu_python
string Classes representing dynamic instances. Contain equation of motion and numerical update. Own separate class so that new dynamics can be added here and instantiated through other modules for new UAV agents import numpy as np import math from scipy.integrate import ode class Dynamics extends object begin function ...
''' Classes representing dynamic instances. Contain equation of motion and numerical update. Own separate class so that new dynamics can be added here and instantiated through other modules for new UAV agents ''' import numpy as np import math from scipy.integrate import ode class Dynamics(object): def __init__(s...
Python
zaydzuhri_stack_edu_python
function reorder_missing_matrix matrix missing reorder_rows=false reorder_cols=false is_diagonal=false inplace=false prefix=none begin if prefix is none begin set prefix = call find_best_blas_type tuple matrix at 0 end set reorder = prefix_reorder_missing_matrix_map at prefix if not inplace begin set matrix = copy np m...
def reorder_missing_matrix(matrix, missing, reorder_rows=False, reorder_cols=False, is_diagonal=False, inplace=False, prefix=None): if prefix is None: prefix = find_best_blas_type((matrix,))[0] reorder = prefix_reorder_missing_matrix_map[prefix]...
Python
nomic_cornstack_python_v1
function __init__ self log_dir seed create_model_dir=true begin set seed = integer seed set log_dir = call Path log_dir set model_dir = call Path log_dir / string model make directory log_dir parents=true exist_ok=true if create_model_dir begin make directory model_dir parents=true exist_ok=true end set tensorboard_dir...
def __init__(self, log_dir, seed, create_model_dir=True): self.seed = int(seed) self.log_dir = Path(log_dir) self.model_dir = Path(log_dir) / 'model' self.log_dir.mkdir (parents=True, exist_ok=True) if create_model_dir: self.model_dir.mkdir(parents=True, exist...
Python
nomic_cornstack_python_v1
import csv with open string ./date.csv as csvFile begin set dates = reader csvFile for x in dates begin print x end end
import csv with open('./date.csv') as csvFile: dates = csv.reader(csvFile) for x in dates: print(x)
Python
zaydzuhri_stack_edu_python
import datetime from django.test import TestCase comment Create your tests here. from django.urls.base import reverse from django.utils import timezone from polls.models import Question function create_questions question_text days begin string Creates a question with the given `question_text` and published the given nu...
import datetime from django.test import TestCase # Create your tests here. from django.urls.base import reverse from django.utils import timezone from polls.models import Question def create_questions(question_text, days): """ Creates a question with the given `question_text` and published the given nu...
Python
zaydzuhri_stack_edu_python
function get_literals self c i depth begin string Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). set result = list string set is_dollar = false try begin while c begin set ignore_brace = is_dollar set i...
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
Python
jtatman_500k
function generate_post_filepath title date begin set post_file_date = string format time datetime date string %Y/%m/%d/ set title = join string generator expression char for char in lower title if is alphanumeric char or char == string return post_file_date + replace title string string - end function
def generate_post_filepath(title, date): post_file_date = datetime.datetime.strftime(date, '%Y/%m/%d/') title = ''.join(char for char in title.lower() if ( char.isalnum() or char == ' ')) return post_file_date + title.replace(' ', '-')
Python
nomic_cornstack_python_v1