content
stringlengths
7
1.05M
class ElementIntersectsFilter(ElementSlowFilter, IDisposable): """ A base class for filters used to match elements which intersect with geometry. """ def Dispose(self): """ Dispose(self: ElementFilter,A_0: bool) """ pass @staticmethod def IsCategorySupported(element): ...
class ApiCollection: items = [] limit = 10 offset = 0 next_href = None
dataset_type = 'CocoDataset' data_root = '../data/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='Resize', img_scale=[(480, 480), (...
class DataStructure: def __init__(self, df, target_column, dataset_type_column='dataset_type'): self.df = df.copy() self.dataset_type_column = dataset_type_column self.target_column = target_column self.feature_columns = set(self.df.columns) - set([self.target_column, self.dataset_ty...
"""This is gramatically correct, but it's still a SyntaxError""" yield from [1, 2] # [yield-outside-function] LAMBDA_WITH_YIELD = lambda: (yield from [1, 2])
#! /usr/bin/env python3 ## create a dictionary switch = {'hostname': 'sw1', 'ip':'10.0.1.1', 'version': '1.2', 'vendor': 'cisco'} ## display parts of the dictionary print(switch['hostname']) print(switch['ip']) ## request a fake key #print(switch['lynx']) ## request a fake key with .get() method print("first key tes...
# # Copyright (c) 2017 Joy Diamond. All rights reserved. # @gem('Topaz.Cache') def gem(): require_gem('Topaz.Core') require_gem('Topaz.CacheSupport') require_gem('Topaz.GeneratedConjureQuadruple') require_gem('Topaz.OldConjureQuadruple') show = 0 # # Specific instances # eig...
simple_tenant_usage_data = \ [{ u'total_volume_gb_usage': 480.0, u'total_memory_mb_usage': 393216.0, u'total_vcpus_usage': 192.0, u'start': u'2012-09-05 00:00:00', u'tenant_id': u'e638ade19b0de826ee1391ee8e84dd7e', u'stop': u'2012-09-06 00:00:00', u'total_hours': 48.0, u'total_local_gb_u...
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-IpxMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-IpxMIB # Produced by pysmi-0.3.4 at Wed May 1 14:30:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Usi...
# # PySNMP MIB module RAQMON-RDS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-RDS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:43:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
class Solution: def subdomainVisits(self, cpdomains): """ :type cpdomains: List[str] :rtype: List[str] """ domains = collections.Counter() subDomains = collections.Counter() # O(N) for item in cpdomains: count, domain = item.split(' ') ...
# coding: utf-8 """ Functional tests for the public app """ class TestPublicViews: """ Test the public app views """ def test_index_returns_200(self, testapp): """ Index page """ client = testapp.get('/') assert client.status_code == 200
ORIG_W, ORIG_H = (800, 500) RENDER_W, RENDER_H = ORIG_W, ORIG_H def adjwidth (x): return (RENDER_W * x) / ORIG_W def adjheight (y): return (RENDER_H * y) / ORIG_H def adjpos (x, y): return (adjwidth (x), adjheight (y)) def adjrect (a, b, c, d): return (adjwidth (a), adjheight (b), adjwidth (c), adjw...
print('----- x2, x3 e raiz -----') nt = float(input ('Escreva um número para teste:')) db = nt*2 tp = nt*3 rz = nt**(1/2) print('O dobro de {} é {}.'.format(nt, db)) print('O triplo de {} é {}.'.format(nt, tp)) print('A raiz quadrada de {} é {:.2f}.'.format(nt, rz)) print('') print('MELHORADO DENTRO DO .FORMAT')
# -*- coding: utf-8 -*- class KeyNotFound(Exception): pass class InvalidUrl(Exception): pass class InvalidAlias(Exception): pass class InvalidGatewayResponse(Exception): pass
class Queries: GET_BOOKS_COUNT = 'SELECT COUNT(*) FROM moscow_books.book;' GET_USER_HISTORY_BOOK_IDS = 'SELECT catalogueRecordID FROM moscow_books.books_issuance WHERE readerID=%s;' GET_BOOK = 'SELECT recId AS id, aut AS author, title FROM moscow_books.book WHERE recId=%s;' GET_BOOK_NEWCOMER = 'SELECT ...
def count_digits(n): if(n == 0): return n if(n < 0): n *= -1 if(n < 10): return 1 return 1 + count_digits(n/10)
class Example: 'Common base class for all employee' def printValue(self): print(Example.__doc__) print(Example.__name__) print(Example.__dict__) print(Example.__module__) print(Example.__bases__) example = Example() example.printValue()
def get_level(): level = input("난이도 (상중하) 중에서 하나 선택하여 입력: ") while level not in {"상","중","하"}: level = input("난이도 (상중하) 중에서 하나 선택하여 입력: ") if level=="하": return 6 if level == "중": return 8 if level == "상": return 10 print(get_level())
default_excluded_paths = ['/health/', '/api/notify/'] def excluded_path(path, excluded_paths): excl_paths = excluded_paths.split(',') + default_excluded_paths return ( path and any([p for p in excl_paths if path.startswith(p)]))
edad = 17 hambre = edad dinero = 2000 helados_consumidos = 0 precio_helado = 100 while (hambre) < 85 and (dinero-precio_helado) > 0: dinero = dinero - precio_helado precio_helado = precio_helado + (precio_helado * 0.2) helados_consumidos = helados_consumidos + 1 hambre = hambre + edad if (hambre + ...
CONFIG_VERSION = 1 config = None class Config: def __init__(self, obj): if 'CONFIG_VERSION' not in obj: raise Exception("Configuration file must contain 'CONFIG_VERSION' field") if obj['CONFIG_VERSION'] != CONFIG_VERSION: raise Exception("Expected CONFIG_VERSION to be %s fo...
# Copyright 2016 Nidium Inc. All rights reserved. # Use of this source code is governed by a MIT license # that can be found in the LICENSE file. { 'targets': [{ 'target_name': 'generate-embed', 'type': 'none', 'actions': [ { 'action_name': 'Generating embed', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lenovo @file: File.py @time: 2021/4/12 13:20 """ def write_to_file(filename,content): with open(filename, 'a') as f: # 如果filename不存在会自动创建, 'w'表示写数据,写之前会清空文件中的原有数据! for i in range(0,len(content)): f.write(content[i]) f.wri...
class Board: def __init__(self, boardInputFile): # initialise board variables self.sizeH, self.sizeV, self.nWallSquares, self.wallCoordinates, self.nBoxes, \ self.boxCoordinates, self.nstorLocations, self.storCoordinates, self.playerLoc = \ None, None, None, None, None, None, None, None, None self.boardInpu...
def displayGrid(src): state = src.copy() state[state.index(-1)] = ' ' print(state[0], state[1], state[2]) print(state[3], state[4], state[5]) print(state[6], state[7], state[8]) print() def gen(state, m, b): temp = state.copy() if m == 'u': temp[b...
DATABASES = { 'default': { 'NAME' : ':memory:', 'ENGINE': 'django.db.backends.sqlite3', 'SUPPORTS_TRANSACTIONS' : 'False' } } INSTALLED_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django_app',) SECRET_KEY = "dmqsTestSecretKey"
""" Part 1 ------ [1,1] => 2 [] => 0 [0] => 0 [1,1,1,0,1,1,0,1] => 3 [1,0,1,1,0,1,1,1] => 3 """ def longestConsecutive(list): """ assume list is a list """ if len(list) == 0: return 0 longest = 0 currentlen = 0 for element in list: if element == 1: currentlen += 1 ...
#!/usr/bin/env python3.8 def starred_return(): my_list = ["value2", "value3"] return "value1", *my_list def starred_yield(): my_list = ["value2", "value3"] yield "value1", *my_list # output #!/usr/bin/env python3.8 def starred_return(): my_list = ["value2", "value3"] return "value1", *...
print("""Welcome! Are you completely new to programming? about why and how to get started with Python. Fortunately an experienced programmer in any programming language (whatever it may be) can pick up Python very quickly. Its also easy for beginners to use and learn, so jump in!""")
#!/usr/bin/env python3 '''a gcode scraper that performs common functions for gcode editing purposes. gscrape is desiged to enable more effecient writing of macros for machine programmers who wish to automate code formatting''' class gscrape(): def __init__(self): self._comment_flags = dict() def ad...
#!/usr/bin/env python3 ######################################################################## # # # Program purpose: Gets all strobogrammatic numbers that are of # # length 'n'. # # ...
class FONT_MODULE: """ font name too long can't remember """ def __init__(self, parent): self.parent = parent self.commands = { "retro": self.retro, "futurism": self.futurism, "stream": self.stream, "default": self.default, } self.add_self() def retro(self, arg=None): self.parent.font_set(...
def create_graph(): return { 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'}, ], 'layout': { 'title': 'Dash Data Visualization' } }
# Find the element that appears once # https://www.geeksforgeeks.org/find-the-element-that-appears-once/ # SGVP387500 | 14:47 26F19 # fun to find the element that appears once def getSingle(arr, n): print("getSingle()- start | 14:55 26F19") ones = 0 twos = 0 for i in range(n): twos = twos | (o...
def can_build(platform): # FIXME: Disabled temporary for gles3 implementation return False def configure(env): pass
tupla = (2,5,9,12) print(tupla) segundo_elemento = tupla[1] print(segundo_elemento) tupla1 = (2,) print(tupla1) tupla_de_lista = tuple([2,5,8]) print(tupla_de_lista) lista_de_tupla = list(tupla) print(lista_de_tupla) tupla_elemento_mutavel = (9,[2,5],12) print(tupla_elemento_mutavel) # erro - AttributeError: 'int...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def set_width(self, new_width): self.width = new_width def set_height(self, new_height): self.height = new_height def get_area(self): return self.width * self.height ...
class ClassForTesting: def use_this_func(self, a): return a class ClassForTesting2(ClassForTesting): def use_this_func(self, a): b = a * 10 return b class ClassForTesting3(ClassForTesting): pass class ClassForTesting4(ClassForTesting2): def use_this_func(self, a): b...
#Python simple if else and while loop example. #Python basit if else ve while döngüsü örneği. #You can copy that file as you want. #Its ok for me :D #Dosyayı istediğiniz gibi kopyalayabilirsiniz. #Benim için sorun yok :D user = input("admin/user ") parola = "1234" haksayac = 0 if user == "admin": ...
#Juan Pablo Montoya Números mayores y menores def menor(a,b): return (a, False) if a<=b else (b, True) def mayor(a,b): return (a, False) if a>=b else (b, True) def main(array = ["a", "b", "c", "d"]): letra_mayor="" letra_menor="" maximo = 0 minimo = float("inf") for valor in ...
class ResourceMetadata (object): def __init__(self, system_meta, science_meta): self.__dict__.update(science_meta) self.__dict__.update(system_meta) @property def url(self): return self.resource_url @property def abstract(self): return self.description @prop...
# -*- coding: utf-8 -*- __version__ = '0.2.0' __doc__ = """ TERA : the Toxicological and Risk Assessment Knowledge Graph. The set of APIs enables aggregation, integration and access of several data sources relevant to the toxicological and risk assessment domain. """
x = 0 depth = 0 with open("data.txt", "r+") as f: lines = f.readlines() for line in lines: commands = line.split(" ") direction = commands[0] val = int(commands[1]) match direction: case "down": depth += val case "up": ...
#Sintaxis basica de una funcion def mi_funcion(): print("Ejecucion de la funcion") #Llamando la funcion mi_funcion()
class Solution: # my solution def heightChecker(self, heights: List[int]) -> int: ordered = sorted(heights) res = 0 for i, j in zip(ordered, heights): if i != j: res += 1 return res
def early_stop(cost_window): if len(cost_window) < 2: return False else: curr = cost_window[0] for idx, cost in enumerate(cost_window): if curr < cost or idx == 0: curr = cost else: return False return True def early_stop2...
# 3.1 names = ['john', 'dirk', 'elon', 'rita', 'bob'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4]) # 3.2 print(f'Hello, {names[0].title()}') print(f'Hello, {names[1].title()}') print(f'Hello, {names[2].title()}') print(f'Hello, {names[3].title()}') print(f'Hello, {names[4].title()}')...
first = int(input('Write a initial term of an arithmetic progression:')) difference = int(input('Write a common difference:')) term = first cont = 1 while cont <= 10: print('{} -> '.format(term), end='') term += difference cont += 1 print('Many terms {}'.format(cont-1))
""" Graph representation - 2 main forms: -------------------- -> use an adjacency matrix & a dictionary -> use an adjacency list -> Adjacency list ----------------- - Use a simple list can be used to present a graph. The indices of the list will represent the nodes/vertices in the graph. At each index, the adjacent n...
def kowsi(): global x x="blue" print("Color is "+x) kowsi()
############################################################################ ## MagicQ FX Constants ## July 22, 2016 ## Austin Tyler ## ## Reference: MagicQ Manual - Chapter 31. ChamSys Remote Protocol Commands ## http://chamsys.co.uk #####################################################################...
class Error(Exception): """Base class for other exceptions""" pass class LoginTimeoutError(Error): """Raised login to device times out""" pass class LoginCredentialsError(Error): """Raised when there is a problem with the user credentials""" pass
# 01-08-2021 # Emma Benjaminson # Binary Tree Implementation (v1) # Source: https://medium.com/swlh/making-data-trees-in-python-3a3ceb050cfd class Tree(): def __init__(self, root): self.root = root self.children = [] def addNode(self, obj): self.children.append(obj) class Node(): ...
# 短信验证码有效期,单位秒 SMS_CODE_TIME = 5 * 60 # 发送短信验证码时间,单位秒 SEND_SMS_CODE_TIME = 60 # 短信验证码模板 SMS_CODE_TEMP_ID = 1
#!/usr/bin/env python3 ''' Return True if every even index contains an even number and every odd index contains an odd number. Else return False ''' def is_special_array(lst): a = [i for i in lst[::2] if i % 2 == 1] b = [i for i in lst[1::2] if i % 2 == 0] return len(a) == len(b) #Alternative Solutions def is_spec...
# -*- coding: utf-8 -*- class NotFoundSchema(Exception): """ When can't find schema raise exception """ pass
def run(program): program_counter = 0 while True: op_code = program[program_counter] if op_code == 1: program[program[program_counter + 3]] = program[program[program_counter + 2]] + program[ program[program_counter + 1]] elif op_code == 2: program[...
class Subkey: def __init__(self, value, origin: str, output_matching: bool=False): ''' Params ------- value: subkey value corresponding to a Vset module origin: str name of the origin Vset of this Subkey output_matching: inherited from the Vse...
# how count the number of items in a list # define count function def conteggio(numbers): total = 0 for x in numbers: # rolling sum if x < 20: total += 1 return total list_1 = [1, 3, 5, 7, 15, 23, 43, 56, 78] conteggio(list_1)
#!/usr/bin/python class Problem7: ''' ''' def solution(self): return 0 p = Problem7() print(p.solution())
#!/bin/python3 if __name__ == '__main__': n = int(input().strip()) if (n % 2) != 0 : print("Weird") elif ((n%2)==0) and n in range(6,21): print("Weird") elif ((n % 2) ==0) and n in range(2,5): print("Not Weird") elif ((n % 2) == 0) and n > 20: print("Not Weird"...
def anagram_check(s1: str, s2: str): s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() if len(s1) != len(s2): return False cache = {} for char in s1: cache[char] = cache.get(char, 0) + 1 for char in s2: if not cache.get(char): return False ...
IN1 = 29 IN2 = 31 IN3 = 33 IN4 = 35 AvoidSensorfor = 40 AvoidSensorbac = 38
"""In-order, pre-order, and post-order tree traversal.""" class Node(object): def __init__(self, val): self.left = None self.right = None self.value = val def inOrder(root): if not root: return out = [] l = inOrder(root.left) if l: out.extend(l) out.append(root.value) r = inOrder(r...
# -*- coding: utf-8 -*- xy = list(map(int, input().split())) lh0 = list(map(int, input().split())) lh1 = list(map(int, input().split())) if lh0[1] + lh1[1] <= xy[1] and max(lh0[0], lh1[0]) <= xy[0]: print("S") elif lh0[0] + lh1[1] <= xy[1] and max(lh0[1], lh1[0]) <= xy[0]: print("S") elif lh0[1] + lh1[0] <=...
class Purchase: def __init__(self, product_name, cost): self.product_name = product_name self.cost = cost def __add__(self, other): name = f'{self.product_name}, {other.product_name}' cost = self.cost + other.cost return Purchase(name, cost) def __repr__(self): ...
HTTP_OK = 200 HTTP_PARTIAL = 206
def get_part2_input(): with open('Day3_input_part2.txt','r') as input_file: input = input_file.read().split("\n") # There is a "\n" at the end that gives problems, we simply delete it del input[-1] return input def solve_part1(input_file): with open(input_file,'r') as input: ...
class CommandIODefinition: """Class which contains a set of inputs and outputs for a command, based on the configuration. """ def __init__(self, input_uris=None, output_uris=None, missing_input_messages=None): if input_uris is None: ...
# Algorytmy Grafowe # Piotr Faliszewski 2019 # Load graph in the DIMACS ascii format + weights def loadCNFFormula( name ): """Load a CNF formula in the DIMACS ascii format from the file "name" and return it as a list of clauses Returns (V,F) V -- highest variable number F -- list of clauses""" ...
clist = [ "\\c[uh0]", "\\c[uh1]", "\\c[uh2]", "\\c[uh3]", "\\c[uh4]", "\\c[uh5]", "\\c[uh6]", "\\c[uh7]", "\\c[uh8]", "\\c[uh9]", "\\c[uh10]", "\\c[uh11]", "\\c[uh12]", "\\c[uh13]", "\\c[uh14]", "\\c[uh15]", "\\c[uh16]", "\\c[uh17]", "\\c[uh18]", "\\c[uh19]", "\\c[uh20]", "\\c[uh21]", "\\c[uh22]", "\\c[uh23]", ...
a = int(input('Digite um número: ')) s = 0 s += a mult = input('Você quer continuar digitando valores? ').lower().strip() cont = 1 maior = menor = a while mult != 'não': a = int(input('Digite um número: ')) cont += 1 s += a mult = input('Você quer continuar digitando valores? ').lower().strip(...
''' .. module:: dsge :platform: Linux :synopsis: The dsge module is just a package which contains all of the modules required to do DSGE modelling, that is solving them and then doing further work with the obtained solutions, such as simulating and generating IRFs. .. moduleauthor:: Eric M. Scheffe...
MEMCACHE_HOST="127.0.0.1" MEMCACHE_PORT=11211 MONGO_HOST="localhost" MONGO_PORT="27017" MONGO_DB="taskqueue" MONGO_LOG_COLLECTION="tasklog" MONGO_TOMBSTONE_COLLECTION="tombstones" BROKER_URL = "pyamqp://someuser:somepassword@somehost.somedomain.com:5672/somevhost" CELERY_RESULT_BACKEND = "mongodb" CELERY_MONGODB_BAC...
if __name__ == '__main__': s = 'spam' print(dir(s)) print(dir(str)) print(s + 'ni!') print(s.__add__('ni!')) print(help(s.replace)) print(help(str.replace))
overlapping = ( ((1, 5), (2, 6)), ((5, 7), (3, 7)), ((-3, 6), (-7, -1)), ((2, 3), (2.5, 5.5)) ) overlapping_edge = ( ((-6, -4), (-5.5, -4.5)), ((1, 9), (5, 6)), ((5, 6), (1, 9)), ((1, 5), (1, 5)), ((1, 1), (1, 1)), ((1, 1), (2, 1)), ((0, 4), (4, 8)), ((4, 6.1), (5.9, 8))...
números = (int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais um número: ')), int(input('Digite o último número: '))) print(f'Você digitou os valores {números}') if números.count(9) > 1: print(f'O valor 9 apareceu {números.count(9)} vezes') else: print(f'O v...
"""Custom Exceptions.""" class NoDataFound(Exception): """Exception for when no data was found for request.""" class UnitsError(Exception): """Exception for bad Units.""" class TextProductException(Exception): """Exception for Text Parsing.""" class HWOException(Exception): """Exception for HWO ...
# https://leetcode.com/problems/keep-multiplying-found-values-by-two/ class Solution: def findFinalValue(self, nums: List[int], original: int) -> int: while True: if original in nums: original *= 2 else: return original
print("Begin") i=input('Enter fno:') j=input('Enter sno:') try: x=int(i) y=int(j) z=x/y print(z) except: print('Erroor occured') print('End')
dict = {'sape': '4139', 'guido': '666'} for k, i in dict.items(): print(k,i)
class Solution: def minCost(self, costs: List[List[int]]) -> int: if not costs: return 0 if len(costs) == 1: return min(costs[0]) def dfs(costs, prev): if not costs: return 0 r = b = g = float("inf") if prev != "red"...
ecoopgroup = {} ecoopgroup['TWC'] = {} ecoopgroup['TWC']['subgroup'] = '' ecoopgroup['TWC']['organization'] = '' ecoopgroup['TWC']['homepageURL'] = '' ecoopgroup['TWC']['mbox'] = '' ecoopgroup['TWC']['address'] = '' ecoopgroup['TWC']['phone'] = '' ecoopgroup['TWC']['name'] = 'TWC' ecoopgroup['TWC']['members'] = ''
# Equality print(2 == 2) print(1 == 2) print('hello' == 'bye') print('Bye' == 'bye') # Not Equality print(3 != 3) print(4 != 5) # Greater than print(1 > 3) print(5 > 2) # Less than print(30 < 10) print(5 < 7) # Greater than or equal print(3 >= 3) print(4 >= 3) print(1 >= 3) # Less than or equal print(3 <= 3) print...
load("@bazel_skylib//lib:dicts.bzl", "dicts") load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install") load("@rules_haskell//haskell:repositories.bzl", "rules_haskell_dependencies") load("@rules_haskell//haskell:toolchain.bzl", "rules_haskell_toolchains") load("@rules_haskell//haskell:cabal.bzl", "stack_snapshot")...
# Reading input file f = open("inputs/day05.txt", "r") lines = f.readlines() def get_position(low, high, seat_code, lower_label): if high - low == 2: if len(seat_code) == 1: if seat_code == lower_label: return low else: return high - 1 else: ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: def add_node(self,x): if self.next is None: self.next=ListNode(x)...
class OrderError(ValueError): pass class CompoundedError(ValueError): pass
""" Crie um programa que tenha um tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.""" # Caique Santana palavras = ('aprender', 'programas', 'linguagem', 'python', 'curso', 'gratis', 'estudar', 'praticar', 'trabalhar', 'me...
#%% """ - Beautiful Arrangement - https://leetcode.com/problems/beautiful-arrangement/ - Medium Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 <= i <= N) in this array: T...
""" INPUTS AND EXPECTED OUTPUTS:- 9 => "1001" 60 => "0011_1100" 100 => "0110_0100" 63000 => "1111_0110_0001_1000" """ def get_binary(n): s = bin(n)[2:]; # Getting binary string strs = []; while s: l = len(s); # Finding lenght of binary string if l > 4: strs.insert(0, s[l-4:]); s = s[:l...
class AmazonItem(object): def __init__(self, title, price, picture_url, amazon_url): self.title = title self.price = price self.picture_url = picture_url self.amazon_url = amazon_url
""" Descrição: Este programa verifica se um caractere está na lista informada. Autor:Henrique Joner Versão:0.0.1 Data:11/01/2019 """ #Inicialização de variáveis L = [] x = "" #Entrada de dados L = ["a", "b", "c", "d"] x = input("Digite a letra que deseja pesquisa na lista: ").lower() #Processamento de dados def ...
"""Plugin commands.""" async def on_reverse(app, message, *args): """Reverse the string in argument and send it back.""" if not args: await app.send_message(message.channel, f"_Usage: {app.prefixize('reverse')} string_") else: await app.send_message(message.ch...
#Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog. class Animals: animalType = "Mammal" class Pets: color = "White" class Dog: @staticmethod def bark(): print("Bark") d = Dog() d.bark()
def create_task_from_section_a5(task_type): # Cell numbering: [[[0, 1, 2]]] # Desired solution: [[[0, 1, whatever]]] grid_sizes = [1, 1, 3] # 1D example represented in 3D for generality rays = [[0, 1, 2]] # linear indices of grid cells are listed for each ray gradient_step_size = 1. # implicitly specified via...
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """ File contains constants used in the integration. """ # Page size to for paged results from Resilient. INC_PAGE_SIZE = 500 # Name of Resilient incident close status template file ...
class Object: ## `A << B -> A[B.tag] = B` left/tag slot assignment def __lshift__(self, that): that = self.box(that) return self.__setitem__(that.tag(), that) ## `A // B -> A.push(B)` stack-like push to end of vector def __floordiv__(self, that): that = self.box(that) s...
class ValueRange: name: str min: float max: float value: float def __init__(self, name, min, max): self.name = name self.min = min self.max = max def __set__(self, parent, value): if value not in range(self.min, self.max): err = f'{self.name} is not...