code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function set_user_auth self user_settings begin set user_settings = user_settings set nodelogger = call DropboxNodeLogger node=owner auth=call Auth owner log action=string node_authorized save=true end function
def set_user_auth(self, user_settings): self.user_settings = user_settings nodelogger = DropboxNodeLogger(node=self.owner, auth=Auth(user_settings.owner)) nodelogger.log(action="node_authorized", save=True)
Python
nomic_cornstack_python_v1
function _add_right self p e begin set node = call _validate p if _right is not none begin raise call ValueError string Right child exists end set _size = _size + 1 comment node is its parent set _right = call _Node e node return call _make_position _right end function
def _add_right(self, p, e): node = self._validate(p) if node._right is not None: raise ValueError('Right child exists') self._size += 1 node._right = self._Node(e, node) # node is its parent return self._make_position(node._right)
Python
nomic_cornstack_python_v1
function fire self begin set tokens = tokens - arc_weight * coefficient_scalar end function
def fire(self): self.place.tokens -= self.arc_weight*self.coefficient_scalar
Python
nomic_cornstack_python_v1
function search_profiles request begin set query = get GET string q set results = filter user__username__icontains=query set template = string profiles/search_profiles.html set context = dict string results results ; string query query return call render request template context end function
def search_profiles(request): query = request.GET.get('q') results = Profile.objects.filter(user__username__icontains=query) template = 'profiles/search_profiles.html' context = { 'results': results, 'query': query } return render(request, template, context)
Python
nomic_cornstack_python_v1
comment coding: utf-8 import itertools import threading import time import sys import os set stop = false function animate begin set stop = false end function
#coding: utf-8 import itertools import threading import time import sys import os stop = False def animate(): stop = False
Python
zaydzuhri_stack_edu_python
import random import collections import tweepy set count = 0 set counter = counter set l = list class MyStreamListener extends StreamListener begin function on_status self status begin global count global counter global l set count = count + 1 if count <= 150 begin append l text set words = split text for w in words b...
import random import collections import tweepy count = 0 counter = collections.Counter() l = [] class MyStreamListener(tweepy.StreamListener): def on_status(self, status): global count global counter global l count +=1 if count <= 150: l.append(status.text...
Python
zaydzuhri_stack_edu_python
import struct set evFmt = string IHBB set evSize = call calcsize evFmt set fp = open string /dev/input/js0 string rb while true begin set data = read fp evSize set tuple time value typ number = call unpack evFmt data end
import struct evFmt = 'IHBB' evSize = struct.calcsize(evFmt) fp = open('/dev/input/js0', 'rb') while True: data = fp.read(evSize) time, value, typ, number = struct.unpack(evFmt, data)
Python
zaydzuhri_stack_edu_python
function keyPressEvent self event begin if call key == Key_Return or call key == Key_Enter begin if call is_valid begin call selected comment Insert item in combo box call keyPressEvent self event end end else begin call keyPressEvent self event end end function
def keyPressEvent(self, event): if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: if self.is_valid(): self.selected() QComboBox.keyPressEvent(self, event) # Insert item in combo box else: QComboBox.keyPressEvent(self, event)
Python
nomic_cornstack_python_v1
function quaternion_from_axis_rotation angle axis begin string Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis. set out = zeros 4 dtype=float if axis == string ...
def quaternion_from_axis_rotation(angle, axis): """Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis. """ ...
Python
jtatman_500k
function create_twitter_timeline_DataFrame screen_name timeline_data_dir=string ./data/output_data/timelines/ begin comment Load a single user twitter timeline (already downloaded as a json object) with open TIMELINE_DATA_DIR + screen_name + string .json string r as f begin set timelines = load json f end comment Data ...
def create_twitter_timeline_DataFrame(screen_name, timeline_data_dir = "./data/output_data/timelines/"): # Load a single user twitter timeline (already downloaded as a json object) with open(TIMELINE_DATA_DIR + screen_name + ".json", "r") as f: timelines = json.load(f) # Data definitions as list co...
Python
nomic_cornstack_python_v1
import json import unittest comment from demo import AnonymousSurvey string question="What langue did you first learn to speak?" my_survey=AnonymousSurvey(question) my_survey.show_question() print("Enter 'q' at any time quite. ") while True: response=input("Langue:") if response=='q': break my_survey.store_responses(re...
import json import unittest #from demo import AnonymousSurvey """question="What langue did you first learn to speak?" my_survey=AnonymousSurvey(question) my_survey.show_question() print("Enter 'q' at any time quite.\n") while True: response=input("Langue:") if response=='q': break my_survey.store_re...
Python
zaydzuhri_stack_edu_python
while true begin try begin set num = integer input string Enter number of the student : if num > 0 begin break end else begin print string number of the student must be bigger than 0 !! end end except any begin print string Enter an integer number end end for i in range num begin while true begin try begin set grd = de...
while True: try: num=int(input("Enter number of the student :")) if num>0: break else: print(" number of the student must be bigger than 0 !! ") except: print("Enter an integer number ") for i in range(num): while True: try:...
Python
zaydzuhri_stack_edu_python
string Input: Four lists with coordinates--each one is a list of x and y coordinates--W1, W2, A, B (Integers). Output: Whether the bullet hits the wall or not, aka True or False. from math import fabs import datetime comment 4 seconds 651000 microseconds function checkio1 data begin function in_beam end sign x begin if...
""" Input: Four lists with coordinates--each one is a list of x and y coordinates--W1, W2, A, B (Integers). Output: Whether the bullet hits the wall or not, aka True or False. """ from math import fabs import datetime # 4 seconds 651000 microseconds def checkio1(data): def in_beam(end, sign, x): if sign ...
Python
zaydzuhri_stack_edu_python
function status_cmd self begin if _status_cmd is none begin raise call NotImplementedError end return _status_cmd end function
def status_cmd(self): if self._status_cmd is None: raise NotImplementedError() return self._status_cmd
Python
nomic_cornstack_python_v1
set name = string Ho Vu Hoang Anh set tuoi = 19 set MSSV = string 1906020128 print string THONG TIN SINH VIEN print string Hello thầy ! Em là: { name } Tuổi: { tuoi } MSSV: { MSSV }
name = "Ho Vu Hoang Anh" tuoi = 19 MSSV = "1906020128" print("THONG TIN SINH VIEN") print(f"Hello thầy ! \nEm là: {name}\nTuổi: {tuoi}\nMSSV: {MSSV}")
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 from g_utils import * function dijkstrALG grafo fonte begin comment inicia (a)ntecedencia vazia set a = dictionary comprehension no : none for no in grafo comment inicia distância infinita set d = dictionary comprehension no : decimal string Inf for no in grafo comment distancia da fonte = 0 set d...
#coding: utf-8 from g_utils import * def dijkstrALG(grafo, fonte): a = {no:None for no in grafo} #inicia (a)ntecedencia vazia d = {no:float('Inf') for no in grafo} #inicia distância infinita d[fonte] = 0 #distancia da fonte = 0 Q = [] heapq.heappush(Q, [d[fonte], fonte]) #fila de prioridades usa h...
Python
zaydzuhri_stack_edu_python
async function handle_user_message r message ws=none begin set address = call get_request_ip r set uid = if expression ws is not none then id else string 0 set now = integer round time * 1000 if address in app at string last_msg begin if now - app at string last_msg at address at string last < 25 begin if app at string...
async def handle_user_message(r : web.Request, message : str, ws : web.WebSocketResponse = None): address = util.get_request_ip(r) uid = ws.id if ws is not None else '0' now = int(round(time.time() * 1000)) if address in r.app['last_msg']: if (now - r.app['last_msg'][address]['last']) < 25: ...
Python
nomic_cornstack_python_v1
function get_type_for_parameter parameter typing=false begin if string content in parameter begin assert string in not in parameter for content in values parameter at string content begin return call type_to_python content at string schema typing=typing end end return call type_to_python get parameter string schema typ...
def get_type_for_parameter(parameter, typing=False): if "content" in parameter: assert "in" not in parameter for content in parameter["content"].values(): return type_to_python(content["schema"], typing=typing) return type_to_python(parameter.get("schema"), typing=typing)
Python
nomic_cornstack_python_v1
function sub num1 num2 begin set subt = num1 - num2 return subt end function set data = sub 75 89 print data
def sub(num1,num2): subt=num1-num2 return subt data=sub(75,89) print(data)
Python
zaydzuhri_stack_edu_python
string Utility functions and classes import ntpath function get_seq sequence begin string Returns string representation of sequence genome given a FASTA file. Assumes only one sequence in the file set consensus = string with open sequence string r as f begin set lines = list comprehension strip line for line in read li...
"""Utility functions and classes""" import ntpath def get_seq(sequence): """ Returns string representation of sequence genome given a FASTA file. Assumes only one sequence in the file """ consensus = str() with open(sequence, 'r') as f: lines = [line.strip() for line i...
Python
zaydzuhri_stack_edu_python
function parse_payload cls payload begin if is instance payload bytes begin set payload = decode payload string utf-8 end if is instance payload basestring begin set text = unquote payload return call _parse_payload_text text end else if has attribute payload string as_text begin return payload end else begin raise cal...
def parse_payload(cls, payload): if isinstance(payload, bytes): payload = payload.decode('utf-8') if isinstance(payload, basestring): text = unquote(payload) return cls._parse_payload_text(text) elif hasattr(payload, 'as_text'): return payload ...
Python
nomic_cornstack_python_v1
print 1 + 4 * 3 - 8 / 2 print 1 + 4 * 3 - 8 / 2 print 1 + 4 * 3 - 8 / 2 print 1 + 4 * 3 - 8 / 2 print 1 + 4 * 3 - 8 // 2 print 1 + 4 * 3 - 8 // 2 print 1 + 4 * 3 - 8 // 2 print 1 + 4 * 3 - 8 // 2 print true or true and false print true or true and false print true or true and false print not true or true and false prin...
print(1 + 4 * 3 - 8 / 2) print((1 + 4) * 3 - 8 / 2) print(1 + 4 * (3 - 8) / 2) print((1 + 4) * (3 - 8) / 2) print(1 + 4 * 3 - 8 // 2) print((1 + 4) * 3 - 8 // 2) print(1 + 4 * (3 - 8) // 2) print((1 + 4) * (3 - 8) // 2) print(True or True and False) print(True or (True and False)) print((True or True) and False) print(...
Python
zaydzuhri_stack_edu_python
function test_is_closest_hour07 self begin set now = call dt 2019 1 25 19 35 0 0 TO_ZONE set sunset = call dt 2019 1 25 19 37 30 0 TO_ZONE set result = call is_closest_time now sunset assert true result string Should be considered the closest (favour before in equal diff) end function
def test_is_closest_hour07(self): now = dt(2019, 1, 25, 19, 35, 0, 0, TO_ZONE) sunset = dt(2019, 1, 25, 19, 37, 30, 0, TO_ZONE) result = is_closest_time(now, sunset) self.assertTrue( result, 'Should be considered the closest (favour before in equal diff)')
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import random from KMeansPlus import K_Means_Plus_Plus string Tests K-means++ with 50 randomly generated 2-var data points in various ranges function KMeansPlusPlus_Test begin set points = list set xs = list set ys = list for a in range 50 begin set a = 100 * random set b = 50 * rando...
import matplotlib.pyplot as plt import random from KMeansPlus import K_Means_Plus_Plus """Tests K-means++ with 50 randomly generated 2-var data points in various ranges""" def KMeansPlusPlus_Test(): points = [] xs = [] ys = [] for a in range(50): a = 100*random.random() b = 50*random.r...
Python
zaydzuhri_stack_edu_python
function checkout_qmk begin if exists string qmk_firmware begin remove tree string qmk_firmware end if not call fetch_source call repo_name QMK_GIT_URL begin call git_clone QMK_GIT_URL QMK_GIT_BRANCH end end function
def checkout_qmk(): if exists('qmk_firmware'): rmtree('qmk_firmware') if not fetch_source(repo_name(QMK_GIT_URL)): git_clone(QMK_GIT_URL, QMK_GIT_BRANCH)
Python
nomic_cornstack_python_v1
function calculate_chocolates_selling_price begin comment Given values set total_chocolates = 24 comment 50% as a decimal set gain_percent = 0.5 comment Calculate the number of chocolates in the selling price comment Using 1 + gain_percent to derive n set n = total_chocolates / 1 + gain_percent comment Convert to integ...
def calculate_chocolates_selling_price(): # Given values total_chocolates = 24 gain_percent = 0.5 # 50% as a decimal # Calculate the number of chocolates in the selling price n = total_chocolates / (1 + gain_percent) # Using 1 + gain_percent to derive n return int(n) # Convert to integer...
Python
dbands_pythonMath
function SetNtpInfo ctx servers broadcastclient=none begin if element is none begin error string You must establish at least one connection and specify which you intend to use. exit end set servers = call parse_array servers info string servers = + string servers + string ; + string broadcastclient = + string broadcast...
def SetNtpInfo(ctx, servers, broadcastclient = None): if ctx.element is None: ctx.logger.error("You must establish at least one connection and specify which you intend to use.") exit() servers = parser.parse_array(servers) ctx.logger.info("""servers = """+str(serv...
Python
nomic_cornstack_python_v1
import hashlib import socket import os import base64 set registeredPassword = call raw_input string Enter registered password comment salt = os.urandom(32).decode() set salt = call urlsafe_b64encode call urandom 32 print format string Salt is {} salt set digest = sha1 salt + registeredPassword set digest = hex digest d...
import hashlib import socket import os import base64 registeredPassword = raw_input("Enter registered password") #salt = os.urandom(32).decode() salt = base64.urlsafe_b64encode(os.urandom(32)) print("Salt is {}".format(salt)) digest = hashlib.sha1(salt + registeredPassword) digest = digest.hexdigest() ss = socket.soc...
Python
zaydzuhri_stack_edu_python
function create_users session members begin comment Set only the users that exist in the input list as active update query session User dict string active false update filter call in_ members dict string active true synchronize_session=string fetch for member in members begin set user = all if not user begin set user =...
def create_users(session, members): # Set only the users that exist in the input list as active session.query(User).update({ 'active': False}) session.query(User).filter(User.user_id.in_(members)).update({ 'active': True }, synchronize_session='fetch') for member in members: ...
Python
nomic_cornstack_python_v1
import multiprocessing import timeit import csv import re import time import requests from selenium import webdriver from bs4 import BeautifulSoup , Tag comment Setup Chrome display set options = call ChromeOptions call add_argument string --ignore-certificate-errors call add_argument string --test-type comment List of...
import multiprocessing import timeit import csv import re import time import requests from selenium import webdriver from bs4 import BeautifulSoup, Tag # Setup Chrome display options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") # L...
Python
zaydzuhri_stack_edu_python
import streamlit as st import yfinance as yf import pandas as pd import tweepy as tp import re import itertools import collections import matplotlib.pyplot as plt from nltk.corpus import stopwords from config import create_api set stop_words = set call words string english set api = call create_api set Tickerdict = dic...
import streamlit as st import yfinance as yf import pandas as pd import tweepy as tp import re import itertools import collections import matplotlib.pyplot as plt from nltk.corpus import stopwords from config import create_api stop_words = set(stopwords.words('english')) api = create_api() Tickerdict = {"Gamestop":'...
Python
zaydzuhri_stack_edu_python
function create_model_version self name source run_id=none tags=none run_link=none description=none local_model_path=none begin function next_version registered_model_name begin set path = call _get_registered_model_path registered_model_name set model_versions = call _list_model_versions_under_path path if model_versi...
def create_model_version( self, name, source, run_id=None, tags=None, run_link=None, description=None, local_model_path=None, ): def next_version(registered_model_name): path = self._get_registered_model_path(registered_model_name)...
Python
nomic_cornstack_python_v1
while true begin set inp = input string Digite a nota do aluno: if inp == string pronto begin break end set valor = decimal inp append numlist valor set Média = sum numlist / length numlist end print string Média: Média print string A média do aluno foi { Média } .
while True: inp= input('Digite a nota do aluno: ') if inp=='pronto' :break valor=float(inp) numlist.append(valor) Média=sum(numlist)/len(numlist) print('Média: ',Média) print(f'A média do aluno foi {Média}.')
Python
zaydzuhri_stack_edu_python
import subprocess run list string dxdiag
import subprocess subprocess.run(['dxdiag'])
Python
flytech_python_25k
function get_east_asian_width_property value is_bytes=false begin string Get `EAST ASIAN WIDTH` property. set obj = if expression is_bytes then ascii_east_asian_width else unicode_east_asian_width if starts with value string ^ begin set negated = value at slice 1 : : set value = string ^ + get unicode_alias at string...
def get_east_asian_width_property(value, is_bytes=False): """Get `EAST ASIAN WIDTH` property.""" obj = unidata.ascii_east_asian_width if is_bytes else unidata.unicode_east_asian_width if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['eastasianwidth'].get(ne...
Python
jtatman_500k
function get_json self relative_url **kwargs begin set target_url = url join base_address relative_url set response = get session target_url keyword kwargs return json response end function
def get_json(self, relative_url, **kwargs): target_url = urlparse.urljoin(self.base_address, relative_url) response = self.session.get(target_url, **kwargs) return response.json()
Python
nomic_cornstack_python_v1
import requests import bs4 set results = get requests string https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer) set soup = call BeautifulSoup text string lxml set image_info = select soup string .thumbimage set kasp = image_info at 0 kasp at string src set image_link = get requests string https://upload.wikimedia...
import requests import bs4 results = requests.get("https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)") soup = bs4.BeautifulSoup(results.text,'lxml') image_info = soup.select('.thumbimage') kasp = image_info[0] kasp['src'] image_link = requests.get('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6...
Python
zaydzuhri_stack_edu_python
function time_of_last_access c runner path begin set cmd = format string stat --format='%x' {} path set owner = strip stdout return owner end function
def time_of_last_access(c, runner, path): cmd = "stat --format='%x' {}".format(path) owner = runner(cmd, hide=True, warn=True).stdout.strip() return owner
Python
nomic_cornstack_python_v1
import os from PIL import Image , ImageFilter set OLD_DIR = string path to directory of images to augment set AUG_DIR = string path to save the augmented images for filename in list directory OLD_DIR begin if string png not in filename begin continue end set path = join path OLD_DIR filename set im = open path set im =...
import os from PIL import Image, ImageFilter OLD_DIR = 'path to directory of images to augment' AUG_DIR = 'path to save the augmented images' for filename in os.listdir(OLD_DIR): if 'png' not in filename: continue path = os.path.join(OLD_DIR, filename) im = Image.open(path) im = im.convert('L...
Python
zaydzuhri_stack_edu_python
function runConcurrentThread self begin call debugLog string runConncurrentThread called for deviceId in deviceList begin comment get device instance & associated IP address set dev = devices at deviceId comment read properties & create EversolarMonitor object set ipAddr = pluginProps at string ipAddress set ipPort = p...
def runConcurrentThread(self): self.debugLog(u"runConncurrentThread called") for deviceId in self.deviceList: # get device instance & associated IP address dev = indigo.devices[deviceId] # read properties & create EversolarMonitor object ...
Python
nomic_cornstack_python_v1
for item in my_list begin set counter = counter + item end print counter
for item in my_list: counter = counter + item print(counter)
Python
zaydzuhri_stack_edu_python
function benchmark self qc=none qubits=none single_gates=none multi_gates=none **kwargs begin comment Parse the arguments from the key list. If not set, use default arguments from the init function set _qc = if expression qc is not none then qc else _qc set _qubits = if expression qubits is not none then qubits else _q...
def benchmark(self, qc: QComputer = None, qubits: List[int] = None, single_gates: List[str] = None, multi_gates: List[str] = None, **kwargs) -> dict: # Parse the arguments from the key list. If not set, use default arguments from the init function self._qc = qc if qc is not None else s...
Python
nomic_cornstack_python_v1
from typing import * class Solution begin function findMin self nums begin set N = length nums set start = 0 set end = N - 1 while start < end begin set mid = start + end // 2 while nums at mid == nums at end and mid < end begin set end = end - 1 end if nums at mid > nums at end begin set start = mid + 1 end else begin...
from typing import * class Solution: def findMin(self, nums: List[int]) -> int: N=len(nums) start=0 end=N-1 while start<end: mid=(start+end)//2 while nums[mid]==nums[end] and mid<end: end-=1 ...
Python
zaydzuhri_stack_edu_python
function bdh self ticker_list fld_list start_date end_date=string format time today string %Y%m%d periodselection=string DAILY overrides=none other_request_parameters=none move_dates_to_period_end=false begin comment Create and fill the request for the historical data call _ensure_refdata_service if call isstring ticke...
def bdh(self, ticker_list, fld_list, start_date, end_date=date.today().strftime('%Y%m%d'), periodselection='DAILY', overrides=None, other_request_parameters=None, move_dates_to_period_end=False): # Create and fill the request for the historical data self._ensure_refdata_service() if isstring(ti...
Python
nomic_cornstack_python_v1
function destroyInterface self remoteInterface begin for interface in _interfaces begin if call destroyExternal remoteInterface begin break end end end function
def destroyInterface(self, remoteInterface): for interface in self._interfaces: if interface.destroyExternal(remoteInterface): break
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python from specialInput import * set numDice = call int_input string How many dice would you like to roll? import random
#! /usr/bin/env python from specialInput import * numDice = int_input("How many dice would you like to roll? ") import random
Python
zaydzuhri_stack_edu_python
function data self begin comment Create a new window set __data_window = call Toplevel __window title __data_window string Students data set __ID_heading = call Label __data_window text=string ID anchor=W set __name_heading = call Label __data_window text=string Name anchor=W set __email_heading = call Label __data_win...
def data(self): # Create a new window self.__data_window = Toplevel(self.__window) self.__data_window.title("Students data") self.__ID_heading = Label(self.__data_window, text="ID", anchor=W) self.__name_heading = Label(self.__data_window, text="Name", anchor=W) self.__em...
Python
nomic_cornstack_python_v1
import tweepy import time import re import sys import string from stemming.porter2 import stem import pickle from decimal import * import math import csv from math import * comment retrieve the tweets from accounts--------------------------------------------- function getStatus classes begin comment fetch account array...
import tweepy import time import re import sys import string from stemming.porter2 import stem import pickle from decimal import * import math import csv from math import * # retrieve the tweets from accounts--------------------------------------------- def getStatus(classes): ...
Python
zaydzuhri_stack_edu_python
comment TODO: THIS WHOLE THING NEEDS TO BE BETTER ORGANIZED... ITS A MESS class TestArena begin set description = string Whats going on here? end class class originRooms begin set description = string A lone dark room with 3 door ways, each one marked in blood end class class door1 begin set description = string A wood...
# TODO: THIS WHOLE THING NEEDS TO BE BETTER ORGANIZED... ITS A MESS class TestArena: description = "Whats going on here?" class originRooms: description = "A lone dark room with 3 door ways, each one marked in blood" class door1: description = "A wooden door, with a 1 on it. The door has a glowing red...
Python
zaydzuhri_stack_edu_python
function get_primeslist N begin comment 为了让下标等于值,便于计算 set flag = list comprehension 1 for i in range N + 1 set flag at 0 = 0 set flag at 1 = 0 set primes_list = list for i in range 2 N + 1 begin comment 值为1代表这个值是素数 if flag at i begin comment 下标等于值 append primes_list i set j = i comment 从素数本身开始自底向上将素数的倍数标记为合数(非素数) whil...
def get_primeslist(N): flag=[1 for i in range(N+1)] #为了让下标等于值,便于计算 flag[0]=flag[1]=0 primes_list=[] for i in range(2,N+1): if flag[i]: #值为1代表这个值是素数 primes_list.append(i) #下标等于值 j = i while j*i <= N : #从素数本身开始自底向上将素数的倍数标记为合数(非素数) flag[j*i] = 0 ...
Python
zaydzuhri_stack_edu_python
function save begin save figure string /home/filippini/Documents/plot/RUN55/compa + INFO_RUN + string .png end function
def save(): pl.savefig('/home/filippini/Documents/plot/RUN55/compa'+INFO_RUN+'.png')
Python
nomic_cornstack_python_v1
comment noqa: F811 function test_root_notfound c begin set rv = get c string / assert status_code == 404 assert string 404 Not Found in string data end function
def test_root_notfound(c): # noqa: F811 rv = c.get('/') assert rv.status_code == 404 assert '404 Not Found' in str(rv.data)
Python
nomic_cornstack_python_v1
function secret_name self begin return call cast str get _properties string secretName end function
def secret_name(self) -> str: return typing.cast( str, self._properties.get("secretName"), )
Python
nomic_cornstack_python_v1
from collections import deque class Node begin function __init__ self data begin set data = data set left = none set right = none end function end class class BinaryTree begin function __init__ self begin set head = none end function function insert self data begin if head is none begin set head = call Node data return...
from collections import deque class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self): self.head = None def insert(self, data): if self.head is None: self.head = Node(data) ...
Python
zaydzuhri_stack_edu_python
function dashboard request begin set template = string dashboard.html set db = call get_dashboard_components request set pie_graph = call dashboard_instrument_pie_chart set files_graph = call dashboard_files_per_day set useage_graph = call dashboard_disk_usage set tuple directories_usage_graph central_store_usage_graph...
def dashboard(request): template = 'dashboard.html' db = get_dashboard_components(request) pie_graph = db.dashboard_instrument_pie_chart() files_graph = db.dashboard_files_per_day() useage_graph = db.dashboard_disk_usage() directories_usage_graph, central_store_usage_graph = db.dashboard_centr...
Python
nomic_cornstack_python_v1
function __naive_matching pattern text begin set matched_positions = list set n = length text set m = length pattern comment Last possible pattern starting position in the text is n - m for pos in range n - m + 1 begin if pattern == text at slice pos : pos + m : begin append matched_positions pos end end return match...
def __naive_matching(pattern, text): matched_positions = [] n = len(text) m = len(pattern) # Last possible pattern starting position in the text is n - m for pos in range((n - m) + 1): if pattern == text[pos:(pos+m)]: matched_positions.append(pos) ...
Python
nomic_cornstack_python_v1
import urllib.request comment Open http://placekitten.com/ for reading on line 4! set kittens = url open string http://placekitten.com/ set response = read kittens set body = response at slice 559 : 1000 : comment Add your 'print' statement here! print decode body string UTF-8
import urllib.request # Open http://placekitten.com/ for reading on line 4! kittens = urllib.request.urlopen('http://placekitten.com/') response = kittens.read() body = response[559:1000] # Add your 'print' statement here! print(body.decode('UTF-8'))
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np comment Column selection print string Column Selection set d = dict string one call Series list 1 2 3 index=list string a string b string c ; string two call Series list 1 2 3 4 index=list string a string b string c string d set df = call DataFrame d dtype=int64 set df = fill miss...
import pandas as pd import numpy as np # Column selection print("\n Column Selection") d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d,dtype=np.int64) df = df.fillna(0) #df = pd.DataFrame(df, dtype=np.int64) df['one'] = df[...
Python
zaydzuhri_stack_edu_python
if t > 0 begin print t end else if t < 0 begin set d = - t print d end
if t>0: print(t) elif t<0: d=-t print(d)
Python
zaydzuhri_stack_edu_python
comment -*- coding=utf-8 -*- comment author = "tungtt" import os from docx import Document from glob import glob from collections import defaultdict import os from io import open function check_duplicate_answer data begin set dup_ans = list for tuple i qa in enumerate data begin set ans = qa at 2 set ans_list = split ...
# -*- coding=utf-8 -*- # author = "tungtt" import os from docx import Document from glob import glob from collections import defaultdict import os from io import open def check_duplicate_answer(data): dup_ans = [] for i,qa in enumerate(data): ans = qa[2] ans_list = ans.split('\n') if ...
Python
zaydzuhri_stack_edu_python
function load path begin set texture = call glGenTextures 1 call glBindTexture GL_TEXTURE_2D texture comment Set the texture wrapping parameters call glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S GL_REPEAT call glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T GL_REPEAT comment Set texture filtering parameters call glT...
def load(path): texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering param...
Python
nomic_cornstack_python_v1
function test_retrieve_recipes self begin call sample_recipe name=string Avocado toast call sample_recipe name=string Baklava set res = get client RECIPES_URL set recipes = all set serializer = call RecipeSerializer recipes many=true assert equal status_code HTTP_200_OK assert equal length data 2 assert equal data data...
def test_retrieve_recipes(self): sample_recipe(name="Avocado toast") sample_recipe(name='Baklava') res = self.client.get(RECIPES_URL) recipes = Recipe.objects.all() serializer = RecipeSerializer(recipes, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) ...
Python
nomic_cornstack_python_v1
from Design_Patterns.Structural.Adapter.example1.emp_adapter import Emp_Adapter from Design_Patterns.Structural.Adapter.example1.client_existing_hr_system import Existing_HR_System class Client begin function __init__ self begin set emp_adapter_obj = call Emp_Adapter end function function demo self begin set existing_h...
from Design_Patterns.Structural.Adapter.example1.emp_adapter import Emp_Adapter from Design_Patterns.Structural.Adapter.example1.client_existing_hr_system import Existing_HR_System class Client: def __init__(self): self.emp_adapter_obj = Emp_Adapter() def demo(self): existing_hr_system_obj =...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Script for producing Figure 6. Plot a graph comparing the Pearson correlations to Visitor rates | Density of social media user-days. Code associated to following article: Henrikki Tenkanen, Enrico Di Minin, Vuokko Heikinheimo, Anna Hausmann, Marna Herbst, Liisa Kajala & Tuuli Toivon...
# -*- coding: utf-8 -*- """ Script for producing Figure 6. Plot a graph comparing the Pearson correlations to Visitor rates | Density of social media user-days. Code associated to following article: Henrikki Tenkanen, Enrico Di Minin, Vuokko Heikinheimo, Anna Hausmann, Marna Herbst, Liisa Kajala & Tuuli Toiv...
Python
zaydzuhri_stack_edu_python
class Solution begin function nthUglyNumber self n a b c begin function gcd a b begin if b == 0 begin return a end return call gcd b a % b end function function lcm a b begin return a * b // call gcd a b end function function count_ugly x begin comment count numbers from [0:x] divisble by a set sa = x // a comment coun...
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return a * b // gcd(a, b) def count_ugly(x): # count numbers from [0:x] div...
Python
zaydzuhri_stack_edu_python
function create cls **kwds begin set supply_mutable = call cast bool get kwds string supply_mutable false set transferable = call cast bool get kwds string transferable true set levy_mutable = call cast bool get kwds string levy_mutable false set divisibility = get kwds string divisibility 0 set duration = get kwds str...
def create(cls, **kwds): supply_mutable = typing.cast(bool, kwds.get('supply_mutable', False)) transferable = typing.cast(bool, kwds.get('transferable', True)) levy_mutable = typing.cast(bool, kwds.get('levy_mutable', False)) divisibility = kwds.get('divisibility', 0) duration = ...
Python
nomic_cornstack_python_v1
for i in range 1 11 begin if i % 3 == 0 begin continue end print string 5 * { i } = { 5 * i } end
for i in range(1, 11): if i % 3 == 0: continue print(f"5 * {i} = {5 * i}")
Python
jtatman_500k
import networkx as nx from tqdm import tqdm from via.util.util import get_networkx_graph function run_randomwalk g given_courses=list num_iters=1000 num_quarters=3 courses_per_quarter=3 course_pool_choices=20 begin string Runs random walk to simulate students taking courses. set course_ids = given_courses set course_i...
import networkx as nx from tqdm import tqdm from via.util.util import get_networkx_graph def run_randomwalk(g, given_courses=[], num_iters=1000, num_quarters=3, courses_per_quarter=3, course_pool_choices=20): """ Runs random walk to simulate students taking courses. """ course_ids =...
Python
zaydzuhri_stack_edu_python
function try_gpu begin try begin set ctx = call gpu set _ = zeros tuple 1 ctx=ctx end except any begin set ctx = cpu mx end return ctx end function
def try_gpu(): try: ctx = mx.gpu() _ = nd.zeros((1,), ctx=ctx) except: ctx = mx.cpu() return ctx
Python
nomic_cornstack_python_v1
comment label: sort difficulty: medium string 分析 我们首先对这些车辆按照它们的起始位置降序排序,并且用 (target - position) / speed 计算出每辆车在不受其余车的影响时, 行驶到终点需要的时间。对于相邻的两辆车 S 和 F,F 的起始位置大于 S,如果 S 行驶到终点需要的时间小于等于 F, 那么 S 一定会在终点前追上 F 并形成车队。这是因为在追上 F 之前,S 的行驶速度并不会减小,而 F 却有可能因为追上前面的车辆而速度减小, 因此 S 总能在终点前追上 F。 算法 将车辆按照起始位置降序排序后,我们顺序扫描这些车辆。如果相邻的两辆车,前者比后者行驶到终...
#label: sort difficulty: medium """ 分析 我们首先对这些车辆按照它们的起始位置降序排序,并且用 (target - position) / speed 计算出每辆车在不受其余车的影响时, 行驶到终点需要的时间。对于相邻的两辆车 S 和 F,F 的起始位置大于 S,如果 S 行驶到终点需要的时间小于等于 F, 那么 S 一定会在终点前追上 F 并形成车队。这是因为在追上 F 之前,S 的行驶速度并不会减小,而 F 却有可能因为追上前面的车辆而速度减小, 因此 S 总能在终点前追上 F。 算法 将车辆按照起始位置降序排序后,我们顺序扫描这些车辆。如果相邻的两辆车,前者比后者行驶到终点需要...
Python
zaydzuhri_stack_edu_python
function _carry_dep self dst src begin set src = call canonical_register src if src == call canonical_register string zero begin return end set dst = call canonical_register dst if dst == call canonical_register string zero begin return end set dep = call RelationBuilder comment If self._condition, cancel out the old v...
def _carry_dep(self, dst, src): src = canonical_register(src) if src == canonical_register("zero"): return dst = canonical_register(dst) if dst == canonical_register("zero"): return dep = RelationBuilder() # If self._condition, cancel out the o...
Python
nomic_cornstack_python_v1
function get_github_content repo path auth=none begin string Retrieve text files from a github repo set request = get requests format file_url repo=repo path=path auth=auth if not ok begin print string There is a problem with the request print format file_url repo=repo path=path print json request exit 1 end if not jso...
def get_github_content(repo,path,auth=None): """ Retrieve text files from a github repo """ request = requests.get(file_url.format(repo=repo, path=path), auth=auth) if not request.ok: print("There is a problem with the request") print(file_url.format(repo=repo, path=path)) print(request.json()) exit(1) if...
Python
jtatman_500k
while i * i <= 10 ^ 9 begin set eh = true set j = 2 while j * j <= i begin if i % j == 0 begin set eh = false break end set j = j + 1 end if eh begin append primos string i end set i = i + 1 end print string { join string , primos string }
while (i*i <= 10**9): eh = True j = 2 while (j*j <= i): if (i % j == 0): eh = False break j += 1 if (eh): primos.append(str(i)) i += 1 print('{',','.join(primos),'}')
Python
zaydzuhri_stack_edu_python
comment pragma: no cover function main begin comment Check if conda is available if not call is_conda_available begin set path = absolute path path directory name path argv at 0 comment print(path, len(sys.argv)) set msg = string # # Please activate the conda root enviroment properly before running the # `anaconda-navi...
def main(): # pragma: no cover # Check if conda is available if not is_conda_available(): path = os.path.abspath(os.path.dirname(sys.argv[0])) # print(path, len(sys.argv)) msg = '''# # Please activate the conda root enviroment properly before running the # `anaconda-navigator` command. ...
Python
nomic_cornstack_python_v1
function arc_lengths self begin set ds = norm points at slice : - 1 : - points at slice 1 : : axis=1 return r_ at tuple 0 cumulative sum np ds end function
def arc_lengths(self): ds = np.linalg.norm(self.points[:-1] - self.points[1:], axis=1) return np.r_[0, np.cumsum(ds)]
Python
nomic_cornstack_python_v1
from selenium import webdriver import logging , traceback from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By import ddt , unittest , time comment 初始化日志对象 call basicConfig level=DEBUG format=string %(asctime)s %(name)s %(levelname)s %(message)s datefmt=string %Y-%m-...
from selenium import webdriver import logging,traceback from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By import ddt,unittest,time #初始化日志对象 logging.basicConfig( level = logging.DEBUG, format = "%(asctime)s %(name)s %(levelname)s %(message)s", datefmt ...
Python
zaydzuhri_stack_edu_python
function infer metadata_location datapackage_location strict=false begin set path = call Path metadata_location set csv_files = list comprehension string name for file in sorted glob path string *.csv if strict begin set including_strict = list for file in csv_files begin set path = stem set strict_name = string datap...
def infer( metadata_location: str, datapackage_location: str, strict: bool = False ) -> None: path = pathlib.Path(metadata_location) csv_files = [str(file.name) for file in sorted(path.glob("*.csv"))] if strict: including_strict = [] for file in csv_files: path = pathlib.Path...
Python
nomic_cornstack_python_v1
function read_start_positions_from_list_of_bam self list_of_file_paths output_file=none begin if output_file is none begin set output_file = call mktemp dir=_tmp_dir prefix=string read_start_positions end assert is instance list_of_file_paths list assert is instance output_file str assert call validate_dir output_file ...
def read_start_positions_from_list_of_bam(self, list_of_file_paths, output_file=None): if output_file is None: output_file = tempfile.mktemp(dir=self._tmp_dir, prefix="read_start_positions") assert isinstance(list_of_file_paths, list) assert isinstance(output_file, str) assert self.validate_dir(output_file, ...
Python
nomic_cornstack_python_v1
function demo_two_map begin comment example using map set temps_c = list tuple string Berlin 29 tuple string Cairo 36 tuple string Buenos Aires 19 tuple string Los Angeles 26 tuple string Tokyo 27 tuple string New York 28 tuple string London 22 tuple string Beijing 32 comment lambda to return tuple with calculated deg....
def demo_two_map(): # example using map temps_c = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19), ("Los Angeles", 26), ("Tokyo", 27), ("New York", 28), ("London", 22), ("Beijing", 32)] # lambda to return tuple with calculated deg. F converted from deg. C c2f = lambda...
Python
nomic_cornstack_python_v1
function __init__ self duration=none name=none begin if is instance duration int begin set _duration = duration end else begin raise call PulseError string Pulse duration should be integer. end if name begin set _name = name end else begin set _name = string p%d % pulseIndex set pulseIndex = pulseIndex + 1 end end func...
def __init__(self, duration: int = None, name: str = None): if isinstance(duration, int): self._duration = duration else: raise PulseError('Pulse duration should be integer.') if name: self._name = name else: self._name = 'p%d' % Command.p...
Python
nomic_cornstack_python_v1
function _strings_to_list one_or_more_strings begin if is instance one_or_more_strings str begin return list one_or_more_strings end else begin return list one_or_more_strings end end function
def _strings_to_list(one_or_more_strings): if isinstance(one_or_more_strings, str): return [one_or_more_strings] else: return list(one_or_more_strings)
Python
nomic_cornstack_python_v1
function __init__ __self__ resource_name opts=none container_properties=none name=none parameters=none platform_capabilities=none propagate_tags=none retry_strategy=none tags=none timeout=none type=none __props__=none begin Ellipsis end function
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, container_properties: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str...
Python
nomic_cornstack_python_v1
import json import os import urllib2 from bs4 import BeautifulSoup function dump_data filename projects begin set fname = split filename string . at 0 + string _comments. + split filename string . at 1 end function
import json import os import urllib2 from bs4 import BeautifulSoup def dump_data(filename, projects): fname = filename.split(".")[0] + "_comments." + filename.split(".")[1]
Python
zaydzuhri_stack_edu_python
set list = list string abc 89892 12.123 string 12dfdfd 932 set tinylist = list 123 string runoob comment 输出完整列表 print list comment 输出列表第一个元素 print list at 0 comment 从第二个开始输出到第三个元素 print list at slice 1 : 3 : comment 输出从第三个元素开始的所有元素 print list at slice 2 : : comment 输出两次列表 print tinylist * 2 comment 连接列表 print list + t...
list = ['abc', 89892, 12.123, '12dfdfd', 932] tinylist = [123, 'runoob'] print(list) # 输出完整列表 print(list[0]) # 输出列表第一个元素 print(list[1:3]) # 从第二个开始输出到第三个元素 print(list[2:]) # 输出从第三个元素开始的所有元素 print(tinylist * 2) # 输出两次列表 print(list + tinylist) # 连接列表
Python
zaydzuhri_stack_edu_python
import re from functools import reduce from subprocess import Popen , PIPE class parser extends object begin function __init__ self view=none **kwargs begin comment OVS port command set ovsname = string br-int set ovscmd = list string sudo string ovs-ofctl string dump-ports-desc append ovscmd ovsname comment Neutron po...
import re from functools import reduce from subprocess import Popen, PIPE class parser(object): def __init__(self, view=None, **kwargs): # OVS port command self.ovsname = "br-int" self.ovscmd = ["sudo", "ovs-ofctl", "dump-ports-desc"] self.ovscmd.append(self.ovsname) # Neut...
Python
zaydzuhri_stack_edu_python
comment -*- coding: iso-8859-1 -*- import time import math import random import os comment if Python Version 3.x try begin from tkinter import * from tkinter import messagebox from tkinter import filedialog set py_version = 3 end comment If Python Version 2.7 except any begin from Tkinter import * import tkMessageBox i...
# -*- coding: iso-8859-1 -*- import time import math import random import os try: ##if Python Version 3.x from tkinter import * from tkinter import messagebox from tkinter import filedialog py_version = 3 except: ##If Python Version 2.7 from Tkinter import * import tkMessageBox ...
Python
zaydzuhri_stack_edu_python
function test_user_model self begin set u = call User email=string test@test.com username=string testuser password=string HASHED_PASSWORD add session u commit session comment User should have no messages & no followers assert equal length messages 0 assert equal length followers 0 end function
def test_user_model(self): u = User( email="test@test.com", username="testuser", password="HASHED_PASSWORD" ) db.session.add(u) db.session.commit() # User should have no messages & no followers self.assertEqual(len(u.messages), 0) ...
Python
nomic_cornstack_python_v1
import math import sys set __author__ = string Gabriel Fishman string Cash Register: See: https://www.codeeval.com/open_challenges/54/ The goal of this challenge is to design a cash register program. You will be given two float numbers. The first is the purchase price (PP) of the item. The second is the cash (CH) given...
import math import sys __author__ = 'Gabriel Fishman' """ Cash Register: See: https://www.codeeval.com/open_challenges/54/ The goal of this challenge is to design a cash register program. You will be given two float numbers. The first is the purchase price (PP) of the item. The second is the cash (CH) given by the ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint string This is the code for all plots and simulations using during the class about linear systems in 2D call use string default comment To improve quality figure dpi=600 comment GENERAL CODE ###################################### func...
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint """ This is the code for all plots and simulations using during the class about linear systems in 2D """ plt.style.use('default') plt.figure(dpi=600) # To improve quality ########################### GENERAL CODE ######...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 from selenium import webdriver import unittest from page.loginpage import LoginPage , login_url class TestLogin extends TestCase begin function setUp self begin set driver = call Firefox set logindriver = call LoginPage driver get driver login_url end function function test_login self begin comment...
# coding:utf-8 from selenium import webdriver import unittest from page.loginpage import LoginPage,login_url class TestLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.logindriver = LoginPage(self.driver) self.driver.get(login_url) def test_login(self)...
Python
zaydzuhri_stack_edu_python
function write mdi_model file_path collapse_frame encoding=string binary begin set mds_model = call convert mdi_model collapse_frame if encoding == string binary begin write mds_model file_path end else if encoding == string xml begin comment TODO pass end else if encoding == string json begin comment TODO pass end els...
def write(mdi_model, file_path, collapse_frame, encoding="binary"): mds_model = mds_mdi_m.MDIToModel.convert(mdi_model, collapse_frame) if encoding == "binary": mds_model.write(file_path) elif encoding == "xml": pass # TODO elif encoding == "json": pass # TODO e...
Python
nomic_cornstack_python_v1
function validate_cluster_node_counts cluster_config begin set num_nodes = integer call get_min_node_count set on_demand_nodes = integer call get_asxys_node_count + integer call get_axuser_on_demand_count set max_nodes = integer call get_max_node_count assert max_nodes >= num_nodes >= integer call get_asxys_node_count ...
def validate_cluster_node_counts(cluster_config): num_nodes = int(cluster_config.get_min_node_count()) on_demand_nodes = int(cluster_config.get_asxys_node_count()) + int(cluster_config.get_axuser_on_demand_count()) max_nodes = int(cluster_config.get_max_node_count()) assert max_nodes >= num_nodes >= in...
Python
nomic_cornstack_python_v1
function remote_get name src begin raise call NotImplementedError string derived class should overload me end function
def remote_get(name, src): raise NotImplementedError('derived class should overload me')
Python
nomic_cornstack_python_v1
function isAssignment self begin return call Rule_isAssignment self end function
def isAssignment(self): return _libsbml.Rule_isAssignment(self)
Python
nomic_cornstack_python_v1
comment !/usr/bin/pyhton3 comment Filename: package_mix.py function package_mix *positions **keywords begin print positions print keywords end function call package_mix 1 2 3 a=7 b=8 c=9
#!/usr/bin/pyhton3 # Filename: package_mix.py def package_mix(*positions, **keywords): print(positions) print(keywords) package_mix(1, 2, 3, a = 7, b = 8, c = 9)
Python
zaydzuhri_stack_edu_python
function api_relation self begin set data = data or get form string data or string if not call get attribute self string check_%s % lower method begin return call response_forbidden end set data = call data_precheck data RelationForm try begin set obj = get where student_id == data at string student_id end except Does...
def api_relation(self): data = request.data or request.form.get('data') or '' if not getattr(self, 'check_%s' % request.method.lower())(): return self.response_forbidden() data = self.data_precheck(data, RelationForm) try: obj = User.select().where(User.student_...
Python
nomic_cornstack_python_v1
function main begin try begin call connect end except OperationalError begin pass end try begin call create_tables list Log Project true end except OperationalError begin pass end try else begin if length argv > 1 begin call cli end else begin set _ = call get_projects display=true end end finally begin close db end en...
def main(): try: db.connect() except OperationalError: pass try: db.create_tables([Log, Project], True) except OperationalError: pass else: if len(argv) > 1: cli() else: _ = get_projects(display=True) finally: db.cl...
Python
nomic_cornstack_python_v1
function update_interface to_do free_robots notifications begin for x in range 30 begin print string end print call print_tasks to_do print call print_robots free_robots print call print_notifications notifications end function
def update_interface(to_do, free_robots, notifications): for x in range(30): print("\n") print(print_tasks(to_do)) print(print_robots(free_robots)) print(print_notifications(notifications))
Python
nomic_cornstack_python_v1
function get_provider provider begin if provider in PROVIDERS_MAP begin return PROVIDERS_MAP at provider end raise call NotImplementedError string Provider %s not implemented % provider end function
def get_provider(provider): if provider in PROVIDERS_MAP: return PROVIDERS_MAP[provider] raise NotImplementedError("Provider %s not implemented" % provider)
Python
nomic_cornstack_python_v1
function map_inputs building_name inputs mapping begin set input_tags = mapping at building_name at string Inputs set ret = list for tag in input_tags begin set matching_input = list comprehension t for t in inputs if t at 0 == tag append ret matching_input at 0 at 1 end return ret end function
def map_inputs(building_name, inputs, mapping): input_tags = mapping[building_name]["Inputs"] ret = [] for tag in input_tags: matching_input = [t for t in inputs if t[0] == tag] ret.append(matching_input[0][1]) return ret
Python
nomic_cornstack_python_v1