code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import math set altura = decimal input string Digite a altura do cilindro: set raio = decimal input string Digite o raio do cilindro: set area_base = 3.14 * raio ^ 2 set area_lateral = 2 * 3.14 * raio * altura set area_total = area_base + area_lateral set latas = ceil area_total / 15 set preco = latas * 50 print string...
import math altura = float(input("Digite a altura do cilindro: ")) raio = float(input("Digite o raio do cilindro: ")) area_base = 3.14*raio**2 area_lateral = 2 * 3.14 * raio * altura area_total = area_base + area_lateral latas = math.ceil(area_total/15) preco = latas * 50 print("O preço fica: $", preco,...
Python
zaydzuhri_stack_edu_python
function addNewAuthor name birth begin if not name or not call checkDate birth begin call abort 400 end set author = call Author name=name birth=birth add session author commit session info string New author with id: { id } added end function
def addNewAuthor(name: str, birth: str): if not name or not checkDate(birth): abort(400) author = Author(name=name, birth=birth) db.session.add(author) db.session.commit() app.logger.info(f"New author with id: {author.id} added")
Python
nomic_cornstack_python_v1
function raw_text_to_tokenized_phrases raw_phrases language=string english begin set tokenized = call sent_tokenize raw_phrases language return list comprehension call tokenize_phrase call Phrase phrase for phrase in tokenized end function
def raw_text_to_tokenized_phrases(raw_phrases, language='english'): tokenized = nltk.sent_tokenize(raw_phrases, language) return [tokenize_phrase(Phrase(phrase)) for phrase in tokenized]
Python
nomic_cornstack_python_v1
function get_post_model begin from django.conf import settings try begin from django.apps import apps set get_model = get_model end except ImportError begin from django.db.models import get_model end try begin set POST_MODEL = get attribute settings string STARDATE_POST_MODEL end except AttributeError begin raise call ...
def get_post_model(): from django.conf import settings try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models import get_model try: POST_MODEL = getattr(settings, 'STARDATE_POST_MODEL') except AttributeError: r...
Python
nomic_cornstack_python_v1
function has_object_permission self request view obj begin if method in SAFE_METHODS begin return true end comment in our case we will assume that all users have permission to delete and update return true end function
def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True # in our case we will assume that all users have permission to delete and update return True
Python
nomic_cornstack_python_v1
function set_label_maker_hook hook begin call set_user_label_maker_hook hook end function
def set_label_maker_hook(hook): disassembly.set_user_label_maker_hook(hook)
Python
nomic_cornstack_python_v1
function update_existing_collection self owner_id collection_id=none json_repr=none auth_info=none parent_sha=none merged_sha=none commit_msg=string begin string Validate and save this JSON. Ensure (and return) a unique collection id set collection = call _coerce_json_to_collection json_repr if collection is none begin...
def update_existing_collection(self, owner_id, collection_id=None, json_repr=None, auth_info=None, parent_sha=None, ...
Python
jtatman_500k
from rest_framework import serializers from models import Question import uuid class QuestionSerializer extends ModelSerializer begin string Serializer of a question set user = call EmailField read_only=true set code = call CharField read_only=true class Meta begin set model = Question set fields = string __all__ end c...
from rest_framework import serializers from .models import Question import uuid class QuestionSerializer(serializers.ModelSerializer): """Serializer of a question""" user = serializers.EmailField(read_only=True) code = serializers.CharField(read_only=True) class Meta: model = Question ...
Python
zaydzuhri_stack_edu_python
function do_all self args begin set args = split shlex args set dicti = all set printall = list if not args begin for i in values dicti begin append printall string i end print printall end else if args at 0 in name_of_class begin for tuple key val in items dicti begin if __name__ == args at 0 begin append printall ca...
def do_all(self, args): args = shlex.split(args) dicti = storage.all() printall = [] if not args: for i in dicti.values(): printall.append(str(i)) print(printall) elif args[0] in name_of_class: for key, val in dicti.items(): ...
Python
nomic_cornstack_python_v1
string Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) class pal begin function palindrome self begin set user_input = input string Enter a string: print if expression user_input == user_input at slice : : - 1 t...
'''Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)''' class pal(): def palindrome(self): user_input = input('Enter a string:') print('The given string is palindrome' if user_input == user_inp...
Python
zaydzuhri_stack_edu_python
function find_available_group group_id groups mem_to_be_allocated max_mem_allowed begin set num_groups = length groups set available_groups = list comprehension true for _ in range num_groups set group_mems = list comprehension memory_mbytes for g_id in range num_groups set lowest_mem_group_id = index group_mems min gr...
def find_available_group(group_id: int, groups: List[Group], mem_to_be_allocated: float, max_mem_allowed: float) -> int: num_groups = len(groups) available_groups = [True for _ in range(num_groups)] group_mem...
Python
nomic_cornstack_python_v1
function DFT array dpoly begin set f = list set uroot = list 0 1 for i in call xrange length array begin set A = list 0 for j in call xrange length array begin set a = call fieldExp uroot j * i dpoly set x = array at j set A = call fieldAdd A call fieldMult x a dpoly end append f A end return f end function
def DFT(array, dpoly): f = [] uroot = [0,1] for i in xrange(len(array)): A = [0] for j in xrange(len(array)): a = finitefield.fieldExp(uroot,j*i,dpoly) x = array[j] A = finitefield.fieldAdd(A, finitefield.fieldMult(x,a,dpoly)) f.append...
Python
nomic_cornstack_python_v1
comment Ejercicio 7 Practica 3: Adrian Arias print string Este programa analiza una fecha: set dia = integer input string Introduce el día: set mes = integer input string Introduce el mes: set año = integer input string Introduce el año: if dia > 31 or dia < 1 or año < 0 begin print string Fecha incorrecta. end else if...
#Ejercicio 7 Practica 3: Adrian Arias print ("Este programa analiza una fecha:\n") dia=int(input("Introduce el día:\n")) mes=int(input("Introduce el mes:\n")) año=int(input("Introduce el año:\n")) if dia>31 or dia<1 or año<0: print("Fecha incorrecta.") elif mes>12 or mes<1: print("Fecha incorrecta.") elif mes==...
Python
zaydzuhri_stack_edu_python
function hardware_address self begin return _hardware_address end function
def hardware_address(self): return self._hardware_address
Python
nomic_cornstack_python_v1
function _Answer questionId choice begin assert equal questionId id string _Answer got questionId == "%s" % questionId + string ; expected "%s" % id assert equal choice answer string _Answer got choice == "%s" % choice + string ; expected "%s" % answer end function
def _Answer(questionId, choice): self.assertEqual(questionId, self.vmQuestion.runtime.question.id, '_Answer got questionId == "%s"' % questionId + '; expected "%s"' % self.vmQuestion.runtime.question.id) self...
Python
nomic_cornstack_python_v1
function min_age self min_age begin set _min_age = min_age end function
def min_age(self, min_age: float): self._min_age = min_age
Python
nomic_cornstack_python_v1
from menu import Menu , MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine from os import system from time import sleep set money_machine = call MoneyMachine set coffee_maker = call CoffeeMaker set menu = call Menu set MORE = true function clear begin call system string cls||clear end ...
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine from os import system from time import sleep money_machine = MoneyMachine() coffee_maker = CoffeeMaker() menu = Menu() MORE = True def clear(): system('cls||clear') while MORE: while True: cl...
Python
zaydzuhri_stack_edu_python
import pandas as pd comment Create a DataFrame from List of Dicts set data = list dict string a 1 ; string b 2 dict string a 5 ; string b 10 ; string c 20 set df = call DataFrame data comment print(df) set df = call DataFrame data index=list string first string second comment print(df) comment With two column indices, ...
import pandas as pd #Create a DataFrame from List of Dicts data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}] df = pd.DataFrame(data) #print(df) df = pd.DataFrame(data, index=['first', 'second']) #print(df) #With two column indices, values same as dictionary keys df1 = pd.DataFrame(data, index=['first', 'second'],...
Python
zaydzuhri_stack_edu_python
function order self id long qty limit=0 stop=0 post_only=false reduce_only=false trailing_stop=0 activationPrice=0 when=true begin call __init_client comment if self.get_margin()['excessMargin'] <= 0 or qty <= 0: comment return if not when begin return end set side = if expression long then string BUY else string SELL ...
def order(self, id, long, qty, limit=0, stop=0, post_only=False, reduce_only=False, trailing_stop=0, activationPrice=0, when=True): self.__init_client() # if self.get_margin()['excessMargin'] <= 0 or qty <= 0: # return if not when: return side = "BUY" if long e...
Python
nomic_cornstack_python_v1
comment 闭包:嵌套函数,内部函数调用外部函数的变量 comment def outer(): comment a=1 comment def inner(): comment print(a) comment print(inner.__closure__) #输出(<cell at 0x0000016612941768: int object at 0x00007FF8E0B96290>,) comment outer() comment def outer(): comment a=1 comment def inner(): comment print(a) comment return inner #返回函数inne...
#闭包:嵌套函数,内部函数调用外部函数的变量 # def outer(): # a=1 # def inner(): # print(a) # print(inner.__closure__) #输出(<cell at 0x0000016612941768: int object at 0x00007FF8E0B96290>,) # outer() # def outer(): # a=1 # def inner(): # print(a) # return inner #返回函数inner 不用带() 因为不是调用 # inn = o...
Python
zaydzuhri_stack_edu_python
from plyj.model import MethodDeclaration , ClassDeclaration , Type , Name , MethodInvocation , VariableDeclaration , Variable , Literal , VariableDeclarator , ExpressionStatement class AST begin string Main class to deal with the parsed .java file AST It can be used to create, update, remove, or call methods As well as...
from plyj.model import MethodDeclaration, ClassDeclaration, Type, Name,\ MethodInvocation, VariableDeclaration, Variable,\ Literal, VariableDeclarator, ExpressionStatement class AST: """ Main class to deal with the parsed .java file AST It can be used to cre...
Python
zaydzuhri_stack_edu_python
comment cannot find CLR method function __init__ self *args begin pass end function
def __init__(self, *args): #cannot find CLR method pass
Python
nomic_cornstack_python_v1
for i in str1 begin append a1 ordinal i - ordinal string a1 end for i in str2 begin append b1 ordinal i - ordinal string a1 end for tuple i j in zip a1 b1 begin append c1 character i + j % 26 + ordinal string a1 + 1 end print join string c1
for i in str1: a1.append(ord(i)-ord('a1')) for i in str2: b1.append(ord(i)-ord('a1')) for i,j in zip(a1,b1): c1.append((chr((i+j)%26+ord('a1')+1))) print("".join(c1))
Python
zaydzuhri_stack_edu_python
print 2 + 3 print 3 - 2 print 2 * 3 print 3 / 2 print 3 ^ 2 print 3 ^ 3 print 10 ^ 6 print 2 + 3 * 4 print 2 + 3 * 4
print(2 + 3) print(3 - 2) print(2 * 3) print(3 / 2) print(3 ** 2) print(3 ** 3) print(10 ** 6) print(2 + 3*4) print((2 + 3) * 4)
Python
zaydzuhri_stack_edu_python
string Extend MDP class to a 10x10 taxi domain. 10 R _ _|_ _ G _ _|C _ 9 _ _ _|_ _ _ _ _|_ _ 8 _ _ _|_ _ _|_ _|_ _ 7 _ _ _|W _ _|_ _|_ _ 6 _ _ _ _ _ _|M _ _ _ 5 _ _ _ _ _ _|_ _ _ _ 4 _|_ _ _|_ _ _ _|_ _ 3 _|_ _ _|_ _ _ _|_ _ 2 Y|_ _ _|_ _ _ _|_ _ 1 _|_ _ _|B _ _ _|_ P 1 2 3 4 5 6 7 8 9 10 string blocked_right = [(1,1),...
''' Extend MDP class to a 10x10 taxi domain. 10 R _ _|_ _ G _ _|C _ 9 _ _ _|_ _ _ _ _|_ _ 8 _ _ _|_ _ _|_ _|_ _ 7 _ _ _|W _ _|_ _|_ _ 6 _ _ _ _ _ _|M _ _ _ 5 _ _ _ _ _ _|_ _ _ _ 4 _|_ _ _|_ _ _ _|_ _ 3 _|_ _ _|_ _ _ _|_ _ 2 Y|_ _ _|_ _ _ _|_ _ 1 _|_ _ _|B _ _ _|_ P 1 2 3 4 5 6 7 8 9 10 ''' ''' blocked_righ...
Python
zaydzuhri_stack_edu_python
import sys set tuple n x = map int split strip read line stdin set a = list set num = list map int split strip read line stdin for i in range n begin if num at i < x begin append a num at i end end for i in a begin print i end=string end
import sys n,x = map(int,sys.stdin.readline().strip().split()) a = [] num = list(map(int,sys.stdin.readline().strip().split())) for i in range(n): if (num[i]<x): a.append(num[i]) for i in a: print(i,end=" ")
Python
zaydzuhri_stack_edu_python
function GetSetEnabled *args **kwargs begin return call UpdateUIEvent_GetSetEnabled *args keyword kwargs end function
def GetSetEnabled(*args, **kwargs): return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs)
Python
nomic_cornstack_python_v1
function get_subset collection_name query order_by=none begin set tuple df _ collection_type = call _open_collection collection_name set condition = ones length df dtype=bool for tuple key val in items query begin if is instance val list begin set condition_i = zeros length df dtype=bool for val_i in val begin set cond...
def get_subset(collection_name, query, order_by=None): df, _, collection_type = _open_collection(collection_name) condition = np.ones(len(df), dtype=bool) for key, val in query.items(): if isinstance(val, list): condition_i = np.zeros(len(df), dtype=bool) for val_i in val:...
Python
nomic_cornstack_python_v1
function default_params pred_type pred_name begin set predictor = none if pred_type == string regressor begin set predictor = get call get_supported_regressors pred_name none end else if pred_type == string classifier begin set predictor = get call get_supported_classifiers pred_name none end if predictor is not none b...
def default_params(pred_type, pred_name): predictor = None if pred_type == "regressor": predictor = get_supported_regressors().get(pred_name, None) elif pred_type == 'classifier': predictor = get_supported_classifiers().get(pred_name, None) if predictor is not None: return pred...
Python
nomic_cornstack_python_v1
function DesiredMinTXInterval self begin if force_auto_sync begin get self string DesiredMinTXInterval end return _DesiredMinTXInterval end function
def DesiredMinTXInterval(self): if self.force_auto_sync: self.get('DesiredMinTXInterval') return self._DesiredMinTXInterval
Python
nomic_cornstack_python_v1
string Send SMS using Twilio API from twilio.rest import Client set account_sid = string Your-SID set auth_token = string Your-Token set client = call Client account_sid auth_token set message = call create body=string hello! this is a programmed message from_=string number to=string number print sid
''' Send SMS using Twilio API ''' from twilio.rest import Client account_sid = 'Your-SID' auth_token = 'Your-Token' client = Client(account_sid, auth_token) message = client.messages \ .create( body="hello! this is a programmed message", from_=...
Python
zaydzuhri_stack_edu_python
function synergy a b t begin comment spike train A set trainA = 0 comment spike train B set trainB = 0 comment for spike trains a and b, sum up the unit impulses (given as Dirac delta functions) over time for i in a begin comment if we average train A and train B over multiple trials set trainA = trainA + call diracdel...
def synergy(a, b, t): trainA = 0 # spike train A trainB = 0 # spike train B for i in a: # for spike trains a and b, sum up the unit impulses (given as Dirac delta functions) over time trainA += diracdelta(t-i) # if we average train A and train B over multiple trials for i in b: ...
Python
nomic_cornstack_python_v1
comment Reads noise from the PCBs for dvrk-psm-force-feedback import utilities import rospy from datetime import datetime from std_msgs.msg import Float32 set size = 1000 comment create arrays to save data set arr_data_1 = list set arr_data_2 = list if __name__ == string __main__ begin comment create node call init_n...
# Reads noise from the PCBs for dvrk-psm-force-feedback import utilities import rospy from datetime import datetime from std_msgs.msg import Float32 size = 1000 # create arrays to save data arr_data_1 = [] arr_data_2 = [] if __name__ == '__main__': # create node rospy.init_node('adc_listener', anonymous=T...
Python
zaydzuhri_stack_edu_python
function save self *args **kwargs begin save *args keyword kwargs if not has attribute self string forum begin call create_forum end end function
def save(self, *args, **kwargs): super(self.__class__, self).save(*args, **kwargs) if not hasattr(self, 'forum'): self.create_forum()
Python
nomic_cornstack_python_v1
function _repeat a repeats batch_size training_batch_size begin return call cond call equal batch_size 1 lambda -> repeat a repeats num_repeats=2 lambda -> repeat a repeats training_batch_size end function
def _repeat(a, repeats, batch_size, training_batch_size): return tf.cond(tf.equal(batch_size, 1), lambda: utility.repeat(a, repeats, num_repeats=2), lambda: utility.repeat(a, repeats, training_batch_size))
Python
nomic_cornstack_python_v1
function get_option mode=string start **kwargs begin if mode == string start begin print string ============================== | | | Pysword | | | ============================== set input_txt = string What do you want to do here? [1]: Add a new password [2]: Get a password [3]: List your password [4]: Set new master ke...
def get_option(mode='start', **kwargs): if mode == 'start': print( '==============================\n' '| |\n' '| Pysword |\n' '| |\n' '==============================\n' ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string A solution to a programming assignment for the Bioinformatics Algorithms (Part 1) on Coursera. The associated textbook is Bioinformatics Algorithms: An Active-Learning Approach by Phillip Compeau & Pavel Pevzner. The course is run on Coursera and the assignments and textbook are host...
#!/usr/bin/env python ''' A solution to a programming assignment for the Bioinformatics Algorithms (Part 1) on Coursera. The associated textbook is Bioinformatics Algorithms: An Active-Learning Approach by Phillip Compeau & Pavel Pevzner. The course is run on Coursera and the assignments and textbook are hosted on Step...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 空のクラス comment 空のクラス class Empty begin pass end class set o = call Empty comment インスタンス変数の設定 set id = 100 set name = string Jiro set job = string Programmer print id name job
# -*- coding: utf-8 -*- # 空のクラス # 空のクラス class Empty: pass o = Empty() # インスタンス変数の設定 o.id = 100 o.name = "Jiro" o.job = "Programmer" print(o.id, o.name, o.job)
Python
zaydzuhri_stack_edu_python
function assign_balanced_list_types pool num_baseline num_nonstim num_stim num_ps=0 n_pairs=6 num_groups=2 begin set stim_halves = tuple generator expression i * num_stim / num_groups for i in range num_groups + 1 set nonstim_halves = tuple generator expression i * num_nonstim / num_groups for i in range num_groups + 1...
def assign_balanced_list_types(pool,num_baseline,num_nonstim,num_stim,num_ps=0,n_pairs=6,num_groups = 2): stim_halves = tuple(i*num_stim/num_groups for i in range(num_groups+1)) nonstim_halves = tuple(i*num_nonstim/num_groups for i in range(num_groups+1)) phases = ["BASELINE"]*num_baseline + ["PS"] * n...
Python
nomic_cornstack_python_v1
function _check_viya_version cls model begin comment No session supplied, assume SAS Viya 4 model if not call current_session begin warn string No current session connection was found to a SAS Viya server. Score code will be written under the assumption that the target server is SAS Viya 4. return none end else comment...
def _check_viya_version(cls, model: Union[str, dict, RestObj]) -> Union[str, None]: # No session supplied, assume SAS Viya 4 model if not current_session(): warn( "No current session connection was found to a SAS Viya server. Score " "code will be written unde...
Python
nomic_cornstack_python_v1
for i in range 26 begin set w = character ordinal string a + i if not w in S begin print w break end end for else begin print string None end
for i in range(26): w = chr(ord("a") + i) if not w in S: print(w) break else: print("None")
Python
zaydzuhri_stack_edu_python
function ta_iter_SWS_bohrium *args begin set arg_behaving = list call make_behaving args at 1 dtype=int32 for tuple i arg in enumerate args at slice 2 : : begin append arg_behaving call make_behaving arg dtype=double end set tuple mask x k1 k2 k1p k2p k3p st ks kf ft dic ta sit ksi pt bt kw kb = arg_behaving set fn = ...
def ta_iter_SWS_bohrium(*args): arg_behaving = [np.user_kernel.make_behaving(args[1], dtype=np.int32)] for i, arg in enumerate(args[2:]): arg_behaving.append(np.user_kernel.make_behaving(arg, dtype=np.double)) mask, x, k1, k2, k1p, k2p, k3p, st, ks, kf, ft, dic, ta, sit, ksi, pt, bt, kw, kb = arg...
Python
nomic_cornstack_python_v1
comment Everything is an object in Python set x = 12 set y = 13.5 set z = string python is a language set w = true print type x print type y print type z print type w
# Everything is an object in Python x = 12 y = 13.5 z = "python is a language" w = True print(type(x)) print(type(y)) print(type(z)) print(type(w))
Python
zaydzuhri_stack_edu_python
function to_basic_block self begin return call atsc_interleaver_sptr_to_basic_block self end function
def to_basic_block(self): return _atsc_swig.atsc_interleaver_sptr_to_basic_block(self)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np from pathlib import Path import cv2 import tensorflow as tf from mtcnn.mtcnn import MTCNN from matplotlib import pyplot as plt from matplotlib.patches import Rectangle comment silence warnings call set_verbosity ERROR set CHANNEL = 3 comment insert your image path set im...
# -*- coding: utf-8 -*- import numpy as np from pathlib import Path import cv2 import tensorflow as tf from mtcnn.mtcnn import MTCNN from matplotlib import pyplot as plt from matplotlib.patches import Rectangle # silence warnings tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) CHANNEL = 3 image_1_path ...
Python
zaydzuhri_stack_edu_python
import asyncio class Timer begin function __init__ self timeout callback begin set _timeout = timeout set _callback = callback set is_alive = false set _task = none end function function start self *args **kwargs begin set is_alive = true set _task = call create_task call _job *args keyword kwargs end function async fu...
import asyncio class Timer: def __init__(self, timeout, callback): self._timeout = timeout self._callback = callback self.is_alive = False self._task = None def start(self, *args, **kwargs): self.is_alive = True self._task = asyncio.create_task(self._job(*args,...
Python
zaydzuhri_stack_edu_python
import glob import re import pandas as pd set p = compile string ([.,?!]) function get_files begin return sorted glob glob string words/pronunciation-text/exceptions/*.txt end function function split_join tail begin set names = list comprehension tail at r for r in range length tail if r % 2 == 0 set texts = list compr...
import glob import re import pandas as pd p = re.compile(r'([.,?!])') def get_files(): return sorted(glob.glob(f'words/pronunciation-text/exceptions/*.txt')) def split_join(tail): names = [tail[r] for r in range(len(tail)) if r % 2 == 0] texts = [tail[r] for r in range(len(tail)) if r % 2 == 1] re...
Python
zaydzuhri_stack_edu_python
function correlate_section sound mvmt cluster sections begin comment Load files set input_file_orig = sound set input_file_sound = call butter_lowpass_filter input_file_orig 0.1 30 set input_file_mvmt = mvmt set input_file_cluster = cluster comment Sampling Rate set sr = 30 comment np.percentile(input_file_sound, 75) s...
def correlate_section(sound, mvmt, cluster, sections): #Load files input_file_orig = sound input_file_sound = butter_lowpass_filter(input_file_orig, 0.1, 30) input_file_mvmt = mvmt input_file_cluster = cluster #Sampling Rate sr = 30 sound_thresh = 0.5*10**13#np.percentile(input_file_so...
Python
nomic_cornstack_python_v1
from utils import * class TimeFreqRepresentation extends ndarray begin string The time-frequency class function __new__ cls stft fs hop_length=512 win_length=2048 begin if not is instance stft TimeFreqRepresentation begin set stft = view stft cls set fs = fs set hop_length = hop_length set win_length = win_length retur...
from utils import * class TimeFreqRepresentation(np.ndarray): """ The time-frequency class """ def __new__(cls, stft, fs, hop_length=512, win_length=2048): if not isinstance(stft, TimeFreqRepresentation): stft = stft.view(cls) cls.fs = fs cls.hop_length = ho...
Python
zaydzuhri_stack_edu_python
import _thread import time import queue import threading set numconsumers = 4 set numproducers = 4 set nummessages = 4 set safeprint = call allocate_lock comment the queue is assigned to a global variable, i.e.shared by all threads set dataQueue = queue function producer idnum begin for msg in range nummessages begin s...
import _thread import time import queue import threading numconsumers = 4 numproducers = 4 nummessages = 4 safeprint = _thread.allocate_lock() # the queue is assigned to a global variable, i.e.shared by all threads dataQueue = queue.Queue() def producer(idnum): for msg in range(nummessages): time.sleep(...
Python
zaydzuhri_stack_edu_python
function get_messages self statuses=DEFAULT_MESSAGE_STATUSES order=string sent_at desc offset=none count=none content=false begin string Returns a list of messages your account sent. Messages are sorted by ``order``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items (in sor...
def get_messages(self, statuses=DEFAULT_MESSAGE_STATUSES, order="sent_at desc", offset=None, count=None, content=False): """Returns a list of messages your account sent. Messages are sorted by ``order``, starting at an optional integer...
Python
jtatman_500k
set n = integer input string leia o numero: set e = 0 set c = 0 set d = 1 set aux = 1 while c < n begin set e = e + aux * 4 / d if aux == 1 begin set aux = - 1 end else begin set aux = 1 end set c = c + 1 set d = d + 2 end print round e 8
n = int(input("leia o numero: ")) e = 0 c = 0 d = 1 aux = 1 while(c<n): e = e + (aux *(4 / d)) if(aux == 1): aux = -1 else: aux = 1 c = c+1 d = d+2 print(round(e, 8))
Python
zaydzuhri_stack_edu_python
from stundengelaeut.feste.fest import Fest class TagFest extends Fest begin string Feste, die an einem bestimmten Datum stattfinden, werden mit dieser Klasse bezeichnet. Attributes ---------- monat : int Monat, in dem das Fest stattfindet (1-12). tag : int Tag, an dem das Fest stattfindet (1-31, 1-30, 1-29 – je nach Mo...
from stundengelaeut.feste.fest import Fest class TagFest(Fest): """ Feste, die an einem bestimmten Datum stattfinden, werden mit dieser Klasse bezeichnet. Attributes ---------- monat : int Monat, in dem das Fest stattfindet (1-12). tag : int Tag, an dem das Fest stattfindet...
Python
zaydzuhri_stack_edu_python
function get_cipher_bits sock begin set cipher = call SSL_get_current_cipher _ssl if cipher == NULL begin return none end return call SSL_CIPHER_get_bits cipher NULL end function
def get_cipher_bits(sock): cipher = binding_lib.SSL_get_current_cipher(sock._ssl) if cipher == binding_ffi.NULL: return None return binding_lib.SSL_CIPHER_get_bits(cipher, binding_ffi.NULL)
Python
nomic_cornstack_python_v1
string & a b a b a # # b a # a # # # 思路: 1、将a, b 放入一个二叉树中,左节点为a, 右节点为b 2、构建二叉树,同时根据a, b 的个数进行剪枝操作 3、中序遍历二叉树,记录访问的结点个数,即判断第K小,同时更新结点的路径 4、访问到第K个结点,即所求字符串,然后按照路径遍历得到字符串 class Tree_node begin function __init__ self s begin set s = s set left = none set right = none end function end class class Solution begin function two_...
''' & a b a b a # # b a # a # # # 思路: 1、将a, b 放入一个二叉树中,左节点为a, 右节点为b 2、构建二叉树,同时根据a, b 的个数进行剪枝操作 3、中序遍历二叉树,记录访问的结点个数,即判断第K小,同时更新结点的路径 4、访问到第K个结点,即所求字符串,然后按照路径遍历得到字符串 ''' class Tree_node: def __init__(self, s): self.s = s self.left = None self.righ...
Python
zaydzuhri_stack_edu_python
function create_binary_annotation key value annotation_type host begin return call BinaryAnnotation key=key value=value annotation_type=annotation_type host=host end function
def create_binary_annotation(key, value, annotation_type, host): return zipkin_core.BinaryAnnotation( key=key, value=value, annotation_type=annotation_type, host=host)
Python
nomic_cornstack_python_v1
function str2num str rf=0 begin try begin set num = call atoi str set format = string d end except any begin try begin set num = call atof str set format = string f end except any begin if not strip string str begin set num = none set format = string end else begin set num = str set format = string s end end end if rf...
def str2num(str, rf=0): try: num = string.atoi(str) format = 'd' except: try: num = string.atof(str) format = 'f' except: if not string.strip(str): num = None format = '' else: num = s...
Python
nomic_cornstack_python_v1
from __future__ import division import sys import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib import numpy as np from matplotlib import cm from matplotlib import pyplot as plt set Ep = 0.0001 set fig = figure set ax = call gca projection=string 3d function f x y...
from __future__ import division import sys import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib import numpy as np from matplotlib import cm from matplotlib import pyplot as plt Ep = 0.0001 fig = plt.figure() ax = fig.gca(projection='3d') def f(x,y): return ...
Python
zaydzuhri_stack_edu_python
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt function accel_from_velocity velocities begin set n_obs = shape at 0 set acceleration_vectors = velocities at slice 1 : : - velocities at slice : n_obs - 1 : set velocity_magnitudes = list for tuple v1 v2 in zip velocities at tuple sl...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt def accel_from_velocity(velocities): n_obs = velocities.shape[0] acceleration_vectors = velocities[1:] - velocities[:(n_obs-1)] velocity_magnitudes = [] for v1, v2 in zip(velocities[:, 0], velocities[:, 1]): if a...
Python
zaydzuhri_stack_edu_python
comment Project 1, starter code part b import math import tensorflow as tf import numpy as np import pylab as plt comment initialization routines for bias and weights function init_bias test_size=1 begin return call Variable zeros test_size dtype=float32 end function function init_weights n_in=1 n_out=1 begin return ca...
# # Project 1, starter code part b # import math import tensorflow as tf import numpy as np import pylab as plt # initialization routines for bias and weights def init_bias(test_size = 1): return(tf.Variable(np.zeros(test_size), dtype=tf.float32)) def init_weights(n_in=1, n_out=1): return (tf.Variable(tf.trun...
Python
zaydzuhri_stack_edu_python
import unittest import os import pandas as pd import numpy as np import hashlib from tradeframework.api.core import Asset , Model from tradeframework.environments import SandboxEnvironment import tradeframework.operations.trader as trader set dir = directory name path absolute path path __file__ class SingleAssetTest e...
import unittest import os import pandas as pd import numpy as np import hashlib from tradeframework.api.core import Asset, Model from tradeframework.environments import SandboxEnvironment import tradeframework.operations.trader as trader dir = os.path.dirname(os.path.abspath(__file__)) class SingleAssetTest(unittest...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Dec 08 22:12:34 2015 @author: Rama function wordsorter word begin if word at 0 == string @ begin return string @user end else if word at slice : 4 : == string http begin return string http://<url> end else if word at 0 == string # begin return string #hashtag end el...
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 22:12:34 2015 @author: Rama """ def wordsorter(word): if word[0]=="@": return "@user" elif word[:4]=="http": return "http://<url>" elif word[0]=="#": return "#hashtag" else: return word if __name__ == "__main__": wo...
Python
zaydzuhri_stack_edu_python
function unzip self directory begin string Write contents of zipfile to directory if not exists path directory begin make directories directory end copy tree src_dir directory end function
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment Time: 2019/9/10 16:31 comment Author: Hou hailun、 string 题目名称:最后一个单词的长度 题目描述:给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 示例: 输入: "Hello World" 输出: 5 解题思路:利用split对空格进行切分,直接len(最后一个单词) class Solution begin functi...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Time: 2019/9/10 16:31 # Author: Hou hailun、 """ 题目名称:最后一个单词的长度 题目描述:给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 示例: 输入: "Hello World" 输出: 5 解题思路:利用split对空格进行切分,直接len(最后一个单词) """ class Solution: def lengthOfLastWord(self, ...
Python
zaydzuhri_stack_edu_python
function pmap x y objs score=9 s=0.5 begin set map = sum list comprehension call activation x y obj at 3 obj at 4 obj at score s for obj in objs return map / max map end function
def pmap( x, y, objs, score = 9, s = 0.5 ): map = sum( [activation( x, y, obj[3], obj[4], obj[score], s ) for obj in objs] ) return map / np.max( map )
Python
nomic_cornstack_python_v1
function get_data self document begin try begin return document at string data end except KeyError begin raise call MalformedDocument string data string /data end end function
def get_data(self, document): try: return document['data'] except KeyError: raise exceptions.MalformedDocument('data', '/data')
Python
nomic_cornstack_python_v1
function get_pipeline region role=none default_bucket=none pipeline_name=string defect-detection-semantic-segmentation-pipeline base_job_prefix=string defect-detection-semantic-segmentation begin set sagemaker_session = call get_session region default_bucket if role is none begin set role = call get_execution_role sage...
def get_pipeline( region, role=None, default_bucket=None, pipeline_name="defect-detection-semantic-segmentation-pipeline", base_job_prefix="defect-detection-semantic-segmentation", ): sagemaker_session = get_session(region, default_bucket) if role is None: rol...
Python
nomic_cornstack_python_v1
from zipfile import ZipFile import json import time set dir_path = string /mnt/ds3lab/yanping/mag set total = 0 set withfos = 0 for idx in range 9 begin with zip file dir_path + string /data/mag_papers_ + string idx + string .zip string r as myzip begin set zip_files = name list myzip for file_name in zip_files begin p...
from zipfile import ZipFile import json import time dir_path = "/mnt/ds3lab/yanping/mag" total = 0 withfos = 0 for idx in range(9): with ZipFile(dir_path+"/data/mag_papers_"+str(idx)+".zip", "r") as myzip: zip_files = myzip.namelist() for file_name in zip_files: print("zip",idx,file_name) start_time = time....
Python
zaydzuhri_stack_edu_python
comment import pygame from level import Level from entity import Entity from player import Player from door import Door from key import Key set WALL_WIDTH = 100 set WALL_HEIGHT = 100 set PLATFORM_WIDTH = WALL_WIDTH set PLATFORM_HEIGHT = 30 set WALL = string = set PLATFORM = string - set PLAYER_1 = string 1 set PLAYER_2...
# import pygame from level import Level from entity import Entity from player import Player from door import Door from key import Key WALL_WIDTH = 100 WALL_HEIGHT = 100 PLATFORM_WIDTH = WALL_WIDTH PLATFORM_HEIGHT = 30 WALL = "=" PLATFORM = "-" PLAYER_1 = "1" PLAYER_2 = "2" DOOR_1 = "R" DOOR_2 = "B" DOOR_1_LOCKED = "...
Python
zaydzuhri_stack_edu_python
comment 良/恶性乳腺癌肿瘤预测 import pandas as pd comment 导入matplotlib工具包的pyplot并化简为plt import matplotlib.pyplot as plt comment 导入numpy工具包,命名为np`a import numpy as np comment 导入sklearn中的逻辑斯蒂回归分类器 from sklearn.linear_model import LogisticRegression comment 调用pandas工具包的read_csv函数/模块,传入训练文件地址参数,获得返回的数据并存放至de_train set df_train = rea...
# 良/恶性乳腺癌肿瘤预测 import pandas as pd # 导入matplotlib工具包的pyplot并化简为plt import matplotlib.pyplot as plt # 导入numpy工具包,命名为np`a import numpy as np # 导入sklearn中的逻辑斯蒂回归分类器 from sklearn.linear_model import LogisticRegression # 调用pandas工具包的read_csv函数/模块,传入训练文件地址参数,获得返回的数据并存放至de_train df_train = pd.read_csv('/home/xieyipeng/Documen...
Python
zaydzuhri_stack_edu_python
function cfdGetOwnersSubArrayForBoundaryPatch self begin for tuple iBPatch theBCInfo in items cfdBoundaryPatchesArray begin set startBFace = cfdBoundaryPatchesArray at iBPatch at string startFaceIndex set endBFace = startBFace + cfdBoundaryPatchesArray at iBPatch at string numberOfBFaces set iBFaces = list range intege...
def cfdGetOwnersSubArrayForBoundaryPatch(self): for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items(): startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex'] endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['numberOfB...
Python
nomic_cornstack_python_v1
string demo usage # this is SERIOUSLY inefficient # call can support 15 at once, this demo uses a link python bitly.py "http://www.meetup.com/occupytogether/New-York-NY/406522/" import sys import logging import urllib2 import urllib try begin import json end except ImportError begin import simplejson as json end set BI...
""" demo usage # this is SERIOUSLY inefficient # call can support 15 at once, this demo uses a link python bitly.py "http://www.meetup.com/occupytogether/New-York-NY/406522/" """ import sys import logging import urllib2 import urllib try: import json except ImportError: import simplejson as js...
Python
zaydzuhri_stack_edu_python
function parse_commandline begin set parser = call OptionParser call add_option string -o string --output_path help=string Output path. default=string ../output call add_option string -i string --image_path help=string Path to images. default=string ../../../../TrainingSet2/H1L1 call add_option string -m string --model...
def parse_commandline(): parser = optparse.OptionParser() parser.add_option("-o", "--output_path", help="Output path.", default="../output") parser.add_option("-i", "--image_path", help="Path to images.", default="../../../../TrainingSet2/H1L1") parser.add_option("-m","--model_path", help="Path to model...
Python
nomic_cornstack_python_v1
from collections import Counter set lst = list 1 2 3 3 3 4 5 6 6 6 set counter = counter lst set counter = dictionary comprehension element : count for tuple element count in items counter if count != 0 set median_count = sorted values counter at length counter // 2 set dictionary = dictionary comprehension element : c...
from collections import Counter lst = [1, 2, 3, 3, 3, 4, 5, 6, 6, 6] counter = Counter(lst) counter = {element: count for element, count in counter.items() if count != 0} median_count = sorted(counter.values())[len(counter)//2] dictionary = {element: count for element, count in counter.items() if count >= median_co...
Python
greatdarklord_python_dataset
function api_list_entries count filter_read=none filter_starred=none oldest=false begin set url = call __get_api_url list_entries set header = call __get_authorization_header set params = dictionary set params at string perPage = count if oldest begin set params at string order = string asc end if filter_read != none b...
def api_list_entries(count, filter_read=None, filter_starred=None, oldest=False): url = __get_api_url(ApiMethod.list_entries) header = __get_authorization_header() params = dict() params['perPage'] = count if oldest: params['order'] = "asc" if filter_read != None: if filter_re...
Python
nomic_cornstack_python_v1
comment import complex math module import cmath import math set a = integer input string Enter the coefficients of a: set b = integer input string Enter the coefficients of b: set c = integer input string Enter the coefficients of c: comment discriminant set d = b ^ 2 - 4 * a * c if d < 0 begin print string This equati...
# import complex math module import cmath import math a = int(input("Enter the coefficients of a: ")) b = int(input("Enter the coefficients of b: ")) c = int(input("Enter the coefficients of c: ")) d = b**2-4*a*c # discriminant if d < 0: print ("This equation has no real solution") x1 = (-b-cmath.sqrt(d))/(2...
Python
zaydzuhri_stack_edu_python
function pre_process_text_block block begin set block at string content = strip block at string content end function
def pre_process_text_block(block): block['content'] = block['content'].strip()
Python
nomic_cornstack_python_v1
function values self begin return _items end function
def values(self): return self._items
Python
nomic_cornstack_python_v1
comment **************************************************************************** # comment # comment ::: :::::::: # comment function_h_test.py :+: :+: :+: # comment +:+ +:+ +:+ # comment By: germancq <germancq@dte.us.es> +#+ +:+ +#+ # comment +#+#+#+#+#+ +#+ # comment Created: 2019/11/04 15:33:36 by germancq #+# #+...
# **************************************************************************** # # # # ::: :::::::: # # function_h_test.py :+: :+: :+: ...
Python
zaydzuhri_stack_edu_python
from turtle import Turtle , Screen import random set is_race_on = false set screen = call Screen setup screen width=600 height=500 set user_bet = call textinput title=string Make your bet prompt=string Wich turtle will win the rave? Enter the colour:.. 'blue', 'red', 'green', 'brown', 'yellow', 'LightSeaGreen' print us...
from turtle import Turtle , Screen import random is_race_on = False screen = Screen() screen.setup(width=600, height=500) user_bet = screen.textinput(title="Make your bet", prompt="Wich turtle will win the rave? Enter the colour:..\n'blue', 'red', 'green', 'brown', 'yellow', 'LightSeaGreen'") print(user_bet) color_li...
Python
zaydzuhri_stack_edu_python
string View module for handling requests from django.core.exceptions import ValidationError from rest_framework import status from django.http import HttpResponseServerError from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import serializers from rest_framewor...
"""View module for handling requests""" from django.core.exceptions import ValidationError from rest_framework import status from django.http import HttpResponseServerError from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework import serializers from rest_framework...
Python
zaydzuhri_stack_edu_python
string 基于命名空间的常见的变量类型 局部变量 在一个函数内部定义得变量 作用域为函数内部 查看局部变量 locals() 全局变量 在函数外部 文件最外层定义的变量 作用域为整个文件内部 查看全局变量 globals() 注意点 访问原则 从内到外 结果规范 结构规范 全局变量 函数定义 使用 修改 后续代码 全局变量和局部变量重名 获取 就近原则 修改 global 全局变量 声明 命名 comment 全局的变量 set a = 999 function test begin set a = 1 set a = 3 print a function test2 begin comment nonlocal a comme...
""" 基于命名空间的常见的变量类型 局部变量 在一个函数内部定义得变量 作用域为函数内部 查看局部变量 locals() 全局变量 在函数外部 文件最外层定义的变量 作用域为整个文件内部 查看全局变量 globals() 注意点 访问原则 从内到外 结果规范 结构规范 全局变量 函数定义 ...
Python
zaydzuhri_stack_edu_python
function test_meta_uid self begin set ae = call AE set ae = call AE set acse_timeout = 5 set dimse_timeout = 5 set network_timeout = 5 call add_supported_context BasicGrayscalePrintManagementMeta call add_supported_context Printer set scp = call start_server tuple string localhost 11112 block=false call add_requested_c...
def test_meta_uid(self): self.ae = ae = AE() ae.acse_timeout = 5 ae.dimse_timeout = 5 ae.network_timeout = 5 ae.add_supported_context(BasicGrayscalePrintManagementMeta) ae.add_supported_context(Printer) scp = ae.start_server(("localhost", 11112), block=False) ...
Python
nomic_cornstack_python_v1
comment Se existir a palavra FREIRE na frase if string FREIRE in frase begin print string Graaaaande Mestre Paulo Freire end else begin print string Qualquer outra coisa end
if 'FREIRE' in frase: #Se existir a palavra FREIRE na frase print("Graaaaande Mestre Paulo Freire") else: print("Qualquer outra coisa")
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import prep import seg import actual_modelling import analytics import viz import util set SEGS_PER_CONT = 5 comment ==Load in== set df = read csv string ../data/new_train.csv comment that's column order set uselessCols = list string id string Gender string Customer string Effecti...
import numpy as np import pandas as pd import prep import seg import actual_modelling import analytics import viz import util SEGS_PER_CONT=5 #==Load in== df = pd.read_csv("../data/new_train.csv") uselessCols=["id", #that's column order "Gender", #modelling on this is illegal "Customer", #discriminating against in...
Python
zaydzuhri_stack_edu_python
function board_value self location begin set tuple t1 t2 = location if not board at t1 at t2 begin return none end return call make_copy end function
def board_value(self, location): t1,t2 = location if not self.board[t1][t2]: return None return self.board[t1][t2][-1].make_copy()
Python
nomic_cornstack_python_v1
function selection self begin set returnData = list comprehension i for i in call selectedNodes return call HouQuery data=returnData prevData=_data end function
def selection(self): returnData = [i for i in hou.selectedNodes()] return HouQuery(data=returnData, prevData=self._data)
Python
nomic_cornstack_python_v1
function load_data self begin info string [ { id } ] Loading data call _initialize_api call _load_survey_props call _load_language_props call _load_questions call _load_responses end function
def load_data(self): logger.info(f"[{self.id}] Loading data") self._initialize_api() self._load_survey_props() self._load_language_props() self._load_questions() self._load_responses()
Python
nomic_cornstack_python_v1
function ensure_text str_or_bytes encoding=string utf-8 begin string Ensures an input is a string, decoding if it is bytes. if not is instance str_or_bytes text_type begin return decode str_or_bytes encoding end return str_or_bytes end function
def ensure_text(str_or_bytes, encoding='utf-8'): """Ensures an input is a string, decoding if it is bytes. """ if not isinstance(str_or_bytes, six.text_type): return str_or_bytes.decode(encoding) return str_or_bytes
Python
jtatman_500k
function get_names self begin return name end function
def get_names(self): return self.name
Python
nomic_cornstack_python_v1
class Painting begin set n_pictures = 0 function __init__ self title painting year begin set title = title set painting = painting set year = year print string " { title } " by { painting } ( { year } ) hangs in the Louvre. end function end class set title_input = input set painting_input = input set year_input = input...
class Painting: n_pictures = 0 def __init__(self, title, painting, year): self.title = title self.painting = painting self.year = year print(f'"{self.title}" by {self.painting} ({self.year}) hangs in the Louvre.') title_input = input() painting_input = input() year_input = inp...
Python
zaydzuhri_stack_edu_python
comment Unit tests for the ChildCareLib Class comment Valid and invalid tests for each function import os import unittest import ChildCare.ChildCareLib as ChildCareLib_Class class TestChildCareLib extends TestCase begin comment Valid test for function read_data with comment a valid file. Return value should be 0. funct...
# Unit tests for the ChildCareLib Class # Valid and invalid tests for each function import os import unittest import ChildCare.ChildCareLib as ChildCareLib_Class class TestChildCareLib(unittest.TestCase): # Valid test for function read_data with # a valid file. Return value should be 0. def test_0_read...
Python
zaydzuhri_stack_edu_python
function load_clean_dataset begin set tuple account card client disp district loan order trans = call load_original_dataset set account at string date = call convert_date account at string date set account = rename columns=dict string date string account_date set account at string frequency = apply account at string fr...
def load_clean_dataset(): account, card, client, disp, district, loan, order, trans = load_original_dataset() account['date'] = convert_date(account['date']) account = account.rename(columns={'date': 'account_date'}) account['frequency'] = account['frequency'].apply(account_freq) card['issued'] ...
Python
nomic_cornstack_python_v1
function release_orphaned_reservations self begin info string Checking for orphaned jobs set active_jobs = set set active_services = set set active_deployments = set for job_info in call get_services task_only=true is_active=true fields=string id begin if not call completed job_info at string status begin add active_jo...
def release_orphaned_reservations(self): logger.info("Checking for orphaned jobs") active_jobs = set() active_services = set() active_deployments = set() for job_info in self.axops_client.get_services(task_only=True, is_active=True, fields='id'): if not ServiceStatus....
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Sep 29 15:30:10 2019 @author: Maibenben import tensorflow as tf from tensorflow.contrib.layers import xavier_initializer_conv2d from tensorflow.contrib.layers import flatten comment 卷积层定义 function conv_op input_op filter_size channel_out step name begin set channel_in...
# -*- coding: utf-8 -*- """ Created on Sun Sep 29 15:30:10 2019 @author: Maibenben """ import tensorflow as tf from tensorflow.contrib.layers import xavier_initializer_conv2d from tensorflow.contrib.layers import flatten # 卷积层定义 def conv_op(input_op, filter_size, channel_out, step, name): channel_in = input_op.g...
Python
zaydzuhri_stack_edu_python
while n > 0 begin set n = n - 1 set tuple a b = map int split input print a - b end
while n > 0: n -= 1 a, b = map(int, input().split()) print(a - b)
Python
zaydzuhri_stack_edu_python
function on_epoch_end self epoch logs=none begin pass end function
def on_epoch_end(self, epoch, logs: Optional[Dict] = None): pass
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment --------------------------------------- comment 程序:百度贴吧爬虫 comment 版本:1.0 comment 作者:gtj comment 日期:2017-02-06 comment 语言:Python 2.7 comment 操作:输入网址后自动只看楼主并保存到本地文件 comment 功能:将楼主发布的内容打包txt存储到本地。 comment --------------------------------------- import urllib2 import re comment -------...
# -*- coding: utf-8 -*- # --------------------------------------- # 程序:百度贴吧爬虫 # 版本:1.0 # 作者:gtj # 日期:2017-02-06 # 语言:Python 2.7 # 操作:输入网址后自动只看楼主并保存到本地文件 # 功能:将楼主发布的内容打包txt存储到本地。 # --------------------------------------- import urllib2 import re # ----------- 处理页面上的各种标签 ----------- class HTML_Tool: #...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from subprocess import check_output set out = check output list string sysctl string hw.sensors.cpu0 set out = string out encoding=string utf8 set out = split out string = at 1 set out = split out string at 0 set temp = decimal out set GREEN = string #00ff00 set YELLOW_ORANGE = string #ffdd...
#!/usr/bin/env python from subprocess import check_output out = check_output(["sysctl", "hw.sensors.cpu0"]) out = str(out, encoding='utf8') out = out.split('=')[1] out = out.split(' ')[0] temp = float(out) GREEN = "#00ff00" YELLOW_ORANGE = "#ffdd00" RED = "#ff0000" if temp < 45.0: print("<fc=...
Python
zaydzuhri_stack_edu_python
function execute self hosts task raise_on_statuses=DEFAULT_ERROR_STATUSES begin debug string Executing task: %s on hosts: %s task hosts set task_play = dict string hosts hosts ; string tasks list task set result = call run_playbook list task_play set log_result = deep copy result debug string Execution completed with %...
def execute(self, hosts, task, raise_on_statuses=DEFAULT_ERROR_STATUSES): LOG.debug('Executing task: %s on hosts: %s', task, hosts) task_play = {'hosts': hosts, 'tasks': [task]} result = self.run_playbook([task_play]) log_result = copy.deepcopy(result) LOG.debug('Execution comp...
Python
nomic_cornstack_python_v1