content
stringlengths
7
1.05M
# The MIT License # # Copyright (c) 2008 James Piechota # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
class Solution: def maxPower(self, s: str) -> int: power = [] i, temp = 1, "" for s_char in s: if s_char == temp: i += 1 else: power.append( i ) i = 1 temp = s_char power.append(i) r...
# 共通の要素を取り出す my_frinends = {'A', 'C', 'D'} A_frinends = {'B', 'D', 'E', 'F'} print(my_frinends & A_frinends) # {'D'} # 種類を調べる fruits = ['apple', 'banana', 'apple', 'banana', 'orange'] kind = set(fruits) print(kind) # {'apple', 'banana', 'orange'}
def multiprocess_state_generator(video_frame_generator, stream_sha256): """Returns a packaged dict object for use in frame_process""" for frame in video_frame_generator: yield {'mode': 'video', 'main_sequence': True}
# Used Python for handling large integers for _ in range(int(input())): a,b = list(map(int,input().split())) print(a*b)
def solution(a, b): answer = '' month = {0:0, 1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} day = {1:'FRI',2:'SAT',3:'SUN', 4:'MON',5:'TUE',6:'WED', 0:'THU'} d = 0 for i in range(0, a): d += month[i] d += b answer = day[(d % 7)] return answer
""" Você deve resolver o clássico exercício das 8 rainhas Nele o usuário lhe passa o tamanho do tabuleiro n (lembrar que tabuleiros são quadrados então o usuário só precisa lhe passar um inteiro) e você deve gerar uma todas as distribuições de n rainhas neste tabuleiro e imprimi-las de uma forma adequada. Veja o livro...
# Function to calculate median def calcMedian(arr, startIndex, endIndex): index = ( startIndex + endIndex ) // 2 if (endIndex - startIndex + 1) % 2 == 0: # return median for even no of elements return ( arr[index] + arr[index + 1] ) // 2 else: # return median for odd no of elements ...
# -*- coding: utf-8 -*- # Initial permutation matrix PI = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 6...
""" Classes for IMPACTS P3 Instruments """ class P3(object): """ """ def __init__(self, filepath, date): pass def readfile(self, filepath, ): pass
class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): a = set(nums) a = sum(a)*2 singleNumber = a - sum(nums) return singleNumber
#!/usr/bin/env python3 # Transistors. "2N3904" "2SC1815" # NPN? "2SA9012" "2SA1015" # PNP?
# coding: utf-8 __all__ = ['EikonError'] class EikonError(Exception): """ Base class for exceptions specific to Eikon platform. """ def __init__(self, code, message): """ Parameters ---------- code: int message: string Indicate the sort direction. ...
class Car: # constructor def __init__(self,name,fuel,consumption,passengers,capacity): self.name = name self.fuel = fuel self.consumption = consumption self.km = 0.0 self.passengers = passengers self.capacity = capacity # Behavior def print_car(sel...
name = "pyilmbase" version = "2.1.0" description = \ """ IlmBase Python bindings """ variants = [ ["platform-linux"] ] requires = [ "ilmbase-%s" % (version), "python", "boost" ] uuid = "repository.pyilmbase" def commands(): env.PATH.prepend("{root}/bin") env.LD_LIBRARY_PATH.pre...
vector = [{"name": "John Doe", "age": 37}, {"name": "Anna Doe", "age": 35}] # for item in vector: # print(item["name"]) print(list(map(lambda item: item["name"], vector)))
# -*- coding: utf-8 -*- """ Created on Sat Feb 9 19:48:15 2019 @author: Utente """ #Exercises Chapter 3 #3.2 do_four def do_twice(func, arg): func(arg) func(arg) def print_twice(arg): print(arg) print(arg) def do_four(func, arg): do_twice(func, arg...
class FormattedWord: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(FormattedWord(word)) def __str__(self) -> str: ...
""" mat data format { 1989: { 'AKS': { 2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor), 3: (0.0534,0.1453), # same format for age 3, 4: (0.0534,0.1453) # same format for age 4 }, ... }, ... } """ def parse_mat(file): yea...
casa = float(input('Valor da casa: R$')) salario = float(input('Salario do comprador R$')) anos = int(input('Quantos anos de financiamento? ')) prestacao = casa / (anos * 12) minimo = salario * 30 / 100 print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos)) if prestacao < minimo: print('Emprestimo ...
class AutomatonListHelper: ''' ' Removes repeated elements from a list ' ' @param list array List that will be iterate ' ' @return list ''' @staticmethod def removeDuplicates(array): final_list = [] for num in array: if num not in final_list: ...
#! /usr/bin/python3 def print_sorted_dictionary_pairs(dict): for key in sorted(dict): print(key, dict[key]) def add_or_change_dictionary_value(dict, key, value): dict[key] = value def delete_dictionary_entry(dict, key): if key in dict: del dict[key] else: print(key, 'not found...
######################################################################## def clamp(value, minimum=0.0, maximum=1.0): return min(maximum, max(minimum, value)) ######################################################################## def find_all_by_name(name, list_entities): name = name.lower() for entity i...
def printPacket(packet): print(packet.to_json())
''' Tipo: Concepto, Ejercicio, Pregunta... Fuente: libro, curso, ... Este chunk tiene como propósito revisar cocneptos fundamentales. Variable de isntancia Variable de clase Una diferencia importante entre clase e instancia e sla forma de usarse, están fuera del constructor __init__() Método de Instancias Método ...
# -*- coding: utf-8 -*- #----------- #@utool.indent_func('[harn]') @profile def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list): r""" Test harness driver function CommandLine: python -m ibeis.expt.harness --exec-test_configurations --verbtd python -m ibeis.expt.harness --e...
# # PySNMP MIB module IANA-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
# expected data for tests using FBgn0031208.gff and FBgn0031208.gtf files # list the children and their expected first-order parents for the GFF test file. GFF_parent_check_level_1 = {'FBtr0300690':['FBgn0031208'], 'FBtr0300689':['FBgn0031208'], 'CG11023:1':['FB...
# [FORMATADOR DE NOTAS KINDLE EM PADRÃO ACADÊMICO ABNT DE CITAÇÃO e REFERÊNCIA] # Função de Tratamento das notas def tratamento_arquivo(arquivo): conteudo = [] paginas = [] checador_final = 0 while arquivo != '': # Encontrando strings que caracterizam o início e o fim do texto conti...
# 请用“*”打印出五行五列的等腰直角三角形 N = 5 for i in range(N): for j in range(i + 1): print("*", end="") print()
def user_class(row_series): """ Defines the user class for this trip list. This function takes a single argument, the pandas.Series with person, household and trip_list attributes, and returns a user class string. """ # print row_series if row_series["hh_id"] == "simpson": return "...
# 1. Even Numbers # Write a program that receives a sequence of numbers (integers), separated by a single space. # It should print a list of only the even numbers. Use filter(). def filter_even(iters): return list(filter(lambda x: x % 2 == 0, iters)) nums = map(int, input().split()) print(filter_even(nums))
class Foo: def __init__(self, id): self.id = id def __str__(self): return 'Foo instance id: {}'.format(self.id) class Bar: def __init__(self, id): self.id = id def __str__(self): return 'Bar instance id: {}'.format(self.id) class Baz: def __init__(self, id): ...
def cli_progress_bar(completed: int, total_iterations: int, length=40, fill_char='█', padding_char='░', prefix='', suffix='', precision=1, complete_as_percent=True): """ Call in a loop to create terminal progress bar. The loop can't print any other output to stdou...
#=========================================================================== # # Convert decoded data to MQTT messages. # #=========================================================================== #=========================================================================== def convert( config, data ): # List of t...
# -*- coding: UTF-8 -*- # # Binary search works for a sorted array. # The All ▲lgorithms library for python # # Contributed by: Carlos Abraham Hernandez # Github: @abranhe # def binary_search(arr, query): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (hi + lo) // 2 val = arr[mid] if val...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 合并两个列表为一个无重复元素的列表 """ def merge_list(*args): s = set() for arg in args: s = s.union(arg) return list(s) l1 = [12, 2, 4, 2, 56, 2] l2 = [2, 4, 5, 77, 8] print(merge_list(l1, l2))
def special_sort(alphabet, s): a = {c: i for i, c in enumerate(alphabet)} return ''.join(sorted(list(s), key=lambda x: a[x.lower()])) a = 'wvutsrqponmlkjihgfedcbaxyz' t = 'camelCasE' print(special_sort(a, t))
# Transformando módulos em pacotes '''Crie um PACOTE chamado uteis que tenha dois módulos internos chamados moeda e dado. Transfira todas as funções utilizadas nos ex107, ex108 e ex109 para o primeiro pacote e mantenha tudo funcionando''' print() print('\033[1:35m''Nesse exercício não há código para escrever') print()...
# Next Greater Element I: https://leetcode.com/problems/next-greater-element-i/ # The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. # You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. # F...
pt = int(input('Primeiro termo: ')) rz = int(input('Razão: ')) for c in range (pt, (pt + (10-1) * rz)+rz, rz): print(f'{c}', end=" → ") print('ACABOU')
''' Cree un programa en Python que le pida al usuario por pantalla un número (int) ("n"). Luego cree un ciclo que se ejecuta tantas veces como el número "n" recibido anteriormente. Luego dentro del ciclo pida al usuario otro número por pantalla. Si el número recibido es par, sumelo en un acumulador, si no, no lo sum...
''' @Date: 2019-12-22 20:38:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors : ywyz @LastEditTime : 2019-12-22 20:52:02 ''' strings = input("Enter the first 12 digits of an ISBN-13 as a string: ") temp = 1 total = 0 for i in strings: if temp % 2 == 0: total += 3 * int(i)...
matriz = [[1, 2], [3, 4], [5, 6], [7]] i = 0 x = 0 while i < len(matriz): try: print(matriz[i][x]) x = x + 1 except IndexError: print("O valor mais alto da lista {i} é: {max}".format(i=i, max=max(matriz[i]))) i = i + 1 x = 0
# Generator used for all the Skinned Lanterns lantern variants! lanterns = ["pufferfish", "zombie", "creeper", "skeleton", "wither_skeleton", "bee", "jack_o_lantern", "ghost", "inky", "pinky", "blinky", "clyde", "pacman", "paper_white", "paper_yellow", "paper_orange", "paper_blue", "paper_light_blue", "paper_cyan", "p...
def count_up_to(max): count = 1 while count <= max: yield count count += 1 counter = count_up_to(5) for num in counter: print(num)
__strict__ = True class SpotifyOauthError(Exception): pass class SpotifyRepositoryError(Exception): def __init__(self, http_status: int, body: str): self.http_status = http_status self.body = body def __str__(self): return 'http status: {0}, code:{1}'.format(str(self.http_status...
# program numbers BASIC = 140624 GOTO = 158250875866513204219300194287615 VARIABLES = 6198727823
ENV_NAMES = { "PASSWORD": "DECT_MAIL_EXTRACT_PASSWORD", "USERNAME": "DECT_MAIL_EXTRACT_USER", "SERVER": "DECT_MAIL_EXTRACT_SERVER", }
@customop('numpy') def my_softmax(x, y): probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) N = x.shape[0] loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N return loss def my_softmax_grad(ans, x, y): def grad(g): N = x...
__all__ = ( "ELLIPSIS", "truncate", ) ELLIPSIS = "…" """The ellipsis character used for :func:`utils.string.truncate`.""" def truncate(string, length): """ Truncate a string to a given length. Functions as follows: * If length is 0 or less, returns an empty string. * If length is less t...
""" This file was made for exercise 9-11""" class Users: def __init__(self, first_name, last_name, email, username): self.first_name = first_name self.last_name = last_name self.email = email self.username = username self.login_attempts = 0 def describe_user(self): ...
''' https://leetcode.com/problems/reverse-integer/ 7. Reverse Integer Easy Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which co...
class MdFile(): def __init__(self, file_path, base_name, title, mdlinks): self.uid = 0 self.file_path = file_path self.base_name = base_name self.title = title if title else base_name self.mdlinks = mdlinks def __str__(self): return f'{self.uid}: {self.file_pat...
#/* *** ODSATag: MinVertex *** */ # Find the unvisited vertex with the smalled distance def minVertex(G, D): v = 0 # Initialize v to any unvisited vertex for i in range(G.nodeCount()): if G.getValue(i) != VISITED: v = i break for i in range(G.nodeCount()): # Now find small...
config = { # -------------------------------------------------------------------------- # Database Connections # -------------------------------------------------------------------------- 'database': { 'default': 'auth', 'connections': { # SQLite # 'auth': { ...
data = open('output_dataset_ALL.txt').readlines() original = open('dataset_ALL.txt').readlines() #data = open('dataset.txt').readlines() out = open('output_gcode_merged.gcode', 'w') for j in range(len(data)/4): i = j*4 x = data[i].strip() y = data[i+1].strip() z = original[i+2].strip() e = original...
def adder_model(a, b): """ My golden reference model """ return my_adder(a, b) def my_adder(a, b): """ My golden reference model """ return a + b
## # Copyright 2018, Ammar Ali Khan # Licensed under MIT. ## # Application configuration APPLICATION_NAME = '' APPLICATION_VERSION = '1.0.1' # HTTP Port for web streaming HTTP_PORT = 8000 # HTTP page template path HTML_TEMPLATE_PATH = './src/common/package/http/template' # Capturing device index (used for web camera...
Total_Fuel_Need =0 Data_File = open("Day1_Data.txt") Data_Lines = Data_File.readlines() for i in range(len(Data_Lines)): Data_Lines[i] = int(Data_Lines[i].rstrip('\n')) Total_Fuel_Need += int(Data_Lines[i] / 3) - 2 print(Total_Fuel_Need)
# This sample tests the special-case handling of Self when comparing # two functions whose signatures differ only in the Self scope. class SomeClass: def __str__(self) -> str: ... __repr__ = __str__
lines = open("input").read().strip().splitlines() print("--- Day11 ---") class Seat: directions = [ (dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0) ] def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def...
#list = [1,2,3,4,5] arr = list(range(1,6)) count = 0 #print(arr) #for i in arr: #print(i) list = ["a","b","c","d","e"] for index in range(len(arr)): print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}') count += 1 print(count)
""" Auteur = Frédéric Castel Date : Avril 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Considérons les billets et pièces de valeurs suivantes : 20 euros, 10 euros, 5 euros, 2 euros et 1 euro. Écrire une fonction rendre_monnaie qui reçoit en paramètre un entier prix et cinq valeu...
def baseline3(X): return ( X['ABS'] | X['INT'] | X['UINT'] | (X['TDEP'] > X['TDEP'].mean()) | (X['FIELD'] > X['FIELD'].mean()) | ((X['UAPI']+X['TUAPI']) > (X['UAPI']+X['TUAPI']).mean()) | (X['EXPCAT'] > 0) | (X['RBFA'] > 0) | (X['CONDCALL'] > 0...
def search_in_rotated_array(alist, k, leftix=0, rightix=None): if not rightix: rightix = len(alist) midpoint = (leftix + rightix) / 2 aleft, amiddle = alist[leftix], alist[midpoint] if k == amiddle: return midpoint if k == aleft: return leftix if aleft > amiddle: ...
# coding:utf-8 # File Name: decorator_test # Author : yifengyou # Date : 2021/07/18 def funA(fn): print("A") fn() return "hello" @funA def funB(): print("B") print(funB)
""" Program functionalities module """ def create_transaction(day, value, type, description): """ :return: a dictionary that contains the data of a transaction """ return {'day': day, 'value': value, 'type': type, 'description': description} def get_day(transaction): """ :retur...
''' https://www.codingame.com/training/easy/brackets-extreme-edition ''' e = input() d = {')': '(', ']': '[', '}': '{'} s = [] for c in e: if c in d.values(): s.append(c) elif c in d.keys(): if len(s) == 0: print("false") exit(0) else: ...
#!/usr/bin/env python # from .api import SteamAPI class SteamUser(object): def __init__(self, steam_id=None, steam_api=None, **kwargs): self.steam_id = steam_id self.steam_api = steam_api self.__dict__.update(**kwargs) self._friends = None self._games = None self._...
def parse_map(_map): """ Returns a dictionary where from you can look up which center a given orbiter has """ orbits = {} for orbit in _map.split("\n"): center, orbiter = orbit.split(")") orbits[orbiter] = center return orbits def count_orbits(_map): orbits = parse_map(_map) orbiters = orbits.keys() i ...
class Solution: def solve(self, matrix): if matrix[0][0] == 1: return -1 R,C = len(matrix),len(matrix[0]) bfs = deque([[0,0]]) dists = {(0,0): 1} while bfs: r,c = bfs.popleft() if (r,c) == (R-1,C-1): return dists[r,c] for nr,n...
class Solution: def rob(self, nums: list[int]) -> int: if len(nums) == 0: return 0 max_loot: list[int] = [0 for _ in nums] for index, num in enumerate(nums): if index == 0: max_loot[index] = num elif index == 1: max_loot[in...
async def processEvent(event): # Do event processing here ... return event
#!/usr/bin/env python # coding=utf-8 """ # pyORM : Implementation of managers.py Summary : <summary of module/class being implemented> Use Case : As a <actor> I want <outcome> So that <justification> Testable Statements : Can I <Boolean statement> .... """ __version__ = "0.1" __author__ = 'Tony Flu...
print("\nAverage is being calculated\n") APITimingFile = open("APITiming.txt", "r") APITimingVals = APITimingFile.readlines() sum = 0 for i in APITimingVals: sum += float(i[slice(len(i)-2)]) print("\nThe average time of start providing is " + str(round(sum/len(APITimingVals), 4)) + "\n")
class OrderLog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = self.log[1:] def get_last(self, i): ...
# # PySNMP MIB module OADHCP-SERVER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OADHCP-SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:22:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
sample_split=1.0 data_loader_usage = 'Training' training_data = "train_train" evaluate_data = "privatetest"
# This function checks if year is a leap year. def isLeapYear(year): if year%100 == 0: return True if year%400 == 0 else False elif year%4 == 0: return True else: return False # This function returns the number of days in a month def monthDays(year, month): MONTHDAYS = (31, 28, ...
#encoding:utf-8 subreddit = 'wtf' t_channel = '@reddit_wtf' def send_post(submission, r2t): return r2t.send_simple(submission)
programming_languages = ["Python", "Scala", "Haskell", "F#", "C#", "JavaScript"] for lang in programming_languages: if (lang == "Haskell"): continue print("Found Haskell !!!", end='\n') # this statement will never be executed print(lang, end=' ')
inc = 1 num = 1 for x in range (5,0,-1): for y in range(x,0,-1): print(" ",end="") print(str(num)*inc) num += 2 inc += 2
n = int(input()) a = list(map(int, input().split())) k_max = 0 g_max = 0 for k in range(2, max(a) + 1): gcdness = 0 for elem in a: if elem % k == 0: gcdness += 1 if gcdness >= g_max: g_max = gcdness k_max = k print(k_max)
# 326. Power of Three # ttungl@gmail.com # Given an integer, write a function to determine if it is a power of three. # Follow up: # Could you do it without using any loop / recursion? class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ ...
class Solution: def getSmallestString(self, n: int, k: int) -> str: result = "" for index in range(n): digitsLeft = n - index - 1 for c in range(1, 27): if k - c <= digitsLeft * 26: k -= c result += chr(ord('a') + c -1...
a_val = int(input()) b_val = int(input()) def gcd(a, b): if b > a: a, b = b, a if a % b == 0: return b else: return gcd(b, a % b) def reduce_fraction(n, m): divider = gcd(n, m) return int(n / divider), int(m / divider) result = reduce_fraction(a_val, b_val) print(*resul...
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 0 elif n < 0: return (1.0 / x) ** abs(n) else: return x ** n s = Solution() print(s.myPow(2.00000, 10))
MOD = 998244353 r, c, n = map(int, input().split()) dp = [[0] * (1 << c) for _ in range(r + 1)] dp[0][0] = 1 for row in range(r): for bit_prev in range(1 << c): bit_prev <<= 1 for bit in range(1 << c): bit <<= 1 count = 0 for i in range(c + 1): i...
array([[ -8.71756106, -1.36180276], [ -8.58324975, -1.6198254 ], [ -8.44660752, -1.87329902], [ -8.30694854, -2.12042891], [ -8.16366778, -2.35941504], [ -8.01626074, -2.58846783], [ -7.8643173 , -2.80576865], [ -7.70752251, -3.0094502 ], [ -7.5458139 , -...
class Solution: """ @param numbersbers : Give an array numbersbers of n integer @return : Find all unique triplets in the array which gives the sum of zero. """ def threeSum(self, numbers): if not numbers or len(numbers) < 3: return set() numbers.sort() triplets =...
"""Module containing scheduling algorithms. Each scheduling algorithm receives a specific set of inputs. They output partial mappings when requested using the query method. Implemented scheduling methods: OpenMPStatic, LPT. Methods with interfaces but no implementation: OpenMPDynamic, OpenMPGuided, RecursiveBipartiti...
NAME = 'comic.py' ORIGINAL_AUTHORS = [ 'Miguel Boekhold' ] ABOUT = ''' Returns a random comic from xkcd ''' COMMANDS = ''' >>> .comic returns a url of a random comic ''' WEBSITE = ''
def printMyName(myName): print('My name is' + myName) print('Who are you ?') myName = input() printMyName(myName)
def get_version_from_win32_pe(file): # http://windowssdk.msdn.microsoft.com/en-us/library/ms646997.aspx sig = struct.pack("32s", u"VS_VERSION_INFO".encode("utf-16-le")) # This pulls the whole file into memory, so not very feasible for # large binaries. try: filedata = open(file).read() e...
class NodeConfig: def __init__(self, node_name: str, ws_url: str) -> None: self.node_name = node_name self.ws_url = ws_url
#always put a repr in place to explicitly differentiate str from repr class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __repr__(self): return '{self.__class__.__name__}({self.color}, {self.mileage})'.format(self=self) def __str__(self): ...
# -*- coding: utf-8 -*- 'Documentation Comments' __author__ = '吴钦飞' def test(): print('location module') if __name__=='__main__': test()
# #星号表达式 # def drop_first_last(grades): # first, *middle, last = grades # return avg(middle) record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') name, email, *phone_numbers = record print(name) print(email) print(phone_numbers) #星号表达式用在列表开始的部分 *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3] ...
BROKER_URL = "mongodb://arbor/celery" CELERY_RESULT_BACKEND = "mongodb" CELERY_MONGODB_BACKEND_SETTINGS = { "host": "arbor", "database": "celery" }