content
stringlengths
7
1.05M
# for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # self.right = right # self.right = right # self.right = right # self.right = right # self.right =...
def process(status): status_info = {} status_info['name'] = status.pos.name status_info['target'] = status.target return status_info
__author__ = 'Ahmed Hani Ibrahim' class TextEncoder(object): @classmethod def encode(cls, categories): categories_matrix = [[0 for i in range(0, len(categories))] for j in range(0, len(categories))] true_index = 0 for i in range(0, len(categories)): categories[i][true_ind...
TRAIN_CONTAINERS = [ 'plate', 'cube_concave', 'table_top', 'bowl_small', 'tray', 'open_box', 'cube', 'torus', ] TEST_CONTAINERS = [ 'pan_tefal', 'marble_cube', 'basket', 'checkerboard_table', ] CONTAINER_CONFIGS = { 'plate': { 'container_position_low': (.50,...
# -*- coding: utf-8 -*- class Solution: def maxProfit(self, prices): minimum_price = float('inf') maximum_profit = 0 for price in prices: if price < minimum_price: minimum_price = price if price - minimum_price > maximum_profit: maxi...
# Program : Find the number of vowels in the string. # Input : string = "Nature" # Output : 3 # Explanation : The string "Nature" has 3 vowels in it, ie, 'a', 'u' and 'e'. # Language : Python3 # O(n) time | O(1) space def length_of_string(number): # Initialize the vowel list. vowels = ["a", "e", "i", "o", "u"...
def reverse_integer(n): reversed = 0 remainder = 0 while n > 0: remainder = n % 10 reversed = reversed * 10 + remainder n = n // 10 return reversed if __name__ == "__main__": print(reverse_integer(12345))
class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade # between 0 - 100 def get_grade(self): return self.grade class Course: def __init__(self, name, max_students): self.name = name self.max_students = max...
class IRobotCreateError(Exception): def __init__(self, errorCode = 0, errorMsg = ""): self.errorCode = errorCode self.errorMsg = errorMsg # self.super() class ErrorCode(): SerialPortNotFound = 1 SerialConnectionTimeout = 2 ConfigFileError = 3 ConfigFileCorrupted = 4 Va...
t=0.0 dt=0.05 cx=0 cy=0 r=180 rs=[(x+2)*1.1 for x in range(500)] dr=-1 wiperon=True sopa=255 wopa=40 sc=[255,255,255] wc=[0,0,0] fpd=10 def setup(): global cx,cy size(1280,720) background(0) stroke(sc[0],sc[1],sc[2],sopa) cx=width/2 cy=height/2 def wipe(): fill(wc[0],wc[1],wc[2],wopa) ...
"""Column Mapping base class.""" class ColumnMapSolver: """Base Solver for the data lineage problem of column dependency.""" def fit(self, list_of_databases): """Fit this solver. Args: list_of_databases (list): List of tuples containing ``MetaData`` instnces and t...
with open('multiplos4.txt', 'w') as multiplos: pares = open('pares.txt') for l in pares.readlines(): num = l.replace('\n', '') if int(num) % 4 == 0: multiplos.write(f'{num}\n')
class BaseSecretEngine: def __init__(self, config_d): self.name = config_d['secret_engine_name'] self.default = config_d.get("default", False) def encrypt(self, data, **context): raise NotImplementedError def decrypt(self, data, **context): raise NotImplementedError
n,k,*x=map(int,open(0).read().split()) def distance(l,r): return min( abs(l)+abs(r-l), abs(r)+abs(r-l)) a=[] for i in range(n-k+1): a.append(distance(x[i],x[i+k-1])) print(min(a))
""" Script testing 14.4.1 control from OWASP ASVS 4.0: 'Verify that every HTTP response contains a Content-Type header. Also specify a safe character set (e.g., UTF-8, ISO-8859-1) if the content types are text/*, /+xml and application/xml. Content must match with the provided Content-Type header.' The script will rai...
# plot a KDE for each attribute def plot_single_kde(data, attr): data[[attr]].plot.kde(figsize=(4,2), legend=None) ax = plt.gca() ax.set_xlim([data[attr].min(), data[attr].max()]) ax.set_xlabel(attr, fontsize=14) ax.set_ylabel('Density', fontsize=14) for attr in data.columns: plot_single_kde(d...
# Solution # O(n) time / O(n) space def sunsetViews(buildings, direction): buildingsWithSunsetViews = [] startIdx = 0 if direction == "WEST" else len(buildings) - 1 step = 1 if direction == "WEST" else - 1 idx = startIdx runningMaxHeight = 0 while idx >= 0 and idx < len(buildings): bu...
N=int(input()) M,K=list(map(int,input().split())) L = list(map(int,input().split())) L.sort(reverse = True) S = M*K for i,j in enumerate(L): S -= j if S<=0: print(i+1) break else: print("STRESS")
#!/usr/bin/env python3 while True: n = int(input("Please enter an Integer: ")) if n < 0: continue #there will retrun while running elif n == 0: break print("Square is ", n ** 2) print("Goodbye")
class Bucket(): '''Utility class for Manber-Myers algorithm.''' def __init__(self,prefix,stringT): self.prefix = prefix # one or more letters self.stringT = stringT # needed for shortcut sort self.suffixes = [] # array of int def __str__(self): viz = "" viz = viz +...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: 属性访问代理 Desc : """ class A: def spam(self, x): pass def foo(self): pass class B1: """简单的代理""" def __init__(self): self._a = A() def spam(self, x): # Delegate to the internal self._a instance ret...
# -*- coding: utf-8 -*- """ idfy_rest_client.models.status This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class Status(object): """Implementation of the 'Status' enum. TODO: type enum description here. Attributes: UNKNOWN: TOD...
arr = [9, 5, 1, 4, 0, 7] def quick_sort_v1(arr, l, r): if l >= r: return x = l y = r base = arr[l] while x <= y: while x <= y and arr[y] > base: y = y - 1 while x <= y and arr[y] < base: x = x + 1 if x <= y: arr[y], arr[x] = arr[x...
# -*- python -*- load("@drake//tools/skylark:drake_py.bzl", "py_test_isolated") def install_lint( existing_rules = None): """Within the current package, checks that any install rules are depended-on by Drake's master //:install rule. """ if existing_rules == None: existing_rules = nati...
schema = [ { "attributes": { "L": [ { "M": { "attr_name": { "S": "wave_name" }, "attr_type": { "S": "wave" }...
print ("Enter a value" ) a = int (input()) print ("Enter b value" ) b = int (input()) print ("value of a is",a) print ("value of b is",b) print ("value of a+b value is", a+b) print ("value of a-b value is", a-b) print ("value of a*b value is", a*b) print ("value of a/b value is", a/b)
i = 0 while (i < 50): print(i) i = i + 1
# -*- coding: utf-8 -*- """ Commonly used band frequencies For your convenience we have predefined some widely adopted brain rhythms. You can access them with .. code-block:: python :linenos: from dyconnmap.bands import * print(bands['alpha']) ============= ================== ================= brain...
languages = { 'en': 'English', 'es': 'Español', } test_basic_params = { 'en': 'Toolkit', 'es': 'Contrataciones', } test_navigation_params = [ ('en', 'Next'), ('es', 'Siguiente'), ] test_search_params = [ ('en', r'found \d+ page\(s\) matching'), ('es', r'encontró \d+ página\(s\) acorde...
for i in range(int(input())): n,base=input().split() base=str(base) aux=0 print("Case %d:"%(i+1)) if base=="bin": aux=int(n, 2) print("%d dec"%aux) aux=hex(aux).replace('0x','') print("%s hex"%aux) elif base=="dec": n=int(n) aux=hex(n).replace('0x'...
v=0 def czytaj_int(prompt, min, max): ok=False while not ok: try: wartosc=int(input(prompt)) ok=True except ValueError: print("Błędna wartość na wejściu") if ok: ok=wartosc >= min and wartosc <= max if not ok: print("Błą...
DATABASES = { 'postgresql_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'quickdb', 'USER': 'sonarsource', 'PASSWORD': '1234', # Noncompliant 'HOST': 'localhost', 'PORT': '5432' } }
class Solution: def partition(self, s: str) -> List[List[str]]: def is_palindrome(s:str): if s == s[::-1]: return True else: return False path = [] res = [] size = len(s) def backtracking(s, start): nonlocal ...
# O(n) time and space where n is number of chars def get_longest_unique_substring(s): start_index = 0 end_index = 0 answer = 0 char_to_position = {} for i,let in enumerate(s): if let not in char_to_position: char_to_position[let] = i elif char_to_position[let] >= start_in...
#How to reverse a number num = int(input("Enter the number : ")) rev_num = 0 while(num>0): #logic rem = num%10 rev_num= (rev_num*10)+rem num = num//10 print("Result : ",rev_num)
def colored(string, color): """ Returns the given string wrapped with a ANSI escape code that gives it color when printed to a terminal. Args: string: String to be colored. color: Chosen color for the string. Can be 'r' for red, 'g' for green, 'y' for yellow, 'b' for blue, 'p' for ...
load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_android_library") load(":databinding_aar.bzl", "databinding_aar") load(":databinding_classinfo.bzl", "direct_class_infos") load("@io_bazel_rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") load(":databinding_r_deps.bzl", "extract_r_txt_deps") load(":databinding_stubs...
expected_output = { "program": { "auto_ip_ring": { "instance": { "default": { "active": "0/RSP1/CPU0", "active_state": "RUNNING", "group": "central-services", "jid": "1156", "sta...
def get_formatted_name(first, middle, last): """Generate a neatly formatted full name""" full_name=f"{first} {middle} {last}" return full_name.title() """this version works for people with middle name but breaks for people with only first and last names"""
def aumentar(n, porcento, formatado=False): multiplicador = porcento * 0.01 final = n * multiplicador + n if formatado: final = moeda(final) return final def diminuir(n, porcento, formatado=False): multiplicador = porcento * 0.01 final = n - n * multiplicador if formatado: ...
name = input("Please enter your first name: ") age = int(input("How old are you, {0}? ".format(name))) print(age) # if age >= 18: # print("You are old enough to vote") # print("Please put an X in the box") # else: # print("Please come back in {0} years".format(18-age)) if age < 18: print("Please come back in {...
states_of_america = ["Delware","Pennsylvanai","Mary land","Texas","New Jersey"] print(states_of_america[0]) # Be careful for index out of range error print(states_of_america[-1]) states_of_america.append("Hawaii") print(states_of_america) states_of_america.extend(["Rakshith","Dheer"]) print(states_of_america) # Y...
#declaring and formatting multiples variables as integer. num01 = int(input('Type the first number: ')) num02 = int(input('Type the second number: ')) s = num01 + num02 #showing to user the sum of numbers. print('The sum of {} and {} is: {}' .format(num01, num02, s))
# Write a Python program to find whether a given number (accept from the user) is even or odd, # prints True if its even and False if its odd. n = int(input("Enter a number: ")) print(n % 2 == 0)
#!/usr/bin/env python #pylint: skip-file # This source code is licensed under the Apache license found in the # LICENSE file in the root directory of this project. class PathResponse(object): def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the val...
sm.setSpeakerID(1012100) sm.sendNext("Hello, #h #. I've heard plenty about you from Mai. You are interested in becoming a Bowman, right? My name is Athena Pierce, Bowman Job Instructor. Nice to meet you!") sm.sendSay("How much do you know about Bowmen? We use bows or crossbows to attack enemies at long range, mainly. W...
#coding: utf-8 """ Foram anotadas as idades e alturas de 30 alunos. Faça um Programa que determine quantos alunos com mais de 13 anos possuem altura inferior à média de altura desses alunos. """ def tratarErrorInt(n): if n != "": return n.isdigit() else: return False def tratarErrorFloat(n): if n != "": d = ...
# Author: Senuri Fernando a = int(input()) # take user input b = int(input()) # take user input print(a+b) # addition print(a-b) # subtraction print(a*b) # multiplication
n, x, xpmin = [int(e) for e in input().split()] for i in range(n): xp, q = [int(e) for e in input().split()] if xp >= xpmin: print(xp + x, q + 1) else: print(xp, q)
""" https://leetcode.com/problems/thousand-separator/ Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: Input: n = 987 Output: "987" Example 2: Input: n = 1234 Output: "1.234" Example 3: Input: n = 123456789 Output: "123.456.789" Example 4: Input: n = 0 Ou...
class Invalid: def __init__(self): self.equivalence_class = "INVALID" def __str__(self): return self.equivalence_class
# Copyright 2019-2021 Wingify Software Pvt. Ltd. # # 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 agr...
class Solution: """ @param n: an integer @return: if n is a power of three """ def isPowerOfThree(self, n): # Write your code here if n == 0: return False while n > 1: if n % 3 != 0: return False n = n / 3 return Tr...
abstract_user = { "id": "", "name": "", "email": "", "avatar": "", "raw": "", "provider": "", }
# Теперь вам опять нужно сдать на проверку программу, которая будет печатать "123424242143132324326922342152 + # 213732174232497412039472189472409 = x" (без кавычек), где x - результат вычисления, посчитанный прямо в программе. # # Эта задача предназначена для того, чтобы вы научились различать числа и строки, состоящи...
# Read lines of text from STDIN. def Beriflapp(): while True: # Reading the input from the user i = input("What is the value of 2+8 = ") # Only exits when meets the condition if i == '10': break print("The value", i, "is the wrong answer. Try again") ...
# -*- coding: utf-8 -*- ''' Manage grains on the minion =========================== This state allows for grains to be set. Grains set or altered this way are stored in the 'grains' file on the minions, by default at: /etc/salt/grains Note: This does NOT override any grains set in the minion file. ''' def present(n...
""" Multiples of 3 and 5 ==================== If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. https://projecteuler.net/problem=1 """ print(sum([n for n in range(1, 1000) if n % 3 ...
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
''' Basic Binary Tree in Array Representation Referred from: www.javatpoint.com/program-to-implement-binary-tree-using-the-linked-list ''' class Node: def __init__(self, key): self.value = key self.left = None self.right = None class BinaryTree: def __init__(self): self.root =...
people = [ { 'name': 'Lucas', 'age': 27, 'gender': 'Male', }, { 'name': 'Miguel', 'age': 4, 'gender': 'Male', }, { 'name': 'Adriana', 'age': 27, 'gender': 'Female', }, ] for person in people: for field, data in person.i...
class Solution: def noOfWays(self, M, N, X): # code here if X > M * N: return 0 ways = [[0 for _ in range(M * N + 1)] for _ in range(N + 1)] for i in range(1, M + 1): ways[1][i] = 1 for i in range(2, N + 1): f...
a_1 = -6 b_1 = -6 a = -5 b = -5 m = 255 n = 255 m_add_1 = 100000 n_add_1 = 100000 if __name__ == '__main__': print(a_1 is b_1) print(a is b) print(m is n) print(m_add_1 is n_add_1)
def hex_to_int(hex): assert hex.startswith('0x') hex = hex[2:] total = 0 for h in hex: total *= 16 total += '0123456789abcdef'.index(h) return total def byte_to_uint(byte): total = 0 for c in byte: total *= 2 if c == '1': total += 1 return tot...
#---- # Строительство зданий, сооружений (коррекция величин): metadict_model['Кирпичная кладка в 0.5 кирпича (квадратный метр)'] = { # http://www.gvozdem.ru/stroim-dom/kirpichnaya-kladka.php # Толщина 125 мм: 'Кирпичная кладка (кубометр)':0.125, } metadict_model['Кирпичная кладка в 1 к...
#stores the current state of the register machine for the interpreter class RMState: def __init__(self, REGS): self.b = 1 self.acc = 0 self.REGS = REGS self.ended = False
class Tower: __slots__ = 'rings', 'capacity' def __init__(self, cap: int): self.rings = list() self.capacity = cap def add(self, ring_size:int): if len(self.rings) >= self.capacity: raise IndexError('Tower already at max capacity') if (len(self.rings) > 0) and (...
{ 'targets' : [ { 'target_name' : 'test', 'type' : 'executable', 'sources' : [ '<!@(find *.cc)', '<!@(find *.h)' ], 'include_dirs' : [ ], 'libraries' : [ ], 'conditions' : [ ['OS=="mac"', { 'xcode_settings': { 'A...
class ShorteningErrorException(Exception): def __init__(self, message=None): super().__init__(f'There was an error on trying to short the url: ' f'{message}') class ExpandingErrorException(Exception): def __init__(self, message=None): super().__init__(f'There w...
# # PySNMP MIB module CISCO-VISM-CAS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VISM-CAS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
# # PySNMP MIB module CISCO-WIRELESS-P2P-BPI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WIRELESS-P2P-BPI-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:05:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=":f"): self.name = name self.fmt = fmt self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val ...
class Solution: def maximum69Number (self, num: int) -> int: n = 1000 m = num #// as it is mentioned constraint as num < 10^4 while m: if((m//n) == 6): num += n*3 break m = m%n n = n/10 return int(num) ...
class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: # how to fill the table n1 = len(nums1) n2 = len(nums2) dp = [[-math.inf] * (n2 + 1) for _ in range(n1 + 1)] for i in range(n1 - 1, -1, -1): for j in range(n2 - 1, -1, -1): ...
# # PySNMP MIB module ADTRAN-IF-PERF-HISTORY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-IF-PERF-HISTORY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:14:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
# coding=utf-8 # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'mysql', 'PORT': 3306, 'USER': 'root', 'PASSWORD': 'root', 'NAME': 'cloudsky_backend' ...
while True: try: s = input() # s = 'haha' print(s) except : # print(e) break
""" Entradas: --- Salidas: 2 valores enteros uno que el dato en la posición 12 de la sucesión, y la suma de los primeros 12 valores de la sucesión Posición 12 --> int --> A Suma --> int --> B """ # Caja negra B = 0 for i in range(12): A = 5*i + 6 B = B + A # Salidas print("\nEl término doceavo en la s...
# -*- python -*- load( "//tools/workspace/lcm:lcm.bzl", "lcm_cc_library", "lcm_java_library", "lcm_py_library", ) load( "@drake//tools/skylark:drake_cc.bzl", "drake_installed_headers", "installed_headers_for_drake_deps", ) def drake_lcm_cc_library( name, deps = [], ...
# copybara:strip_for_google3_begin def pyproto_test_wrapper(name): src = name + "_wrapper.py" native.py_test( name = name, srcs = [src], legacy_create_init = False, main = src, data = ["@com_google_protobuf//:testdata"], deps = [ "//python:message_ext...
class History: def __init__(self): self.HistoryVector = [] def Add(self, action, observation=-1, state=None): self.HistoryVector.append(ENTRY(action, observation, state)) def GetVisitedStates(self): states = [] if self.HistoryVector: for history in sel...
def test_answer(test_client, login, confirmation, answerchecking): """ Тест процесса проверки выбора правильного варианта ответа в тестовом вопросе закрытого типа, категория алерта - success, возможность повторно ответить блокируется """ response = test_client.get('/course/1/lesson/1', follow_re...
#!/usr/bin/python # -*- coding: UTF-8 -*- # Given a 32-bit signed integer, reverse digits of an integer. class Solution: max32BitsNum = 1 << 31 def reverse(self, x): """ :type x: int :rtype: int """ if x > Solution.max32BitsNum - 1 or x < -Solution.max32BitsNum: ...
def check_tag(tag): ''' Checks the syntax of tags. ''' assert len(tag) == 7, f'Error with {tag}: tag should have length 7.' assert tag[0] in ['E', 'F'], f'Error with {tag}: the first character of the tag should either be E (Efterår) or F (Forår)' try: year = int(tag[1:2]) as...
# # Copyright 2018 Asylo authors # # 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 writi...
_FONT = { 32: [10, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575, 1048575], 33: [10, 1048575, 1048575, 1048575, 1048575, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1044735, 1048575, 104...
""" 335 / 335 test cases passed. Status: Accepted Runtime: 40 ms """ class Solution: def checkPossibility(self, nums: List[int]) -> bool: cnt = 0 for i in range(1, len(nums)): if nums[i - 1] > nums[i]: cnt += 1 if cnt > 1: return False ...
# Problem: Implement a 3 stack # Algorithm for n-stacks using dynamic arrays (list) # Stack: LIFO (Last In First Out) # pop from top and push to top # data = our dynamic array # Maintain tops array for n-number of stacks and initialize to -1 # Maintain lengths for each stack. # Push(stack, value) # Check i...
n1 = int(input('Digite o 1° número: ')) n2 = int(input('Digite o 2° número: ')) ex = False while not ex: print('''{0} [1] - SOMAR [2] - MULTIPLICAR [3] - MAIOR [4] - NOVOS NÚMEROS [5] - SAIR DO PROGRAMA {0}'''.format('-=-' * 8)) o = int(input('Qual sua opção? ')) if o == 0 or o > 5: print('Opção inv...
#User gives input and loop continues until user keeps entering even numbers Evennumber=0; while(Evennumber%2==0): print("Let me check if the entered number is even or not"); Evennumber=int(input()); if(Evennumber%2==0): print("Number enter is even"); if(Evennumber%2!=0): print("You hav...
arquivo = open('exemplo.txt', 'r', encoding='utf8') for linha in arquivo: print(linha.strip()) arquivo.close()
def bonAppetit(bill, k, b): rest = b - int((sum(bill) - bill[k]) / 2) if rest != 0: print(rest) else: print('Bon Appetit') return
"""Setup constants, ymmv.""" PIN_MEMORY = True NON_BLOCKING = True BENCHMARK = True MAX_THREADING = 40 SHARING_STRATEGY = 'file_descriptor' # file_system or file_descriptor DEBUG_TRAINING = False DISTRIBUTED_BACKEND = 'gloo' # nccl would be faster, but require gpu-transfers for indexing and stuff cifar10_mean = [...
"""Provide exceptions to be raised by the `dynamic_models` app. All exceptions inherit from a `DynamicModelError` base class. """ class DynamicModelError(Exception): """Base exception for use in dynamic models.""" class OutdatedModelError(DynamicModelError): """Raised when a model's schema is outdated on s...
prices = {} quantities = {} while True: tokens = input() if tokens == 'buy': break else: tokens = tokens.split(" ") product = tokens[0] price = float(tokens[1]) quantity = int(tokens[2]) prices[product] = price if product not in quantities: quantitie...
def addFriendship(d, u1, u2): if u1 not in d: d[u1] = [u2] else: x = d[u1] x.append(u2) d[u1] = x inFile = open("friendship.txt", "r") d = {} for line in inFile: infos = line.split("\t") user1 = int(infos[0]) user2 = int(infos[1].replace("\n", "")) ...
#Make a menu driven program to accept, delete and display the following data stored in a dictionary. #Book_Id.........string #Book_Name.... string #Price......float #Discount...int #The program should continue as long as the user wishes to. At one point of time, I should be able to view minimum 3 records. class P...
""" Module: 'usocket' on esp8266 v1.11 """ # MCU: (sysname='esp8266', nodename='esp8266', release='2.2.0-dev(9422289)', version='v1.11-8-g48dcbbe60 on 2019-05-29', machine='ESP module with ESP8266') # Stubber: 1.1.0 AF_INET = 2 AF_INET6 = 10 IPPROTO_IP = 0 IP_ADD_MEMBERSHIP = 1024 SOCK_DGRAM = 2 SOCK_RAW = 3 SOCK_STREA...
# PEGANDO O PRIMEIRO E O ÚLTIMO NOME DE UMA PESSOA nome = input('Digite seu nome completo: ') nnome = nome.split() prinome = nnome[0] ultinome = nnome[-1] print(prinome) print(ultinome)
# N digit numbers with digit sum S # https://www.interviewbit.com/problems/n-digit-numbers-with-digit-sum-s-/ # # Find out the number of N digit numbers, whose digits on being added equals to a given number S. # Note that a valid number starts from digits 1-9 except the number 0 itself. i.e. leading # zeroes are not al...