code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function read_binning_file file_name lmax begin set tuple bin_lo bin_hi bin_c = call loadtxt file_name unpack=true set id = where bin_hi < lmax set tuple bin_lo bin_hi bin_c = tuple bin_lo at id bin_hi at id bin_c at id if bin_lo at 0 < 2 begin set bin_lo at 0 = 2 end set bin_hi = as type bin_hi int set bin_lo = as typ...
def read_binning_file(file_name, lmax): bin_lo,bin_hi,bin_c = plt.loadtxt(file_name,unpack=True) id = np.where(bin_hi <lmax) bin_lo,bin_hi,bin_c=bin_lo[id],bin_hi[id],bin_c[id] if bin_lo[0]<2: bin_lo[0]=2 bin_hi=bin_hi.astype(np.int) bin_lo=bin_lo.astype(np.int) bin_size=bin_hi-bin_...
Python
nomic_cornstack_python_v1
function frange start stop increment begin while start <= stop begin yield start set start = start + increment end end function
def frange(start, stop, increment): while(start <= stop): yield start start += increment
Python
zaydzuhri_stack_edu_python
function is_installed self begin set result = run list string which string brotab if returncode == 0 begin return true end return false end function
def is_installed(self): result = subprocess.run(['which', 'brotab']) if result.returncode == 0: return True return False
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import sys import re import numpy as np function main argv begin if length argv != 2 begin print format string Usage: {} INPUT_FILE argv at 0 exit 1 end set pattern = compile string #*@ (.*),(.*): (.*)x(.*) set fabric = zeros tuple 1000 1000 with open argv at 1 string r encoding=string utf-8 a...
#!/usr/bin/python3 import sys import re import numpy as np def main(argv): if len(argv) != 2: print("Usage: {} INPUT_FILE".format(argv[0])) sys.exit(1) pattern = re.compile("#*@ (.*),(.*): (.*)x(.*)") fabric = np.zeros((1000, 1000)) with open(argv[1], "r", encoding="utf-8") as fin: ...
Python
zaydzuhri_stack_edu_python
from frontend.configuration import FILE_BUCKET_NAME import frontend.db import simplejson as json class File begin decorator classmethod function key cls owner name begin return join string __ list owner name end function decorator classmethod function get_file cls owner name begin set file_json = call get_item FILE_BUC...
from frontend.configuration import FILE_BUCKET_NAME import frontend.db import simplejson as json class File(): @classmethod def key(cls, owner, name): return '__'.join([owner, name]) @classmethod def get_file(cls, owner, name): file_json = frontend.db.get_item(FILE_BUCKET_NAME, File....
Python
zaydzuhri_stack_edu_python
function test_part_icc_err_status self begin comment Set the partition status to an invalid status for this operation set partition1 = get urihandler hmc string /api/partitions/1 true set partition1 at string status = string starting comment the function to be tested: with raises HTTPError begin post hmc string /api/pa...
def test_part_icc_err_status(self): # Set the partition status to an invalid status for this operation partition1 = self.urihandler.get(self.hmc, '/api/partitions/1', True) partition1['status'] = 'starting' # the function to be tested: with pytest.raises(HTTPError): ...
Python
nomic_cornstack_python_v1
function primes n begin set sieve = list true * n for i in range 3 integer n ^ 0.5 + 1 2 begin if sieve at i begin set sieve at slice i * i : : 2 * i = list false * n - i * i - 1 // 2 * i + 1 end end return list 2 + list comprehension i for i in range 3 n 2 if sieve at i end function
def primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1, 2): if sieve[i]: sieve[i*i::2*i]=[False] * ((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3, n, 2) if sieve[i]]
Python
nomic_cornstack_python_v1
for line in file begin set line = strip line string set word = split line set lines = lines + 1 set words = words + length word set characters = characters + length line end close file print string print string No of Lines== lines print string No of Words== words print string No of Charactters== characters print string
for line in file: line = line.strip("\n") word = line.split() lines = lines + 1 words = words + len(word) characters = characters + len(line) file.close() print("") print("No of Lines==",lines) print("No of Words==",words) print("No of Charactters==",characters) print("")
Python
zaydzuhri_stack_edu_python
comment Desenvolva um programa que leia o comprimento de três retas comment e diga ao usuário se elas podem ou não formar um triângulo. print string Olá, vamos formar um triangulo! set r1 = decimal input string Digite a primeira reta: set r2 = decimal input string Digite a segunda reta: set r3 = decimal input string Di...
#Desenvolva um programa que leia o comprimento de três retas #e diga ao usuário se elas podem ou não formar um triângulo. print('Olá, vamos formar um triangulo!') r1 = float(input('Digite a primeira reta: ')) r2 = float(input('Digite a segunda reta: ')) r3 = float(input('Digite a terceira reta: ')) if r1 < r2 + r3 and...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment _*_ coding: utf-8 _*_ comment Exercise 25: Even More Practice function break_words stuff begin string This fucntion will break up wpords for us. set words = split stuff string return words end function function sort_words words begin string Sortes the words. return sorted words end...
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ # Exercise 25: Even More Practice def break_words(stuff): """This fucntion will break up wpords for us.""" words = stuff.split(' ') return words def sort_words(words): """Sortes the words.""" return sorted(words) def print_first_word(words): """...
Python
zaydzuhri_stack_edu_python
function upload_material request username course_code begin if method == string POST begin set errors = dict comment try to get user that upload file comment if user log in try begin set user = get objects username=username if call ensure_login user == false begin return call JsonResponse dict string login string User...
def upload_material(request, username, course_code): if request.method == "POST": errors = {} # try to get user that upload file # if user log in try: user = User.objects.get(username=username) if ensure_login(user) == False: return ...
Python
nomic_cornstack_python_v1
function _do_ratio objects ax=false tal=false obj=false seg=false mul=false cos=false td=false options=false ylim=false xlim=false begin comment internal function to make a new mctal object with ratio values and plot it on ax import numpy import MCNPtools.tally import MCNPtools.mctal end function comment input check
def _do_ratio(objects,ax=False,tal=False,obj=False,seg=False,mul=False,cos=False,td=False,options=False,ylim=False,xlim=False): ### internal function to make a new mctal object with ratio values and plot it on ax import numpy import MCNPtools.tally import MCNPtools.mctal ### input check
Python
zaydzuhri_stack_edu_python
function sink_update self sink_name filter_ destination unique_writer_identity=false begin comment parse name out of full resoure name set name = split sink_name string / at - 1 set sink_pb = call LogSink name=name filter=filter_ destination=destination set request = call UpdateSinkRequest sink_name=sink_name sink=sink...
def sink_update( self, sink_name, filter_, destination, *, unique_writer_identity=False, ): name = sink_name.split("/")[-1] # parse name out of full resoure name sink_pb = LogSink( name=name, filter=filter_, destina...
Python
nomic_cornstack_python_v1
comment def process(user_input, nlu_data): comment out_text = 'this is deposit.py' comment output = { comment 'bot_response_text': out_text, comment 'context': 'None' comment } comment return output import config import sqlite3 import re import createlog function do_deposit username amount begin try begin set conn = ca...
# def process(user_input, nlu_data): # out_text = 'this is deposit.py' # output = { # 'bot_response_text': out_text, # 'context': 'None' # } # return output import config import sqlite3 import re import createlog def do_deposit(username,amount): try: conn = sqlite3.connect(...
Python
zaydzuhri_stack_edu_python
comment should be a easy implementation problem for i in range 10 99 begin for j in range i + 1 100 begin set s1 = string i set s2 = string j end end
#should be a easy implementation problem for i in range(10,99): for j in range(i+1,100): s1 = str(i) s2 = str(j)
Python
zaydzuhri_stack_edu_python
function icon self begin return ICON_PRESENCE_HOLD end function
def icon(self): return ICON_PRESENCE_HOLD
Python
nomic_cornstack_python_v1
function run self command begin debug string running:%s on %s % tuple command instance_id set status = 0 try begin set t = call exec_command command end except SSHException begin set status = 1 end set std_out = read t at 1 set std_err = read t at 2 close t at 0 close t at 1 close t at 2 debug string stdout: %s % std_o...
def run(self, command): boto.log.debug('running:%s on %s' % (command, self.server.instance_id)) status = 0 try: t = self._ssh_client.exec_command(command) except paramiko.SSHException: status = 1 std_out = t[1].read() std_err = t[2].read() ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from __future__ import unicode_literals import pylab import numpy as np import matplotlib.pyplot as plt import matplotlib from scipy.optimize import curve_fit from scipy.stats import chisquare function main begin set rcParams at string text.usetex = true set rc...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import pylab import numpy as np import matplotlib.pyplot as plt import matplotlib from scipy.optimize import curve_fit from scipy.stats import chisquare def main(): matplotlib.rcParams['text.usetex'] = True matplotlib.rcParam...
Python
zaydzuhri_stack_edu_python
comment Probability of n d-sided dices to give a total of s function prob n d s begin if s <= 0 begin return 0 end else if n == 1 and s <= d begin return 1 / d end else if n > 1 begin set o = 0 for r in range 1 d + 1 begin set o = o + call prob n - 1 d s - r * 1 / d end return o end else begin return 0 end end function...
# Probability of n d-sided dices to give a total of s def prob(n, d, s): if s <= 0: return 0 elif n == 1 and s <= d: return 1 / d elif n > 1: o = 0 for r in range(1, d + 1): o += prob(n - 1, d, s - r) * 1 / d return o else: return 0 # What is...
Python
zaydzuhri_stack_edu_python
function __init__ self filepath begin comment Convert to path instance if passed a string if is instance filepath str begin set filepath : Path = call Path filepath end comment Assert that the file exist try begin assert exists filepath end except AssertionError begin raise FileNotFoundError end comment Attch object pr...
def __init__(self, *, filepath: Union[str, Path] ) -> None: # Convert to path instance if passed a string if isinstance(filepath, str): filepath: Path = Path(filepath) # Assert that the file exist try: assert filepath.exists() ...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- from PIL import Image set img1 = open string test.png show comment getbands() - 显示该图像的所有通道,返回一个tuple set bands = call getbands
# -*- coding:utf-8 -*- from PIL import Image img1 = Image.open("test.png") img1.show() # getbands() - 显示该图像的所有通道,返回一个tuple bands = img1.getbands()
Python
zaydzuhri_stack_edu_python
function net_return self begin set returns = __market_value + __cash / __original_value - 1 return returns end function
def net_return(self) -> int: returns = ((self.__market_value + self.__cash)/self.__original_value) - 1 return returns
Python
nomic_cornstack_python_v1
function read_file fp begin set word_dict = dict for word in fp begin set word = strip word if length word < 3 begin pass end else if string - in word begin pass end else if string ' in word begin pass end else begin lower word set word_dict at word = 1 end end return word_dict end function
def read_file(fp): word_dict = {} for word in fp: word = word.strip() if len(word) < 3: pass elif '-' in word: pass elif "'" in word: pass else: word.lower() word_dict[word] = 1 return word_dict
Python
nomic_cornstack_python_v1
import sys import csv import random import logging set options = list string wanna top up string wanna scoop set fortune = list string успех string фейл set total_attempt = 0 set scoop_attempt = 0 set top_attempt = 0 set total_scoop = 0 set total_top = 0 set total_failed_scoop = 0 set total_failed_top = 0 set scoop_mis...
import sys import csv import random import logging options = ['wanna top up', 'wanna scoop'] fortune = ['успех', 'фейл'] total_attempt = 0 scoop_attempt = 0 top_attempt = 0 total_scoop = 0 total_top = 0 total_failed_scoop = 0 total_failed_top = 0 scoop_mistake = 0 top_mistake = 0 format = '%(asctim...
Python
zaydzuhri_stack_edu_python
function plot_violin res begin set tuple fig ax = call subplots figsize=tuple 5 5 set data = list set labels = list for k in keys res begin append data res at k append labels k end call violinplot data showmeans=false showmedians=true call set_title string Violin plot comment adding horizontal grid lines grid true ca...
def plot_violin(res): fig, ax = plt.subplots(figsize=(5, 5)) data = [] labels = [] for k in res.keys(): data.append(res[k]) labels.append(k) ax.violinplot(data, showmeans=False, showmedians=True) ax.set_title('Violin plot') # adding horizontal grid lines ax.yaxis.grid(Tru...
Python
nomic_cornstack_python_v1
function read_cpu_usage begin set cpuInfo = ordered dictionary with open string /proc/stat as f begin for line in f begin set l = split line if length l < 5 begin continue end if starts with l at 0 string cpu begin set cpuInfo at l at 0 = l end end end return cpuInfo end function
def read_cpu_usage(): cpuInfo = OrderedDict() with open('/proc/stat') as f: for line in f: l = line.split() if len(l) < 5: continue if l[0].startswith('cpu'): cpuInfo[l[0]] = l return cpuInfo
Python
nomic_cornstack_python_v1
import sys import random import threading import numpy as np import time import math from uart import uart
import sys import random import threading import numpy as np import time import math from uart import uart
Python
zaydzuhri_stack_edu_python
class Solution begin comment @param A : list of integers comment @return a list of integers function plusOne self A begin if A at 0 == 0 and length A == 1 begin set A at 0 = 1 return A end comment Remove front zero from the list for item in A begin if item == 0 begin set A = A at slice 1 : : end else begin break end ...
class Solution: # @param A : list of integers # @return a list of integers def plusOne(self, A): if A[0] == 0 and len(A) == 1: A[0] = 1 return A # Remove front zero from the list for item in A: if item == 0: A = A[1:] e...
Python
zaydzuhri_stack_edu_python
function create cls name begin return call create name=name end function
def create(cls, name): return cls.objects.create(name=name)
Python
nomic_cornstack_python_v1
function collect_archive_information self begin call update_extra_data dict string filename name ; string size st_size ; none call multi_checksums archive_path end function
def collect_archive_information(self): self.project.update_extra_data( { "filename": self.archive_path.name, "size": self.archive_path.stat().st_size, **multi_checksums(self.archive_path), } )
Python
nomic_cornstack_python_v1
comment script is a text file containing the statements that comprise a Python program. Once you have created the script, you can execute #it over and over without having to retype it each time. Scripts are editable. from sys import argv comment read the WYSS section for how to run this set tuple script first second th...
#script is a text file containing the statements that comprise a Python program. Once you have created the script, you can execute #it over and over without having to retype it each time. Scripts are editable. from sys import argv # read the WYSS section for how to run this script, first, second, third = argv print("...
Python
zaydzuhri_stack_edu_python
import random comment DNA : Unique information each entity holds class DNA extends object begin function __init__ self color=none begin if color == none begin set gene = 0 end else begin set gene = color end end function function __hash__ self begin return gene end function function mutate self mutationRate begin if ra...
import random #### DNA : Unique information each entity holds class DNA(object): def __init__(self, color = None): if ( color==None): self.gene = 0 else : self.gene = color def __hash__(self): return self.gene def mutate(self, mutationRate): ...
Python
zaydzuhri_stack_edu_python
function get_all_games self begin set games = string for i in range 0 call llen list_name begin set games = games + decode call lindex list_name i string utf-8 + string end set games = games or string Sorry. No recent game found in your searches return games end function
def get_all_games(self) -> str: games = "" for i in range(0, redisClient.llen(self.list_name)): games += redisClient.lindex(self.list_name, i).decode("utf-8") + "\n" games = games or "Sorry. No recent game found in your searches" return games
Python
nomic_cornstack_python_v1
function update_application_resource_lifecycle ApplicationName=none ResourceLifecycleConfig=none begin pass end function
def update_application_resource_lifecycle(ApplicationName=None, ResourceLifecycleConfig=None): pass
Python
nomic_cornstack_python_v1
string Project Euler Problem 18 http://projecteuler.net/index.php?section=problems&id=18 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of...
""" Project Euler Problem 18 http://projecteuler.net/index.php?section=problems&id=18 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom ...
Python
zaydzuhri_stack_edu_python
import pyautogui import time import pyperclip import json import requests from datetime import datetime call click 94 1059 sleep 1 call typewrite string kakaotalk sleep 1 call moveTo 94 520 sleep 1 call doubleClick sleep 20 call click 838 338 sleep 1 call click 1082 276 sleep 1 copy pyperclip string 3학년 애반(선미쌤) call ho...
import pyautogui import time import pyperclip import json import requests from datetime import datetime pyautogui.click(94,1059) time.sleep(1) pyautogui.typewrite("kakaotalk") time.sleep(1) pyautogui.moveTo(94,520) time.sleep(1) pyautogui.doubleClick() time.sleep(20) pyautogui.click(838,338) time.sleep(1) pyautogui.cl...
Python
zaydzuhri_stack_edu_python
function draw self canvas begin set left = pos at 0 set width = width set height = call getHeight set top = pos at 1 - height / 2 comment outline perimeter set x = 0.5 * angle * width set A = tuple left top set C = tuple left top + height set E = tuple left + 0.5 * width top + height + x set D = tuple left + width C at...
def draw(self, canvas): left = self.pos[0] width = self.width height = self.getHeight() top = self.pos[1] - height/2 # outline perimeter x = 0.5 * self.angle * width A = (left, top) C = (left, top + height) E = (left + 0.5 * width, top + height + x) D = (left + width, C[1]) B = (left + width, to...
Python
nomic_cornstack_python_v1
function close self begin return _close end function
def close(self) -> float: return self._close
Python
nomic_cornstack_python_v1
function fetch_sample_data self table begin set sampler = call DatalakeSampler session=client table=data_frame_list profile_sample_config=profile_sample_config partition_details=partition_details profile_sample_query=profile_query return call fetch_dl_sample_data end function
def fetch_sample_data(self, table) -> TableData: sampler = DatalakeSampler( session=self.client, table=self.data_frame_list, profile_sample_config=self.profile_sample_config, partition_details=self.partition_details, profile_sample_query=self.profile_q...
Python
nomic_cornstack_python_v1
function test_rotate_left_reassigns_root small_tree begin call _rotate_left root assert value == 80 end function
def test_rotate_left_reassigns_root(small_tree): small_tree._rotate_left(small_tree.root) assert small_tree.root.value == 80
Python
nomic_cornstack_python_v1
function graph_transformation_answer begin set correct_option = string D print string The correct answer is: { correct_option } return correct_option end function comment Call the function to see the output call graph_transformation_answer
def graph_transformation_answer(): correct_option = 'D' print(f"The correct answer is: {correct_option}") return correct_option # Call the function to see the output graph_transformation_answer()
Python
dbands_pythonMath
import requests , sqlite3 from bs4 import BeautifulSoup set url = string https://news.google.com/topics/CAAqJQgKIh9DQkFTRVFvSUwyMHZNR3QwTlRFU0JYcG9MVlJYS0FBUAE?hl=zh-TW&gl=TW&ceid=TW%3Azh-Hant function cleanup dom begin set title = list comprehension call getText for tt in find all dom string a string DY5T1d set source...
import requests, sqlite3 from bs4 import BeautifulSoup url = 'https://news.google.com/topics/CAAqJQgKIh9DQkFTRVFvSUwyMHZNR3QwTlRFU0JYcG9MVlJYS0FBUAE?hl=zh-TW&gl=TW&ceid=TW%3Azh-Hant' def cleanup(dom): title = [tt.getText() for tt in dom.find_all('a', 'DY5T1d')] source = [s.getText() for s in dom.find_all('a', cla...
Python
zaydzuhri_stack_edu_python
for i in listofpeople begin set fronthalf = i at slice 0 : 7 : set backhalf = i at slice 7 : : set thelistofrows = listofrows set thelistofcolumns = listofcolumns for z in fronthalf begin if z == string F begin set thelistofrows = thelistofrows at slice : integer length thelistofrows / 2 : end else if z == string ...
for i in listofpeople: fronthalf = i[0:7] backhalf = i[7:] thelistofrows = listofrows thelistofcolumns = listofcolumns for z in fronthalf: if z =='F': thelistofrows = thelistofrows[:int((len(thelistofrows)/2))] elif z == 'B': ...
Python
zaydzuhri_stack_edu_python
function _get_extract_iter self begin comment type: () -> Iterator[TableMetadata] for tuple key group in group by call _get_raw_extract_iter _get_table_key begin set columns = list for row in group begin set last_row = row append columns call ColumnMetadata row at string col_name row at string col_description row at s...
def _get_extract_iter(self): # type: () -> Iterator[TableMetadata] for key, group in groupby(self._get_raw_extract_iter(), self._get_table_key): columns = [] for row in group: last_row = row columns.append(ColumnMetadata(row['col_name'], row['col_...
Python
nomic_cornstack_python_v1
function test_get_albums_query_param self id_name_elms service_config request begin set return_value = id_name_elms set args at string query = string Dummy set params = parameters request request set service = call AvalonMetadataService service_config set results = call get_albums params assert results == id_name_elms ...
def test_get_albums_query_param(self, id_name_elms, service_config, request): service_config.search.search_albums.return_value = id_name_elms request.args['query'] = 'Dummy' params = avalon.web.request.Parameters(request) service = avalon.web.services.AvalonMetadataService(service_confi...
Python
nomic_cornstack_python_v1
function train self inputData BATCH_SIZE=64 lstm_hidden_cells=list 150 100 epochs=50 earlystop_patience=5 begin set data = call prepare_data inputData call create_model lstm_hidden_cells set batch_size = BATCH_SIZE set earlystop = call EarlyStopping monitor=string loss min_delta=0 patience=earlystop_patience verbose=0 ...
def train(self, inputData, BATCH_SIZE=64, lstm_hidden_cells=[150, 100], epochs=50, earlystop_patience=5): self.data = self.prepare_data(inputData) self.create_model(lstm_hidden_cells) self.batch_size = BATCH_SIZE earlystop = EarlyStopping( monitor='loss', min_delta=0, patience=earlystop_patience, verbose=0...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- encoding: utf-8 -*- import sys import codecs from math import sqrt import datetime import MySQLdb import gensim import gensim.parsing function handler begin return call connect host=string localhost port=3306 user=string twitter passwd=string db=string twitter use_unicode=1 end...
#!/usr/bin/env python #-*- encoding: utf-8 -*- import sys import codecs from math import sqrt import datetime import MySQLdb import gensim import gensim.parsing def handler(): return MySQLdb.connect( host = "localhost", port = 3306, user = "twitter", passwd = "", db = "twitter", use_unicode=1 ) def cr...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import dbus import sys function set_br level begin set bus = call SystemBus set kbd_blight_proxy = call get_object string org.freedesktop.UPower string /org/freedesktop/UPower/KbdBacklight set kbd_blight = call Interface kbd_blight_proxy string org.freedesktop...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import dbus import sys def set_br(level:int): bus = dbus.SystemBus() kbd_blight_proxy = bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower/KbdBacklight') kbd_blight = dbus.Interface(kbd_blight_proxy, 'org.freedesktop.UPower.KbdBacklight') m...
Python
zaydzuhri_stack_edu_python
function optimization_parameters self topology begin set parameters = zeros call number_of_parameters for tuple pkey parameter in items parameters begin set parameters at pkey = call start_value topology end return parameters end function
def optimization_parameters(self, topology): parameters = np.zeros(self.number_of_parameters()) for pkey, parameter in self.parameters.items(): parameters[pkey] = parameter.start_value(topology) return parameters
Python
nomic_cornstack_python_v1
function posterior_prediction self begin if __posterior_prediction is not none begin return __posterior_prediction end else begin if predictions is not none begin try begin if nnz_obs == 0 begin log string no non-zero obs, posterior equals prior return prior_prediction end log string propagating posterior to prediction...
def posterior_prediction(self): if self.__posterior_prediction is not None: return self.__posterior_prediction else: if self.predictions is not None: try: if self.pst.nnz_obs == 0: self.log("no non-zero obs, posterior eq...
Python
nomic_cornstack_python_v1
function get_targets self sampling_results rcnn_train_cfg concat=true begin set pos_proposals = list comprehension pos_bboxes for res in sampling_results set neg_proposals = list comprehension neg_bboxes for res in sampling_results set pos_gt_bboxes = list comprehension pos_gt_bboxes for res in sampling_results set pos...
def get_targets(self, sampling_results: List[SamplingResult], rcnn_train_cfg: ConfigDict, concat: bool = True) -> tuple: pos_proposals = [res.pos_bboxes for res in sampling_results] neg_proposals = [res.neg_bboxes for res in sampling_results] ...
Python
nomic_cornstack_python_v1
import os import argparse import math import xml.etree.ElementTree as ET function main begin comment Commandline arguments set parser = call ArgumentParser call add_argument string -i string --in dest=string inputfile required=true call add_argument string -o string --out dest=string outputfile default=string set args ...
import os import argparse import math import xml.etree.ElementTree as ET def main(): # Commandline arguments parser = argparse.ArgumentParser() parser.add_argument("-i", "--in", dest="inputfile", required=True) parser.add_argument("-o", "--out", dest="outputfile", default="") args = parser.parse_ar...
Python
zaydzuhri_stack_edu_python
function sort_list_of_strings list_of_strings begin sort list_of_strings for string in list_of_strings begin print string end end function
def sort_list_of_strings(list_of_strings): list_of_strings.sort() for string in list_of_strings: print(string)
Python
flytech_python_25k
function add self name value begin if name in _data and not _ignore_clashes begin set l = _data at name if has attribute l string extend begin comment it is already a list append l value end else begin set _data at name = list l value end end else begin set name value end end function
def add(self, name, value): if name in self._data and not self._ignore_clashes: l = self._data[name] if hasattr(l, 'extend'): # it is already a list l.append(value) else: self._data[name] = [l, value] else: s...
Python
nomic_cornstack_python_v1
function getCommand self begin comment check if currently recalculating ==> wait if recalculate begin return WAIT end comment check if no route is available ==> turn around to expand map if route == none begin return TURN_RIGHT end set position = call getpos comment check if target is reached and if new targets are ava...
def getCommand(self): #check if currently recalculating ==> wait if(self.recalculate): return self.commands.WAIT #check if no route is available ==> turn around to expand map if(self.route == None): return self.commands.TURN_RIGHT position = self.slam.getpos() #check if...
Python
nomic_cornstack_python_v1
import time import random import opc from colors import * set ADDRESS = string 192.168.7.2:7890 set no_of_matrices = 4 set leds = 100 * no_of_matrices comment Create a client object set client = call Client ADDRESS comment Test if it can connect
import time import random import opc from colors import * ADDRESS = '192.168.7.2:7890' no_of_matrices = 4 leds = 100*no_of_matrices # Create a client object client = opc.Client(ADDRESS) # Test if it can connect
Python
zaydzuhri_stack_edu_python
string Shell commands of the drupalindustry.scripts package. comment import ConfigParser from optparse import OptionParser import os import subprocess import sys class DrupalIndustryCommand extends object begin string Proxy to scripts in bin/. function __init__ self argv=list begin set argv = argv set config_file = non...
"""Shell commands of the drupalindustry.scripts package.""" #import ConfigParser from optparse import OptionParser import os import subprocess import sys class DrupalIndustryCommand(object): """Proxy to scripts in bin/.""" def __init__(self, argv=[]): self.argv = argv self.config_file = None ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: UTF-8 -*- from vectorizer import cluster_paragraphs from random import shuffle from preprocessing import mythril_process , oyente_process , slither_process , listToString set mythril_filename = string scanner_res/my_visibility_not_set.txt set oyente_filename = string scanner...
#!/usr/bin/python # -*- coding: UTF-8 -*- from vectorizer import cluster_paragraphs from random import shuffle from preprocessing import mythril_process, oyente_process, slither_process, listToString mythril_filename = 'scanner_res/my_visibility_not_set.txt' oyente_filename = 'scanner_res/oy_visibility_not_set.txt' sl...
Python
zaydzuhri_stack_edu_python
import ccxt import os import datetime import json import sys set exchange = call ftx set exc_name = replace name string string set symbolForThis = string function main begin if length argv not in list 2 3 begin exit string Usage: python CcxtData.py <SYMBOL> end set symbolForThis = argv at 1 + string -PERP print call ...
import ccxt import os import datetime import json import sys exchange = ccxt.ftx() exc_name = exchange.name.replace(" ", "") symbolForThis = "" def main(): if len(sys.argv) not in [2, 3]: sys.exit("Usage: python CcxtData.py <SYMBOL>") symbolForThis = sys.argv[1]+'-PERP' print(getTickerPrice(symb...
Python
zaydzuhri_stack_edu_python
import time from Аlg_sort import * function bench *funcs arr count_iter=10 begin comment Замеряет скорость работы функции(функций) для заданного списка set dict_bench = dict for func in funcs begin set time_sum = 0 for i in range count_iter begin set arr_copy = arr at slice : : set start = time set s = call func ar...
import time from Аlg_sort import * def bench(*funcs, arr, count_iter=10): # Замеряет скорость работы функции(функций) для заданного списка dict_bench = {} for func in funcs: time_sum = 0 for i in range(count_iter): arr_copy = arr[:] start = time.time() ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import math import os import sys import time from geometry_msgs.msg import WrenchStamped import rospy import trajectory_msgs.msg import actionlib from actionlib_msgs.msg import GoalStatus from tmc_control_msgs.msg import GripperApplyEffortAction , GripperApplyEffortGoal set FT_SENSOR_TOPIC ...
#!/usr/bin/env python import math import os import sys import time from geometry_msgs.msg import WrenchStamped import rospy import trajectory_msgs.msg import actionlib from actionlib_msgs.msg import GoalStatus from tmc_control_msgs.msg import ( GripperApplyEffortAction, GripperApplyEffortGoal ) FT_SENSOR_TO...
Python
zaydzuhri_stack_edu_python
function startup_user_interaction_required self begin return plugin in list string manual string user-interact string user-interact-verify end function
def startup_user_interaction_required(self): return self.plugin in ['manual', 'user-interact', 'user-interact-verify']
Python
nomic_cornstack_python_v1
import itertools set file = open string input set data = list comprehension integer l for l in read lines file for pair in call combinations data 3 begin if pair at 0 + pair at 1 + pair at 2 == 2020 begin print string Solution: + string pair at 0 * pair at 1 * pair at 2 end end
import itertools file = open("input") data = [int(l) for l in file.readlines()]; for pair in itertools.combinations(data, 3): if pair[0]+pair[1]+pair[2] == 2020: print("Solution: "+str(pair[0]*pair[1]*pair[2]))
Python
zaydzuhri_stack_edu_python
string Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. There are some basic programming concepts in OOP: Abstraction Polymorphism Encapsulation Inheritance The abstraction is simplifying complex reality by modeling classe...
""" Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. There are some basic programming concepts in OOP: Abstraction Polymorphism Encapsulation Inheritance The abstraction is simpl...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment Copyright 2020 Yedaffon Author. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/licenses/LICENSE-2.0 comment Unless ...
# coding=utf-8 # Copyright 2020 Yedaffon Author. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Python
zaydzuhri_stack_edu_python
string 给定一个字符串列表,你可以将这些字符串连接成一个循环字符串,对于每个字符串,你可以选择是否翻转它。在所有可能的循环字符串中,你需要分割循环字符串(这将使循环字符串变成一个常规的字符串),然后找到字典序最大的字符串。 具体来说,要找到字典序最大的字符串,你需要经历两个阶段: 将所有字符串连接成一个循环字符串,你可以选择是否翻转某些字符串,并按照给定的顺序连接它们。 在循环字符串的某个位置分割它,这将使循环字符串从分割点变成一个常规的字符串。 你的工作是在所有可能的常规字符串中找到字典序最大的一个。 示例: 输入: "abc", "xyz" 输出: "zyxcba" 解释: 你可以得到循环字符串 "-abcxyz-", "...
""" 给定一个字符串列表,你可以将这些字符串连接成一个循环字符串,对于每个字符串,你可以选择是否翻转它。在所有可能的循环字符串中,你需要分割循环字符串(这将使循环字符串变成一个常规的字符串),然后找到字典序最大的字符串。 具体来说,要找到字典序最大的字符串,你需要经历两个阶段: 将所有字符串连接成一个循环字符串,你可以选择是否翻转某些字符串,并按照给定的顺序连接它们。 在循环字符串的某个位置分割它,这将使循环字符串从分割点变成一个常规的字符串。 你的工作是在所有可能的常规字符串中找到字典序最大的一个。 示例: 输入: "abc", "xyz" 输出: "zyxcba" 解释: 你可以得到循环字符串 "-abcxyz-", "-a...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Jan 17 06:02:45 2021 @author: C64990 import numpy as np import pandas as pd import matplotlib.pyplot as plt function upd_v u a t begin return u + a * t end function function upd_s u a t begin return u * t + 0.5 * a * t ^ 2 end function function upd_x_u x0 u0 a tau beg...
# -*- coding: utf-8 -*- """ Created on Sun Jan 17 06:02:45 2021 @author: C64990 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt def upd_v(u, a, t): return u + a*t def upd_s(u, a, t): return u*t + 0.5*a*t**2 def upd_x_u(x0, u0, a, tau): if u0 > 0: de...
Python
zaydzuhri_stack_edu_python
function empty_list begin from linked_list import LinkedList set new_list = call LinkedList return new_list end function
def empty_list(): from linked_list import LinkedList new_list = LinkedList() return new_list
Python
nomic_cornstack_python_v1
function normdat inpath outpath begin comment load annotations of this set with open join path inpath set string anno_%s.pickle % set string rb as fi begin set anno_all = load pickle fi end comment iterate samples of the set set itr = 0 for tuple sample_id anno in items anno_all begin comment load data set impath_img =...
def normdat(inpath, outpath): # load annotations of this set with open(os.path.join(inpath, set, 'anno_%s.pickle' % set), 'rb') as fi: anno_all = pickle.load(fi) # iterate samples of the set itr = 0 for sample_id, anno in anno_all.items(): # load data impath_img = os.path.jo...
Python
nomic_cornstack_python_v1
import os import pandas as pd from sklearn.utils import shuffle set image_list = list set label_list = list function remote_path begin string sample: image: /root/data/LaneSeg/Image_Data/Road02/Record001/Camera 5/170927_064620420_Camera_6.jpg label: /root/data/LaneSeg/Gray_Label/Label_road02/Label/Record001/Camera 51...
import os import pandas as pd from sklearn.utils import shuffle image_list = [] label_list = [] def remote_path(): """ sample: image: /root/data/LaneSeg/Image_Data/Road02/Record001/Camera 5/170927_064620420_Camera_6.jpg label: /root/data/LaneSeg/Gray_Label/Label_road02/Label/Record001/Camera 5...
Python
zaydzuhri_stack_edu_python
from __future__ import annotations import typing as t import contextlib class GetOrDefault begin set data : Optional at tuple dict list str function __init__ self dict_list_str begin set data = dict_list_str end function function __call__ self item default=none begin string get or default try begin comment key/index re...
from __future__ import annotations import typing as t import contextlib class GetOrDefault: data: t.Optional[dict, list, str] def __init__(self, dict_list_str: t.Optional[dict, list, str]): self.data = dict_list_str def __call__(self, item, default=None): """ get or default ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys set buf = string for line in stdin begin set line = right strip line string if starts with line string begin set buf = buf + line at slice 1 : : end else begin print buf set buf = line end end if buf begin print buf end
#!/usr/bin/env python import sys buf = "" for line in sys.stdin: line = line.rstrip("\r\n") if line.startswith(" "): buf += line[1:] else: print(buf) buf = line if buf: print(buf)
Python
zaydzuhri_stack_edu_python
from django import forms from models import product_person class Personform extends ModelForm begin set first_name = call CharField label=string your name widget=call TextInput attrs=dict string placeholder string enter your name class Meta begin set model = product_person set fields = list string first_name string mid...
from django import forms from .models import product_person class Personform(forms.ModelForm): first_name = forms.CharField(label= 'your name', widget= forms.TextInput( attrs={ "placeholder":"enter your name" })) class Meta: model=product_person fields=[ 'first_name', 'middle_name', 'last_nam...
Python
zaydzuhri_stack_edu_python
comment 2-1. Simple Message: Store a message in a variable, and then print that message. set msg = string hello world! print msg
# 2-1. Simple Message: Store a message in a variable, and then print that message. msg = "hello world!" print(msg)
Python
zaydzuhri_stack_edu_python
function preprocess self path=none begin set path = if expression path then path else path set data = get load Data path=path __name__ for subject in data begin call preprocess model=model detector=detector append data subject end return data end function
def preprocess(self, path=None): path = path if path else self.path data = Data.load(path=path).get(Data.__name__) for subject in data: subject.preprocess(model=self.model, detector=self.detector) self.data.append(subject) return self.data
Python
nomic_cornstack_python_v1
function unicode2ascii _unicrap begin set xlate = dict 192 string A ; 193 string A ; 194 string A ; 195 string A ; 196 string A ; 197 string A ; 198 string Ae ; 199 string C ; 200 string E ; 201 string E ; 202 string E ; 203 string E ; 204 string I ; 205 string I ; 206 string I ; 207 string I ; 208 string Th ; 209 stri...
def unicode2ascii(_unicrap): xlate = {0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 0xc6:'Ae', 0xc7:'C', 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', 0xd0:'Th', 0xd1:'N', 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'...
Python
nomic_cornstack_python_v1
import turtle set a = call Pen call reset for i in range 1 9 begin call forward 200 call left 225 end
import turtle a=turtle.Pen() a.reset() for i in range(1,9): a.forward(200) a.left(225)
Python
zaydzuhri_stack_edu_python
function onStoreCorrectChange self event=none begin if call GetValue begin show show end else begin comment self.paramCtrls['correctAns'].typeCtrl.Show() comment self.paramCtrls['correctAns'].updateCtrl.Show() call Hide call Hide end comment self.paramCtrls['correctAns'].typeCtrl.Hide() comment self.paramCtrls['correct...
def onStoreCorrectChange(self,event=None): if self.paramCtrls['storeCorrect'].valueCtrl.GetValue(): self.paramCtrls['correctAns'].valueCtrl.Show() self.paramCtrls['correctAns'].nameCtrl.Show() #self.paramCtrls['correctAns'].typeCtrl.Show() #self.paramCtrls['c...
Python
nomic_cornstack_python_v1
comment -> float: function weights_none mol begin Ellipsis end function
def weights_none(mol): # -> float: ...
Python
nomic_cornstack_python_v1
function countPlayers tid begin set DB = call connect set c = call cursor set sql = string SELECT count(player) AS num FROM scoreboard WHERE tournament = %s execute c sql tuple tid set players = call fetchone at 0 close DB return players end function
def countPlayers(tid): DB = connect() c = DB.cursor() sql = """SELECT count(player) AS num FROM scoreboard WHERE tournament = %s""" c.execute(sql, (tid,)) players = c.fetchone()[0] DB.close() return players
Python
nomic_cornstack_python_v1
function predict u v begin return dot u v end function
def predict(u, v): return np.dot(u, v)
Python
nomic_cornstack_python_v1
comment CS3243 Introduction to Artificial Intelligence comment Project 2 import sys import copy comment Running script: given code can be run with the command: comment python file.py, ./path/to/init_state.txt ./output/output.txt class Sudoku extends object begin function __init__ self puzzle begin comment you may add m...
# CS3243 Introduction to Artificial Intelligence # Project 2 import sys import copy # Running script: given code can be run with the command: # python file.py, ./path/to/init_state.txt ./output/output.txt class Sudoku(object): def __init__(self, puzzle): # you may add more attributes if you ne...
Python
zaydzuhri_stack_edu_python
function read_puppy_hk_pickles lfile key=none begin set d = load pickle open lfile string rb comment print "d.keys", d.keys() comment data = d["y"][:,0,0] # , d["y"] set rate = 20 set offset = 0 comment data = np.atleast_2d(data).T comment print "wavdata", data.shape comment special treatment for x,y with addtional dim...
def read_puppy_hk_pickles(lfile, key = None): d = pickle.load(open(lfile, 'rb')) # print "d.keys", d.keys() # data = d["y"][:,0,0] # , d["y"] rate = 20 offset = 0 # data = np.atleast_2d(data).T # print "wavdata", data.shape # special treatment for x,y with addtional dimension data = ...
Python
nomic_cornstack_python_v1
function run self begin raise NotImplementedError end function
def run(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
function insSorted lst n leftIdx rightIdx begin print lst n leftIdx rightIdx if not lst or leftIdx == length lst or leftIdx > rightIdx begin insert lst leftIdx n return leftIdx end set midIdx = leftIdx + rightIdx - leftIdx // 2 if n < lst at midIdx begin return call insSorted lst n leftIdx midIdx - 1 end else if n > ls...
def insSorted(lst,n,leftIdx,rightIdx): print(lst,n,leftIdx,rightIdx) if not lst or leftIdx==len(lst) or leftIdx>rightIdx: lst.insert(leftIdx,n) return leftIdx midIdx=leftIdx+(rightIdx-leftIdx)//2 if n<lst[midIdx]: return insSorted(lst,n,leftIdx,midIdx-1) elif n>lst[midIdx]: return insSorted(lst,n,midI...
Python
zaydzuhri_stack_edu_python
function RefreshDetails self item=none begin if details begin return call RefreshDetails item end set item = item or call GetDetailsItem if item not in data begin set item = none end end function
def RefreshDetails(self,item=None): if self.details: return self.details.RefreshDetails(item) item = item or self.GetDetailsItem() if item not in self.data: item = None
Python
nomic_cornstack_python_v1
function add_timing_or_data_tag row value begin if not value begin return string NO VALUE end set lower_value = lower value if string min in lower_value begin call add_tag row string Min end else if string max in lower_value begin call add_tag row string Max end else if string avg in lower_value begin call add_tag row ...
def add_timing_or_data_tag(row, value): if not value: return "NO VALUE" lower_value = value.lower() if 'min' in lower_value: add_tag(row, 'Min') elif 'max' in lower_value: add_tag(row, 'Max') elif 'avg' in lower_value: add_tag(row, 'Average') elif 'average' in low...
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup from download import * from urllib import urlencode function replace a begin return replace a string string %20 end function set url = string http://www.allitebooks.com/modern-programming-made-easy/ set html = call download url set soup = call BeautifulSoup html set span = find soup attrs...
from bs4 import BeautifulSoup from download import * from urllib import urlencode def replace(a): return a.replace(" ", "%20") url = "http://www.allitebooks.com/modern-programming-made-easy/" html = download(url) soup = BeautifulSoup(html) span = soup.find(attrs={'class':'download-links'}) #a = span.find...
Python
zaydzuhri_stack_edu_python
import numpy as np from fcm import fcmean from plots import plot_points , plot_points_colored set recs = 200 comment data = np.random.normal(0, 5, size=(recs, 2)) set data1 = call normal 10 1 size=tuple recs 2 set data2 = call normal 12 1 size=tuple recs 2 set data3 = call normal 14 1 size=tuple recs 2 set data = conca...
import numpy as np from fcm import fcmean from plots import plot_points, plot_points_colored recs = 200 # data = np.random.normal(0, 5, size=(recs, 2)) data1 = np.random.normal(10, 1, size=(recs, 2)) data2 = np.random.normal(12, 1, size=(recs, 2)) data3 = np.random.normal(14, 1, size=(recs, 2)) data = np.concatenate...
Python
zaydzuhri_stack_edu_python
if N > K begin set N = N % K end set min_N = decimal string inf while min_N != N begin set min_N = min N min_N if N == K or N == 0 or K == 0 begin print 0 exit 0 end set N = absolute N - K end print min_N
if N > K: N = N % K min_N = float("inf") while min_N != N: min_N = min(N,min_N) if N == K or N == 0 or K == 0: print(0) exit(0) N = abs(N - K) print(min_N)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- encoding: utf-8 -*- string @File : task5.py @Time : 2020/03/29 10:49:43 @Author : KingFar @Version : 1.0 @Contact : 1136421682@qq.com @WebSite : https://github.com/KingFarGrace comment here put the import lib import pickle string 在2个文件中存放了英文计算机技术文章(可以选择2篇关于Python技术文件操作处理技巧的2篇英文技术文章...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """ @File : task5.py @Time : 2020/03/29 10:49:43 @Author : KingFar @Version : 1.0 @Contact : 1136421682@qq.com @WebSite : https://github.com/KingFarGrace """ # here put the import lib import pickle """ 在2个文件中存放了英文计算机技术文章(可以选择2篇关于Python技术文件操作处理技巧的2篇英文技术文章), 请读取文章内容,进行词频的统...
Python
zaydzuhri_stack_edu_python
function dynamic_allpass source frequency Q=i_sqrt_two srate=none begin set frequency = call to_iterable frequency set Q = call to_iterable Q set srate = call get_srate srate set dw = two_pi / srate set y0 = 0j set x1 = 0.0 set x2 = 0.0 for tuple sample f q in zip source frequency Q begin set w0 = dw * f set cosw0 = co...
def dynamic_allpass(source, frequency, Q=i_sqrt_two, srate=None): frequency = to_iterable(frequency) Q = to_iterable(Q) srate = get_srate(srate) dw = two_pi / srate y0 = 0j x1 = 0.0 x2 = 0.0 for sample, f, q in zip(source, frequency, Q): w0 = dw * f cosw0 = cos(w0) ...
Python
nomic_cornstack_python_v1
function test_root_get self begin set result = get app string / assert equal status_code 200 string Get of / did not return 200 end function
def test_root_get(self): result = self.app.get('/') self.assertEqual(result.status_code, 200, "Get of / did not return 200")
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd from parsen import Parsen import matplotlib.pyplot as plt set data = read csv string height_weight2.csv set indexes = call to_numpy set heights_weights = call to_numpy set tuple X_train y_train = tuple heights_weights indexes set data = read csv string height_weight_test.csv set X...
import numpy as np import pandas as pd from parsen import Parsen import matplotlib.pyplot as plt data = pd.read_csv("height_weight2.csv") indexes = data['Index'].to_numpy() heights_weights = data[['Height', 'Weight']].to_numpy() X_train, y_train = heights_weights, indexes data = pd.read_csv("height_weight_test.csv")...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string Task 15 relationship city state from relationship_state import State from relationship_city import City , Base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import sys if __name__ == string __main__ begin set t = string mysql+mysqldb://{}:{}@localhost/{} s...
#!/usr/bin/python3 '''Task 15 relationship city state''' from relationship_state import State from relationship_city import City, Base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import sys if __name__ == "__main__": t = 'mysql+mysqldb://{}:{}@localhost/{}' s1 = sys.argv[1] ...
Python
zaydzuhri_stack_edu_python
function set self q r val begin if not tuple q r in spaces begin raise call KeyError format string ({}, {}) not in range q r end set spaces at tuple q r = val end function
def set(self, q, r, val): if not (q, r) in self.spaces: raise KeyError("({}, {}) not in range".format(q, r)) self.spaces[q, r] = val
Python
nomic_cornstack_python_v1
function ascii_name_plaque name begin set st = string * + string string __ + name + string __ + string * set star = string * * length st - 1 + string set space = string * + string * length st - 3 + string * print star + space + st + space + star end function
def ascii_name_plaque(name: str): st = "*" + str(" __" + name + "__ ") + "*\n" star = "*" * (len(st)-1) + "\n" space = "*" + (" " * (len(st)-3)) + "*\n" print(star + space + st + space + star)
Python
nomic_cornstack_python_v1
class Queue begin function __init__ self begin set tuple s1 s2 = tuple list list end function function enqueue self data begin append s1 data end function function dequeue self begin if s1 == list and s2 == list begin return none end if s2 == list begin while not s1 == list begin append s2 pop s1 end end set res ...
class Queue: def __init__(self): self.s1, self.s2 = [], [] def enqueue(self, data): self.s1.append(data) def dequeue(self): if self.s1 == [] and self.s2 == []: return None if self.s2 == []: while not self.s1 == []: self.s2.append(...
Python
zaydzuhri_stack_edu_python
from data import db_connection decorator connection_handler function fetch_details_by_show_id cursor show_id begin set sql_string = string SELECT seasons.id AS season_id, seasons.season_number AS season_number, episodes.title AS episode_title, episodes.id AS episode_id FROM shows LEFT JOIN seasons ON shows.id = seasons...
from data import db_connection @db_connection.connection_handler def fetch_details_by_show_id(cursor, show_id): sql_string = """ SELECT seasons.id AS season_id, seasons.season_number AS season_number, episodes.title AS episode_title, ...
Python
zaydzuhri_stack_edu_python
function __str__ self begin return title end function
def __str__(self): return self.title
Python
nomic_cornstack_python_v1