code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import xml.etree.cElementTree as ET import pprint import re string Your task is to explore the data a bit more. Before you process the data and add it into your database, you should check the "k" value for each "<tag>" and see if there are any potential problem...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET import pprint import re """ Your task is to explore the data a bit more. Before you process the data and add it into your database, you should check the "k" value for each "<tag>" and see if there are any potential problems. We...
Python
zaydzuhri_stack_edu_python
comment connect to the data base import psycopg2 set conn = call connect string your dsn comment create cursor object set cur = call cursor execute cur SELECT tuple vaule1 vaule2 comment use fetch many method to get all data from data base comment extracts data from multible tables function getdata cursor size=10 begin...
# connect to the data base import psycopg2 conn = psycopg2.connect("your dsn") # create cursor object cur = conn.cursor() cur.execute(SELECT, (vaule1,vaule2)) # use fetch many method to get all data from data base def getdata (cursor, size=10): #extracts data from multible tables while True: ...
Python
zaydzuhri_stack_edu_python
function encrypt_file plain_fn crypt_fn recipients begin comment raise error if file doesn't exist if not exists path plain_fn begin raise call FileNotFoundError string Cleartext file '%s' not found. % plain_fn end with open plain_fn string rb as inf begin with open crypt_fn string wb as outf begin set keys = list comp...
def encrypt_file(plain_fn, crypt_fn, recipients): # raise error if file doesn't exist if not os.path.exists(plain_fn): raise FileNotFoundError("Cleartext file '%s' not found." % plain_fn) with open(plain_fn, "rb") as inf: with open(crypt_fn, "wb") as outf: keys = [r.key for r i...
Python
nomic_cornstack_python_v1
function print_flags begin for tuple key value in items variables FLAGS begin print key + string : + string value end end function
def print_flags(): for key, value in vars(FLAGS).items(): print(key + ' : ' + str(value))
Python
nomic_cornstack_python_v1
function _fromfile self fh begin seek fh 0 set data = read fh 4096 if length data < 7 or not b'0' < data at slice 1 : 2 : < b'8' begin raise call ValueError string Not a Netpbm file: %s % data at slice : 32 : end try begin call _read_pam_header data end except Exception begin try begin call _read_pnm_header data end ...
def _fromfile(self, fh): fh.seek(0) data = fh.read(4096) if (len(data) < 7) or not (b'0' < data[1:2] < b'8'): raise ValueError("Not a Netpbm file:\n%s" % data[:32]) try: self._read_pam_header(data) except Exception: try: ...
Python
nomic_cornstack_python_v1
comment Filename: randomFruit2.py comment Author: Mark Parry comment Created: 06/02/2021 comment Purpose: Prints out a random fruit using a different method random.choice comment Research: askpython website comment Generate Random Integers comment The random module provides some special methods for generating random in...
#Filename: randomFruit2.py #Author: Mark Parry #Created: 06/02/2021 #Purpose: Prints out a random fruit using a different method random.choice #Research: askpython website # Generate Random Integers # The random module provides some special methods for generating random integers. # ...
Python
zaydzuhri_stack_edu_python
function to_list begin decorator sinks function _dagpype_internal_fn_act target begin set l = list try begin while true begin append l yield end end except GeneratorExit begin call send l close target end end function return _dagpype_internal_fn_act end function
def to_list(): @sinks def _dagpype_internal_fn_act(target): l = [] try: while True: l.append((yield)) except GeneratorExit: target.send(l) target.close() return _dagpype_internal_fn_act
Python
nomic_cornstack_python_v1
comment calculando os scores de cada url/notícia for tuple idUrl idPalavraUrl in urlPalavras begin if idAnterior != idUrl begin set tuplaSomadora = list 0 0 0 0 0 end for tuple idPalavraPlvr polLIWC polOpLex polReliLex polSenti polWordNet in palavrasPolaridade begin if idPalavraPlvr == idPalavraUrl begin print tuplaSom...
#calculando os scores de cada url/notícia for idUrl, idPalavraUrl in urlPalavras: if idAnterior != idUrl: tuplaSomadora = [0, 0, 0, 0, 0] for idPalavraPlvr, polLIWC, polOpLex, polReliLex, polSenti, polWordNet in palavrasPolaridade: if idPalavraPlvr == idPalavraUrl: print(tupl...
Python
zaydzuhri_stack_edu_python
function send_delta_counter self name value source tags timestamp=none begin if not starts with name DELTA_PREFIX or starts with name DELTA_PREFIX_2 begin set name = DELTA_PREFIX + name end if value > 0 begin call send_metric name value timestamp source tags end end function
def send_delta_counter(self, name, value, source, tags, timestamp=None): if not (name.startswith(self.DELTA_PREFIX) or name.startswith(self.DELTA_PREFIX_2)): name = self.DELTA_PREFIX + name if value > 0: self.send_metric(name, value, timestamp, source, tags)
Python
nomic_cornstack_python_v1
function terminal_guardian self begin set terminal_devices = list all for td in terminal_devices begin try begin comment get all register set sn = sn set terminals = all set dev_state = call keep_alive sn timeout=TERMINAL_TIMEOUT if is_active != call get_curr_state begin set is_active = call get_curr_state save end set...
def terminal_guardian(self): terminal_devices = list(TerminalDevice.objects.all()) for td in terminal_devices: try: # get all register sn = td.sn terminals = td.terminal_set.all() dev_state = keep_alive.AliveStateAPI.keep_alive(sn, timeout=TERMINAL_TIMEO...
Python
nomic_cornstack_python_v1
function _numeric_files_in_dir self path begin return generator expression x for x in call _files_in_dir path if is digit x end function
def _numeric_files_in_dir(self, path): return (x for x in self._files_in_dir(path) if x.isdigit())
Python
nomic_cornstack_python_v1
function init self begin with call as_default begin set init_op = call global_variables_initializer run init_op end end function
def init(self): with self._sess.graph.as_default(): init_op = tf.global_variables_initializer() self._sess.run(init_op)
Python
nomic_cornstack_python_v1
import cv2 as cv import dlib as dl import face_recognition import os import pickle from keras.models import load_model from keras.preprocessing.image import img_to_array import numpy as np set face_detector_model = call get_frontal_face_detector set classifier = call load_model string Emotion_Detection.h5 set class_lab...
import cv2 as cv import dlib as dl import face_recognition import os import pickle from keras.models import load_model from keras.preprocessing.image import img_to_array import numpy as np face_detector_model = dl.get_frontal_face_detector() classifier = load_model("Emotion_Detection.h5") class_labels = ['Angry', 'Ha...
Python
zaydzuhri_stack_edu_python
function _get_oppo_names env begin set n_players = length spaces assert n_players > 1 msg string only one agent, no opponent at all! set names = list string oppo if n_players > 2 begin set names = names + list comprehension format string oppo{} i + 1 for i in range n_players - 2 end return names end function
def _get_oppo_names(env): n_players = len(env.action_space.spaces) assert n_players > 1, "only one agent, no opponent at all!" names = ['oppo'] if n_players > 2: names += ['oppo{}'.format(i + 1) for i in range(n_players - 2)] return names
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Nov 21 07:36:53 2017 @author: Dharmang from sklearn.model_selection import StratifiedKFold from sklearn.svm import LinearSVC import sklearn import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm from sklearn.model_selection impo...
# -*- coding: utf-8 -*- """ Created on Fri Nov 21 07:36:53 2017 @author: Dharmang """ from sklearn.model_selection import StratifiedKFold from sklearn.svm import LinearSVC import sklearn import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm from sklearn.model_selection impor...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAH...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAP...
Python
zaydzuhri_stack_edu_python
comment Python program to read JSON file import json comment Opening JSON File set f = open string employee_data.json comment Return JSON as a dictionary set data = load json f comment Iterating through the json list and print value for "emp_name" for i in data at string emp_details begin print i at string emp_name end...
# Python program to read JSON file import json # Opening JSON File f = open('employee_data.json',) # Return JSON as a dictionary data = json.load(f) # Iterating through the json list and print value for "emp_name" for i in data['emp_details']: print(i["emp_name"]) # Closing file f.close()
Python
zaydzuhri_stack_edu_python
function dgTimerOff self begin pass end function
def dgTimerOff(self): pass
Python
nomic_cornstack_python_v1
comment codin:utf-8 string 剑指 Offer 26. 树的子结构 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A: 3 / 4 5 / 1 2 给定的树 B: 4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 comment Definition fo...
# codin:utf-8 ''' 剑指 Offer 26. 树的子结构 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 例如: 给定的树 A:      3     / \    4   5   / \  1   2 给定的树 B:    4    /  1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= ...
Python
zaydzuhri_stack_edu_python
function url self begin return _url end function
def url(self): return self._url
Python
nomic_cornstack_python_v1
function __init__ self ioloop client begin set ioloop = ioloop set client = client end function
def __init__(self, ioloop, client): self.ioloop = ioloop self.client = client
Python
nomic_cornstack_python_v1
function inputs_of self i begin set links = _graph at i at 3 set weights = _graph at i at 4 return zip links weights end function
def inputs_of(self, i): links = self._graph[i][3] weights = self._graph[i][4] return zip(links, weights)
Python
nomic_cornstack_python_v1
import random import string set word_list = list string dog string candy string edison string smart string dumb string white string black string tigers string field string person set the_word = random choice word_list set word = list the_word print the_word set guesses = 8 set letter_guessed = list set win = false set...
import random import string word_list = ["dog", "candy", "edison", "smart", "dumb", "white", "black", "tigers", "field", "person"] the_word = random.choice(word_list) word = list(the_word) print(the_word) guesses = 8 letter_guessed = [] win = False alphabet = list(string.ascii_letters) print(list(string.ascii_letters)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Short summary here. Longer docstring summary goes here. comment import built-in modules below import pickle from tqdm import tqdm comment import own modules below import Kaprekar as K set TIKZFILE = string Attempt01.tex function write_preamble begin set preamble = join string list s...
#!/usr/bin/env python '''Short summary here. Longer docstring summary goes here. ''' # import built-in modules below import pickle from tqdm import tqdm # import own modules below import Kaprekar as K TIKZFILE = 'Attempt01.tex' def write_preamble(): preamble = '\n'.join([r'\documentclass[border=5mm]{standalone...
Python
zaydzuhri_stack_edu_python
string 使用者輸入兩個數num1 and num2, 並使用function def 求最小公倍數 value = lcm(num1, num2) function lcm x y begin if x > y begin set largest = x end else begin set largest = y end while true begin if largest % x == 0 and largest % y == 0 begin set lcm = largest break end set largest = largest + 1 end return lcm end function set num1...
''' 使用者輸入兩個數num1 and num2, 並使用function def 求最小公倍數 value = lcm(num1, num2) ''' def lcm(x, y): if x > y: largest = x else: largest = y while(True): if((largest % x == 0) and (largest % y == 0)): lcm = largest break largest += 1 return lcm num1 = int(input("輸入...
Python
zaydzuhri_stack_edu_python
function cli_cosmosdb_update client resource_group_name account_name locations=none tags=none default_consistency_level=none max_staleness_prefix=none max_interval=none ip_range_filter=none enable_automatic_failover=none capabilities=none enable_virtual_network=none virtual_network_rules=none enable_multiple_write_loca...
def cli_cosmosdb_update(client, resource_group_name, account_name, locations=None, tags=None, default_consistency_level=None, max_staleness_prefix=None, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment from random import random from numpy.random import random , normal from numpy import array , exp , savetxt from pylab import plot , show function polyPlusGauss point begin set a = 1.0 set b = - 0.5 set c = - 0.3 set d = - 0.2 set A = 1.0 set B = 0.5 set C = 10.0 set point2 = point * poi...
#!/usr/bin/python #from random import random from numpy.random import random, normal from numpy import array, exp, savetxt from pylab import plot, show def polyPlusGauss( point ): a = 1.0 b = -0.5 c = -0.3 d = -0.2 A = 1.0 B = 0.5 C = 10.0 point2=point*point point3=point2*point...
Python
zaydzuhri_stack_edu_python
import numpy as np from constants import RHO_WATER , MAX_ELEMENT_COLUMNS comment pylint: disable=unused-argument function odefun_tree t y model begin string Calculates the right hand side of the model ODEs related to tree and model classes. The modelled systen and the ODEs are described in the [modelled system](modelle...
import numpy as np from .constants import RHO_WATER, MAX_ELEMENT_COLUMNS def odefun_tree(t: float, y: np.ndarray, model) -> np.ndarray: # pylint: disable=unused-argument """ Calculates the right hand side of the model ODEs related to tree and model classes. The modelled systen and the ODEs are described in ...
Python
zaydzuhri_stack_edu_python
function enrich_pubmed_citations manager graph group_size=none sleep_time=none begin string Overwrite all PubMed citations with values from NCBI's eUtils lookup service. Sets authors as list, so probably a good idea to run :func:`pybel_tools.mutation.serialize_authors` before exporting. :type manager: pybel.manager.Man...
def enrich_pubmed_citations(manager, graph, group_size: Optional[int] = None, sleep_time: Optional[int] = None, ) -> Set[str]: """Overwrite all PubMed citations with values from NCBI's eUtils lookup servi...
Python
jtatman_500k
import sys set stdin = open string input.txt string r from pprint import pprint set TC = integer input for test_case in range 1 TC + 1 begin set tuple N M K = map int split input set info = list set data = list comprehension list 0 * M for i in range N set max_count = 0 for _ in range K begin set row = list map int sp...
import sys sys.stdin = open('input.txt', 'r') from pprint import pprint TC =int(input()) for test_case in range(1, TC+1): N, M, K = map(int, input().split()) info = [] data = [[0]*M for i in range(N)] # max_count = 0 for _ in range(K): row = list(map(int, input().split())) info....
Python
zaydzuhri_stack_edu_python
function transaction context event begin info string START comment Lock "DOOR KEY(23) "GPIO.output HIGH" lock comment "Green Light" and "Red Light" will be deactivated call deactivate list GREEN_LIGHT RED_LIGHT comment Debugging App. This topic does not contain debug. However, this is used for debug application set pay...
def transaction(context, event): logger.info("START") # Lock "DOOR KEY(23) "GPIO.output HIGH" SolenoidLock.lock() # "Green Light" and "Red Light" will be deactivated LightControl.deactivate([LightControl.GREEN_LIGHT, LightControl.RED_LIGHT]) # Debugging App. This topic does not contain debug. ...
Python
nomic_cornstack_python_v1
comment Serial port for syringe pump communication import time import serial import struct class SyringePumper begin set debug = true set INFUSE = 1 set WITHDRAW = 2 function __init__ self start_t syringe_size prate begin set start_t = start_t set syringe_size = syringe_size set direction = INFUSE comment Connect to se...
# Serial port for syringe pump communication import time import serial import struct class SyringePumper: debug = True INFUSE = 1 WITHDRAW = 2 def __init__(self, start_t, syringe_size, prate): self.start_t = start_t self.syringe_size = syringe_size self.direction = se...
Python
zaydzuhri_stack_edu_python
comment Dustin Davis comment AST 381 Computational Astrophysics comment Homework #2 comment Februrary 26, 2019 set __author__ = string Dustin Davis string Interesting observations: 1) selecting dt s|t the |Xi| is exactly 1, Lax-Wendroff reduces to Lax. In all other cases (< 1) Lax-Wendroff is superior 2) With exception...
#Dustin Davis #AST 381 Computational Astrophysics #Homework #2 #Februrary 26, 2019 __author__ = "Dustin Davis" """ Interesting observations: 1) selecting dt s|t the |Xi| is exactly 1, Lax-Wendroff reduces to Lax. In all other cases (< 1) Lax-Wendroff is superior 2) With exception of Lax-Wendroff at high resolution,...
Python
zaydzuhri_stack_edu_python
comment it saves the address of data stored and where to save the data produced by algorithms from conf import * import time comment regular expression library import re comment for random strategy from random import random , choice from operator import itemgetter import datetime import numpy as np from scipy.sparse im...
from conf import * # it saves the address of data stored and where to save the data produced by algorithms import time import re # regular expression library from random import random, choice # for random strategy from operator import itemgetter import datetime import numpy as np from scipy.sparse import csgraph...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self begin set items = list end function function push self item begin append items item end function function pop self begin if not call is_empty begin return pop items end end function function peek self begin if not call is_empty begin return items at - 1 end end function functio...
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() def peek(self): if not self.is_empty(): return self.items[-1] def ...
Python
jtatman_500k
from typing import List class Materia begin comment constructor function __init__ self nombre creditos begin set nombre = nombre set creditos = creditos set calificacion = string end function end class class Estudiante begin function __init__ self nombre id carrera materias indice_acu puntos_acumu creditos_acu credito...
from typing import List class Materia: def __init__(self, nombre:str, creditos:str): # constructor self.nombre = nombre self.creditos = creditos self.calificacion = "" class Estudiante: def __init__(self, nombre: str, id: str, carrera: str,materias: List[Materia], indice_acu:...
Python
zaydzuhri_stack_edu_python
import random import collections , numpy set alphabet = sorted list set list lower string АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя + list string function get_code begin set perm = call permutation range length alphabet comment perm = list(range(len(alphabet))) print perm set code = dictionary...
import random import collections, numpy alphabet = sorted(list(set(list('АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя'.lower()))))+[' '] def get_code(): perm = numpy.random.permutation(range(len(alphabet))) #perm = list(range(len(alphabet))) print(perm) code = dict() for i in...
Python
zaydzuhri_stack_edu_python
from random import choice , uniform from sys import stdout , stderr from time import sleep , time from datetime import datetime from numpy import array from tkinter import Tk set DEBUG = true set SLEEP_TIME = 3 set MIN_KHT = 0.1 set MAX_KHT = 1.0 set MIN_KIT = 0.1 set MAX_KIT = 1.0 comment TEXTS = [ "My password is inc...
from random import choice, uniform from sys import stdout, stderr from time import sleep, time from datetime import datetime from numpy import array from tkinter import Tk DEBUG = True SLEEP_TIME = 3 MIN_KHT = 0.1 MAX_KHT = 1.0 MIN_KIT = 0.1 MAX_KIT = 1.0 # TEXTS = [ "My password is incorrect.", "Are you frustrated o...
Python
zaydzuhri_stack_edu_python
set mesto = input string Unesite mesto u kojem zivite: set prvo_slovo = mesto at 0 set poslednje_slovo = mesto at length mesto - 1 print prvo_slovo print poslednje_slovo print mesto at slice 1 : 3 : print is upper prvo_slovo
mesto=input("Unesite mesto u kojem zivite:") prvo_slovo=mesto[0] poslednje_slovo=mesto[len(mesto)-1] print(prvo_slovo) print(poslednje_slovo) print(mesto[1:3]) print(prvo_slovo.isupper())
Python
zaydzuhri_stack_edu_python
comment 导入selenium from selenium import webdriver import time comment 函数:写日志 function WriteLog logPath logContent begin string 写日志 :return: comment 获取当天日期 set currentData = string format time time string %Y-%m-%d call localtime comment print(currentData) comment 日志名称 set logtitle = string Log_ + currentData + string .t...
# 导入selenium from selenium import webdriver import time # 函数:写日志 def WriteLog(logPath,logContent): ''' 写日志 :return: ''' # 获取当天日期 currentData = time.strftime('%Y-%m-%d',time.localtime()) # print(currentData) # 日志名称 logtitle = 'Log_' + currentData + '.txt' # print(logtitle) # ...
Python
zaydzuhri_stack_edu_python
function web_vtt_settings self web_vtt_settings begin comment type: (ConvertSccCaptionWebVttSettings) -> None if web_vtt_settings is not none begin if not is instance web_vtt_settings ConvertSccCaptionWebVttSettings begin raise call TypeError string Invalid type for `web_vtt_settings`, type has to be `ConvertSccCaption...
def web_vtt_settings(self, web_vtt_settings): # type: (ConvertSccCaptionWebVttSettings) -> None if web_vtt_settings is not None: if not isinstance(web_vtt_settings, ConvertSccCaptionWebVttSettings): raise TypeError("Invalid type for `web_vtt_settings`, type has to be `Conver...
Python
nomic_cornstack_python_v1
function conditions self begin return get pulumi self string conditions end function
def conditions(self) -> Sequence['outputs.GoogleCloudRunV2ConditionResponse']: return pulumi.get(self, "conditions")
Python
nomic_cornstack_python_v1
function create server_ begin string Create a single BareMetal server from a data dict. try begin comment Check for required profile parameters before sending any API calls. if server_ at string profile and call is_profile_configured __opts__ __active_provider_name__ or string scaleway server_ at string profile vm_=ser...
def create(server_): ''' Create a single BareMetal server from a data dict. ''' try: # Check for required profile parameters before sending any API calls. if server_['profile'] and config.is_profile_configured(__opts__, __act...
Python
jtatman_500k
function SetAlpha self arg0 begin return call itkLevelSetMotionRegistrationFilterISS3ISS3IVF23_SetAlpha self arg0 end function
def SetAlpha(self, arg0: 'double') -> "void": return _itkLevelSetMotionRegistrationFilterPython.itkLevelSetMotionRegistrationFilterISS3ISS3IVF23_SetAlpha(self, arg0)
Python
nomic_cornstack_python_v1
comment !/usr/local/bin/python3 import os import json import tarfile import glob set cwd = get current directory print cwd set fname2 = string comment Deleting existing files for fname2 in list directory cwd begin if starts with fname2 string sample begin remove os join path cwd fname2 end end with open string test.tx...
# !/usr/local/bin/python3 import os import json import tarfile import glob cwd = os.getcwd() print (cwd) fname2 = "" # Deleting existing files for fname2 in os.listdir(cwd): if fname2.startswith("sample"): os.remove(os.path.join(cwd, fname2)) with open("test.txt") as f: content = f.readlines() cont...
Python
zaydzuhri_stack_edu_python
function set_npix_x self npix_x begin comment type: int comment type: (...) -> None set metadata_dict at string npix_x = npix_x end function
def set_npix_x(self, npix_x # type: int ): # type: (...) -> None self.metadata_dict['npix_x'] = npix_x
Python
nomic_cornstack_python_v1
import math set m = square root 5 + 1 / 2 set n = integer call raw_input for i in call xrange n begin set tuple a b = map int split call raw_input set tuple a b = tuple min a b max a b set delta = b - a end
import math m = (math.sqrt(5) + 1) / 2 n = int(raw_input()) for i in xrange(n): (a, b) = map(int, raw_input().split()) (a, b) = min(a, b), max(a, b) delta = b - a
Python
zaydzuhri_stack_edu_python
function __enter__ self begin lock return self end function
def __enter__(self): self.lock() return self
Python
nomic_cornstack_python_v1
function _format_envvars ctx begin string Format all envvars for a `click.Command`. set params = list comprehension x for x in params if get attribute x string envvar for param in params begin yield format string .. _{command_name}-{param_name}-{envvar}: command_name=replace command_path string string - param_name=nam...
def _format_envvars(ctx): """Format all envvars for a `click.Command`.""" params = [x for x in ctx.command.params if getattr(x, 'envvar')] for param in params: yield '.. _{command_name}-{param_name}-{envvar}:'.format( command_name=ctx.command_path.replace(' ', '-'), param_na...
Python
jtatman_500k
comment It's like an assert, but softer function exit_if condition message begin if condition begin print message exit end end function function quad_equation a b c begin function common_root x begin return - b + x / 2 * a end function set d = b ^ 2 - 4 * a * c if d > 0 begin set sqrt = b ^ 2 - 4 * a * c ^ 0.5 return t...
# It's like an assert, but softer def exit_if(condition, message): if condition: print(message) exit() def quad_equation(a, b, c): def common_root(x): return (-b + x) / (2 * a) d = b ** 2 - 4 * a * c if d > 0: sqrt = (b ** 2 - 4 * a * c) ** 0.5 return common_roo...
Python
zaydzuhri_stack_edu_python
function _get_permission self obj_type path username begin if obj_type == Collection begin comment XXX - in iRODS < 4.2, CollectionUser.name isn't supported. comment query = self.session.query(Collection, CollectionAccess).filter( comment CollectionUser.name == username, Collection.name == path) comment result = [self....
def _get_permission(self, obj_type, path, username): if obj_type == Collection: # XXX - in iRODS < 4.2, CollectionUser.name isn't supported. # query = self.session.query(Collection, CollectionAccess).filter( # CollectionUser.name == username, Collection.name == path) # resul...
Python
nomic_cornstack_python_v1
function ex_stop_node self node begin set result = object return get result string response in VALID_RESPONSE_CODES end function
def ex_stop_node(self, node): result = self.connection.request('/server/cloud/%s/initiator/stop/' % node.id, method='POST').object return result.get('response') in VALID_RESPONSE_CODES
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import os , shutil , pg , re from db_functions import * comment Config variables set dir = string chordpro_files function createHymnFile hnum data begin string Create or replace the file for this hymn, using the specified data for content, and the hnum for the filename. set fileName = dir +...
#!/usr/bin/env python import os, shutil, pg, re from db_functions import * #Config variables dir = "chordpro_files" def createHymnFile(hnum, data): "Create or replace the file for this hymn, using the specified data for content, and the hnum for the filename." fileName = dir+"/"+hnum+".cho" file = open(fileName...
Python
zaydzuhri_stack_edu_python
import other comment Dataset.generate_anchor for calculate crossover point between comment gt box and a x-axis function cal_y_crossover_pt box x begin set result = dict string y list ; string edge list set pt1 = list box at 0 box at 1 set pt2 = list box at 2 box at 3 set pt3 = list box at 4 box at 5 set pt4 = list bo...
import other # Dataset.generate_anchor for calculate crossover point between # gt box and a x-axis def cal_y_crossover_pt(box, x): result = {'y': [], 'edge': []} pt1 = [box[0], box[1]] pt2 = [box[2], box[3]] pt3 = [box[4], box[5]] pt4 = [box[6], box[7]] y1 = other.cal_line_y(pt1, pt2, x, int) ...
Python
zaydzuhri_stack_edu_python
class Sensor begin function __init__ self interface begin set _interface = interface call _init end function function read self begin return call _read end function function set_unit self unit begin set _unit = unit end function end class
class Sensor: def __init__(self, interface): self._interface = interface self._init() def read(self): return self._read() def set_unit(self, unit): self._unit = unit
Python
zaydzuhri_stack_edu_python
function pr_A_given_f self f1 f2 theta begin raise exception string pr_A_given_f is not implemented! end function
def pr_A_given_f(self,f1,f2,theta): raise Exception("pr_A_given_f is not implemented!")
Python
nomic_cornstack_python_v1
function test_sitedata_local rf begin set site_ch = call SiteData label=string catalysthunter set site_nmb = call SiteData label=string nextminingboom set request = get rf string / HTTP_HOST=hostname call process_request request from sitedata import LOCAL assert label == label set request = get rf string / HTTP_HOST=ho...
def test_sitedata_local(rf): site_ch = SiteData(label='catalysthunter') site_nmb = SiteData(label='nextminingboom') request = rf.get('/', HTTP_HOST=site_ch.hostname) SiteDataMiddleware().process_request(request) from sitedata import LOCAL assert LOCAL.sitedata.label == site_ch.label reques...
Python
nomic_cornstack_python_v1
string *Snakess* ! Game Made By Dhruv Lohar. ! Copyright will be claimed if done. ! Do not delete or modify any content or code. ! Do not delete files under static_media folder. ! Keep calm and enjoy the snakess. ! Completed at 28 April, 2020. ! Check out more projects at https://github.com/DhruvLohar import pygame fro...
""" *Snakess* ! Game Made By Dhruv Lohar. ! Copyright will be claimed if done. ! Do not delete or modify any content or code. ! Do not delete files under static_media folder. ! Keep calm and enjoy the snakess. ! Completed at 28 April, 2020. ! Check out more projects at https://github.com/DhruvLohar """ impo...
Python
zaydzuhri_stack_edu_python
function _is_loaded self begin return if expression patch_index is none then false else true end function
def _is_loaded(self): return False if self.patch_index is None else True
Python
nomic_cornstack_python_v1
import subprocess import os import re import tokenize function main begin while true begin set cmnd = input string >>> comment cmnd1 = list(cmnd) comment cmnd2 = tokenize.tokenize(cmnd1) comment print("command is", cmnd2) if cmnd == string exit begin break end else if cmnd == string cd begin set newpath = input string ...
import subprocess import os import re import tokenize def main(): while True: cmnd = input(">>> ") #cmnd1 = list(cmnd) #cmnd2 = tokenize.tokenize(cmnd1) #print("command is", cmnd2) if cmnd == "exit": break elif cmnd == "cd": newpath = input("What path?") new_cd(newpath) elif cmnd == "help": ...
Python
zaydzuhri_stack_edu_python
class Translit begin comment Преобразование слова с русский букв, на английские, потому что не нашел set symbols = dict string й string i ; string ц string tc ; string у string u ; string к string k ; string е string e ; string н string n ; string г string g ; string ш string sh ; string щ string shch ; string з string...
class Translit(): # Преобразование слова с русский букв, на английские, потому что не нашел symbols = {'й':'i','ц':'tc','у':'u','к':'k','е':'e','н':'n','г':'g','ш':'sh','щ':'shch','з':'z','х':'kh','ъ':'^', 'ё':'e','э':'e','ж':'zh','д':'d','л':'l','о':'o','р':'r','п':'p','а':'a','в':'v','ы':'y','ф...
Python
zaydzuhri_stack_edu_python
function GenerateMoves position begin return list comprehension move for move in POSSIBLE_MOVES if move <= position end function
def GenerateMoves(position): return [move for move in POSSIBLE_MOVES if move <= position]
Python
nomic_cornstack_python_v1
function get identifier begin if identifier is none begin return none end if is instance identifier string_types begin set identifier = string identifier return call deserialize identifier end if is instance identifier dict begin return call deserialize identifier end else if callable identifier begin return identifier...
def get(identifier): if identifier is None: return None if isinstance(identifier, six.string_types): identifier = str(identifier) return deserialize(identifier) if isinstance(identifier, dict): return deserialize(identifier) elif callable(identifier): return ident...
Python
nomic_cornstack_python_v1
function SCase Sentence begin if Sentence == none begin return Sentence end end function
def SCase(Sentence): if Sentence == None: return Sentence
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup import pandas as pd import urllib function scrape_art begin string Combs through the NYC School Construction Authority website, and gathers links for images of artwork in schools. Returns a dataframe with the link formatted as an html image tag. set count = 0 set art_links_...
import requests from bs4 import BeautifulSoup import pandas as pd import urllib def scrape_art(): """Combs through the NYC School Construction Authority website, and gathers links for images of artwork in schools. Returns a dataframe with the link formatted as an html image tag.""" count = 0 art_links_...
Python
zaydzuhri_stack_edu_python
from numpy import * set notas = array eval input string notas do aluno: set nomes = array eval input string nomes dos alunos: comment contador set i = 0 set f = 0 set a = 0 set r = 0 set s = 0 set sizep = 0 set m = 0 while i < size notas begin if notas at i == - 1 begin set f = f + 1 end if notas at i >= 6 begin set a ...
from numpy import * notas = array(eval(input("notas do aluno: "))) nomes = array(eval(input("nomes dos alunos: "))) i = 0 #contador f = 0 a = 0 r = 0 s = 0 sizep = 0 m = 0 while(i<size(notas)): if(notas[i] == -1): f = f + 1 if(notas[i] >= 6): a = a + 1 if(notas[i] < 6 and notas[i] != -1): r = r + 1 if(notas[i...
Python
zaydzuhri_stack_edu_python
import gensim import numpy as np import timeit import pandas as pd from nltk.stem import * from nltk import word_tokenize , ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from scipy.sparse.csr import csr_matrix comment Ideas on features based on...
import gensim import numpy as np import timeit import pandas as pd from nltk.stem import * from nltk import word_tokenize, ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from scipy.sparse.csr import csr_matrix #Ideas on features based on word2v...
Python
zaydzuhri_stack_edu_python
from PVI import euler , taylor , rungekutta2 , rungekutta4 , multipaso2 , multipasoAB from math import cos , sin import matplotlib.pyplot as plt import numpy as np from time import time import math import statistics function f_analitica t begin set f = 2 * t ^ 4 comment f = np.cos(t) return f end function function f t ...
from PVI import euler,taylor,rungekutta2,rungekutta4,multipaso2,multipasoAB from math import cos,sin import matplotlib.pyplot as plt import numpy as np from time import time import math import statistics def f_analitica(t): f = 2*(t**4) #f = np.cos(t) return f def f(t,y): f = 8*(t**3) #f = -1 * np...
Python
zaydzuhri_stack_edu_python
function plot_2D self func show=true save=false filename=string fig.png method=string linear logscale=none begin set tuple xlen ylen = call shape func set tuple b1 b2 b3 = lattice set bn1 = b1 / xlen set bn2 = b2 / ylen set R = list for j in range ylen begin for i in range xlen begin append R i * bn1 + j * bn2 end end...
def plot_2D(self, func, show=True, save=False, filename='fig.png', method='linear', logscale=None): xlen, ylen = np.shape(func) b1, b2, b3 = self.poscar.structure.lattice bn1 = b1 / xlen bn2 = b2 / ylen R = [] for j in range(ylen): for i in range(xlen): ...
Python
nomic_cornstack_python_v1
from PyQt5.QtCore import pyqtSignal , Qt from PyQt5.QtGui import QPalette from PyQt5.QtWidgets import QWidget , QVBoxLayout , QHBoxLayout , QSpacerItem , QSizePolicy , QPushButton class Page extends QWidget begin set finished = call pyqtSignal function __init__ self parent=none begin call __init__ self parent=parent en...
from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtGui import QPalette from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QSpacerItem, QSizePolicy, QPushButton class Page(QWidget): finished = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent=parent) class Con...
Python
zaydzuhri_stack_edu_python
function testParseMultiple self begin set parser = call PAMParser comment Parse the simplest 'normal' config we can. comment e.g. a single entry for 'telnet' with no includes etc. set tuple pathspecs file_objs = call GenPathspecFileData TELNET_ONLY_CONFIG set out = list call ParseFiles kb pathspecs file_objs call asser...
def testParseMultiple(self): parser = linux_pam_parser.PAMParser() # Parse the simplest 'normal' config we can. # e.g. a single entry for 'telnet' with no includes etc. pathspecs, file_objs = artifact_test_lib.GenPathspecFileData( TELNET_ONLY_CONFIG) out = list(parser.ParseFiles(self.kb, pa...
Python
nomic_cornstack_python_v1
function find_next_action self child begin set found = false for dchild in call children begin if found and is instance dchild QtAction begin return widget end else begin set found = child is dchild end end set parent = call parent if parent is not none begin return call find_next_action self end end function
def find_next_action(self, child): found = False for dchild in self.children(): if found and isinstance(dchild, QtAction): return dchild.widget else: found = child is dchild parent = self.parent() if parent is not None: ...
Python
nomic_cornstack_python_v1
function notify_observers self joinpoint post=false begin set _observers = tuple observers for observer in _observers begin notify observer joinpoint=joinpoint post=post end end function
def notify_observers(self, joinpoint, post=False): _observers = tuple(self.observers) for observer in _observers: observer.notify(joinpoint=joinpoint, post=post)
Python
nomic_cornstack_python_v1
function start_test_app target width=500 qapp_or_args=none begin if is instance qapp_or_args QApplication begin set qapp = qapp_or_args end else begin set qapp = call QApplication qapp_or_args or list string end if is instance target Driver begin set main = call DriverTestWidget none target end else begin set main = ca...
def start_test_app(target, width=500, qapp_or_args=None): if isinstance(qapp_or_args, QtGui.QApplication): qapp = qapp_or_args else: qapp = QtGui.QApplication(qapp_or_args or ['']) if isinstance(target, Driver): main = DriverTestWidget(None, target) else: main = SetupTe...
Python
nomic_cornstack_python_v1
from random import shuffle from card import Card import itertools class Deck begin function __init__ self begin set deck = call generate set play = list end function function generate self begin set cards = list set colors = list string red string green string purple set shapes = list string oval string squiggle stri...
from random import shuffle from card import Card import itertools class Deck: def __init__(self): self.deck = self.generate() self.play = [] def generate(self): cards = [] colors = ['red', 'green', 'purple'] shapes = ['oval', 'squiggle', 'diamond'] fills = ['em...
Python
zaydzuhri_stack_edu_python
function _scale_data self data begin set kwargs = scale_kwargs or dict set data at features = call scaler data return_scaler=false scale_method=scale keyword kwargs return data end function
def _scale_data(self, data: pd.DataFrame): kwargs = self.scale_kwargs or {} data[self.features] = scaler(data, return_scaler=False, scale_method=self.scale, **kwargs) return data
Python
nomic_cornstack_python_v1
function mutateSentences sentence begin comment Build the graph set graph = dict set words = split sentence set res = set for i in range length words - 1 begin set w = words at i if not w in graph begin set graph at w = set end add graph at w words at i + 1 end comment Helper function that recursively find and append ...
def mutateSentences(sentence): # Build the graph graph = {} words = sentence.split() res = set() for i in range(len(words) - 1): w = words[i] if not w in graph: graph[w] = set() graph[w].add(words[i + 1]) # Helper function that recursively find and append next...
Python
nomic_cornstack_python_v1
from gpiozero import LED , Buzzer import time comment Set up the LEDs and Buzzer set red = call LED 18 set blue = call LED 24 set buzzer = call Buzzer 22 print string Lights and sound on call on call on call on comment Pause for one second sleep 1 print string Lights and sound off call off call off call off
from gpiozero import LED, Buzzer import time # Set up the LEDs and Buzzer red = LED(18) blue = LED(24) buzzer = Buzzer(22) print("Lights and sound on") red.on() blue.on() buzzer.on() # Pause for one second time.sleep(1) print("Lights and sound off") red.off() blue.off() buzzer.off()
Python
zaydzuhri_stack_edu_python
function show self begin set screen = call initscr comment don't echo the keys on the screen call noecho call cbreak comment don't show cursor. call curs_set 0 call draw_elements end function
def show(self): self.screen = curses.initscr() curses.noecho() # don't echo the keys on the screen curses.cbreak() curses.curs_set(0) # don't show cursor. self.draw_elements()
Python
nomic_cornstack_python_v1
import pdb from mingus.core import * from mingus.containers import * import random import TransitionTable set PitchRange = range 1 6 class MusicComposer begin string A music composer who constructs a couple of bars from a given scale function __init__ self scale begin set scale = call get_notes scale end function funct...
import pdb from mingus.core import * from mingus.containers import * import random import TransitionTable PitchRange = range(1,6) class MusicComposer: """ A music composer who constructs a couple of bars from a given scale """ def __init__(self, scale): self.scale = scales.get_notes(scale) ...
Python
zaydzuhri_stack_edu_python
function _locate path begin if path == string begin raise call ImportError string Empty path end from importlib import import_module from types import ModuleType set parts = list comprehension part for part in split path string . for part in parts begin if not length part begin raise call ValueError string Error loadi...
def _locate(path: str) -> Any: if path == "": raise ImportError("Empty path") from importlib import import_module from types import ModuleType parts = [part for part in path.split(".")] for part in parts: if not len(part): raise ValueError( f"Error loadin...
Python
nomic_cornstack_python_v1
function run self begin comment ms = {} info string Waiting to receive... for stream in _streams begin set item_group = call ItemGroup comment Loop over all heaps in the stream. for heap in stream begin info format string Received heap {} cnt comment Extract data from the heap into a dictionary. set data = dict set it...
def run(self): # ms = {} self._log.info('Waiting to receive...') for stream in self._streams: item_group = spead2.ItemGroup() # Loop over all heaps in the stream. for heap in stream: self._log.info("Received heap {}".format(heap.cnt)) ...
Python
nomic_cornstack_python_v1
function harmonic_angle_stable conf params angle_idxs cos_angles=true begin if shape at 0 == 0 begin return 0.0 end set tuple ci cj ck = conf at T set tuple kas a0s eps = T set vij = ci - cj set vkj = ck - cj set top = sum vij * vkj - 1 set bot = square root sum vij * vij axis=- 1 + eps ^ 2 * sum vkj * vkj axis=- 1 + e...
def harmonic_angle_stable(conf, params, angle_idxs, cos_angles=True): if angle_idxs.shape[0] == 0: return 0.0 ci, cj, ck = conf[angle_idxs.T] kas, a0s, eps = params.T vij = ci - cj vkj = ck - cj top = jnp.sum(vij * vkj, -1) bot = jnp.sqrt((jnp.sum(vij * vij, axis=-1) + eps ** 2) ...
Python
nomic_cornstack_python_v1
import sys set args = argv at 1 set limit = integer split args string at 1 set prev = 0 set counter = 0 for line in read lines stdin begin set current = decimal eval line at 2 end
import sys args=sys.argv[1] limit=int(args.split(" ")[1]) prev = 0 counter = 0 for line in sys.stdin.readlines(): current = float(eval(line)[2])
Python
zaydzuhri_stack_edu_python
string Provides classes for working with data set labels. from glob import glob from os.path import join from os.path import basename class Label begin string Encapsulates a label. function __init__ self path index begin set path = path set name = base name path set index = index end function function __repr__ self beg...
""" Provides classes for working with data set labels. """ from glob import glob from os.path import join from os.path import basename class Label: """Encapsulates a label.""" def __init__(self, path, index): self.path = path self.name = basename(path) self.index = index def __repr__(self): retu...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import numpy as np import argparse as arg import matplotlib.pyplot as plt from matplotlib import ticker , gridspec from matplotlib import rc call rc string font keyword dict string family string sans-serif ; string sans-serif list string Helvetica comment for Palatino and other s...
#!/usr/bin/env python import sys import numpy as np import argparse as arg import matplotlib.pyplot as plt from matplotlib import ticker, gridspec from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) ## for Palatino and other serif fonts use: #rc('font',**{'family':'serif','serif':...
Python
zaydzuhri_stack_edu_python
from wordcount import main import sys comment setup set FILE = string code/letras.txt set FILE_EXP_PRINT_WORDS = string code/tests/expected_print_words.txt set FILE_EXP_PRINT_TOP = string code/tests/expected_print_top.txt with open FILE_EXP_PRINT_WORDS as file begin set out_print_words = read file end with open FILE_EX...
from wordcount import main import sys # setup FILE = "code/letras.txt" FILE_EXP_PRINT_WORDS = "code/tests/expected_print_words.txt" FILE_EXP_PRINT_TOP = "code/tests/expected_print_top.txt" with open(FILE_EXP_PRINT_WORDS) as file: out_print_words = file.read() with open(FILE_EXP_PRINT_TOP) as file: out_print_...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import numpy as np import sys import logging as log import os import viola_jones as vj import logging as log import pylab from matplotlib.font_manager import FontProperties string Importe les images liste "filename" et les convertient en vecteurs function loadImageData trainTest=string tra...
# -*- coding: utf-8 -*- import numpy as np import sys import logging as log import os import viola_jones as vj import logging as log import pylab from matplotlib.font_manager import FontProperties """ Importe les images liste "filename" et les convertient en vecteurs """ def loadImageData( trainTest="train", categori...
Python
zaydzuhri_stack_edu_python
from menu import MENU , resources function check_ingredients coffee begin if coffee == string expresso or string latte or string cappuccino begin for item in MENU at coffee at string ingredients begin if MENU at coffee at string ingredients at item > resources at item begin print string Not sufficient { item } return f...
from menu import MENU, resources def check_ingredients(coffee): if coffee == "expresso" or "latte" or "cappuccino": for item in MENU[coffee]["ingredients"]: if MENU[coffee]["ingredients"][item] > resources[item]: print(f"Not sufficient {item}") return False r...
Python
zaydzuhri_stack_edu_python
function calcSecondLipShape scale point1 point2 point3 begin set dist1 = call euclidean point1 point2 / scale set dist2 = call euclidean point1 point3 / scale set result = dist1 + dist2 return result end function
def calcSecondLipShape(scale, point1, point2, point3): dist1 = distance.euclidean(point1, point2) / scale dist2 = distance.euclidean(point1, point3) / scale result = dist1 + dist2 return result
Python
nomic_cornstack_python_v1
function run_request_2 self begin set result_list = list comment We can use a with statement to ensure threads are cleaned up promptly with call ThreadPoolExecutor max_workers=40 as executor begin comment Start the load operations and mark each future with its URL set future_to_url = dictionary comprehension call subm...
def run_request_2(self): result_list = [] # We can use a with statement to ensure threads are cleaned up promptly with concurrent.futures.ThreadPoolExecutor(max_workers=40) as executor: # Start the load operations and mark each future with its URL future_to_url = {ex...
Python
nomic_cornstack_python_v1
import os import sys import cv2 import matplotlib.pyplot as plt import numpy as np set face_cascade = call CascadeClassifier string /usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml function help_message begin print string Usage: [Question_Number] [Input_Video] [Output_Directory] print string [Qu...
import os import sys import cv2 import matplotlib.pyplot as plt import numpy as np face_cascade = cv2.CascadeClassifier( '/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml') def help_message(): print("Usage: [Question_Number] [Input_Video] [Output_Directory]") print("[Question Numb...
Python
zaydzuhri_stack_edu_python
function upgradeToVersion2 self begin set autoCompletion = true set autoCompletionInstruc = call _ string Allow auto completion when user filling the gaps. end function
def upgradeToVersion2(self): self.content.autoCompletion = True self.content.autoCompletionInstruc = _(u"Allow auto completion when " u"user filling the gaps.")
Python
nomic_cornstack_python_v1
function setUp self begin set user = call create_user email=string test@test.com password=string testpass name=string fname set client = call APIClient call force_authenticate user=user end function
def setUp(self): self.user = create_user( email='test@test.com', password='testpass', name='fname', ) self.client = APIClient() self.client.force_authenticate(user=self.user)
Python
nomic_cornstack_python_v1
import matplotlib call use string Agg import matplotlib.pyplot as plt , mpld3 import matplotlib.dates as mdates import csv import datetime set probe1 = list set probe2 = list set pyro_time = list function hms x pos=none begin set td = time delta seconds=x set hours = integer days * 24 set hoursPlus = integer seconds...
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt, mpld3 import matplotlib.dates as mdates import csv import datetime probe1 = [] probe2 = [] pyro_time = [] def hms(x, pos=None): td = datetime.timedelta(seconds = x) hours = int((td.days * 24)) hoursPlus = int(td.seconds / 3600) hours = hours...
Python
zaydzuhri_stack_edu_python
class Linked_List_Node begin function __init__ self x begin set item = x set next = none end function function later_node self i begin if i == 0 begin return self end assert next return call later_node i - 1 end function end class class Linked_List_Seq begin function __init__ self begin set head = none set size = 0 end...
class Linked_List_Node: def __init__(self, x): self.item = x self.next = None def later_node(self, i): if i == 0: return self assert self.next return self.next.later_node(i - 1) class Linked_List_Seq: def __init__(self): self.head = None self.size =...
Python
zaydzuhri_stack_edu_python
function version begin call echo VERSION end function
def version(): click.echo(VERSION)
Python
nomic_cornstack_python_v1
import requests set res = get requests string https://api.themotivate365.com/stoic-quote set quote = json res at string data print string " + string quote at string quote + string " set author = quote at string author if author is none begin set author = string unkown end print string - + string author
import requests res = requests.get("https://api.themotivate365.com/stoic-quote") quote = res.json()["data"] print('"' + str(quote["quote"]) + '"') author = quote["author"] if author is None: author = "unkown" print("\n\t-" + str(author))
Python
zaydzuhri_stack_edu_python
function create_with_value cls value begin return call cls time value end function
def create_with_value(cls, value: int) -> "TimedMetricItem": return cls(time.time(), value)
Python
nomic_cornstack_python_v1
function colourRequest self event begin call colourSelect end function
def colourRequest(self, event): self.colourSelect()
Python
nomic_cornstack_python_v1