content
stringlengths
7
1.05M
N, C = map(int, input().split()) l = [tuple(map(int, input().split())) for i in range(N)] s = set() for a, b, c in l: s.add(a) s.add(b + 1) d = {} s = sorted(list(s)) for i, j in enumerate(s): d[j] = i m = [0] * (len(s) + 1) for a, b, c in l: m[d[a]] += c m[d[b + 1]] -= c ans = 0 for i in range(len(s) - 1): c = m[i] if m[i] < C else C ans += (s[i + 1] - s[i]) * c m[i + 1] += m[i] print(ans)
print( 1 == 1 or 2 == 2 ) print( 1 == 1 or 2 == 3 ) print( 1 != 1 or 2 == 2 ) print( 2 < 1 or 3 > 6 )
class Node: def __init__(self, data): self.data = data self.next = None class llist: def __init__(self): self.head = None def reverse(self, head): if head is None or head.next is None: return head rest = self.reverse(head.next) head.next.next = head head.next = None return rest def __str__(self): llistStr = "" temp = self.head while temp: llistStr = (llistStr + str(temp.data) + " ") temp = temp.next return llistStr def push(self, data): temp = Node(data) temp.next = self.head self.head = temp llist = llist() llist.push(98) llist.push(10) llist.push(15) llist.push(23) llist.push(24) llist.push(76) llist.push(13) print("Given linked list") print(llist) llist.head = llist.reverse(llist.head) print("Reversed linked list") print(llist)
class Funcionario: def __init__(self, nome, cpf, salario): self._nome = nome self._cpf = cpf self._salario = salario def get_bonificacao(self): return self._salario * 0.10 + 1000.0 class Gerente(Funcionario): def __init__(self, nome, cpf, salario, senha, qtd_gerenciados): super().__init__(nome, cpf, salario) self._senha = senha self._qtd_gerenciados = qtd_gerenciados def get_bonificacao(self): return super().get_bonificacao() + 1000 def autentica(self, senha): if self._senha == senha: print('acesso permitido') return True else: print('acesso negado') return False funcionario = Funcionario('João', '111.111.111-11', 2000.0) print(funcionario.__dict__) gerente1 = Gerente('José', '222.222.222-22', 5000.0, '1234', 0) print(gerente1.__dict__) print(gerente1.get_bonificacao()) class ControleDeBonificacoes: def __init__(self, total_bonificacoes=0): self._total_bonificacoes = total_bonificacoes def registra(self, obj): if(hasattr(obj, 'get_bonificacao')): self._total_bonificacoes += funcionario.get_bonificacao() else: print( f'instância de {self.__class__.__name__}' 'não implementa o método get_bonificacao()' ) @property def total_bonificacoes(self): return self._total_bonificacoes if __name__ == '__main__': funcionario = Funcionario('João', '111.111.111-11', 2000.0) print(f'bonificação funcionário: {funcionario.get_bonificacao()}') gerente = Gerente('José', '222.222.222-22', 5000.0, '1234', 0) print(f'bonificação gerente: {gerente.get_bonificacao()}') controle = ControleDeBonificacoes() controle.registra(funcionario) controle.registra(gerente) print(f'total: {controle.total_bonificacoes}')
texto = input("Ingrese su texto: ") def SpaceToDash(texto): return texto.replace(" ", "-") print (SpaceToDash(texto))
nome = 'Fabio Rodrigues Dias' cores = {'limpa':'\033[m', 'azul':'\033[1;7;34m', 'amarelo':'\033[33m', 'pretoebranco': '\033[7;30m'} print('Ola!! Muito prazer em te conhecer, {}{}{}'.format(cores['azul'], nome , cores['limpa']))
"""Warnings""" # Authors: Jeffrey Wang # License: BSD 3 clause class ConvergenceWarning(UserWarning): """ Custom warning to capture convergence issues. """ class InitializationWarning(UserWarning): """ Custom warning to capture initialization issues. """ class StabilizationWarning(UserWarning): """ Custom warning to capture stabilization issues. """
# Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. def CheckDoNotMerge(input_api, output_api): for l in input_api.change.FullDescriptionText().splitlines(): if l.lower().startswith('do not merge'): msg = 'Your cl contains: \'Do not merge\' - this will break WIP bots' return [output_api.PresubmitPromptWarning(msg, [])] return [] def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(CheckDoNotMerge(input_api, output_api)) return results
# I wouldn't be able to say if this question was hard or easy. It uses the fundamental stuff. No modules. # However changing the rules of math was mind-boggling def Part1(part2): calc = list() with open("Day18.txt") as f: for line in f: operation = line.strip().replace(" ", "") start = 0 parentheses = list() while(True): # Taking the parenthesis and removing (.pop()) them from the list for i in range(start, len(operation)): if operation[i] == "(": parentheses.append(i) elif operation[i] == ")": parenthsis_i = parentheses.pop() # Calling the change function in order the change the laws of the math val = change(operation[parenthsis_i+1:i], part2) start = parenthsis_i operation = operation[:parenthsis_i] + \ str(val) + operation[i+1:] break if operation.count("(") == 0: calc.append(change(operation, part2)) break return sum(calc) # The function that does it all def change(operation, part2): n = 0 while(True): opi = -1 op = None opfound = False if part2: n1i = 0 n2i = -1 for i, c in enumerate(operation): if c == "+" or c == "*": if opfound: n2i = i break else: if part2: if not (c == "+" or operation.count("+") == 0): n1i = i + 1 else: opfound = True opi = i op = c else: opfound = True opi = i op = c if i == len(operation) - 1: n2i = i + 1 if part2: n1 = int(operation[n1i:opi]) n2 = int(operation[opi+1:n2i]) else: n1 = int(operation[0:opi]) n2 = 0 n2 = int(operation[opi+1:n2i]) if op == "+": n = n1 + n2 elif op == "*": n = n1 * n2 if part2: operation = operation[:n1i] + str(n) + operation[n2i:] if operation.count("+") + operation.count("*") == 0: return n else: if len(operation[n2i:]) == 0: return n operation = str(n) + operation[n2i:] print(f"Q1: {Part1(False)}") print(f"Q2: {Part1(True)}")
class VCard(): def __init__(self, filename:str): self.filename = filename def create(self, display_name:list, full_name:str, number:str, email:str=None): '''Create a vcf card''' bp = [1, 2, 0] pp = [0, 1, 2] rn = [] for i, j in zip(bp, pp): rn.insert(i, display_name[j]+";") fd = self.filename f = open(fd, "w") f.write("BEGIN:VCARD\n") f.write("VERSION:2.1\n") f.write("N:") for i in rn: f.write("{}".format(i)) f.write("\n") f.write("FN:{}\n".format(full_name)) f.write("TEL;CELL;PREF:{}\n".format(number)) f.write("EMAIL;HOME:{}\n".format(email)) f.write("END:VCARD") f.close() def read(self, att:str): '''Read a card''' global name, full_name, number, email filenameWithDirectory = self.filename bp = [1, 2, 0] pp = [0, 1, 2] oriname = [] nameind, fnind, phind, emind = None, None, None, None with open(filenameWithDirectory, 'r') as f: card = [line.strip() for line in f] for i in card: if "N:" in i: nameind = card.index(i) if "FN:" in i: fnind = card.index(i) if "TEL;CELL;PREF:" in i: phind = card.index(i) if "TEL;CELL:" in i: phind = card.index(i) if "EMAIL;HOME:" in i: emind = card.index(i) if nameind != None: name = card[fnind] name = name[2:len(name)] name = name.replace(":","") name = name[0:len(name)] namel = name.split(";") if fnind != None: full_name = card[nameind] full_name = full_name[3:len(full_name)] if phind != None: number = card[phind] try: number = str(number).replace("TEL;CELL:","") number = int(number) except: number = str(number).replace("TEL;CELL;PREF:","") number = int(number) if emind != None: email = card[emind] email = email[11:len(email)] elif emind == None: email = None info = {} infol = ["name", "full_name", "number", "email"] infola = [name, full_name, number, email] for i, j in zip(infol, infola): info[i] = j return info[att] @property def number(self): return self.read("number") @property def name(self): return self.read("name") @property def fullName(self): return self.read("full_name") @property def email(self): return self.read("email")
#!/usr/bin/env python3 """genomehubs version.""" __version__ = "2.2.0"
# # Copyright (c) 2017 Joy Diamond. All rights reserved. # @gem('Quartz.Parse1') def gem(): require_gem('Quartz.Match') require_gem('Quartz.Core') show = true @share def parse1_mysql_from_path(path): data = read_text_from_path(path) many = [] append = many.append iterate_lines = z_initialize(path, data) for s in iterate_lines: m1 = mysql_line_match(s) if m1 is none: raise_unknown_line() identifier_s = m1.group('identifier') if identifier_s is not none: identifier = lookup_identifier(identifier_s) if identifier is none: lower = identifier_s.lower() line('lower: %s', lower) identifier_start = m1.start('identifier') line('identifier_start: %d', identifier_start) line('identifier: %r', identifier) line('identifier_s: %r', identifier) comment_start = m1.end('pound_sign') if comment_start is -1: # # '+ 1' due to the required space after --. # comment_start = m1.end('dash_dash') + 1 if comment_start is 0: # '0' instead of '-1' due to the '+ 1' above. append(EmptyLine(s)) continue comment_end = m1.end('dash_dash_comment') if comment_end is -1: append(conjure_comment_newline(s)) continue append(conjure_tree_comment(s[:comment_start], s[comment_start : comment_end], s[comment_end:])) continue comment_end = m1.end('pound_sign_comment') if comment_end is -1: append(conjure_comment_newline(s)) continue append(conjure_tree_comment(s[:comment_start], s[comment_start : comment_end], s[comment_end:])) continue if show: for v in many: line('%r', v) with create_StringOutput() as f: w = f.write for v in many: v.write(w) if data != f.result: with create_DelayedFileOutput('oops.txt') as oops: oops.write(f.result) raise_runtime_error('mismatch on %r: output saved in %r', path, 'oops.txt')
#!/usr/bin/env python3 """Front Back. Given a string, return a new string where the first and last chars have been exchanged. front_back('code') == 'eodc' front_back('a') == 'a' front_back('ab') == 'ba' """ def front_back(str_: str) -> str: """Swap the first and last characters of a string.""" if len(str_) > 1: return f'{str_[-1]}{str_[1:-1]}{str_[0]}' return str_ if __name__ == "__main__": assert front_back('code') == 'eodc' assert front_back('a') == 'a' assert front_back('ab') == 'ba' assert front_back('abc') == 'cba' assert front_back('') == '' assert front_back('Chocolate') == 'ehocolatC' assert front_back('aavJ') == 'Java' assert front_back('hello') == 'oellh' print('Passed')
# https://leetcode.com/problems/encode-and-decode-strings/ class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ return ''.join(s.replace('|', '||') + ' | ' for s in strs) def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ return [x.replace('||', '|') for x in s.split(' | ')[:-1]] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(strs))
a = range(2, 10, 2) b = list(a) c = [a] print('')
stages = [''' +---+ | | O | /|\ | / \ | | ========= ''', ''' +---+ | | O | /|\ | / | | ========= ''', ''' +---+ | | O | /|\ | | | ========= ''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | | | | | ========= ''', ''' +---+ | | O | | | | ========= ''', ''' +---+ | | | | | | ========= '''] logo = ''' __ __ _ ______ __˘__ _ \ \ / / | | ____|/ ____| /\ | | /\ \ \ / / | | |__ | (___ / \ | | / \ \ \/ / | | __| \___ \ / /\ \ | | / /\ \ \ / |__| | |____ ____) / ____ \| |____ / ____ \ \/ \____/|______|_____/_/ \_\______/_/ \_\ "Vješala" igra, ver 0.0.1 na hrvatskom jeziku - Sonja Hranjec 2021. '''
"""Preço e desconto""" # Operadores aritmeticos preco = int(input('Digite o preço do produto: ')) off = (price * 5) / 100 precofinal = price - off print('O preço final do produto com 5% de desconto é: R$ {}'.format(pricef))
# This si a hello worls script # written in Python def main(): print("Hello, world") if __name__ == "__main__": main()
## To modify by developper(s) of the plugin SHORT_PLUGIN_NAME = 'amplitude' #for instance daqmx package_url = 'https://github.com/CEMES-CNRS/pymodaq_plugins_amplitude' #to modify description = 'Set of PyMoDAQ plugins for Amplitude Systems Lasers' author = 'Sébastien Weber' author_email = 'sebastien.weber@cemes.fr' #packages required for your plugin: packages_required = ['serial', 'crcmod', ] ##
# Your code below: number_list = range(9) print(list(number_list)) zero_to_seven = range(8) print(list(zero_to_seven))
# Solution to problem 6 # #Student: Niamh O'Leary# #ID: G00376339# #Write a program that takes a user input string and outputs every second word# string = "The quick broen fox jumps over the lazy dog" even_words = string.split(' ')[::2] #split the original string. Then use slice to select every second word# # For method and refernces please see accompying README file in GITHUB repository #
# # This file is part of pySMT. # # Copyright 2014 Andrea Micheli and Marco Gario # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class Interpolator(object): def __init__(self): self._destroyed = False def binary_interpolant(self, a, b): """Returns a binary interpolant for the pair (a, b), if And(a, b) is unsatisfaiable, or None if And(a, b) is satisfiable. """ raise NotImplementedError def sequence_interpolant(self, formulas): """Returns a sequence interpolant for the conjunction of formulas, or None if the problem is satisfiable. """ raise NotImplementedError def __enter__(self): """Manage entering a Context (i.e., with statement)""" return self def __exit__(self, exc_type, exc_val, exc_tb): """Manage exiting from Context (i.e., with statement) The default behaviour is to explicitely destroy the interpolator to free the associated resources. """ self.exit() def exit(self): """Destroys the solver and closes associated resources.""" if not self._destroyed: self._exit() self._destroyed = True def _exit(self): """Destroys the solver and closes associated resources.""" raise NotImplementedError
def left(i): return 2*i+1 def right(i): return 2*i+2 def max_heapify(data, size, i): l = left(i) r = right(i) val = data[i] largest = i if l < size and data[l] > data[largest]: largest = l if r < size and data[r] > data[largest]: largest = r if largest != i: data[largest], data[i] = data[i], data[largest] max_heapify(data, size, largest) def build_max_heap(data): n = len(data)//2-1 for i in range(n, -1, -1): max_heapify(data, len(data), i) def heapsort(data, k): build_max_heap(data) size = len(data) for i in range(size-1, k-1, -1): data[i], data[0] = data[0], data[i] size -= 1 max_heapify(data, size, 0) def solution(a, k): heapsort(a, k) return a if __name__ == "__main__": r = solution([4, 1, 3, 2, 16, 9, 10, 14, 8, 7], 1) print(r)
# Calculate the standard deviation by taking the square root port_standard_dev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) # Print the results print(str(np.round(port_standard_dev, 4) * 100) + '%')
class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 self.res = 0 self.dfs(root) return self.res-1 def dfs(self, root): if not root: return 0 left = self.dfs(root.left) right = self.dfs(root.right) self.res = max(self.res, left+right+1) return max(left, right) +1
def partida_ajedrez(nombrefichero): tablero_inicial = '♜\t♞\t♝\t♛\t♚\t♝\t♞\t♜\n♟\t♟\t♟\t♟\t♟\t♟\t♟\t♟\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n♙\t♙\t♙\t♙\t♙\t♙\t♙\t♙\n♖\t♘\t♗\t♕\t♔\t♗\t♘\t♖' tablero = [] for i in tablero_inicial.split('\n'): tablero.append(i.split('\t')) f = open(nombrefichero, "w") for i in partida_ajedrez: f.write('\t'.join(i) + '\n') f.close() movimiento = 0 while True: seguirjugando = input("Deseas hacer otro movimiento (si/no): ") if seguirjugando == "no" : break else: filainicial = int(input("Introduce la fila de la pieza a mover: ")) columnainicial = int(input("Introduce la columna de la pieza a mover: ")) filadestino = int(input("Introduce la fila de destino: ")) columnadestino = int(input("Introduce la columna de destino: ")) tablero[filadestino-1][columnadestino-1] = tablero[filainicial-1][columnainicial-1] tablero[filainicial-1][columnainicial-1] = " " movimiento += 1 f = open("nombrefichero", "a") f.write("Movimiento" + str(movimiento) + '\n') for i in tablero: f.write('\t'.join(i) + '\n') f.close() return(partida_ajedrez) partida_ajedrez("partida1.txt") def tablero(nombre_fichero, n): f = open(nombre_fichero, 'r') tableros = f.read().split('\n') for i in tableros[n*9:n*9+8]: print(i) return tablero('partida1.txt', 2)
def _set_status(task_list, task_name, status): task = task_list.get_task(task_name) task.status = status def done(task_list, args): _set_status(task_list, args.task, "completed") return def start(task_list, args): _set_status(task_list, args.task, "started") return def pause(task_list, args): _set_status(task_list, args.task, "paused") return
# coding: utf-8 class ArrayBasedQueue: def __init__(self): self.array = [] def __len__(self): return len(self.array) def __iter__(self): for item in self.array: yield item # O(1) def enqueue(self, value): self.array.append(value) # O(n) def dequeue(self): try: return self.array.pop(0) except IndexError: raise ValueError('queue is empty')
# -*- coding:utf-8 -*- class Trade(object): """ 交易模块基类,根据模型预测的涨跌信号和实时数据发出交易指令 """ def __init__(self): self.tradeinfo = [] def trade(self, signal, dataset): """ 交易 :param signal: 模型预测的涨跌信号(+-1,0) :param dataset: 实时行情,DataSet基类 :return: 交易指令 """ pass def rcvtrade(self, trade): print(*trade) if isinstance(trade, list): self.tradeinfo += trade else: self.tradeinfo.append(trade) class Deal(object): """ 每笔交易记录。如果涉及多笔交易记录,用list<Deal>存储 """ __slots__ = ('time', 'target', 'amount', 'price') def __init__(self, time, target, amount, price): """ 初始化函数 :param time: 交易时间 :param target: 交易标的 :param amount: 成交量,以股为单位,<0为做空,>0为做多 :param price: 成交金额 :return: """ self.time = time self.target = target self.amount = amount self.price = price def __str__(self): return "Deal: <time: {0}, target: {1}, amount: {2}, price: {3}>".format(self.time, self.target, self.amount, self.price) if __name__ == "__main__": print(*[Deal(1, 2, 3, 4), Deal(5,6,7,8)])
#1. Create a greeting for your program. print("\nSimple Name Generator\n") #2. Ask the user for the city that they grew up in. #raw_input() for python v2 , input() for python v3 # Make sure the input cursor shows on a new line raw_input("Press enter : ") print("\nSimple Name Generator\n") city = raw_input("What is the name of the city you grew up ? : ") #3. Ask the user for the name of a pet. # Make sure the input cursor shows on a new line family_name = raw_input("What is your family name ? : ") #4. Combine the name of their city and pet and show them their brand name. print("The name of your new brand is: \n" + city + " " + family_name )
class Solution: def solve(self, height, blacklist): blacklist = set(blacklist) if height in blacklist: return 0 dp = [[0,1]] MOD = int(1e9+7) for i in range(1,height+1): if height-i in blacklist: dp.append([0,0]) continue ans0,ans1 = 0,0 ans0 += dp[i-1][1] if i-1>=0 else 0 ans0 += dp[i-2][1] if i-2>=0 else 0 ans0 += dp[i-4][1] if i-4>=0 else 0 ans0 %= MOD ans1 += dp[i-1][0] if i-1>=0 else 0 ans1 += dp[i-3][0] if i-3>=0 else 0 ans1 += dp[i-4][0] if i-4>=0 else 0 ans1 %= MOD dp.append([ans0,ans1]) # print(dp) return sum(dp[-1])%MOD
""" [A. Is it rated?](https://codeforces.com/contest/1331/problem/A) """ print("No") # The contest was not rated
def addFeatureDataStruc(data): data['LenCarName']=data['car name'].apply(lambda x: len(x.split())) newFeat=[ 'cylinders', 'displacement', 'horsepower', 'weight','acceleration','lrScore','LenCarName'] return data[newFeat],data[['mpg']]
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: min_heap.py @time: 2019/4/29 20:23 @desc: ''' # please see the comments in max_heap.py def min_heap(array): if not array: return None length = len(array) if length == 1: return array for i in range(length // 2 - 1, -1, -1): current_idx = i temp = array[current_idx] flag = False while not flag and 2 * current_idx + 1 < length: left_idx = 2 * current_idx + 1 idx = left_idx if left_idx + 1 < length and array[left_idx] > array[left_idx + 1]: idx = left_idx + 1 if temp > array[idx]: array[current_idx] = array[idx] current_idx = idx else: flag = True array[current_idx] = temp if __name__ == '__main__': array = [7,6,5,4,3,2,1] min_heap(array) print(array)
# -*- coding: utf-8 -*- #Lists myList = [1, 2, 3, 4, 5, "Hello"] print(myList) print(myList[2]) print(myList[-1]) myList.append("Simo") print(myList) #Tuples - like lists, but you cannot modify their values. monthsOf = ("Jan","Feb","Mar","Apr") print(monthsOf) #Dictionary - a collection of related data PAIRS myDict = {"One":1.35, 2.5:"Two Point Five", 3:"+", 7.9:2} print(myDict) del myDict["One"] print(myDict)
cobranca_sob_ameaca = [ """ DECISÃO 1) Preenchidos os requisitos legais, defiro a gratuidade de justiça requerida pela parte autora, uma vez demonstrada a sua situação de hipossuficiência econômica, através dos documentos acostados junto à petição inicial. ANOTE-SE ONDE C$ 2) Pretende a parte autora o deferimento da tutela de urgência para determinar que a parte ré exclua o seu nome dos cadastros restritivos de crédito, sob pena de multa a ser arbitrada pelo juízo. Aduz que possui contrato de prestação de serviços com a requerida e que, durante o ano de 2017, possuía uma média de consumo de 90kwh, em torno de R$ 60,00. Salienta que a fatura com vencimento em junho/2017 veio no valor de R$ 1.373,50, decorrente de um TOI, acusando um consumo de 1.492 kwh. Em virtude do inadimplemento da referida fatura, seu nome foi incluído nos cadastros restritivos. Informa que a partir de julho/2017 a requerida passou a não emitir qualquer fatura em seu nome e seu consumo se encontra zerado. Dispõe o artigo 300 do Novo Código de Processo Civil que a tutela de urgência será concedida quando houver elementos que evidenciem a probabilidade do direito e o perigo de dano ou o risco ao resultado útil do processo. Entretanto, a antecipação de tutela, previamente à oitiva da parte contrária e em fase de cognição sumária, é medida excepcional, ao mitigar a garantia constitucional do contraditório, sendo deferida quando convencido o Julgador da prob$ Analisando os argumentos expendidos na inicial, bem assim a documentação colacionada pelo autor, não verifico presentes os requisitos autorizadores do deferimento da medida, especialmente a verossimilhança alegada, visto que, consoante $ Nesse sentido, a iterativa jurisprudência deste Tribunal: Direito do consumidor. Inscrição do nome da autora no SERASA. Autora que alega que a ´negativação´ se deu em razão do pagamento mínimo da fatura vencida em novembro de 2010. Inadimplemento da fatura de setembro do mesmo ano que deu orig$ Assim, estando ausentes os pressupostos autorizadores previstos no artigo 300 do NCPC, INDEFIRO, POR ORA, O PEDIDO DE TUTELA ANTECIPADA. 3) Considerando que este órgão jurisdicional não conta com conciliador ou mediador nomeado pelo Tribunal de Justiça, bem como que em causas semelhantes, invariavelmente as partes manifestam a total ausência de intenção de transigir send$ Resta certo, no entanto, que poderá ser designada audiência de conciliação se as partes demonstrarem intuito de transação e assim o requererem, a qualquer momento. Determino a citação da parte ré por carta ´AR´ para que apresente contestação, querendo, no prazo de 15 dias úteis contados da juntada do comprovante de citação. Com a resposta do réu, a serventia deverá certificar sua tempestividade. Em havendo reconvenção, impugnação, exceção ou qualquer tipo de intervenção de terceiros na defesa, a serventia deverá certificar o recolhimento exato e integral das custas e em caso negativo os autos deverão ser remetidos à conclusão p$ 4) Sem prejuízo, manifeste-se ainda quanto à eventual prescrição ou decadência do direito que fundamenta a sua pretensão e sobre o preenchimento, especificadamente, das condições da ação proposta e de seus pressupostos processuais, no p$ """ ] nao_cobranca_sob_ameaca = [ """ OMOLOGO o projeto de sentença proferido pelo Juiz Leigo, para que produza seus jurídicos e legais efeitos, na forma do art. 40 da Lei 9.099/95. Até deliberação em contrário, os prazos em sede de Juizados Especiais Cíveis continuarão a ser contados em dias corridos, sendo inaplicável o artigo 219 do NCPC, nos termos do Aviso Cojes nº 02/2016, publicado no DOERJ de 31.03.2016, p. 25. Nas Sentenças de procedência, com obrigação de pagar, fica a parte ré ciente de que caso não pague a quantia certa a que foi condenada em 15 dias, contados do trânsito em julgado da sentença, o valor da condenação será acrescido de multa de 10%, por aplicação do artigo 523, §1º do CPC, sendo certo, ainda, que a comprovação do depósito deverá vir aos autos até o 5º dia após o término do referido prazo. Fica desde já cientificado o credor de que não incidem, em sede de Juizados Especiais Cíveis, honorários na fase de execução, eis que o rol do artigo 55 da Lei 9.099/95 é taxativo, o que atende, ainda, à atual redação do Enunciado nº 97 do FONAJE. Comprovado o depósito, após a quitação integral das obrigações de pagar e fazer impostas na sentença, expeça-se mandado de pagamento em favor da parte autora. Após, dê-se baixa e arquive-se. Caso negativo, após o decurso do prazo de trinta dias do trânsito em julgado, não havendo manifestação, dê-se baixa e arquive-se. Cientes as partes, na forma do artigo 1º, § 1º do Ato Normativo Conjunto 01/2005 (modificado pelo Ato Executivo TJ 5156/09), que os autos processuais findos serão eliminados após o prazo de 90 (noventa) dias da data do arquivamento definitivo. P. I. Registrada eletronicamente. """ ] cobranca_servico_nao_fornecido = [ """ Em 23 de outubro de 2017, na sala de audiências deste Juízo, perante a M.M. Dra. Juíza de Direito ANNA CAROLINNE LICASALIO DA COSTA, foi aberta a audiência designada nos autos. Ao pregão, respondeu a parte autora; bem como o réu, por seu preposto, devidamente acompanhado de seu advogado, ambos devidamente constituídos, conforme documentos de representação (carta de preposição e procuração/substabelecimento). Proposta a conciliação entre as partes, ela restou infrutífera. A parte autora juntou documentos, dos quais teve vista a parte ré. A parte ré apresentou sua contestação escrita. Pelas partes foi dito não haver mais qualquer prova a ser produzida nos autos, reportando-se às suas manifestações anteriores. PELA MM. DRA. JUÍZA FOI PROFERIDA A SEGUINTE SENTENÇA: Dispenso o relatório, com fulcro no art. 38 da Lei nº 9.099/95. Segundo se infere da documentação apresentada pela autora nos autos, até a inspeção da Light não era medido qualquer consumo de energia. Consoante histórico contido nas faturas recentes, desde, pelo menos, ano passado o consumo sempre esteve zerado, pagando autor apenas pelo custo de disponibilidade do sistema. Com a troca do medido, o consumo saiu de 0 para 195, 57 e 63kwh, em cada um os meses seguintes. Infere-se, portanto, que de fato o medidor anterior estava defeituoso, com prejuízo à cobrança da LIGHT. Contudo, a verificação do montante que deixou de ser pago e a correção dos valores que estão sendo cobrados pela LIGHT enfrenta a necessidade de produção de prova pericial, incompatível com o rito sumaríssimo, sobretudo no âmbito dos ônibus da justiça itinerante. Assim, em razão da complexidade da causa, JULGO EXTINTO O FEITO SEM RESOLUÇÃO DE MÉRITO, nos termos do artigo 485, inciso IV, do NCPC, em razão da incompetência do juízo. Sem custas em função do rito, Certificado o trânsito em julgado, nada mais sendo requerido, dê-se baixa e arquivem-se. Publicada em audiência. Intimados os. Cientes os presentes. Nada mais havendo, encerrou-se o ato às 10h48. """ ] nao_cobranca_servico_nao_fornecido_toi = [ """ Em 23 de outubro de 2017, na sala de audiências deste Juízo, perante a M.M. Dra. Juíza de Direito ANNA CAROLINNE LICASALIO DA COSTA, foi aberta a audiência designada nos autos. Ao pregão, respondeu a parte autora; bem como o réu, por seu preposto, devidamente acompanhado de seu advogado, ambos devidamente constituídos, conforme documentos de representação (carta de preposição e procuração/substabelecimento). Proposta a conciliação entre as partes, ela restou infrutífera. A parte autora juntou documentos, dos quais teve vista a parte ré. A parte ré apresentou sua contestação escrita. TOI Pelas partes foi dito não haver mais qualquer prova a ser produzida nos autos, reportando-se às suas manifestações anteriores. PELA MM. DRA. JUÍZA FOI PROFERIDA A SEGUINTE SENTENÇA: Dispenso o relatório, com fulcro no art. 38 da Lei nº 9.099/95. Segundo se infere da documentação apresentada pela autora nos autos, até a inspeção da Light não era medido qualquer consumo de energia. Consoante histórico contido nas faturas recentes, desde, pelo menos, ano passado o consumo sempre esteve zerado, pagando autor apenas pelo custo de disponibilidade do sistema. Com a troca do medido, o consumo saiu de 0 para 195, 57 e 63kwh, em cada um os meses seguintes. Infere-se, portanto, que de fato o medidor anterior estava defeituoso, com prejuízo à cobrança da LIGHT. Contudo, a verificação do montante que deixou de ser pago e a correção dos valores que estão sendo cobrados pela LIGHT enfrenta a necessidade de produção de prova pericial, incompatível com o rito sumaríssimo, sobretudo no âmbito dos ônibus da justiça itinerante. Assim, em razão da complexidade da causa, JULGO EXTINTO O FEITO SEM RESOLUÇÃO DE MÉRITO, nos termos do artigo 485, inciso IV, do NCPC, em razão da incompetência do juízo. Sem custas em função do rito, Certificado o trânsito em julgado, nada mais sendo requerido, dê-se baixa e arquivem-se. Publicada em audiência. Intimados os. Cientes os presentes. Nada mais havendo, encerrou-se o ato às 10h48. """ ] nao_cobranca_servico_nao_fornecido = [ """ Trata-se de ação de obrigação de fazer combinada com indenizatória proposta por LUIZ ALBERTO MIRANDA NUNES em face de LIGHT - SERVIÇOS DE ELETRICIDADE S/A. Decisão a fls. 40 indeferindo a gratuidade de justiça à parte autora e determinando o recolhimento das custas no prazo de 15 (quinze) dias, sob pena de extinção. Petição da parte autora a fls. 46 requerendo a reconsideração do indeferimento da gratuidade de justiça. O despacho de fls. 55 manteve a decisão de fls. 40. Certidão a fls. 57 informando que não houve o recolhimento das custas e que a decisão de fls. 40 precluiu. É O BREVE RELATÓRIO. DECIDO. Com efeito, consoante o artigo 290 do novo Código de Processo Civil, será cancelada a distribuição do feito se a parte, intimada na pessoa de seu advogado, não realizar o pagamento das custas e despesas de ingresso em 15 (quinze) dias. No caso vertente, a parte autora teve indeferido o pedido de gratuidade de justiça e foi intimada a efetuar o recolhimento das custas processuais, conforme decisão de fls. 40. Não obstante, esta quedou-se inerte (fls. 57), deixando de recolher as custas processuais no prazo legal. Insta mencionar que a novel codificação processual civil, nos termos do supracitado artigo 290, encerrando controvérsia doutrinária quanto à necessidade de intimação pessoal da parte, estabeleceu de forma peremptória que a intimação para recolhimento das custas ocorrerá na pessoa do advogado. Assim, na ausência de pressuposto de constituição e de desenvolvimento válido e regular do processo, caracterizada por falta de preparo, determino o cancelamento da distribuição. Pelo exposto, JULGO EXTINTO O PROCESSO sem exame de mérito, na forma do artigo 485, IV, c/c artigo 290, do CPC. Condeno a parte autora ao pagamento das custas processuais. Transitada em julgado, cancele-se a distribuição e arquive-se. P.I. Na forma do inciso I do art. 229-A da Consolidação Normativa da CGJ, acrescentado pelo Provimento 20/2013, ficam as partes, desde logo, intimadas para dizer se tem algo mais a requerer. """ ] dano_eletrodomestico = [ """ 1. Defiro JG. Considerando a probabilidade do direito que se pretende antecipar, que decorre da impugnação dirigida ao lavrado pela ré, de forma unilateral, bem como o perigo de dano ou risco ao resultado útil do processo, que se depreende da incidência imediata das sanções deste decorrentes (referidas a serviço de natureza essencial), e, ainda, a inexistência do perigo de irreversibilidade dos efeitos desta decisão, pela possibilidade de ulterior dos valores com juros, se alteradas as razões desta decisão, entendo presentes os requisitos legais do artigo 300 do CPC e concedo a tutela de urgência incidente antecipada, determinado que a parte ré que se abstenha de interromper """ ] nao_dano_eletrodomestico_toi = [ """ 1. Defiro JG. Considerando a probabilidade do direito que se pretende antecipar, que decorre da impugnação dirigida ao termo de ocorrência de irregularidade lavrado pela ré, de forma unilateral, bem como o perigo de dano ou risco ao resultado útil do processo, que se depreende da incidência imediata das sanções deste decorrentes (referidas a serviço de natureza essencial), e, ainda, a inexistência do perigo de irreversibilidade dos efeitos desta decisão, pela possibilidade de ulterior dos valores com juros, se alteradas as razões desta decisão, entendo presentes os requisitos legais do artigo 300 do CPC e concedo a tutela de urgência incidente antecipada, determinado que a parte ré que se abstenha de interromper """ ] nao_dano_eletrodomestico = [ """ 1. Defiro JG. Considerando a probabilidade do direito que se pretende antecipar, que decorre da impugnação dirigida ao lavrado pela ré, de forma unilateral, bem como o perigo de ou risco ao resultado útil do processo, que se depreende da incidência imediata das sanções deste decorrentes (referidas a serviço de natureza essencial), e, ainda, a inexistência do perigo de irreversibilidade dos efeitos desta decisão, pela possibilidade de ulterior dos valores com juros, se alteradas as razões desta decisão, entendo presentes os requisitos legais do artigo 300 do CPC e concedo a tutela de urgência incidente antecipada, determinado que a parte ré que se abstenha de interromper """ ] dificuldade_contratar = [ """De análise dos documentos acostados, verifico que o débito apontado é do antigo morador, visto que o contrato de locação do imóvel foi assinado pelo autor em julho do ano em curso. Assim, entendo que presentes os pressupostos do artigo 300 do CPC/2015, e tratando-se de serviço essencial, indispensável à sobrevivência, devendo ser prestado de forma adequada, eficiente, segura e contínua, DEFIRO o pedido de antecipação dos efeitos da tutela para determinar que a parte ré realize a transferência de titularidade dos serviços vinculados ao imóvel situado na Estrada Rio do A nº 1.711 Loja D, Campo Grande, CEP.: 23080-300 para o nome da parte autora, restabelecendo o serviço de energia elétrica no local, no prazo de 24 horas, sob pena de multa diária no valor de R$ 300,00 a vigorar, inicialmente, pelo prazo de 30 dias, devendo a parte informar ao juízo em caso de descumprimento, para a tomada das providências cabíveis. Intime-se. """ ] interrupcao_fornecimento = [ """ A interrupção do serviço afeta a dignidade do consumidor que também possui proteção constitucional (artigo 1º, III da CF), pois, o fornecimento de energia elétrica à semelhança de outros como: água, transporte, esgoto, telefonia é indispensável à manutenção e preservação da vida, saúde e higiene das pessoas. A descontinuidade do serviço essencial acarreta lesão ao consumidor, sendo ilegal, pois, contrária ao CDC e à CF/88. """ ] negativacao_indevida = [ """ Depreende-se do comunicado de fl. 31 que o nome da autora fora incluído em cadastros restritivos de crédito pelo não pagamento da fatura com vencimento em 11/01/2018 (fl.39), sendo certo que nesta está incluído um dos débitos questionados pela autora nesta ação. A manutenção do nome do consumidor em rol de devedores acarreta enormes prejuízos, pois impede de realizar contratos que impulsionam a vida em nossa sociedade, que à evidência impõe a celebração de diversos contratos em especial os de natureza creditícia, já que vivemos em uma sociedade eminentemente capitalista, assim, para evitar danos de ordem moral e material à autora, seu nome deve ser retirado do cadastro de devedores. """ ] nao_negativacao_indevida = [ """ Trata-se de pedido de tutela provisória, visando a parte autora a que a ré se abstenha de suspender o fornecimento de energia elétrica em sua residência, em razão de suposto débito apurado unilateralmente e que deu azo à lavratura de ´TOI´, bem como de incluir, ou se já estiver incluído, que exclua o nome do autora no cadastro de maus pagadores, e cobrar nas faturas o parcelamento a ela imposto, até ulterior decisão. """ ] dificuldade_renegociacao = [ """ Trata-se de pedido de antecipação de tutela, formulado pela autora em razão de irregularidades na cobrança de parcelamento efetivado junto à concessionária, pleiteando a mesma que a empresa ré se abstenha de incluir seu nome no cadastro de inadimplentes, e, ainda, não proceda à eventual interrupção no fornecimento de energia elétrica que abastece a sua residência. """ ] sac = [ """ Aduz que entrou em contato mais de uma vez com a ré, através do SAC 0800-282.0120, e requereu o cancelamento das cobranças e restituição dos referidos valores, tendo sido informado na ocasião que se tratava de suposto TOI, contudo até o presente momento nenhum esclarecimento foi dado e nenhuma providência adotada. """ ] tarifa = [ """ Tendo em vista que a tarifa de fornecimento de energia elétrica é obrigação pessoal, com natureza contratual e, não é uma obrigação propter rem, o débito tarifário não pode ser transferido ao novo usuário do serviço essencial, nos termos da súmula nº 196 deste EgrégioTribunal. Assim sendo, a recusa do restabelecimento do fornecimento de energia elétrica ao autor no caso em tela é injustificada. """ ]
SCAN_COMMANDS = {'arp', 'arp-scan', 'fping', 'nmap'} def rule(event): # Filter out commands if event['event'] == 'session.command' and not event.get('argv'): return False # Check that the program is in our watch list return event.get('program') in SCAN_COMMANDS def title(event): return 'User [{}] has issued a network scan with [{}]'.format( event.get('user', 'USER_NOT_FOUND'), event.get('program', 'PROGRAM_NOT_FOUND'))
def getPeopleHarvest(req): try: # result = req.get("result") # username = "pescettoe@amvbbdo.com" # password = "Welcome1!" # top_level_url = "https://xlaboration.harvestapp.com/people/1514150" # # # create an authorization handler # p = urllib.request.HTTPPasswordMgrWithDefaultRealm() # p.add_password(None, top_level_url, username, password); # auth_handler = urllib.request.HTTPBasicAuthHandler(p) # opener = urllib.request.build_opener(auth_handler) # opener.addheaders = [("Authorization", "Basic cGVzY2V0dG9lQGFtdmJiZG8uY29tOldlbGNvbWUxIQ==")] # opener.addheaders = [("Accept", "application/json")] # opener.addheaders = [("Content-Type", "application/json")] # # opener.add_header("Accept", "application/json") # # opener.add_header("Content-Type", "application/json") # urllib.request.install_opener(opener) # result = opener.open(top_level_url) # a = result.read() # data = json.loads(a) # res = makeWebhookHarvestPeople(data) # return res q = Request("https://xlaboration.harvestapp.com/people/1514150") q.add_header("Authorization", "Basic cGVzY2V0dG9lQGFtdmJiZG8uY29tOldlbGNvbWUxIQ==") q.add_header("Accept", "application/json") q.add_header("Content-Type", "application/json") a = urlopen(q).read() data = json.loads(a) res = makeWebhookResult(data) return res except: speech = sys.exc_info()[0] displayText = traceback.print_exc() print("Response:") print(speech) return { "speech": speech, "displayText": displayText, # "data": data, # "contextOut": [], "source": "apiai-weather-webhook-sample" }
""" URL: https://codeforces.com/problemset/problem/1421/A Author: Safiul Kabir [safiulanik at gmail.com] Tags: bitmasks, math """ t = int(input()) for _ in range(t): a, b = map(int, input().split()) print(a ^ b)
ASCII = [c for c in (chr(i) for i in range(32, 127))] def cipher(text, key, decode): op = '' for i, j in enumerate(text): if j not in ASCII: op += j else: text_index = ASCII.index(j) k = key[i % len(key)] key_index = ASCII.index(k) if decode: key_index *= -1 code = ASCII[(text_index + key_index) % len(ASCII)] op += code return op def main(): print(cipher('Aditya', 'Upadhyay', 0)) print(cipher('vUKYb[', 'Upadhyay', 1)) main()
# Exercício Python 01 - Aprovando Empréstimo #Exercício: 01 Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. casa = float(input('Valor da Casa: R$')) salario = float(input('Salario do comprador: R$')) anos = int(input('Quantos anos de fincanciamento? ')) prestação = casa/(anos * 12) minimo = salario * 30 / 100 print('Para pagar unma casa de R${:.2f} em {} anos '.format(casa,anos), end='') print('A prestação será de {:.2f}'.format(prestação)) if prestação <= minimo: print('Emprestimo pode ser CONCEDIDO !') else: print('Emprestimo ! NEGADO !')
"""This is a 'Hello, world' program.""" def hello(): """Say, hello.""" print("Hello, World!") if __name__ == "__main__": hello()
''' Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. Hint: In case of input data being supplied to the question, it should be assumed to be a console input. ''' print('Input number word for : ') n = input() mp = list(map(lambda x: ord(x), n)) mp.sort() mc = list(map(lambda y: chr(y), mp)) dd = '' for z in mc : dd = dd + z print(dd)
class subject (): def __init__(self): x=[] self.students=[] def addstudents(self): n=int(input("Enter No. Of Students :- ")) for i in range (n): self.name=input("Enter Name :- ") self.rno=input("Enter Roll No. :- ") self.marks=input("Enter Total Marks :- ") print() self.students+=[[self.name,self.rno,self.marks]] print("ORIGINAL LIST :- ",self.students) def final(self): v=len(self.students) for i in range(v): minpos=i for j in range(i+1,v): if self.students[j][2]>self.students[i][2]: minpos=j temp=self.students[minpos] self.students[minpos]=self.students[i] self.students[i]=temp print() print("SORTED LIST :- ",self.students) a=subject() a.addstudents() a.final()
def make_dot(count, left, right): if left == "" and right == "": return count * "." if right == "": if left == "L": return '.'*count else: return 'R'*count if left == "": if right == "L": return count * "L" else: return count * "." if left == "L" and right == "R": return '.'*count elif right == "L" and left == "R": if count % 2 == 1: return ((count//2) * "R") + "." + ((count//2) * "L") else: return (count//2) * 'R' + 'L' * (count//2) elif left == "L" and right == "L": return count*'L' elif left == "R" and right == "R": return count*'R' class Solution: def pushDominoes(self, dominoes): result_list = [] letter_cache = [] last = '' dot_count = 0 for i in dominoes: if i == ".": if last != '' and last != '.': result_list.append("".join(letter_cache)) letter_cache = [] dot_count += 1 else: if last == ".": result_list.append(dot_count) letter_cache.append(i) dot_count = 0 else: letter_cache.append(i) last = i if dot_count != 0: result_list.append(dot_count) elif letter_cache != []: result_list.append("".join(letter_cache)) print(result_list) for ind in range(len(result_list)): left = '' right = '' if type(result_list[ind]) == int: if ind-1 >= 0: left = result_list[ind-1][-1] if ind+1 < len(result_list): right = result_list[ind+1][0] result_list[ind] = make_dot(result_list[ind], left, right) return "".join(result_list) a = Solution() a.pushDominoes(".L.R...LR..L..") == "LL.RR.LLRRLL.." a.pushDominoes("RR.L") == "RR.L" a.pushDominoes(".") == "." a.pushDominoes("LL") == "LL"
{ 'FONTS': [ ('杨任东竹石体-Regular.ttf', '杨任东竹石体-Regular'), ('杨任东竹石体-Semibold.ttf', '杨任东竹石体-Semibold') ], }
"""Do a one-time build of default.png""" # Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. if __name__ == '__main__': f = file('default.png', 'rb') default_png = f.read() f.close() f = file('_default_png.py', 'wU') f.write('DEFAULT_PNG = %r\n' % default_png) f.close()
""" docsting of empty_all module. """ __all__ = [] def foo(): """docstring""" def bar(): """docstring""" def baz(): """docstring"""
load( "@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context", ) load( "@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibrary", "DotnetResource", ) load( "@io_bazel_rules_dotnet//dotnet/private:rules/launcher_gen.bzl", "dotnet_launcher_gen", ) def _core_binary_impl(ctx): """dotnet_binary_impl emits actions for compiling dotnet executable assembly.""" dotnet = dotnet_context(ctx) name = ctx.label.name executable = dotnet.binary(dotnet, name = name, srcs = ctx.attr.srcs, deps = ctx.attr.deps, resources = ctx.attr.resources, out = ctx.attr.out, defines = ctx.attr.defines, unsafe = ctx.attr.unsafe, data = ctx.attr.data, ) return [ DefaultInfo( files = depset([executable.result]), runfiles = ctx.runfiles(files = ctx.attr._native_deps.files.to_list() + [dotnet.runner], transitive_files = executable.runfiles), executable = executable.result, ), ] _core_binary = rule( _core_binary_impl, attrs = { "deps": attr.label_list(providers=[DotnetLibrary]), "resources": attr.label_list(providers=[DotnetResource]), "srcs": attr.label_list(allow_files = FileType([".cs"])), "out": attr.string(), "defines": attr.string_list(), "unsafe": attr.bool(default = False), "data": attr.label_list(allow_files = True), "_dotnet_context_data": attr.label(default = Label("@io_bazel_rules_dotnet//:core_context_data")), "_native_deps": attr.label(default = Label("@core_sdk//:native_deps")) }, toolchains = ["@io_bazel_rules_dotnet//dotnet:toolchain_core"], executable = True, ) def core_binary(name, srcs, deps = [], defines = None, out = None, resources = None, data = None): _core_binary(name = "%s_exe" % name, deps = deps, srcs = srcs, out = out, defines = defines, resources = resources, data = data) exe = ":%s_exe" % name dotnet_launcher_gen(name = "%s_launcher" % name, exe = exe) native.cc_binary( name=name, srcs = [":%s_launcher" % name], deps = ["@io_bazel_rules_dotnet//dotnet/tools/runner_core", "@io_bazel_rules_dotnet//dotnet/tools/common"], data = [exe], )
if sys.version_info.minor > 9: phr = {"user_id": user_id} | content else: z = {"user_id": user_id} phr = {**z, **content}
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k <= 1 : return 0 prod =1 res = 0 i,j = 0, 0 while j < len(nums): prod *= nums[j] if prod < k : res += (j-i+1) elif prod >= k : while prod >= k : prod = prod//nums[i] i+=1 res += j-i+1 j+=1 return res
""" This module defines the learner interface. """ class Learner: """ A learner ingests data, manipulates internal state by learning off this data, supplies agents for taking further actions, and provides an opaque interface to internal evaluation. """ def train(self, data, timesteps): """ Fit the learner using the given dataset of transitions. data is the current ringbuffer and timesteps indicates how many new transitions we have just sampled. """ raise NotImplementedError def agent(self): """ Return an agent.Agent to take some actions. """ raise NotImplementedError def tf_action(self, states_ns): """ Accept a TF state and return a TF tensor for the action this learner would have taken. This is used to evaluate the dynamics quality, so take the action that is used to expand dynamics if the learner uses a dynamics model for planning or learning. """ raise NotImplementedError def evaluate(self, data): """ Report evaluation information. """ raise NotImplementedError
# helpers def create_data_list(dic): """ This function creates a list from a data dictionary where all user data is stored """ lst = [] lst.append(dic['cough']) lst.append(dic['fever']) lst.append(dic['sore_throat']) lst.append(dic['shortness_of_breath']) lst.append(dic['head_ache']) lst.append(int(dic['age'])) lst.append(dic['gender']) lst.append(dic['additional_factor']) return lst
# -*- coding: utf-8 -*- # ScrollBar part codes # Left arrow of horizontal scroll bar. # @see ScrollBar::scrollStep sbLeftArrow = 0 # Right arrow of horizontal scroll bar. # @see ScrollBar::scrollStep sbRightArrow = 1 # Left paging area of horizontal scroll bar. # @see ScrollBar::scrollStep sbPageLeft = 2 # Right paging area of horizontal scroll bar. # @see ScrollBar::scrollStep sbPageRight = 3 # Top arrow of vertical scroll bar. # @see ScrollBar::scrollStep sbUpArrow = 4 # Bottom arrow of vertical scroll bar. # @see ScrollBar::scrollStep sbDownArrow = 5 # Upper paging area of vertical scroll bar. # @see ScrollBar::scrollStep sbPageUp = 6 # Lower paging area of vertical scroll bar. # @see ScrollBar::scrollStep sbPageDown = 7 # Position indicator on scroll bar. # @see ScrollBar::scrollStep sbIndicator = 8 # ScrollBar options for Window.StandardScrollBar # The scroll bar is horizontal. # @see Window::standardScrollBar sbHorizontal = 0x000 # The scroll bar is vertical. # @see Window::standardScrollBar sbVertical = 0x001 # The scroll bar responds to keyboard commands. # @see Window::standardScrollBar sbHandleKeyboard = 0x002
BLACK = u"\u001b[30m" RED = u"\u001b[31m" GREEN = u"\u001b[32m" YELLOW = u"\u001b[33m" BLUE = u"\u001b[34m" MAGENTA = u"\u001b[35m" CYAN = u"\u001b[36m" WHITE = u"\u001b[37m" BBLACK = u"\u001b[30;1m" BRED = u"\u001b[31;1m" BGREEN = u"\u001b[32;1m" BYELLOW = u"\u001b[33;1m" BBLUE = u"\u001b[34;1m" BMAGENTA = u"\u001b[35;1m" BCYAN = u"\u001b[36;1m" BWHITE = u"\u001b[37;1m" RESET = u"\u001b[0m"
""" Modulo -> apenas um arquivo python Pacote -> pe um diretório contendo um coleção de módulos OBS.: Nas versões do python abaixo de 3, os pacotes deveriam conter um arquivo chamado __init__.py Nas versões acima de 3, não é mais necessário. """
''' module for implementation of merge sort ''' def merge_sort(arr: list): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i, j, k = 0, 0, 0 while (i < len(L) and j < len(R)): if (L[i] < R[j]): arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while (i < len(L)): arr[k] = L[i] i += 1 k += 1 while (j < len(R)): arr[k] = R[j] j += 1 k += 1 return arr ''' PyAlgo Devansh Singh, 2021 '''
#!/usr/bin/env python3 class MessageBroadcast: def __init__(self, friend_graph, start_person): self.friend_graph = friend_graph self.start_person = start_person self.people_without_message = list(friend_graph.keys()) self.step_number = 0 self.new_people_with_message_in_last_step = [] def broadcast(self): self.people_without_message.remove(self.start_person) self.new_people_with_message_in_last_step.append(self.start_person) while len(self.people_without_message) > 0 and len(self.new_people_with_message_in_last_step) > 0: self.broadcast_step() self.step_number += 1 def broadcast_step(self): people_who_broadcast_in_this_step = self.new_people_with_message_in_last_step self.new_people_with_message_in_last_step = [] for broadcaster in people_who_broadcast_in_this_step: self.send_message_to_all_friends(broadcaster) def send_message_to_all_friends(self, broadcaster): friends_of_broadcaster = self.friend_graph[broadcaster] for receiver in friends_of_broadcaster: self.receive_message(receiver) def receive_message(self, receiver): if receiver in self.people_without_message: self.people_without_message.remove(receiver) self.new_people_with_message_in_last_step.append(receiver) def has_notified_every_people(self): return len(self.people_without_message) == 0 def get_number_of_steps(self): return self.step_number class Case: def __init__(self): self.friend_graph = {} self.min_steps = -1 self.start_persons_with_min_steps = [] def add_person(self, person_id, their_friends): self.friend_graph[person_id] = their_friends def run_case(self): for person in self.friend_graph: self.try_broadcast_starting_with(person) def try_broadcast_starting_with(self, person): broadcast = MessageBroadcast(self.friend_graph, person) broadcast.broadcast() if broadcast.has_notified_every_people(): steps = broadcast.get_number_of_steps() self.successful_broadcast_for(person, steps) def successful_broadcast_for(self, person, steps): if self.min_steps == -1 or steps < self.min_steps: self.new_broadcast_min_steps(steps, person) elif steps == self.min_steps: self.same_as_current_min_steps(person) def new_broadcast_min_steps(self, steps, person): self.min_steps = steps self.start_persons_with_min_steps = [person] def same_as_current_min_steps(self, person): self.start_persons_with_min_steps.append(person) def get_person_to_notify(self): if self.min_steps == -1: return "0" else: self.start_persons_with_min_steps.sort() return " ".join([str(i) for i in self.start_persons_with_min_steps]) number_of_cases = int(input()) for c in range(number_of_cases): case = Case() number_of_people = int(input()) for p in range(number_of_people): case.add_person(p + 1, [int(i) for i in input().split()]) case.run_case() print(case.get_person_to_notify())
''' pythagorean_triples.py: When given the sides of a triangle, tells the user whether the triangle is a right triangle. Based on https://www.redd.it/19jwi6 ''' while True: sides = input('Enter the three sides of a triangle, separated by spaces: ') try: sides = [int(x) for x in sides.split()] except ValueError: print('Error: please enter numbers only!') else: sides.sort() right = 'is' if (sides[0]**2 + sides[1]**2 == sides[2]**2) else 'is not' print('That {0} a right triangle.'.format(right)) if input('Would you like to check another triangle? (Y/n) ').strip()[0].lower() == 'n': break;
# -*- coding: utf-8 -*- # Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE.TXT file) ID = r"[0-9]+" SLUG = r"[a-z0-9\-]+" USERNAME = r"[\w.@+-]+" # see django.contrib.auth.forms.UserCreationForm def _build_arg(name, pattern): return "(?P<%s>%s)" % (name, pattern) def arg_id(name): return _build_arg(name, ID) def arg_slug(name): return _build_arg(name, SLUG) def arg_username(name): return _build_arg(name, USERNAME)
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT """ _decode_step_codes = { 'LE': {'mask': 0b00010000, 'test': 0b00010000}, # Laser Enable (ON) 'LP': {'mask': 0b10000000, 'test': 0b01111111}, # Laser Power Setting 'XP': {'mask': 0b00000011, 'test': 0b00000001}, # X+ Step 'XN': {'mask': 0b00000011, 'test': 0b00000011}, # X- Step 'YN': {'mask': 0b00001100, 'test': 0b00000100}, # Y- Step 'YP': {'mask': 0b00001100, 'test': 0b00001100}, # Y+ Step 'ZP': {'mask': 0b01100000, 'test': 0b00100000}, # Z+ Step 'ZN': {'mask': 0b01100000, 'test': 0b01100000}, # Z- Step } _SPEED = 1000 def decode_all_steps(puls: bytes, data: dict = None, mode: tuple = (8, 2)) -> dict: cnt = { 'XP': 0, 'XN': 0, 'XTOT': 0, 'XEND': 0, 'YP': 0, 'YN': 0, 'YTOT': 0, 'YEND': 0, 'ZP': 0, 'ZN': 0, 'ZTOT': 0, 'ZEND': 0, 'LE': 0, 'LP': 0, } for step in puls: if step & _decode_step_codes['LP']['mask']: # Power Setting (LP) cnt['LP'] = cnt['LP'] + 1 else: for action in sorted(_decode_step_codes): if not (step & _decode_step_codes[action]['mask']) ^ _decode_step_codes[action]['test']: cnt[action] = cnt[action] + 1 if action != 'LE': cnt[action[0:1] + 'TOT'] = cnt[action[0:1] + 'TOT'] + 1 cnt[action[0:1] + 'END'] = cnt[action[0:1] + 'END'] + 1 \ if action[1:2] == 'P' else cnt[action[0:1] + 'END'] - 1 for axis in ('X', 'Y'): cnt[axis + 'MM'] = (cnt[axis + 'END'] / mode[0]) * 0.15 cnt['ZMM'] = (cnt['ZEND'] / mode[1]) * 0.70612 for axis in ('X', 'Y', 'Z'): cnt[axis + 'IN'] = cnt[axis + 'MM'] / 25.4 if data is not None: for key, val in cnt.items(): cnt[key] = val + data.get(key, 0) return cnt def generate_linear_puls(x: int, y: int, outfile: str) -> None: expected_count = abs(x) if abs(x) >= abs(y) else abs(y) max_speed = 5 min_speed = 55 acc = 10 acc_dist = int((min_speed - max_speed) / acc) acc_dist = acc_dist if acc_dist < (expected_count / 2) else int(expected_count / 2) steps = 0 d = min_speed with open(outfile, 'bw') as f: for xs, ys in _step_gen(x, y): steps += 1 s = 0 if xs != 0: s |= 0b00000001 if xs > 0 else 0b00000011 if ys != 0: s |= 0b00001100 if ys > 0 else 0b00000100 f.write(bytes([s])) if steps <= acc_dist: # Accelerating d = d - acc if d > max_speed - acc else max_speed elif steps >= (expected_count - acc_dist): # Decelerating d = d + acc if d < min_speed + acc else min_speed f.write('\0'.encode() * d) def _step_gen(x: int, y: int) -> tuple: xd = 1 if x >= 0 else -1 yd = 1 if y >= 0 else -1 xt = abs(x) yt = abs(y) if xt >= yt: maj_target = xt min_target = yt maj_dir = xd min_dir = yd else: maj_target = yt min_target = xt maj_dir = yd min_dir = xd if min_target > 0: maj_per_min = round(maj_target / min_target, 4) else: maj_per_min = maj_target maj_cnt = 0 min_cnt = 0 while maj_cnt < maj_target or min_cnt < min_target: if maj_cnt < maj_target: maj_cnt += 1 if maj_cnt % maj_per_min < 1 and min_cnt < min_target: min_out = min_dir min_cnt += 1 else: min_out = 0 else: maj_dir = 0 min_out = min_dir min_cnt += 1 yield maj_dir if xt >= yt else min_out, min_out if xt >= yt else maj_dir
translations = { "startMessage": "I can help you see all of your EqualHash.pt statistics\n\nYou can control me by " "sending these " "commands:\n\n/newaddr - Add new address\n/myaddrs - View all address\n\n*Edit " "Addresses*\n/setname - Change a address's name\n/setaddress - Change the " "address\n/deleteaddr - Delete a address\n\n*Stats*\n/seestats - View " "Stats\n\n*Notifications*\n/enablenotification - Enable workers status " "notifications\n/disablenotification - Disable workers status notifications", "newAddr": "Alright, a new address. How are we going to call it? Please choose a name for your address.", "newAddr2": "All right!! Now enter the address.", "newAddr3": "Done! Congratulations for your new address:\n\nNow you can start checking your statistics, " "run the /seestats command and choose your address.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*", "delAddrC": "Choose a address to delete.", "setnameAddrC": "Choose the address to which you want to change the name.", "setcodeAddrC": "Choose the address to which you want to change the code.", "stats1": "Where do you want to consult the statistics?", "statsaddr": "My Addresses", "statsp2m": "EqualHash", "statsReturn": "<< Back to Stats", "noneAddr": "You have not added an address yet.\nYou can use the /newaddr command to add a new address.", "selectAddr": "Choose a address from the list below:", "noStats": "I'm sorry but there's still no information for this address. Try it later.", "return": "<< Return", "viewAddr": "Here it is:\n - Name: *<NAMEADDRESS>*\n - Address: *<ADDRESS>*\n\nWhat do you want to do " "with the address?", "viewStats": "See stats", "editAddr": "Edit address", "editNameAddr": "Edit name", "editCodeAddr": "Edit code", "delAddr": "Delete Address", "delAddr2": "Are you sure you want to delete the following address?\n - Name: *<NAMEADDRESS>*\n - " "Address: *<ADDRESS>*", "yesDelAddr": "Yes, delete the address", "addrDelOk": "Address deleted correctly.", "optEdit": "Select an option:", "newNameAddr": "OK. Send me the new name for your address.", "newCodeAddr": "OK. Send me the new code for your address.", "addrUpdate": "Your address information has been updated.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*", "changeWorkers": "Change in workers status:\n", "notifications": "Notifications", "descNotifications": "Activating the notification service will receive a message every time there is a change " "of status in your *Workers*.", "statusNotifications": "Status notifications: *<STATUS>*", "enableNotifications": "Choose the address you want to - *Activate* - notifications:", "disableNotifications": "Choose the address you want to - *Disable* - notifications:" }
# A Python program to demonstrate need # of packing and unpacking # A sample function that takes 4 arguments # and prints them. def fun(a, b, c, d): print(a, b, c, d) # Driver Code my_list = [1, 2, 3, 4] # This doesn't work fun(my_list)
# coding=utf-8 __author__ = "Gina Häußge <osd@foosel.net>, Christopher Bright <christopher.bright@gmail.com>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' class reverse_proxied(object): """ Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind this to a URL other than / and to an HTTP scheme that is different than what is used locally. In nginx: location /myprefix { proxy_pass http://192.168.0.1:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Script-Name /myprefix; } :param app: the WSGI application """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('X-Forwarded-Proto', '') if scheme: environ['wsgi.url_scheme'] = scheme host = environ.get('HTTP_X_FORWARDED_HOST', '') if host: environ['HTTP_HOST'] = host return self.app(environ, start_response)
''' 1. Write a Python program for binary search. Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time. Test Data : binary_search([1,2,3,5,8], 6) -> False binary_search([1,2,3,5,8], 5) -> True 2. Write a Python program for sequential search. Sequential Search : In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted. The list need not be ordered. Test Data : Sequential_Search([11,23,58,31,56,77,43,12,65,19],31) -> (True, 3) 3. Write a Python program for binary search for an ordered list. Test Data : Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3) -> True Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17) -> False '''
nums = int(input()) points = [] for i in range(0, nums): read_list = list(map(int, input().split())) # read_list = [int(i) for i in input().split()] points.append((read_list[0], read_list[1])) print(points) """ 3 1 2 23 4 4 5 [(1, 2), (23, 4), (4, 5)] """
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: __init__.py MCL_OS_ARCH_I386 = 0 MCL_OS_ARCH_SPARC = 1 MCL_OS_ARCH_ALPHA = 2 MCL_OS_ARCH_ARM = 3 MCL_OS_ARCH_PPC = 4 MCL_OS_ARCH_HPPA1 = 5 MCL_OS_ARCH_HPPA2 = 6 MCL_OS_ARCH_MIPS = 7 MCL_OS_ARCH_X64 = 8 MCL_OS_ARCH_IA64 = 9 MCL_OS_ARCH_SPARC64 = 10 MCL_OS_ARCH_MIPS64 = 11 MCL_OS_ARCH_UNKNOWN = 65535 archNames = {MCL_OS_ARCH_I386: 'i386', MCL_OS_ARCH_SPARC: 'sparc', MCL_OS_ARCH_ALPHA: 'alpha', MCL_OS_ARCH_ARM: 'arm', MCL_OS_ARCH_PPC: 'ppc', MCL_OS_ARCH_HPPA1: 'hppa1', MCL_OS_ARCH_HPPA2: 'hppa2', MCL_OS_ARCH_MIPS: 'mips', MCL_OS_ARCH_X64: 'x64', MCL_OS_ARCH_IA64: 'ia64', MCL_OS_ARCH_SPARC64: 'sparc64', MCL_OS_ARCH_MIPS64: 'mips64', MCL_OS_ARCH_UNKNOWN: 'unknown' } MCL_OS_WIN9X = 0 MCL_OS_WINNT = 1 MCL_OS_LINUX = 2 MCL_OS_SOLARIS = 3 MCL_OS_SUNOS = 4 MCL_OS_AIX = 5 MCL_OS_BSDI = 6 MCL_OS_DEC = 7 MCL_OS_FREEBSD = 8 MCL_OS_IRIX = 9 MCL_OS_HPUX = 10 MCL_OS_MIRAPOINT = 11 MCL_OS_OPENBSD = 12 MCL_OS_SCO = 13 MCL_OS_SELINUX = 14 MCL_OS_DARWIN = 15 MCL_OS_VXWORKS = 16 MCL_OS_PSOS = 17 MCL_OS_WINMOBILE = 18 MCL_OS_IPHONE = 19 MCL_OS_JUNOS = 20 MCL_OS_ANDROID = 21 MCL_OS_UNKNOWN = 65535 osNames = {MCL_OS_WIN9X: 'win9x', MCL_OS_WINNT: 'winnt', MCL_OS_LINUX: 'linux', MCL_OS_SOLARIS: 'solaris', MCL_OS_SUNOS: 'sunos', MCL_OS_AIX: 'aix', MCL_OS_BSDI: 'bsdi', MCL_OS_DEC: 'tru64', MCL_OS_FREEBSD: 'freebsd', MCL_OS_IRIX: 'irix', MCL_OS_HPUX: 'hpux', MCL_OS_MIRAPOINT: 'mirapoint', MCL_OS_OPENBSD: 'openbsd', MCL_OS_SCO: 'sco', MCL_OS_SELINUX: 'linux_se', MCL_OS_DARWIN: 'darwin', MCL_OS_VXWORKS: 'vxworks', MCL_OS_PSOS: 'psos', MCL_OS_WINMOBILE: 'winmobile', MCL_OS_IPHONE: 'iphone', MCL_OS_JUNOS: 'junos', MCL_OS_ANDROID: 'android', MCL_OS_UNKNOWN: 'unknown' }
#!/usr/bin/python ''' --- Part Two --- "Great work; looks like we're on the right track after all. Here's a star for your effort." However, the program seems a little worried. Can programs be worried? "Based on what we're seeing, it looks like all the User wanted is some information about the evenly divisible values in the spreadsheet. Unfortunately, none of us are equipped for that kind of calculation - most of us specialize in bitwise operations." It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. ''' inFile = open("2.txt",'r') lines = inFile.readlines() #real input #lines = ["5 9 2 8", "9 4 7 3", "3 8 6 5"] #debug only, should yield 9 def check_div(i,j): if j>i: i,j = j,i if i%j == 0: return i//j else: return 0 checksum = 0 for line in lines: line = map(int,line.strip().split()) div = 0 found = False for i in range(len(line)-1): for j in range(i+1,len(line)): div = check_div(line[i],line[j]) if div > 0: checksum += div found = True break if found: break print("Solution: "+str(checksum))
class Restaurant: """Beskriva saker om restauranger och deras typ av kök""" def __init__(self, restaurant_name, cuisine_type): """Ta in parameter för vilken namn och typ av kök restaurangen har""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(f"This is a {self.cuisine_type} restaurant, called {self.restaurant_name}!") def open_restaurant(self): print(f"{self.restaurant_name} is currently open") my_restaurant = Restaurant('KumbaYa', 'African') print(f"We have a new place in town it's calle {my_restaurant.restaurant_name}") print(f"It serves {my_restaurant.cuisine_type} food") my_restaurant.open_restaurant() my_restaurant.describe_restaurant()
File1 = open(input("File path of first list in text file:"), "rt") File2 = open(input("File path of second list in text file:"), "rt") file = open("Compared_List.txt", "a+") suffix_sp = [] #a list of genuses with "sp." suffix to denote the entire genus species = [] #list of species from File1 if __name__ == "__main__": for line in File1: if line[-4:-1] == "sp.": suffix_sp.append(line[:-5]) #extracts the genus identifiers from the list seperates it into the suffix_sp list else: species.append(line.strip()) File1.close() for line in File2: if line[-4:-1] == "sp.": #if theres a genus identifier in the file, this block will find the species in the other list under this genus. for spec in species: if line[:-5] == spec[:len(line[:-5])]: file.write(spec.replace("_", " ")+"\n") species.remove(spec) #checks whether the genus identifier is in the other list and adds to the final text file if line[:-5] in suffix_sp: file.write(line.replace("_", " ")) #finds whether there's a species of same name in other list elif line[:-1] in species: file.write(line.replace("_", " ")) species.remove(line[:-1]) else: #this checks whether a species is in a genus from the list of genuses. for suf_spec in suffix_sp: if suf_spec == line[:len(suf_spec)+1]: file.write(line.replace("_", " ")) File2.close() file.close() #Fin.
class Solution: def zigzagLevelOrder(self, root): if root is None: return [] res = [] res.append([root.val]) queue = [] queue.append(root) level_nodes = [] level_node_count = 1 next_level_node_count = 0 left_to_right = True while len(queue) > 0: node = queue.pop(0) level_node_count -= 1 if node.left is not None: level_nodes.append(node.left.val) queue.append(node.left) next_level_node_count += 1 if node.right is not None: queue.append(node.right) level_nodes.append(node.right.val) next_level_node_count += 1 if len(level_nodes) > 0: if level_node_count == 0: left_to_right = not left_to_right if left_to_right: res.append(level_nodes) else: res.append(level_nodes[::-1]) level_nodes = [] level_node_count = next_level_node_count next_level_node_count = 0 return res
"""Adding routes for the configuration to find.""" def includeme(config): config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('list', '/') config.add_route('profile', '/profile/{id:\d+}') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('register', '/register')
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n, lo=0): """ :type n: int :rtype: int """ if lo >= n: return n if guess(n) == 0: return n x = lo + (n - lo) // 2 compar = guess(x) if compar < 0: return self.guessNumber(x, lo) elif compar > 0: return self.guessNumber(n, x) return x
############################################################################################### # 直接暴力,遍历一次,每次要排序 ########### # 时间复杂度:O(n*klogk),n为strs长度,k为每个串的长度 # 空间复杂度:O(nk),哈希表存放全部字符串 ############################################################################################### class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dict_ = defaultdict(list) for str_ in strs: dict_["".join(sorted(str_))].append(str_) return list(dict_.values())
"""Figure size settings.""" # Some useful constants _GOLDEN_RATIO = (5.0 ** 0.5 - 1.0) / 2.0 _INCHES_PER_POINT = 1.0 * 72.27 # Double-column formats def icml2022_half(**kwargs): """Double-column (half-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def icml2022_full(**kwargs): """Single-column (full-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def aistats2022_half(**kwargs): """Double-column (half-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def aistats2022_full(**kwargs): """Single-column (full-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def _icml2022_and_aistats2022_half( *, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): figsize = _from_base_in( width_in=3.25, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _icml2022_and_aistats2022_full( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): figsize = _from_base_in( width_in=6.75, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def cvpr2022_half( *, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Double-column (half-width) figures for CVPR 2022.""" figsize = _from_base_pt( width_pt=237.13594, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def cvpr2022_full( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Single-column (full-width) figures for CVPR 2022.""" figsize = _from_base_pt( width_pt=496.85625, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) # Single-column formats def jmlr2001( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """JMLR figure size. Source: https://www.jmlr.org/format/format.html The present format is for US letter format. """ figsize = _from_base_in( width_in=6.0, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def neurips2021( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Neurips 2021 figure size.""" figsize = _from_base_pt( width_pt=397.48499, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _from_base_pt(*, width_pt, **kwargs): width_in = width_pt / _INCHES_PER_POINT return _from_base_in(width_in=width_in, **kwargs) def _from_base_in(*, width_in, nrows, height_to_width_ratio, ncols): height_in = height_to_width_ratio * width_in * nrows / ncols return width_in, height_in # Other formats def beamer_169( *, rel_width=0.9, rel_height=0.6, constrained_layout=True, tight_layout=False ): """Beamer figure size for `aspectratio=169`.""" textwidth_169_pt = 398.3386 # via '\showthe\textwidth' in latex textwidth_169_in = textwidth_169_pt / _INCHES_PER_POINT textheight_169_in = textwidth_169_in / 16.0 * 9.0 figsize = (textwidth_169_in * rel_width, textheight_169_in * rel_height) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _figsize_to_output_dict(*, figsize, constrained_layout, tight_layout): return { "figure.figsize": figsize, "figure.constrained_layout.use": constrained_layout, "figure.autolayout": tight_layout, }
""" 1: Client Message 2: Phase1A 3: Phase1B 4: Phase2A 5: Phase2B 6: Decision 7: Leader 8: Catchup 9: Catchup_Answer """ class Message: def __init__(self, msg_type, message=0, instance=0, iid=0, c_rnd=0, c_val=0, rnd=0, v_val=0, v_rnd=0, current_leader=0, prop_id=0, msg_memory=None, print_order=None, total_order=None, total_order_sent=None, total_order_memory=None): # Basic message variables needed for various applications inside Paxos self.message = message self.type = msg_type self.instance = instance self.iid = iid # The values as known from the slides self.c_rnd = c_rnd self.c_val = c_val self.rnd = rnd self.v_val = v_val self.v_rnd = v_rnd # current leader and prop_id needed for leader election self.current_leader = current_leader self.prop_id = prop_id # msg_memory and total order needed for learner catch_up self.msg_memory = msg_memory self.print_order = print_order self.total_order = total_order self.total_order_sent = total_order_sent self.total_order_memory = total_order_memory
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Python for AHDA. Part 1, Example 9. """ # Deduplication of a list rhyme = ['Peter', 'Piper', 'picked', 'a', 'piece', 'of', 'pickled', 'pepper', 'A', 'piece', 'of', 'pickled', 'pepper', 'Peter', 'Piper', 'picked'] deduplicated_rhyme = set(rhyme) print(deduplicated_rhyme)
class Solution: # @param {int[]} nums an integer array # @return nothing, do this in-place def moveZeroes(self, nums): # Write your code here i = 0 for j in xrange(len(nums)): if nums[j]: num = nums[j] nums[j] = 0 nums[i] = num i += 1
''' key-value methods in dictionary ''' # Keys key_dictionary = { 'sector': 'Keys method', 'variable': 'dictionary' } print(key_dictionary.keys()) # Values value_dictionary = { 'sector': 'Values method', 'variable': 'dictionary' } print(value_dictionary.values()) # Key-value key_value_dictionary = { 'sector': 'key-value method', 'variable': 'dictionary' } print(key_value_dictionary.items())
for _ in range(int(input())): tr = int(input()) ram_task = list(map(int, input().split(' '))) dr = int(input()) ram_dare = list(map(int, input().split(' '))) ts = int(input()) sham_task = list(map(int, input().split(' '))) ds = int(input()) sham_dare = list(map(int, input().split(' '))) lose = False for i in sham_task: if i not in ram_task: lose = True for i in sham_dare: if i not in ram_dare: lose = True if lose: print('no') else: print('yes')
q1 = 1 q2 = -2 q3 = 4 state = (q1, q2, q3) state = (-state[0], -state[1], -state[2]) #str(state[0]) = '33' print(state)
def dfs(at, graph, visited): if visited[at]: return visited[at] = True print(at, end=" -> ") neighbours = graph[at] for next in neighbours: dfs(next, graph, visited) if __name__ == "__main__": n = int(input("No. of Nodes : ")) graph = [] for i in range(n): graph.append(list(map(int, input("Nodes linked with {} : ".format(i)).split()))) start_node = int(input("Starting Node : ")) # graph = [[1, 2], [3], [1], [2], [3, 5], [5]] visited = [False] * n print("\nNodes in DFS are : ", end=" ") dfs(start_node, graph, visited) print(" / ") """ Input : No. of Nodes : 6 Nodes linked with 0 : 1 2 Nodes linked with 1 : 3 Nodes linked with 2 : 1 Nodes linked with 3 : 2 Nodes linked with 4 : 3 5 Nodes linked with 5 : 5 Starting Node : 4 Output: Nodes in DFS are : 4 -> 3 -> 2 -> 1 -> 5 -> / """
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", ) all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] all_compile_actions = [ ACTION_NAMES.assemble, ACTION_NAMES.c_compile, ACTION_NAMES.clif_match, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.lto_backend, ACTION_NAMES.preprocess_assemble, ] def _impl(ctx): tool_paths = [ tool_path( name = "ar", path = "wrappers/aarch64-none-linux-gnu-ar", ), tool_path( name = "cpp", path = "wrappers/aarch64-none-linux-gnu-cpp", ), tool_path( name = "gcc", path = "wrappers/aarch64-none-linux-gnu-gcc", ), tool_path( name = "gcov", path = "wrappers/aarch64-none-linux-gnu-gcov", ), tool_path( name = "ld", path = "wrappers/aarch64-none-linux-gnu-ld", ), tool_path( name = "nm", path = "wrappers/aarch64-none-linux-gnu-nm", ), tool_path( name = "objdump", path = "wrappers/aarch64-none-linux-gnu-objdump", ), tool_path( name = "strip", path = "wrappers/aarch64-none-linux-gnu-strip", ), ] default_compiler_flags = feature( name = "default_compiler_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-no-canonical-prefixes", "-fno-canonical-system-headers", "-Wno-builtin-macro-redefined", "-D__DATE__=\"redacted\"", "-D__TIMESTAMP__=\"redacted\"", "-D__TIME__=\"redacted\"", ], ), ], ), ], ) default_linker_flags = feature( name = "default_linker_flags", enabled = True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups = ([ flag_group( flags = [ "-lstdc++", ], ), ]), ), ], ) features = [ default_compiler_flags, default_linker_flags, ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, cxx_builtin_include_directories = [ "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/include/c++/10.2.1/", "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/usr/include/", "/proc/self/cwd/external/aarch64-none-linux-gnu/lib/gcc/aarch64-none-linux-gnu/10.2.1/include/", "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/lib/", ], features = features, toolchain_identifier = "aarch64-toolchain", host_system_name = "local", target_system_name = "unknown", target_cpu = "unknown", target_libc = "unknown", compiler = "unknown", abi_version = "unknown", abi_libc_version = "unknown", tool_paths = tool_paths, ) cc_toolchain_config = rule( implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo], )
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def maxSubArray(self, nums): n = len(nums) prefixSum = [0 for _ in range(n + 1)] minIdx = 0 largeSum = -sys.maxsize - 1 for i in range(1, n + 1): # update prefixSum prefixSum[i] = prefixSum[i - 1] + nums[i - 1] # compare largeSum = max(largeSum, prefixSum[i] - prefixSum[minIdx]) # update minIdx if prefixSum[i] < prefixSum[minIdx]: minIdx = i return largeSum
def predicate(h, n): ''' Returns True if we can build a triangle of height h using n coins, else returns False ''' return h*(h+1)//2 <= n t = int(input()) for __ in range(t): n = int(input()) # binary search for the greatest height which can be reached using n coins lo = 0 hi = n while lo<hi: mid = lo + (hi-lo+1)//2 # round UP if predicate(mid, n): lo = mid else: hi = mid-1 print(lo)
class Solution: def hammingDistance(self, x: int, y: int) -> int: count = 0 for i in range(30, -1, -1): mask = 1 << i digitX = x & mask digitY = y & mask if digitX != digitY: count += 1 return count
''' import tkinter as tk window = tk.Tk() window.geometry ("800x450+0+0") window.title ('Conversor de base') des = 'Desafio-037 estrutura condição aninhada-002' print ('{}'.format(des)) ''' #Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. n = int(input('Digite um número inteiro: ')) print (''' [1] Converter para BINARIO [2] Converter para OCTAL [3] Converter para HEXADECIMAL ''') opção = int(input('Sua opção: ')) if opção == 1: print ('\033[0;32m{} Converido para BINARIO é igual a: {}\033[m'.format(n, bin(n)[2:])) elif opção == 2: print ('\033[0;31m{} Convertido para OCTAL é igual a: {}\033[m'.format(n, oct(n)[2:])) elif opção == 3: print ('\033[0;36m{} Convertido para HEXADECIMAL é igual a: {}\033[m'.format(n, hex(n)[2:]))
# https://javl.github.io/image2cpp/ # 40x40 CALENDAR_40_40 = bytearray([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x3c, 0x00, 0x1c, 0x00, 0x01, 0xff, 0xff, 0xff, 0x80, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0x80, 0x00, 0x01, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x80, 0x00, 0x01, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x01, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])
class Category: """ Categories of vehicles sold. """ NEW = "new" DEMO = "demo" USED = "preowned" class VehicleType: """ Types of vehicles sold. """ CARGO_VAN = "CARGO VAN" CAR = "Car" SUV = "SUV" TRUCK = "Truck" VAN = "Van"
#Ввести с клавиатуры строку, проверить является ли строка палиндромом и вывести результат (yes/no) на экран. Палиндром - это слово или фраза, которые одинаково читаются слева направо и справа налево polin = str(input( "Введите слово: ")) polin_test = polin[::-1] if polin == polin_test: print("YES") else: print("NO")
class BaseObject(object): """ A base class to provide common features to all models. """
expected_output = { "interfaces": { "GigabitEthernet1/0/17": { "mac_address": { "0024.9bff.0ac8": { "acct_session_id": "0x0000008d", "common_session_id": "0A8628020000007168945FE6", "current_policy": "Test_DOT1X-DEFAULT_V1", "domain": "DATA", "handle": "0x86000067", "iif_id": "0x1534B4E2", "ipv4_address": "Unknown", "ipv6_address": "Unknown", "user_name": "host/Laptop123.test.com", "status": "Authorized", "oper_host_mode": "multi-auth", "oper_control_dir": "both", "session_timeout": {"type": "N/A"}, "server_policies": { 1: { "name": "ACS ACL", "policies": "xACSACLx-IP-Test_ACL_PERMIT_ALL-565bad69", "security_policy": "None", "security_status": "Link Unsecured", } }, "method_status": { "dot1x": {"method": "dot1x", "state": "Authc Success"}, "mab": {"method": "mab", "state": "Stopped"}, }, } } } } }
def my_plot(df, case_type, case_thres=50000): m = Basemap(projection='cyl') m.fillcontinents(color='peru', alpha=0.3) groupby_columns = ['Country/Region', 'Province/State', 'Lat', 'Long'] max_num_cases = df[case_type].max() for k, g in df.groupby(groupby_columns): country_region, province_state, lat, long = k num_cases = g.loc[g['Date'] == g['Date'].max(), case_type].sum() if num_cases > case_thres: x, y = m(long, lat) opacity = np.log(num_cases) / np.log(max_num_cases) size = num_cases / max_num_cases #print(country_region, opacity) #p = m.plot(x, y, marker='o',color='darkblue', alpha=opacity*4) p = m.scatter(long, lat, marker='o',color='darkblue', s=size*500, alpha=opacity) if num_cases > 1000000: plt.text(x, y, province_state or country_region)
class Review: all_reviews = [] def __init__(self,news_id,title,name,author,description,url, urlToImage,publishedAt,content): self.new_id = new_id self.title = title self.name= name self.author=author self.description=description self.url=link self. urlToImage= imageurl self.publishedAt = date self.content=content def save_review(self): Review.all_reviews.append(self) @classmethod def clear_reviews(cls): Review.all_reviews.clear()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """HMC5883L: Surface-mount, multi-chip module designed for low-field magnetic sensing with a digital interface for applications such as lowcost compassing and magnetometry""" __author__ = "ChISL" __copyright__ = "TBD" __credits__ = ["Honeywell"] __license__ = "TBD" __version__ = "Version 0.1" __maintainer__ = "https://chisl.io" __email__ = "info@chisl.io" __status__ = "Test" # # THIS FILE IS AUTOMATICALLY CREATED # D O N O T M O D I F Y ! # class REG: ConfigA = 0 ConfigB = 1 Mode = 2 DataOutputX = 3 DataOutputZ = 5 DataOutputY = 7 Status = 9 Identification = 16
class Solution: def countBits(self, num: int) -> List[int]: ans=[] for i in range(num+1): ans.append(bin(i).count('1')) return ans
def change(img2_head_mask, img2, cv2, convexhull2, result): (x, y, w, h) = cv2.boundingRect(convexhull2) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) #can change it to Mix_clone seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE) return seamlessclone
# Created by MechAviv # Map ID :: 100000000 # NPC ID :: 9110000 # Perry maps = [["Showa Town", 100000000], ["Ninja Castle", 100000000], ["Six Path Crossway", 100000000]]# TODO sm.setSpeakerID(9110000) selection = sm.sendNext("Welcome! Where to?\r\n#L0# To Showa Town#l\r\n#L1# To Ninja Castle#l\r\n#L2# To Six Path Crossway#l") sm.setSpeakerID(9110000) if sm.sendAskYesNo(maps[selection][0] + "? Drive safely!"): sm.warp(maps[selection][1]) else: sm.setSpeakerID(9110000) sm.sendNext("I hope the ride wasn't too uncomfortable. I can't upgrade the seating without charging fares.")
'''input 98 56 Worse 12 34 Better ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': x, y = list(map(int, input().split())) if x < y: print('Better') else: print('Worse')
INVALID_ARGUMENT = 'invalid argument' PERMISSION_DENIED = 'permission denied' UNKNOWN = 'unknown' NOT_FOUND = 'not found' INTERNAL = 'internal error' TOO_MANY_REQUESTS = 'too many requests' SERVER_UNAVAILABLE = 'service unavailable' BAD_REQUEST = 'bad request' AUTH_ERROR = 'authorization error' class TRError(Exception): def __init__(self, code, message, type_='fatal'): super().__init__() self.code = code or UNKNOWN self.message = message or 'Something went wrong.' self.type_ = type_ @property def json(self): return {'type': self.type_, 'code': self.code, 'message': self.message} class URLScanInternalServerError(TRError): def __init__(self): super().__init__( INTERNAL, 'The URLScan internal error.' ) class URLScanNotFoundError(TRError): def __init__(self): super().__init__( NOT_FOUND, 'The URLScan not found.' ) class URLScanInvalidCredentialsError(TRError): def __init__(self): super().__init__( PERMISSION_DENIED, 'The request is missing a valid API key.' ) class URLScanUnexpectedResponseError(TRError): def __init__(self, payload): error_payload = payload.json() super().__init__( UNKNOWN, str(error_payload) ) class URLScanTooManyRequestsError(TRError): def __init__(self): super().__init__( TOO_MANY_REQUESTS, 'Too many requests have been made to ' 'URLScan. Please, try again later.' ) class URLScanUnavailableError(TRError): def __init__(self): super().__init__( SERVER_UNAVAILABLE, 'The urlscan.io is unavailable. Please, try again later.' ) class URLScanBadRequestError(TRError): def __init__(self): super().__init__( BAD_REQUEST, 'You sent weird url. ' 'Please check the correctness of your url and try again.' ) class URLScanSSLError(TRError): def __init__(self, error): message = getattr( error.args[0].reason.args[0], 'verify_message', '' ) or error.args[0].reason.args[0].args[0] super().__init__( UNKNOWN, f'Unable to verify SSL certificate: {message}' ) class AuthorizationError(TRError): def __init__(self, message): super().__init__( AUTH_ERROR, f"Authorization failed: {message}" ) class BadRequestError(TRError): def __init__(self, error_message): super().__init__( INVALID_ARGUMENT, error_message ) class WatchdogError(TRError): def __init__(self): super().__init__( code='health check failed', message='Invalid Health Check' )