code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment -*- coding: utf-8 -*- string Created on Wed Aug 29 08:09:55 2018 @author: minlam import numpy as np set h = 5.5 set u = call log10 h set v = call sign u * ceil absolute u set nice_h = 10 ^ v print string The Nice Bin-Width = nice_h
# -*- coding: utf-8 -*- """ Created on Wed Aug 29 08:09:55 2018 @author: minlam """ import numpy as np h = 5.5 u = np.log10(h) v = np.sign(u) * np.ceil(np.abs(u)) nice_h = 10 ** v print('The Nice Bin-Width = ', nice_h)
Python
zaydzuhri_stack_edu_python
function __init__ __self__ name begin set __self__ string name name end function
def __init__(__self__, *, name: str): pulumi.set(__self__, "name", name)
Python
nomic_cornstack_python_v1
function create_policy name policy_name policy_type policy region=none key=none keyid=none profile=none begin string Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' set ...
def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolic...
Python
jtatman_500k
function sum a b begin print a + b end function
def sum(a, b): print (a + b)
Python
zaydzuhri_stack_edu_python
comment Mock Exam 2019-10-27 bachelor party (while loops) **************************** set guest_fee = integer input set people = input set meal_price = 0 set total_meal_price = 0 set total_people = 0 while not people == string The restaurant is full begin set people = integer people if people < 5 begin set meal_price ...
# Mock Exam 2019-10-27 bachelor party (while loops) **************************** guest_fee = int(input()) people = input() meal_price = 0 total_meal_price = 0 total_people = 0 while not people == 'The restaurant is full': people = int(people) if people < 5: meal_price += people * 100 ...
Python
zaydzuhri_stack_edu_python
import math import time function calc x begin return string log absolute 12 * sin integer x end function comment Импортируем вебдрайвер from selenium import webdriver comment Открываем ссылку set link = string http://suninjuly.github.io/math.html set browser = call Chrome get browser link comment Ищем элемент, где запи...
import math import time def calc(x): return str(math.log(abs(12*math.sin(int(x))))) # Импортируем вебдрайвер from selenium import webdriver # Открываем ссылку link = "http://suninjuly.github.io/math.html" browser = webdriver.Chrome() browser.get(link) # Ищем элемент, где записано значение X x_eleme...
Python
zaydzuhri_stack_edu_python
import socket class RecieveData begin string Class that starts a socket connection and recieves eye coordinates for eye simulator to use function __init__ self begin set __host = string 192.168.191.125 set __port = 65432 set __eyeXR = 30 set __eyeYR = 30 set __eyeXL = 30 set __eyeYL = 30 set __socket = call socket AF_I...
import socket class RecieveData(): """ Class that starts a socket connection and recieves eye coordinates for eye simulator to use """ def __init__(self): self.__host = '192.168.191.125' self.__port = 65432 self.__eyeXR = 30 self.__eyeYR = 30 self._...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 string Task 15 Write a function find_longest_word() that takes a list of words and returns the length of the longest one. comment TIME SPENT: # comment 6 min # function find_longest_word l begin string This finds and returns the longest words in a given list 'l' comment check if the arg is a l...
# -*- coding: utf-8 ''' Task 15 Write a function find_longest_word() that takes a list of words and returns the length of the longest one. ''' ############### # TIME SPENT: # # 6 min # ############### def find_longest_word(l): """This finds and returns the longest words in a given list 'l' """ #check if t...
Python
zaydzuhri_stack_edu_python
import math for i in range 3 333 begin for j in range i 500 begin set k = integer square root i * i + j * j if k == square root i * i + j * j and i + j + k <= 1000 begin print format string {} {} {} i j k end end end
import math for i in range(3, 333): for j in range(i, 500): k = int(math.sqrt(i*i+j*j)) if k == math.sqrt(i*i+j*j) and i+j+k <= 1000: print('{} {} {}'.format(i, j, k))
Python
zaydzuhri_stack_edu_python
import sys import re function main begin if length argv < 2 begin call print_help exit 1 end end function function print_help begin string Prints usage information print string usage: python argv at 0 string <filename> print string Prints the index of 'filename' where each word has a list of all the line numbers it app...
import sys import re def main(): if len(sys.argv) < 2: print_help() sys.exit(1) def print_help(): """ Prints usage information """ print("usage: python", sys.argv[0], "<filename>") print("Prints the index of 'filename' where each word has a list of all the line numbers it appears on.",...
Python
zaydzuhri_stack_edu_python
function install_mu_no_ha_base_negative self begin call check_run string install_mu_no_ha_base_negative call show_step 1 call revert_snapshot string prepare_for_install_mu_non_ha_cluster set cluster_id = call get_last_created_cluster call show_step 2 set cmd = format string fuel2 update install --env {} --restart-rabbi...
def install_mu_no_ha_base_negative(self): self.check_run("install_mu_no_ha_base_negative") self.show_step(1) self.env.revert_snapshot("prepare_for_install_mu_non_ha_cluster") cluster_id = self.fuel_web.get_last_created_cluster() self.show_step(2) cmd = "fuel2 update...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- import sys set input = readline set N = integer input print 2 ^ N
# -*- coding:utf-8 -*- import sys input = sys.stdin.readline N = int(input()) print(2**N)
Python
zaydzuhri_stack_edu_python
function create_dummy_objects vdomxml parent=none begin set objects = dict set attr_map = dict set type_obj = call get_type_by_name lname for attr_name in call get_attributes begin set attr_map at lower attr_name = default_value end comment parse attributes for attr_name in attributes begin if attr_name in attr_map o...
def create_dummy_objects(vdomxml, parent=None): objects = {} attr_map = {} type_obj = managers.xml_manager.get_type_by_name(vdomxml.lname) for attr_name in type_obj.get_attributes(): attr_map[attr_name.lower()] = type_obj.get_attributes()[attr_name].default_value # parse attr...
Python
nomic_cornstack_python_v1
from cImage import * set win = call ImageWin string My Window 800 640 set oImage = call FileImage string cat.gif print call getWidth call getHeight call draw win set myImage = copy oImage set msg = string This is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an imageThi...
from cImage import * win = ImageWin("My Window",800,640) oImage = FileImage('cat.gif') print(oImage.getWidth(), oImage.getHeight()) oImage.draw(win) myImage = oImage.copy() msg = "This is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an imageThis is an ...
Python
zaydzuhri_stack_edu_python
from mTree.microeconomic_system.agent import Agent from mTree.microeconomic_system.directive_decorators import * from mTree.microeconomic_system.message_space import Message import numpy as np import math as mat decorator directive_enabled_class class LotteryAgent extends Agent begin function __init__ self begin commen...
from mTree.microeconomic_system.agent import Agent from mTree.microeconomic_system.directive_decorators import * from mTree.microeconomic_system.message_space import Message import numpy as np import math as mat @directive_enabled_class class LotteryAgent(Agent): def __init__(self): self.theta = None # for...
Python
zaydzuhri_stack_edu_python
function digest_secure_bootloader args begin string Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. if iv is not none begin print string WARNING: --iv argument is for TESTING PURPOSES ONLY set iv = ...
def digest_secure_bootloader(args): """ Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. """ if args.iv is not None: print("WARNING: --iv argument is for TESTING PURPOSES ONLY...
Python
jtatman_500k
function contact begin return call render_template string contact.html nav=nav title=string Contact me year=year message=string The following are ways to contact me end function
def contact(): return render_template( 'contact.html', nav=nav, title='Contact me', year=datetime.now().year, message='The following are ways to contact me' )
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import sys function solve N A begin sort A if all list comprehension a <= 0 for a in A begin print A at - 1 - sum A - A at - 1 for i in range N - 1 begin print A at - 1 A at i set A at - 1 = A at - 1 - A at i end return end if all list comprehension a >= 0 for a in A begin print sum A - A ...
#!/usr/bin/env python3 import sys def solve(N: int, A: "List[int]"): A.sort() if all([a <= 0 for a in A]): print(A[-1]-(sum(A)-A[-1])) for i in range(N-1): print(A[-1],A[i]) A[-1] -= A[i] return if all([a >= 0 for a in A]): print(sum(A)-A[0]-A[0]) ...
Python
zaydzuhri_stack_edu_python
import socket import time import subprocess import sys set connected = false set ports = list 21 22 80 443 8000 set server = string targetsvr while not connected begin set done = false set mysocket = call socket for port in ports begin sleep 1 end end
import socket import time import subprocess import sys connected=False ports = [21,22,80,443,8000] server = "targetsvr" while not connected: done=False mysocket=socket.socket() for port in ports: time.sleep(1)
Python
zaydzuhri_stack_edu_python
comment -------------------------------------------------------------------------- comment Name: Sum of Root To Leaf Binary Numbers comment Author(s): Phu Tran comment -------------------------------------------------------------------------- string Given a binary tree, each node has value 0 or 1. Each root-to-leaf pat...
# -------------------------------------------------------------------------- # Name: Sum of Root To Leaf Binary Numbers # Author(s): Phu Tran # -------------------------------------------------------------------------- """ Given a binary tree, each node has value 0 or 1. Each root-to-leaf path repres...
Python
zaydzuhri_stack_edu_python
function regularisation self l=100 alpha=0.01 stop=0.001 begin while true begin set cost = call cost_function + l / 2 * m * sum t at tuple slice 1 : : ^ 2 print string Cost at current state: cost set old_t = t comment gradient calculation set t = t - alpha / m * matrix multiply transpose np x hypo - y set t at tuple ...
def regularisation(self,l = 100, alpha = 0.01, stop = 0.001): while True: self.cost = self.cost_function()+(l/(2*self.m))*np.sum(self.t[1:,]**2) print("Cost at current state: ",self.cost) old_t = self.t self.t = self.t - (alpha/self.m)*np.matmul(np.transpose(self.x),(self.hypo-self.y)) #gradien...
Python
nomic_cornstack_python_v1
function test_offload_udp_trunk_vlan self test=string offload_udp_trunk_vlan begin info format string Start test_{} test. test call run_offload_testcase test string udp string trunk_vlan end function
def test_offload_udp_trunk_vlan(self, test='offload_udp_trunk_vlan'): LOG.info('Start test_{} test.'.format(test)) self.run_offload_testcase(test, "udp", "trunk_vlan")
Python
nomic_cornstack_python_v1
set a = input string ВВедите число: print integer a + integer a * 2 + integer a * 3
a = input('ВВедите число: ') print(int(a) + int(a * 2) + int(a * 3))
Python
zaydzuhri_stack_edu_python
function __call__ self array begin if not is instance array ndarray begin raise call TypeError string expected numpy.ndarray, got %s instead % string type array end set tuple rows cols = shape if rows != cols begin raise call ValueError string non-square matrix end if rows == 1 begin return array at 0 at 0 end if rows ...
def __call__(self, array): if not isinstance(array, np.ndarray): raise TypeError('expected numpy.ndarray, got %s instead' % str(type(array))) rows, cols = array.shape if rows != cols: raise ValueError('non-square matrix') if rows == 1: return array[0...
Python
nomic_cornstack_python_v1
comment Datatypes and Lists comment this is an integer (int) set whole_number = 5 comment this is a string (str) set word = string word! comment this is a float (float) set decimal = 2.3 print whole_number / 2 comment the type method is used for finding out the datatype print type decimal comment implicit casting set x...
#Datatypes and Lists whole_number = 5 #this is an integer (int) word = 'word!' #this is a string (str) decimal = 2.3 #this is a float (float) print(whole_number/2) print(type(decimal)) #the type method is used for finding out the datatype #implicit casting x = 1 y = 3.5 z = 'hello' #implicit cas...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import ROOT import sys call SetStyle string Plain comment (000001111) is default call SetOptStat 0 load gSystem string libMathCore comment Global definitions set hList = list set colours = list kWhite kBlack kOrange + 8 set DOF = list 6 6 6 set alpha = 2 set xMin = list 0.0 0.0 0.95 * alph...
#!/usr/bin/env python import ROOT import sys ROOT.gROOT.SetStyle("Plain") ROOT.gStyle.SetOptStat(000000000) #(000001111) is default ROOT.gSystem.Load("libMathCore"); ### Global definitions hList = [] colours = [ROOT.kWhite, ROOT.kBlack, ROOT.kOrange+8] DOF = [6, 6, 6] alpha = 2 xMin = [ 0.0, 0.0...
Python
zaydzuhri_stack_edu_python
import requests from lxml import etree set url = string https://www.zhihu.com/question/377547324/answer/1516614122 set header = dict string User-Agent string Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Mobile Safari/537.36 set s = call Session set re...
import requests from lxml import etree url = "https://www.zhihu.com/question/377547324/answer/1516614122" header = { "User-Agent": r"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Mobile Safari/537.36" } s = requests.Session() response = s.get(u...
Python
zaydzuhri_stack_edu_python
function test_go_term_has_type_biological_process begin set query = string MATCH (go:GOTerm) WHERE go.primaryKey = 'GO:0000003' AND go.type = 'biological_process' RETURN count(go) AS counter with call run_single_query query as result begin for record in result begin assert record at string counter == 1 end end end func...
def test_go_term_has_type_biological_process(): query = """MATCH (go:GOTerm) WHERE go.primaryKey = 'GO:0000003' AND go.type = 'biological_process' RETURN count(go) AS counter""" with Neo4jHelper.run_single_query(query) as result: for record in result: assert re...
Python
nomic_cornstack_python_v1
function bulk_process_images inputpath outputpath extension begin for tuple dirpath dirnames filenames in walk inputpath begin set structure = join path outputpath dirpath at slice length inputpath + 1 : : for file in filenames begin if ends with file extension begin set src = join path dirpath file set dest = join pa...
def bulk_process_images(inputpath, outputpath, extension): for dirpath, dirnames, filenames in os.walk(inputpath): structure = os.path.join(outputpath, dirpath[len(inputpath) + 1:]) for file in filenames: if file.endswith(extension): src = os.path.join(dirpath, file) ...
Python
nomic_cornstack_python_v1
comment Ищем самую часто встречающуюся букву после двух одинаковых set cort = dict with open string ../files/type4b.txt as file begin set text = read file for i in range 1 length text begin set sli = text at slice i - 1 : i + 2 : if sli at 0 == sli at 1 begin comment Эта штука прибавляет 1 в значение буквы set cort a...
# Ищем самую часто встречающуюся букву после двух одинаковых cort = {} with open('../files/type4b.txt') as file: text = file.read() for i in range(1, len(text)): sli = text[i - 1:i + 2] if sli[0] == sli[1]: # Эта штука прибавляет 1 в значение буквы cort[sli[2]] = cort.get...
Python
zaydzuhri_stack_edu_python
function getSimulationEventGenerators self begin raise call NotImplementedError end function
def getSimulationEventGenerators(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function test_with_localsite_in_data_and_instance self begin set config = call create integration_id=integration_id set form = call MyConfigForm integration=integration request=request data=dict string name string Test ; string my_conditions_last_id string 0 ; string my_conditions_mode string all ; string my_conditions...
def test_with_localsite_in_data_and_instance(self): config = IntegrationConfig.objects.create( integration_id=self.integration.integration_id) form = MyConfigForm( integration=self.integration, request=self.request, data={ 'name': 'Test', ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import socket set UDP_IP = string 127.0.0.1 set UDP_SEND_PORT = 5006 set UDP_RECV_PORT = 5005 set sock = call socket AF_INET SOCK_DGRAM call bind tuple UDP_IP UDP_RECV_PORT import select call setblocking 0 import serial import time set ser = call Serial string /dev/tty.usbmodemfd141 57600 timeo...
#!/usr/bin/python import socket UDP_IP = "127.0.0.1" UDP_SEND_PORT = 5006 UDP_RECV_PORT = 5005 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind((UDP_IP,UDP_RECV_PORT)) import select sock.setblocking(0) import serial import time ser = serial.Serial('/dev/tty.usbmodemfd141',57600,timeout=0.05,writ...
Python
zaydzuhri_stack_edu_python
comment 안타(1루타), 2루(2루타), 3루(3루타), 홈런 import csv from matplotlib import pyplot as plt import pandas as pd import numpy as np set years = list string 2018 string 2019 string 2020 set count = 0 set df_result = read csv string ../dataSet/2018선수정보_단계변경/최재훈.csv encoding=string UTF-8 set x = list 1 2 3 for year in years begi...
# 안타(1루타), 2루(2루타), 3루(3루타), 홈런 import csv from matplotlib import pyplot as plt import pandas as pd import numpy as np years=['2018', '2019', '2020'] count=0 df_result= pd.read_csv('../dataSet/2018선수정보_단계변경/최재훈.csv', encoding='UTF-8') x=[1,2,3] for year in years: # 선수 이름 파일 선택 f = open('../dataSet/' + year +...
Python
zaydzuhri_stack_edu_python
async function rall self ctx role begin set member_list = call get_member_list members role false await call super_massrole ctx member_list role string No one on the server has this role. false end function
async def rall(self, ctx: commands.Context, *, role: StrictRole): member_list = self.get_member_list(ctx.guild.members, role, False) await self.super_massrole( ctx, member_list, role, "No one on the server has this role.", False )
Python
nomic_cornstack_python_v1
import xml.etree.ElementTree as ET import xml.dom.minidom as minidom import sys , getopt import os import shutil set defdict = dictionary set cwd = get current directory comment Adds xml version and reference to the stylesheet. Makes it easier to read in xml readers. function insertStylesheet fileName begin with open f...
import xml.etree.ElementTree as ET import xml.dom.minidom as minidom import sys, getopt import os import shutil defdict = dict() cwd = os.getcwd() #Adds xml version and reference to the stylesheet. Makes it easier to read in xml readers. def insertStylesheet(fileName): with open(fileName, "r") as f3: ...
Python
zaydzuhri_stack_edu_python
function send_worker_pause self worker_id begin pass end function
def send_worker_pause(self, worker_id): pass
Python
nomic_cornstack_python_v1
from PIL import ImageDraw from PIL import Image import random function getRandomColor begin string 获取一个随机颜色(r,g,b)格式的 set c1 = random integer 0 255 set c2 = random integer 0 255 set c3 = random integer 0 255 return tuple c1 c2 c3 end function function getRandomStr begin string 获取一个随机字符串,每个字符的颜色也是随机的 set random_num = st...
from PIL import ImageDraw from PIL import Image import random def getRandomColor(): '''获取一个随机颜色(r,g,b)格式的''' c1 = random.randint(0, 255) c2 = random.randint(0, 255) c3 = random.randint(0, 255) return (c1, c2, c3) def getRandomStr(): '''获取一个随机字符串,每个字符的颜色也是随机的''' random_num = str(random.randi...
Python
zaydzuhri_stack_edu_python
import requests import csv from bs4 import BeautifulSoup from datetime import datetime from multiprocessing import Pool function get_html url begin set response = get requests url return text end function function get_all_links html begin set soup = call BeautifulSoup html string lxml set table_data_list = find all fin...
import requests import csv from bs4 import BeautifulSoup from datetime import datetime from multiprocessing import Pool def get_html(url): response = requests.get(url) return response.text def get_all_links(html): soup = BeautifulSoup(html, 'lxml') table_data_list = soup.find('table', id='currencies-all').f...
Python
zaydzuhri_stack_edu_python
function get_stargaze_report begin comment lat_selected, lng_selected, lat_org=None, lng_org=None, time=None): set lat_selected = get args string lat_selected type=float set lng_selected = get args string lng_selected type=float set lat_org = get args string lat_org none type=float set lng_org = get args string lng_org...
def get_stargaze_report(): # lat_selected, lng_selected, lat_org=None, lng_org=None, time=None): lat_selected = flask.request.args.get('lat_selected', type = float) lng_selected = flask.request.args.get('lng_selected', type = float) lat_org = flask.request.args.get('lat_org', None, type = float) ln...
Python
nomic_cornstack_python_v1
import pulp from pulp.solvers import PULP_CBC_CMD import time from pathlib import Path class VariableNameGenerator extends object begin function __init__ self begin set count = 0 end function function get self begin set ret = hexadecimal count at slice 1 : : set count = count + 1 return ret end function end class fun...
import pulp from pulp.solvers import PULP_CBC_CMD import time from pathlib import Path class VariableNameGenerator(object): def __init__(self): self.count = 0 def get(self): ret = hex(self.count)[1:] self.count += 1 return ret def narrow_prunning(width, length): if width...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import os import re import time import threading from functools import partial from sys import exc_info from difflib import SequenceMatcher import tkinter as tk from tkinter.filedialog import askdirectory comment the secret sauce I found on stack overflow: set DEVICE = string alsa_output.p...
#!/usr/bin/env python3 import os import re import time import threading from functools import partial from sys import exc_info from difflib import SequenceMatcher import tkinter as tk from tkinter.filedialog import askdirectory # the secret sauce I found on stack overflow: DEVICE = 'alsa_output.pci-0000_00_1f.3.anal...
Python
zaydzuhri_stack_edu_python
function calc T F begin set r = F - 2 * T / 2 set c = T - r return tuple c r end function set tuple c r = call calc 83 240 print string 雞有%d隻 兔子有%d隻 隻數:%d 腳數:%d % tuple c r c + r 2 * c + 4 * r
def calc(T,F): r=((F-2*T))/2 c=T-r return c,r c,r=calc(83,240) print("雞有%d隻 兔子有%d隻 隻數:%d 腳數:%d" %(c,r,c+r,(2*c+4*r)))
Python
zaydzuhri_stack_edu_python
function clear_buffer self starting_position total_points begin call __sendByte__ COMMON call __sendByte__ CLEAR_BUFFER call __sendInt__ starting_position call __sendInt__ total_points call __get_ack__ end function
def clear_buffer(self,starting_position,total_points): self.H.__sendByte__(COMMON) self.H.__sendByte__(CLEAR_BUFFER) self.H.__sendInt__(starting_position) self.H.__sendInt__(total_points) self.H.__get_ack__()
Python
nomic_cornstack_python_v1
function lift_pass_pricing_app begin set p = process target=server args=tuple TEST_PORT start p set server_url = string http://127.0.0.1: { TEST_PORT } call wait_for_server_to_start server_url yield server_url terminate p end function
def lift_pass_pricing_app(): p = multiprocessing.Process(target=server, args=(TEST_PORT,)) p.start() server_url = f"http://127.0.0.1:{TEST_PORT}" wait_for_server_to_start(server_url) yield server_url p.terminate()
Python
nomic_cornstack_python_v1
function user username begin if method == string GET begin string [GET] /v2/users/<username> return call user_by_username_get username end if method == string PUT begin string [PUT] /v2/users/<username> return call user_by_username_put username end if method == string DELETE begin string [DELETE] /v2/users/<username> r...
def user(username) -> Response: if request.method == "GET": """[GET] /v2/users/<username>""" return user_by_username_get(username) if request.method == "PUT": """[PUT] /v2/users/<username>""" return user_by_username_put(username) if request.method == "DELETE": """[D...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string Advent Of Code 2022 Day 10 https://adventofcode.com/2022/day/10 function parse filename begin with open filename as file begin return list comprehension call parse_line strip line for line in read lines file end end function function parse_line line begin if string in line begin set...
#!/usr/bin/env python """ Advent Of Code 2022 Day 10 https://adventofcode.com/2022/day/10 """ def parse(filename): with open(filename) as file: return [parse_line(line.strip()) for line in file.readlines()] def parse_line(line): if " " in line: cmd, arg = line.split(" ") return [cmd,...
Python
zaydzuhri_stack_edu_python
function promise_then_job job promise prev_promise_returned begin set then_handler = loads then_dill set tuple resolved rejected = prev_promise_returned if rejected is none begin comment Actually run this child promise try begin comment Get the result from the then handler and resolve with it set result = call then_han...
def promise_then_job(job, promise, prev_promise_returned): then_handler = dill.loads(promise.then_dill) resolved, rejected = prev_promise_returned if rejected is None: # Actually run this child promise try: # Get the result from the then handler and resolv...
Python
nomic_cornstack_python_v1
function create_models_list all_binary_values_N variables begin set models_list = list set var_list = variables if type variables == set begin comment we get a dict , we need to sort it. set var_list = sorted list variables end if type variables == list begin set var_list = variables end for values in all_binary_value...
def create_models_list(all_binary_values_N, variables): models_list = [] var_list = variables if type(variables) == set: var_list = sorted(list(variables)) # we get a dict , we need to sort it. if type(variables) == list: var_list = variables for values in all_binary_...
Python
nomic_cornstack_python_v1
for i in range 1 n + 1 begin set s = list input set swp = 0 if length s <= 1 begin print string Case #%d: %s % tuple i join string s continue end set ptr = length s - 1 while ptr > 0 begin comment print(" ", "".join("[%s]" % s[ii] if ii == ptr else s[ii] for ii in range(len(s)))) if s at ptr - 1 <= s at ptr and not sw...
for i in range(1, n + 1): s = list(input()) swp = 0 if len(s) <= 1: print("Case #%d: %s" % (i, "".join(s))) continue ptr = len(s) - 1 while ptr > 0: # print(" ", "".join("[%s]" % s[ii] if ii == ptr else s[ii] for ii in range(len(s)))) if s[ptr-1] <= s[ptr] and not s...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from __future__ import division import math comment COMECE SEU CODIGO AQUI comment Entrada set T1 = input string Digite aqui T1: set T2 = input string Digite aqui T2: set T3 = input string Digite aqui T3: set T4 = input string Digite aqui T4: comment Processamento e Saída set n = T1 + T2 +...
# -*- coding: utf-8 -*- from __future__ import division import math #COMECE SEU CODIGO AQUI #Entrada T1=input('Digite aqui T1:') T2=input('Digite aqui T2:') T3=input('Digite aqui T3:') T4=input('Digite aqui T4:') #Processamento e Saída n=(T1+T2+T3+T4)-3 print ('n=%d'%n)
Python
zaydzuhri_stack_edu_python
function reverse self transformed_trial begin set reversed_point = tuple generator expression reverse dim flatten params at name for tuple name dim in items self return call change_trial_params transformed_trial reversed_point self end function
def reverse(self, transformed_trial: Trial) -> Trial: reversed_point = tuple( dim.reverse(flatten(transformed_trial.params)[name]) for name, dim in self.items() ) return change_trial_params( transformed_trial, reversed_point, self, ...
Python
nomic_cornstack_python_v1
import pygame import sys import random import os from pygame.image import load from time import sleep call init set screen = call set_mode tuple 640 480 update display set ys = list 200 210 220 230 240 250 set xs = list 240 240 240 240 240 240 set red = tuple 255 0 0 set green = tuple 0 255 0 set blue = tuple 0 0 255 s...
import pygame import sys import random import os from pygame.image import load from time import sleep pygame.init() screen= pygame.display.set_mode((640,480)) pygame.display.update() ys=[200,210,220,230,240,250] xs=[240,240,240,240,240,240] red = (255,0,0) green = (0,255,0) blue = (0,0,255) darkBlue =...
Python
zaydzuhri_stack_edu_python
function set_device device_id begin if device_id < 0 begin comment Use CPU return end try begin from cupy.cuda import Device from cupy.cuda.runtime import CUDARuntimeError end except ImportError begin print string Failed to import CuPy. Use CPU instead. return end try begin call use end except CUDARuntimeError as e beg...
def set_device(device_id): if device_id < 0: # Use CPU return try: from cupy.cuda import Device from cupy.cuda.runtime import CUDARuntimeError except ImportError: print("Failed to import CuPy. Use CPU instead.") return try: Device(device_id).use(...
Python
nomic_cornstack_python_v1
comment Soldier class Soldier begin comment add code here function __init__ self health strength begin set health = health set strength = strength end function function attack self begin return strength end function function receiveDamage self Damage begin set health = health - Damage end function pass end class commen...
# Soldier class Soldier: # add code here def __init__(self, health, strength): self.health=health self.strength=strength def attack(self): return self.strength def receiveDamage(self,Damage): self.health=self.health-Damage pass # Viking class Viking(Soldier): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Listens to the topic for new spawned turtles in the floor, comment Listens to the topic for remoed turtles from the floor comment provides a service to tell what is the nearest object from the current comment position, or if there are no more objects. import rospy import numpy as np...
#!/usr/bin/env python #Listens to the topic for new spawned turtles in the floor, #Listens to the topic for remoed turtles from the floor #provides a service to tell what is the nearest object from the current #position, or if there are no more objects. import rospy import numpy as np from std_msgs.msg import String ...
Python
zaydzuhri_stack_edu_python
function findDigit img begin set thresh = 128 set dimensions = tuple 28 28 set border = 10 set gray = call threshold img thresh 255 THRESH_BINARY at 1 set contours = call findContours gray RETR_LIST CHAIN_APPROX_SIMPLE set contours = if expression length contours == 2 then contours at 0 else contours at 1 set ROI = non...
def findDigit(img): thresh = 128 dimensions = (28, 28) border = 10 gray = cv.threshold(img, thresh, 255, cv.THRESH_BINARY)[1] contours = cv.findContours(gray, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1] ROI = None for contour in con...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Jun 22 01:41:58 2021 @author: kazuk string 使い方 1. なんでもよいので初期化用のリストを用意 a = [14, 5, 9, 13, 7, 12, 11, 1, 7, 8] 2. 区間に行う操作を決める 区間の最小値、最大値を求めたい、区間の和を求めたいなど。今回は、最小値を求めるとします。segfuncに関数を書き込んでください。 def segfunc(x, y): return min(x, y) 3. 単位元を定める 初期化に使います。演算に影響を与えないものです。最小値を求める...
# -*- coding: utf-8 -*- """ Created on Tue Jun 22 01:41:58 2021 @author: kazuk """ """ 使い方 1. なんでもよいので初期化用のリストを用意 a = [14, 5, 9, 13, 7, 12, 11, 1, 7, 8] 2. 区間に行う操作を決める 区間の最小値、最大値を求めたい、区間の和を求めたいなど。今回は、最小値を求めるとします。segfuncに関数を書き込んでください。 def segfunc(x, y): return min(x, y) 3. 単位元を定...
Python
zaydzuhri_stack_edu_python
function update self title state=string description=string due_on=string begin set data = dumps dict string title title ; string state state ; string description description ; string due_on due_on set json = call _json call _patch _api data=data 200 if json begin call _update_ json return true end return false end fu...
def update(self, title, state='', description='', due_on=''): data = dumps({'title': title, 'state': state, 'description': description, 'due_on': due_on}) json = self._json(self._patch(self._api, data=data), 200) if json: self._update_(json) return True ...
Python
nomic_cornstack_python_v1
function test_company_edit self begin set user = call _create_user true true set project = call _create_project call get_profile set result = call login username=username password=string 1 assert equal result true string Login process Failed set response = get client reverse string company_edit args=tuple id assert equ...
def test_company_edit(self): user = self._create_user(True, True) project = self._create_project(user.get_profile()) result = self.client.login(username=user.username, password='1') self.assertEqual(result, True, 'Login process Failed') response = self.client.get( rev...
Python
nomic_cornstack_python_v1
function list _ begin if not is directory path DOT_FILE_PATH begin print string Run spawn, first. exit 1 end set current_time = integer time set we_said_something = false for node_file in list directory DOT_FILE_PATH begin set node = call node_info split node_file string . at 0 if current_time < node at string end_of_l...
def list(_): if not os.path.isdir(DOT_FILE_PATH): print('Run spawn, first.') exit(1) current_time = int(time()) we_said_something = False for node_file in os.listdir(DOT_FILE_PATH): node = node_info(node_file.split('.')[0]) if current_time < node['end_of_life']: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string branching.py Author: Taylor Kessinger Date: July 4, 2016 Description: Simulation of density independent (Desai and Fisher) and density dependent branching processes. import numpy as np import matplotlib.pyplot as plt import seaborn as sns call set_style string whitegrid call set_cont...
#!/usr/bin/env python ''' branching.py Author: Taylor Kessinger Date: July 4, 2016 Description: Simulation of density independent (Desai and Fisher) and density dependent branching processes. ''' import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") sns.set_context("talk",...
Python
zaydzuhri_stack_edu_python
string 125. Valid Palindrome Easy 574 1685 Favorite Share Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Examp...
""" 125. Valid Palindrome Easy 574 1685 Favorite Share Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true E...
Python
zaydzuhri_stack_edu_python
comment birth = input("생년월일 6자리를 입력해주세요.(yymmdd) : " ) comment print("당신의 생일은 "+birth[0:2]+'년'+birth[2:4]+"월"+birth[4:]+"일") set birth = input string 생년월일 6자리로 입력해주세요(yymmdd) : print string 당신의 생일은 birth at slice : 2 : string 년 birth at slice 2 : 4 : string 월 birth at slice 4 : : string 일 입니다.
# birth = input("생년월일 6자리를 입력해주세요.(yymmdd) : " ) # print("당신의 생일은 "+birth[0:2]+'년'+birth[2:4]+"월"+birth[4:]+"일") birth = input("생년월일 6자리로 입력해주세요(yymmdd) : ") print("당신의 생일은",birth[:2], '년',birth[2:4],"월",birth[4:], "일 입니다.")
Python
zaydzuhri_stack_edu_python
function shutdown self begin call shutdown join thread end function
def shutdown(self): self.thread.server.shutdown() self.thread.join()
Python
nomic_cornstack_python_v1
function ReadInput self begin set SelectedJlab = text set grid = children at 0 set abc = 0 call deselect_all_nodes grid for a in children begin if string text == string SelectedJlab begin call select_node a set abc = 1 end end if abc == 0 begin if SelectedJlab != string begin set popup = call LookupErrorPopup open end...
def ReadInput(self): SelectedJlab = (self.children[1].children[1].children[0].children[2].children[1].text) grid = self.children[1].children[1].children[0].children[0].children[0] abc = 0 grid.deselect_all_nodes(grid) for a in self.children[1].children[1].children[0].children[0]....
Python
nomic_cornstack_python_v1
function heartbeat self begin return dict split call heartbeat end function
def heartbeat(self): return {ModuleStoreEnum.Type.split: self.db_connection.heartbeat()}
Python
nomic_cornstack_python_v1
function test_correct_edges self begin call assert_equal list tuple 0 1 string edge01 tuple 3 4 string edge34 sorted call edges data=string name end function
def test_correct_edges(self): assert_equal([(0, 1, 'edge01'), (3, 4, 'edge34')], sorted(self.H.edges(data='name')))
Python
nomic_cornstack_python_v1
function read_twitter_stream client end logging_step=60 begin global NB_TWEETS set req = call request string statuses/filter dict string track string 4sq,swarmapp set new_tweet = string get {}, {}/{}, {:.1f} seconds to go set nb_cand = 0 for item in call get_iterator begin set candidate = call parse_tweet item set NB_T...
def read_twitter_stream(client, end, logging_step=60): global NB_TWEETS req = client.request('statuses/filter', {'track': '4sq,swarmapp'}) new_tweet = 'get {}, {}/{}, {:.1f} seconds to go' nb_cand = 0 for item in req.get_iterator(): candidate = th.parse_tweet(item) NB_TWEETS += 1 ...
Python
nomic_cornstack_python_v1
comment Used for loading the data from a directory structure comment [Pretrained models](https://pytorch.org/docs/master/torchvision/models.html) from torchvision import transforms , datasets , models comment Used to create dataloader object import torch comment Otherwise we cannot simply use nn.* ==> torch.nn.* from t...
# Used for loading the data from a directory structure # [Pretrained models](https://pytorch.org/docs/master/torchvision/models.html) from torchvision import transforms, datasets, models # Used to create dataloader object import torch # Otherwise we cannot simply use nn.* ==> torch.nn.* from torch import nn # To make o...
Python
zaydzuhri_stack_edu_python
function v1exchangemax24_hr self **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call v1exchangemax24_hr_with_http_info keyword kwargs end else begin set data = call v1exchangemax24_hr_with_http_info keyword kwargs return data end end function
def v1exchangemax24_hr(self, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.v1exchangemax24_hr_with_http_info(**kwargs) else: (data) = self.v1exchangemax24_hr_with_http_info(**kwargs) return data
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. comment For example, comment Given: comment s1 = "aabcc", comment s2 = "dbbca", comment When s3 = "aadbbcbcac", return true. comment When s3 = "aadbbbaccc", return false. comment Link: comment https://lee...
# -*- coding: utf-8 -*- # Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. # # For example, # Given: # s1 = "aabcc", # s2 = "dbbca", # # When s3 = "aadbbcbcac", return true. # When s3 = "aadbbbaccc", return false. # # # Link: # https://leetcode.com/problems/interleaving-string/ class...
Python
zaydzuhri_stack_edu_python
function dd_1d_moment data size_factor=none verbose=true k=2 Nr=1 begin if k > 4 begin print string ## The program only outputs at most 4 moments end if verbose begin set start_time = time print string #time start: 0.0s end set tuple Nc G = shape if verbose begin print string n_cell=%d, n_gene=%d % tuple Nc G end comme...
def dd_1d_moment(data, size_factor=None, verbose=True, k=2, Nr=1): if k>4: print('## The program only outputs at most 4 moments') if verbose: start_time=time.time() print('#time start: 0.0s') Nc,G = data.shape if verbose: print('n_cell=%d, n_gene=%d'%(Nc,G))...
Python
nomic_cornstack_python_v1
function compress self data_list begin string Return the cleaned_data of the form, everything should already be valid set data = dict if data_list begin return dictionary generator expression tuple name data_list at i for tuple i f in enumerate form end return data end function
def compress(self, data_list): """ Return the cleaned_data of the form, everything should already be valid """ data = {} if data_list: return dict( (f.name, data_list[i]) for i, f in enumerate(self.form)) return data
Python
jtatman_500k
string Method Checks that New in assertEqual('foo'.upper(), 'FOO') assertTrue('FOO'.isupper()) assertFalse('Foo'.isupper()) assertEqual(s.split(), ['hello', 'world']) assertAlmostEqual(a, b) round(a-b, 7) == 0 assertNotAlmostEqual(a, b) round(a-b, 7) != 0 assertGreater(a, b) a > b 2.7 assertGreaterEqual(a, b) a >= b 2....
''' Method Checks that New in assertEqual('foo'.upper(), 'FOO') assertTrue('FOO'.isupper()) assertFalse('Foo'.isupper()) assertEqual(s.split(), ['hello', 'world']) assertAlmostEqual(a, b) round(a-b, 7) == 0 assertNotAlmostEqual(a, b) round(a-b, 7) != 0 assertGreater(a, b) a > b 2.7 assertGreate...
Python
zaydzuhri_stack_edu_python
for i in range 1 101 begin if i % 7 == 0 begin continue end else if i % 10 % 7 == 0 and i % 10 != 0 begin continue end else if i // 10 % 10 % 7 == 0 and i // 10 % 10 % 10 != 0 begin continue end else begin print i end end
for i in range(1,101): if i%7==0: continue elif (i%10)%7==0 and i%10!=0: continue elif (i//10%10)%7==0 and (i//10%10)%10!=0: continue else: print(i)
Python
zaydzuhri_stack_edu_python
comment NOTE: this module was renamed from exceptions.py due to side effects of comment python relative import and potential class with a builtin exceptions module class DianeException extends Exception begin function __init__ self msg exc=false begin call __init__ self msg if exc begin from diane.util.compatibility im...
# NOTE: this module was renamed from exceptions.py due to side effects of # python relative import and potential class with a builtin exceptions module class DianeException(Exception): def __init__(self,msg,exc=False): Exception.__init__(self,msg) if exc: from diane.util.compatibility i...
Python
zaydzuhri_stack_edu_python
function sample_delay self *args **kwargs begin return call scrambler_sptr_sample_delay self *args keyword kwargs end function
def sample_delay(self, *args, **kwargs): return _my_lte_swig.scrambler_sptr_sample_delay(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
import cups import UpdateDisplay function initial_print total_image_count begin comment Connect to cups and select printer 0 set conn = call Connection set printers = call getPrinters set printer_name = keys printers at 0 comment Increment the large image counter set total_image_count = total_image_count + 1 return tot...
import cups import UpdateDisplay def initial_print(total_image_count): # Connect to cups and select printer 0 conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[0] # Increment the large image counter total_image_count = total_image_count + 1 return total...
Python
zaydzuhri_stack_edu_python
function clone self begin import copy return deep copy self end function
def clone(self): import copy return copy.deepcopy(self)
Python
nomic_cornstack_python_v1
function test_bluerWhiteDeck self begin add mydeck card1 add mydeck card1 add mydeck card2 set colors = call colorBreakdown assert equal 0.3333333333333333 colors at string W assert equal 0.6666666666666666 colors at string B end function
def test_bluerWhiteDeck(self): self.mydeck.add(self.card1) self.mydeck.add(self.card1) self.mydeck.add(self.card2) colors = self.mydeck.colorBreakdown() self.assertEqual(0.33333333333333331, colors["W"]) self.assertEqual(0.66666666666666663, colors["B"])
Python
nomic_cornstack_python_v1
function removeNonAscii self s begin return join string list comprehension x for x in s if ordinal x < 128 end function
def removeNonAscii(self, s): return "".join([x for x in s if ord(x) < 128])
Python
nomic_cornstack_python_v1
function test_upload_body db_conn cards_table begin set tuple card errors = insert UploadCard db_conn dict string unit_id string RUF531 ; string name string What is? ; string file_extensions list string jpg ; string rubric true comment TODO assert length errors == 1 set tuple card errors = update card db_conn dict stri...
def test_upload_body(db_conn, cards_table): card, errors = UploadCard.insert(db_conn, { 'unit_id': 'RUF531', 'name': 'What is?', 'file_extensions': ['jpg'], 'rubric': True, # TODO }) assert len(errors) == 1 card, errors = card.update(db_conn, {'body': 'Testing 1234'}) ...
Python
nomic_cornstack_python_v1
function putBoolean self key value begin set path = _path + key return call setEntryValue path call makeBoolean value end function
def putBoolean(self, key: str, value: bool) -> bool: path = self._path + key return self._api.setEntryValue(path, Value.makeBoolean(value))
Python
nomic_cornstack_python_v1
function get_distribution_counts self amt_per_loan=25 begin set dframe = call DataFrame data=values distribution index=keys distribution columns=list string allocation set num_loans = integer invest_amt / integer amt_per_loan if not num_loans > 0 begin raise string please set correct invest_amt and amt_per_loan end set...
def get_distribution_counts(self, amt_per_loan=25): dframe = pd.DataFrame(data=self.distribution.values(), index=self.distribution.keys(), columns=['allocation']) ...
Python
nomic_cornstack_python_v1
function find_minima_mid arr_inputs begin set arr_boo_roll_plus_1 = call roll arr_inputs 1 set arr_boo_roll_plus_2 = call roll arr_inputs 2 set arr_boo_roll_minus_1 = call roll arr_inputs - 1 set arr_boo_roll_minus_2 = call roll arr_inputs - 2 comment Find peaks set arr_boo_peak_roll_1 = call logical_and arr_boo_roll_p...
def find_minima_mid(arr_inputs): arr_boo_roll_plus_1 = np.roll(arr_inputs,1) arr_boo_roll_plus_2 = np.roll(arr_inputs,2) arr_boo_roll_minus_1 = np.roll(arr_inputs,-1) arr_boo_roll_minus_2 = np.roll(arr_inputs,-2) # Find peaks arr_boo_peak_roll_1 = np.logical_and((arr_boo_roll_plus_1 > arr_input...
Python
nomic_cornstack_python_v1
function partition arr low high begin set pivot = arr at low set i = low + 1 set j = high set swaps = 0 while i <= j begin while i <= j and arr at i < pivot begin set i = i + 1 end while i <= j and arr at j >= pivot begin set j = j - 1 end if i < j begin set tuple arr at i arr at j = tuple arr at j arr at i set swaps =...
def partition(arr, low, high): pivot = arr[low] i = low + 1 j = high swaps = 0 while i <= j: while i <= j and arr[i] < pivot: i += 1 while i <= j and arr[j] >= pivot: j -= 1 if i < j: arr[i], arr[j] = arr[j], arr[i] swaps += ...
Python
jtatman_500k
function url_join *args begin set parts = list for arg in args begin append parts strip arg string / end return join string / parts end function
def url_join( *args ): parts = [] for arg in args: parts.append( arg.strip( '/' ) ) return '/'.join( parts )
Python
nomic_cornstack_python_v1
import socket set answer = dict set ADDRESS = tuple string 0.0.0.0 33337 function get_answer begin set file = open string chat.txt string r for line in file begin set word = split line string 1 set answer at word at 0 = word at 1 end close file end function function find_answer begin set xiaomei_socket = call socket ...
import socket answer = {} ADDRESS = ('0.0.0.0', 33337) def get_answer(): file = open('chat.txt', 'r') for line in file: word = line.split(' ', 1) answer[word[0]] = word[1] file.close() def find_answer(): xiaomei_socket = socket.socket() xiaomei_socket.bind(ADDRESS) xiaomei_s...
Python
zaydzuhri_stack_edu_python
function uri_for_api api_name params=none external=true begin import urllib set r = _api_to_route at api_name set res = right strip call url_for string _dispatch_empty _external=external + base_uri string / for p in params begin if name in params begin set v = params at name if not v is none and length v > 0 begin if n...
def uri_for_api(api_name, params=None, external=True): import urllib r = _api_to_route[api_name] res = (flask.url_for('_dispatch_empty', _external=external) + r.base_uri).rstrip('/') for p in r.params: if p.name in params: v = params[p.name] if not v is None and len(v) >...
Python
nomic_cornstack_python_v1
function get_color topo_value bw begin comment if type(topo_value) == type(None): comment return(0, 0, 0) comment -20 to +256 if bw begin if topo_value < 0 begin set bwValue = 64 - absolute topo_value return tuple bwValue bwValue bwValue end else begin set bwValue = 64 + absolute topo_value return tuple bwValue bwValue...
def get_color(topo_value: int, bw: bool): # if type(topo_value) == type(None): # return(0, 0, 0) # -20 to +256 if bw: if topo_value < 0: bwValue = 64 - abs(topo_value) return (bwValue, bwValue, bwValue) else: bwValue = 64 + abs(topo_value) ...
Python
nomic_cornstack_python_v1
function chunks l n begin for i in range 0 length l n begin yield l at slice i : i + n : end end function
def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n]
Python
nomic_cornstack_python_v1
import numpy as np import RPi.GPIO as gp import cv2 import os import sys import time import math import subprocess string Parameter setting set width = 1280 set height = 1280 string GPIO initialize call setwarnings false call setmode BOARD setup gp 7 OUT setup gp 11 OUT setup gp 12 OUT string Functions function take_L_...
import numpy as np import RPi.GPIO as gp import cv2 import os import sys import time import math import subprocess ###################################### ''' Parameter setting ''' width = 1280 height = 1280 ###################################### ''' GPIO initialize ''' gp.setwarnings(False) gp.setmode(gp.BOARD) gp....
Python
zaydzuhri_stack_edu_python
comment Set Dependencies: import os import csv comment Declare Variables: set candidate_list = list set voting_list = list set percent_list = list set number_of_votes = 0 set candidate = 0 set winner = 0 comment Describe the file path to the csv file: set csv_path = join path string Resources string election_data.cs...
# Set Dependencies: import os import csv # Declare Variables: candidate_list = [] voting_list = [] percent_list = [] number_of_votes = 0 candidate = 0 winner = 0 # Describe the file path to the csv file: csv_path = os.path.join('Resources', 'election_data.csv') # Opening and reading the file: with open(csv_path, new...
Python
zaydzuhri_stack_edu_python
import os from os.path import join from os import makedirs , listdir from PIL import Image function is_image_file file_name begin return any generator expression ends with file_name extension for extension in list string .png string .jpg string jpeg string JPEG string .bmp and not starts with file_name string . end fun...
import os from os.path import join from os import makedirs, listdir from PIL import Image def is_image_file(file_name): return any(file_name.endswith(extension) for extension in [".png", ".jpg", "jpeg", "JPEG", ".bmp"]) and not file_name.startswith(".") def get_valid_size(image, upscale_factor): valid_h = image.he...
Python
zaydzuhri_stack_edu_python
from dataclasses import dataclass from datetime import datetime from time import mktime decorator dataclass class Episode begin set title : str set summary : str set date : datetime set tags : list set duration : int set season_number : str set episode_number : str function __init__ self item begin set title = item at ...
from dataclasses import dataclass from datetime import datetime from time import mktime @dataclass class Episode: title: str summary: str date: datetime tags: list duration: int season_number: str episode_number: str def __init__(self, item: dict): self.title = item['title'] self.summary ...
Python
zaydzuhri_stack_edu_python
function copy_directory self relativePath newRelativePath overwrite=false raiseError=true ntrials=3 begin assert is instance raiseError bool msg string raiseError must be boolean assert is instance overwrite bool msg string overwrite must be boolean assert is instance ntrials int msg string ntrials must be integer asse...
def copy_directory(self, relativePath, newRelativePath, overwrite=False, raiseError=True, ntrials=3): assert isinstance(raiseError, bool), "raiseError must be boolean" assert isinstance(overwrite, bool), "overwrite must be boolean" assert isinstance(ntrials, int), "n...
Python
nomic_cornstack_python_v1
function __init__ self begin set rundles = dict for dname in list directory string data begin set fname = join sep list string data dname string groupno.txt if is file fname begin with open fname string r as f begin set number = strip read f set rundles at dname = number end end end end function
def __init__(self): self.rundles = {} for dname in listdir('data'): fname = sep.join(['data', dname, 'groupno.txt']) if isfile(fname): with open(fname, 'r') as f: number = f.read().strip() self.rundles[dname] = number
Python
nomic_cornstack_python_v1
function comma_splitter tag_string begin set tag_string = replace replace tag_string string string string , string , return list comprehension lower strip t for t in split tag_string string , if strip t end function
def comma_splitter(tag_string): tag_string = tag_string.replace(' ', '').replace(',', ',') return [t.strip().lower() for t in tag_string.split(',') if t.strip()]
Python
zaydzuhri_stack_edu_python
function _predict_corechain self _q _question_dep _question_dep_mask_matrix _p _p_words _p1=none _p2=none _p3=none _p4=none begin comment print(len(np_array)) function distribute_it np_array k begin return call array_split np_array at slice : : k axis=0 end function comment Pad questions set Q = zeros tuple length _...
def _predict_corechain(self, _q, _question_dep, _question_dep_mask_matrix, _p, _p_words, _p1=None, _p2=None, _p3=None, _p4=None): def distribute_it(np_array, k): # print(len(np_array)) return np.array_split(np_array[:], k, axis=0) ###Pad questions Q = np.zeros((len(_p), self.paramete...
Python
nomic_cornstack_python_v1