content stringlengths 7 1.05M |
|---|
# Time: O(n) | Space: O(1)
def validateSubsequence(array, sequence):
seqIdx = 0
arrIdx = 0
while arrIdx < len(array) and seqIdx < len(sequence):
if array[arrIdx] == sequence[seqIdx]:
seqIdx += 1
arrIdx += 1
return seqIdx == len(sequence)
# Time: O(n) | Space: O(1)
def vali... |
# 1.1 Is Unique:
# Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
# O(n)
# Assuming ASCII - American Standard Code for Information Interchange
def isUniqueChars(string):
if len(string) > 128:
return False
char_set = [Fal... |
#
# PySNMP MIB module Sentry3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Sentry3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:07:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
dp=[[0 for _ in range(len(grid[0]))] for _ in range(len(grid))]
for row in range(len(grid)):
for col in range(len(grid[0])):
dp[row][col]=grid[row][col]
if row==0 and col==0:
... |
class Stack:
def __init__(self):
self._elems = []
def isEmpty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise Exception('Stack is empty when using top()!')
else:
return self._elems[-1]
def push(self, elem):
self... |
a = int(input())
if a < 10 :
print("small")
|
#!/usr/bin/env python3
n = int(input())
i = 0
while i < n:
print(n - i)
i = i + 1
|
"""
Converter between Unix and WIndows line endings.
"""
class EOLFixer:
"""
Converter between Unix and WIndows line endings.
"""
CRLF = "\r\n"
LF = "\n"
@classmethod
def is_crlf(cls, text: str) -> bool:
"""
Check whether text has `\r\n` characters.
Arguments:
... |
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
avg, count, currentSum = total // 3, 0, 0
for i in arr:
currentSum += i
if currentSum == avg:
count += 1
... |
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__()
return cls._instances[cls]
class ResourceManagerExample(metaclass=SingletonMeta):
def __init__(self, resource=100):
se... |
def test():
# Test
assert("'hello world'" in __solution__ or "'Hello World'" in __solution__ or "'Hello world'" in __solution__ or "'HELLO WORLD'" in __solution__
or '"hello world"' in __solution__ or '"Hello World"' in __solution__ or '"Hello world"' in __solution__ or '"HELLO WORLD"' in __solution_... |
"""
Tool for Multi-Ancestor Hypergraphs
Copyright: (c) 2010-2021 Sahana Software Foundation
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 ... |
class ListNode:
def __init__(self, val, next, *args, **kwargs):
self.val = val
self.next = None
# return super().__init__(*args, **kwargs)
def reverse(self, head):
prev = None
while head:
temp = head.next
h... |
"""Mixin for Metadata.
Adds methods ``add_metadata()``, ``extend_metadata()`` and
``fetch_metadata_as_attrs()`` to the class.
Metadata will be extracted into Sink. So created feature datasets
contain metadata for e.g. features and sources.
"""
class MetadataMixin:
"""MetadataMixin class
Adding metadata fun... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
class Printer:
"""
A stream filter that prints the objects that pass through it
"""
def __call__(self, stream):
"""
Print the objects in {stream} and pass them through
"""
... |
"""
= Features wanted =
* When not moving it can take only update parts of the screen.
* update(dirty_rects) can be used to speed up drawing.
* by only updating areas which are dirty.
* if the map is not moving we can make it lots speedier.
* Offscreen buffer. Blit all smaller tiles to an offscreen buffer th... |
'''All of the below settings apply only within the level that this config file
is situated. However, some of these options can also be applied at a
project-level within settings.py (see the docs for info on which options
transfer). Note that any inconsistencies are resolved in favour of the more
'local' settings, unle... |
class dotEnumerator_t(object):
# no doc
AdditionalId=None
aFilterName=None
aObjects=None
aObjectTypes=None
ClientId=None
Filter=None
MaxPoint=None
MinPoint=None
ModificationStamp=None
MoreObjectsLeft=None
nObjects=None
nObjectToStart=None
ReturnAlsoIfObjectIsCreatedAndDeletedAfterEvent=None
SubFilter=Non... |
def pattern(n):
k = 2 * n - 2
for i in range(0, n-1):
for j in range(0, k):
print(end=" ")
k = k - 2
for j in range(0, i + 1):
print("* ", end="")
print(" ")
k = -1
for i in range(n-1,-1,-1):
for j in range(k,-1,-1):
print(end="... |
# basiclass.py
class Student:
def __init__(self,name): #self คือคำพิเศษใช้แทนตัวมันเอง
self.name = name
self.exp = 0
self.lesson = 0
def Hello(self):
print('สวัสดีจ้า ผมชื่อ {}'.format(self.name))
def Coding(self):
print('{}: กำลังเขียนโปรแกรม..'.format... |
class Solution:
def __init__(self):
self.f = defaultdict(int)
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
self._post_order(root)
res = []
maxf = 0
for k, v in self.f.items():
if v > maxf:
maxf = v
res =... |
# -*- coding:utf-8 -*-
class Level:
id = ''
word_id = ''
name = ''
|
class User:
'''
Class that generates new instances of users
'''
users = []
def __init__(self, login_username, password):
'''
___init___ method that helps us define properties for our objects.
Args:
name: New user name
password: New user password
'''
self.login_username = lo... |
def __main__( deadlinePlugin ):
job = deadlinePlugin.GetJob()
cpus = list(deadlinePlugin.CpuAffinity())
cpus_linux = [str(x) for x in cpus]
cpus_linux = ','.join(cpus_linux)
# Edwin hex math for building the CPU affinity
cpus_windows = 0
for cpu in cpus:
cpus_windows |= 1 << int(... |
#
# @lc app=leetcode id=448 lang=python3
#
# [448] Find All Numbers Disappeared in an Array
#
# @lc code=start
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
list = [0] * len(nums)
result = []
for n in nums:
list[n-1] = list[n-1] + 1
... |
'''
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor.
'''
#Recebendo valor:
num = int(input('Digite o numero: '))
#Declarando variaveis:
antecessor = num - 1
sucessor = num + 1
#Resultado:
print('Seu sucessor é: {}\nNumero digitado: {}\nSeu antecessor é {}'.format(sucessor... |
#!/usr/bin/env python3
"""
Common errors defined here:
"""
class WrongFormatError(BaseException):
"""Raised when the input file is not in the correct format"""
def __init__(self, *args, **kwargs):
default_message = (
"The file you passed is not supported! Only .txt files are accepted."
... |
'''
Created on Feb 5, 2017
@author: safdar
'''
# from operations.vehicledetection.entities import Vehicle
# class VehicleManager(object):
# def __init__(self, lookback_frames, clusterer):
# self.__lookback_frames__ = lookback_frames
# self.__vehicles__ = []
# self.__clusterer__ = clusterer
... |
with open("Input.txt") as f:
lines = f.readlines()
# remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in lines]
num_lines = len(lines)
width = len(lines[0])
print(f"{num_lines} lines of width {width}")
diffs = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
hits = []
for diff in d... |
def pairwise_slow(iterable):
it = iter(iterable)
while True:
yield it.next(), it.next()
|
#
# PySNMP MIB module ASCEND-MIBATMQOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBATMQOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:26:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class Screen(object):
"""docstring for Screen"""
@property
def width(self):
return self._width
@width.setter
def width(self,width):
if not isinstance(width,int):
raise ValueError('width must be an integer!')
elif width < 0:
raise ValueError('width must be positive number!')
else:
self._width = wid... |
""" Advent of Code, 2020: Day 07, a """
with open(__file__[:-5] + "_input") as f:
inputs = [line.strip() for line in f]
bags = dict()
def count_bags(bag):
""" Recursively count bags """
if bag not in bags:
return 1
return 1 + sum(b[0] * count_bags(b[1]) for b in bags[bag])
def run():
"... |
#
# @lc app=leetcode id=464 lang=python3
#
# [464] Can I Win
#
# @lc code=start
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int):
# first player must win
if maxChoosableInteger > desiredTotal:
return True
nums = [num for num in range(1, maxChoosable... |
def top_level_function1() -> None:
return
class TopLevelClass1:
def __init__(self) -> None:
return
def instance_method1(self) -> None:
return
@classmethod
def class_method1(cls) -> None:
return
def instance_method2(self) -> None:
return
def top_level_func... |
def zero_matrix(matrix):
rows = set()
cols = set()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for row in rows:
for i in range(len(matrix[row])):
matrix[row][i] = 0
... |
class Order:
def __init__(self):
self.items = []
self.quantities = []
self.prices = []
self.status = "open"
def add_item(self, name, quantity, price):
self.items.append(name)
self.quantities.append(quantity)
self.prices.append(price)
def total_price... |
class Guerra():
def __init__(self, numTerricolas=3, numMarcianos=3):
self.__terricolasNave = Nave(Guerreros.TERRICOLA, "Millenium Falcon", numTerricolas)
self.__marcianosNave = Nave(Guerreros.MARCIANO, "Wing X", numTerricolas)
def start_war(self):
numTerricolasInNave = self.__terricolasN... |
"""
Crie um programa que leia um número e mostre seu sucessor e antecessor.
"""
num = int(input('Digite um número: '))
print(f'\nO número informado foi: {num}\nSeu sucessor é: {num + 1}\nSeu antecessor é: {num - 1}')
|
class EnvConstants:
EUREKA_SERVER = "EUREKA_SERVER"
APP_IP = "APP_IP"
FLUENTD_IP_PORT = "FLUENTD_IP_PORT"
HTTP_AUTH_USER = "HTTP_AUTH_USER"
HTTP_AUTH_PASSWORD = "HTTP_AUTH_PASSWORD"
TEMPLATES_DIR = "TEMPLATES_DIR"
VARS_DIR = "VARS_DIR"
TEMPLATE = "TEMPLATE"
VARIABLES = "VARIABLES"
... |
def add(a,b):
return a+b
def subtraction(a,b):
return a-b
def multiply(a,b):
return a*b
def division(a,b):
return a/b
def modulas(a,b):
return a%b |
#Escreva um programa para aprovar empréstimo bancário para a compra de 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 :'))
salario=float(input('salario do compra... |
{
'targets': [
{
'target_name': 'mysys_ssl',
'type': 'static_library',
'standalone_static_library': 1,
'includes': [ '../config/config.gypi' ],
'cflags!': [ '-O3' ],
'cflags_cc!': [ '-O3' ],
'cflags_c!': [ '-O3' ],
'cflags+': [ '-O2', '-g' ],
'cflags_c+': [ '-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2018, WeBank Inc. All Rights Reserved
#
################################################################################
# ====================================================... |
# Return the number of times that the string "hi" appears anywhere in the given string.
# def count_hi(str):
# return str.count('hi')
def count_hi(str):
return count(str, 'hi')
def count(str, term):
count = 0
for i in range(len(str)-len(term)+1):
if str[i:i+len(term)] == term:
count +=1
return co... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mLISTA COM PARES E ÍMPARES\033[m')
# Objetos
valores = [[], []]
# Lógica
for c in range(1, 8):
n = int(input(f'Digite o {c}° valor: '))
if n % 2 == 0:
valores[0].append(n)
else:
valores[1].append(n)
valores[0].sort()
v... |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
print(nums)
result =[]
for i in range(len(nums)):
if i> 0 and nums[i] == nums[i-1]:
continue
# print('4sum',nums[i],target- nums[i])
tmp... |
salario = float(input('Qual é o salario: R$ '))
if salario <= 1250:
novo = salario + (salario * 15 / 100)
else:
novo = salario + (salario * 10 / 100)
print(' Quem ganhava R$:{:.2f} passa a ganhar R$: {:.2f} agora.'.format(salario, novo)) |
class BufferedStream(Stream,IDisposable):
"""
Adds a buffering layer to read and write operations on another stream. This class cannot be inherited.
BufferedStream(stream: Stream)
BufferedStream(stream: Stream,bufferSize: int)
"""
def BeginRead(self,buffer,offset,count,callback,state):
""" BeginRea... |
#missoes astronauta
print("Divisor")
n=int(input("Digite o primeiro numero"))
n2=int(input("digite o segundo numero"))
soma=n/n2
print(soma)
#missao contas
#. -5 + 8 * 6
#b. (55 + 9)% 9
#c. 20 + -3 * 5/8
#d. 5 + 15/3 * 2 - 8% 3
print("resultado de -5+8*6")
soma=-5+8*6
print("-",soma)
print("resultado de (55+9)%9")
... |
'''
Recall from the video that a pivot table allows you to see all of your variables as a function of two other variables. In this exercise, you will use the .pivot_table() method to see how the users DataFrame entries appear when presented as functions of the 'weekday' and 'city' columns. That is, with the rows indexe... |
"""Specify colors of an othello bpard."""
class ColorPallet():
def __init__(self):
self.COLOR_BLACK_DISK = "#000000"
self.COLOR_WHITE_DISK = "#FFFFFF"
self.COLOR_BOARD = "#009600"
self.COLOR_BOARD_EDGE = "#000000"
self.COLOR_BOARD_LINE = "#000000"
self.COLOR_PANEL... |
def chemical_precipitation_costs(wastewater_flowrate_m3_per_hour, n, i):
wastewater_flowrate_gpd = wastewater_flowrate_m3_per_hour * 264.1721 * 24 # [gpd] There are 264 gallons per cubic meter and 24 hours per day
capital_costs = 7040000 + (35.0 * wastewater_flowrate_gpd) # [$]
o_and_m_costs = 230000 + (4.... |
# Copyright 2018 The Bazel Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
class ORMError(Exception):
"""Base class for all ORM-related errors"""
class UniqueKeyViolation(ORMError):
"""Raised when trying to save an entity without a distinct column value"""
class InvalidOperation(ORMError):
"""
Raised when trying to delete or modify a column that
cannot be deleted or mo... |
def validBraces(string):
buffer = []
for i in string:
if i == '(' or i == '[' or i == '{':
buffer.append(i)
else:
try:
a = buffer.pop()
except IndexError:
return False
if i == ')' and a != '(':
return... |
point_1 = Point(IN1, IN2)
point_2 = Point(IN3, IN4)
point_1.switch_point(1)
print("Point 1 right")
point_2.switch_point(1)
print("Point 2 right")
train = Locomotive(1)
track_enable(1)
print("Throttle 0, 70")
while GPIO.input(T6) == GPIO.HIGH:
train.throttle(0, 70)
train.stop()
print("train stop")
print("Thr... |
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
count = Counter()
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
sum = root.val + dfs(root.left) + dfs(root.right)
count[sum] += 1
... |
n = int(input('Digite um ano: '))
n1 = (n % 4) == 0
n2 = (n % 100) == 00
n3 = (n % 400) == 0
if n1 == True and n2 == False and n3 == False:
print('Fevereiro do ano {} tem 29 dias!'.format(n))
else:
print('O ano {} não é bissexto'.format(n)) |
#
# Dutch National Flag
# in-place
def dutch_flag_sort(balls):
r = -1 # red pointer
g = -1 # green pointer
i = 0 # current pointer
while (i < len(balls)):
if balls[i] == 'G':
g += 1
balls[i], balls[g] = balls[g], balls[i]
elif (balls[i] == "R"):
... |
load("//packages/bazel:index.bzl", "protractor_web_test_suite")
load("//tools:defaults.bzl", "ts_library")
def example_test(name, srcs, server, data = [], **kwargs):
ts_library(
name = "%s_lib" % name,
testonly = True,
srcs = srcs,
tsconfig = "//modules/playground:tsconfig-e2e.json"... |
pchars = "abcdefghijklmnopqrstuvwxyz,.?!'()[]{}┬─┬_"
fchars = "ɐqɔpǝɟƃɥıɾʞlɯuodbɹsʇnʌʍxʎz'˙¿¡,)(][}{┻━┻─"
# Flipping only works one way, pchars -> fchars
flipper = dict(zip(pchars, fchars))
def flip(s):
charlist = [flipper.get(x, x) for x in s.lower()]
charlist.reverse()
return "".join(charlist)
|
class Collectionitem:
collectionitemcnt = 0
def __init__(self, colldict):
self.colldict = colldict
Collectionitem.collectionitemcnt+=1
def birthyearcreator1(self):
if ("birth_year" in self.colldict['creators'][0]):
byear = self.colldict['creators'][0]['birth_year']
else:
... |
# Python Object Oriented Programming by Joe Marini course example
# Using the __str__ and __repr__ magic methods
class Book:
def __init__(self, title, author, price):
super().__init__()
self.title = title
self.author = author
self.price = price
self._discount = 0.1
# T... |
gen_bases = [
{'name': 'Crude Bow'},
{'name': 'Short Bow'},
{'name': 'Long Bow'},
{'name': 'Composite Bow'},
{'name': 'Recurve Bow', 'implicit': ['to Global Critical Strike Multiplier']},
{'name': 'Bone Bow'},
{'name': 'Royal Bow', 'implicit': ['increased Elemental Damage with Attack Skills']},
{'name': 'Death ... |
TAPIERROR_LOGIN = 10001
TAPIERROR_LOGIN_USER = 10002
TAPIERROR_LOGIN_DDA = 10003
TAPIERROR_LOGIN_LICENSE = 10004
TAPIERROR_LOGIN_MODULE = 10005
TAPIERROR_LOGIN_FORCE = 10006
TAPIERROR_LOGIN_STATE = 10007
TAPIERROR_LOGIN_PASS = 10008
TAPIERROR_LOGIN_RIGHT = 10009
TAPIERROR_LOGIN_COUNT = 10010
TAPIERROR_LOGIN_NOTIN_SERVE... |
def can_channel_synchronize(channel):
return channel.mirror_channel_url and (channel.mirror_mode == "mirror")
def can_channel_reindex(channel):
return True
|
# output from elife04953.xml
expected = [
{
"xlink_href": "elife04953f001",
"type": "graphic",
"parent_type": "fig",
"parent_ordinal": 1,
"parent_sibling_ordinal": 1,
"parent_component_doi": "10.7554/eLife.04953.003",
"position": 1,
"ordinal": 1,
}... |
encoded = "cvpbPGS{abg_gbb_onq_bs_n_ceboyrz}"
decoded = "".join([chr(ord('a') + (ord(c.lower())-ord('a')+13)%26) if c.isalpha() else c for c in encoded])
print(decoded) |
def main():
with open('input.txt') as f:
ids = f.read().splitlines()
ids.sort()
for i in range(len(ids) - 1):
cur = ids[i]
nex = ids[i + 1]
diff = 0
diff_idx = 0
for j in range(len(cur)):
if diff > 1:
break
if cur[... |
Images=[(0,255,0,255,0,255 ,
255,0,255,0,255,0,
0,255,0,255,0,255 ,
255,0,255,0,255,0,
0,255,0,255,0,255 ,
255,0,255,0,255,0),
(255,255,255,0,0,0,
0,0,0,255,255,255,
255,255,255,0,0,0,
255,255,255,0,0,0,
0,0,0,255,255,255,
255,255,255,0,0,0,),
(255,255,255,255,255,255,
... |
print('=' * 5, 'AULA_009a', '=' * 5)
frase = 'Curso em Video Python'
print(frase[9])
print(frase[9:13])
print(frase[9:14])
print(frase[9:21])
print(frase[9:21:2])
print(frase[:5])
print(frase[15:])
print(frase[9::3])
print(len(frase))
print(frase.count('o'))
print(frase.count('o', 0, 13))
print(frase.find('deo'))
print... |
# while True:
# pass
# keyboard interrupt.
class MyEmptyClass:
pass
def initLog(*args):
pass
# pass statement is ignore.
|
"""
>>> bus1 = HauntedBus(['Alice', 'Bill'])
>>> bus1.passengers
['Alice', 'Bill']
>>> bus1.pick('Charlie')
>>> bus1.drop('Alice')
>>> bus1.passengers
['Bill', 'Charlie']
>>> bus2 = HauntedBus()
>>> bus2.pick('Carrie')
>>> bus2.passengers
['Carrie']
>>> bus3 = HauntedBus()
>>> bus3.passengers
['Carrie']
>>> bus3.pick('... |
def counting_sort(array, area, index):
counting_array = [0] * area
sorted_array = [0] * len(array)
for j in range(len(array)):
counting_array[ord(array[j][index]) - ord("a")] += 1
for j in range(1, area):
counting_array[j] += counting_array[j - 1]
for j in range(len(array) - 1, -1, ... |
def GCD(a,b):
if b==0:
return a
else:
return GCD(b,a%b)
print("Enter A")
a=int(input())
print("Enter B")
b=int(input())
print("GCD = "+str(GCD(a,b))) |
''' For Loop Break Statement
'''
frui |
n=int(input("Enter n -> "))
res=0
while(n > 0):
temp = n % 10
res = res * 10 + temp
n = n // 10
print(res) |
class TrainingConfig:
def __init__(self, trainingConfig):
self.downloadStackoverflowEnabled = trainingConfig.get("downloadStackoverflowEnabled", False)
self.includeStackoverflow = trainingConfig.get("includeStackoverflow", True)
self.stackoverflowTags = trainingConfig.get("stackoverflowTags", [])
self.stackove... |
# Desenvolva um programa que leia seis números inteiros e mostre
# A soma apenas daqueles que forem pares. Se o valor digitado for impar Desconsidere-o
d = 0
cont = 0
for c in range(0, 6):
n = int(input('Digite um número: '))
if n % 2 == 0:
d = d + n
cont += 1
print('Você informou {} números PAR... |
'''
-------------------------
Counting Array Inversions
-------------------------
An array inversion is defined as a single pair of elements A[i] and A[j] in the array 'A'
such that i < j but A[i] > A[j].
This implementation runs in O(n log n) time, and uses a recursive approach similar to Merge Sort in order
to effi... |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
See https://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
USE_PYTHON... |
# model settings
model = dict(
type='MOCO',
queue_len=65536,
feat_dim=128,
momentum=0.999,
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(3,), # no conv-1, x-1: stage-x
norm_cfg=dict(type='BN'),
style='pytorch'),
neck=dict(
... |
"""
Calcule a soma entre todos os numeros impares que são multiplos de 3 e que se encontram no intervalo
de 1 ate 500
FORMA DE UTILIZAR MESMO PROCESSAMENTO
for cont in range(1, 501, 2)
"""
soma = 0
c = 0
for cont in range(1, 501):
if cont % 2 == 1 and cont % 3 == 0:
soma = soma + cont # acumulador, receb... |
# -*- coding: utf-8 -*-
def get_lam_by_label(self, label):
"""Returns the lamination by its labels. Accepted labels are 'Stator_X' and
'Rotor_X' with X the number of the lamination starting with 0.
For convenience also 'Stator' or 'Rotor' are allowed here to get respective first
stator or rotor lamina... |
class Model:
def __init__(self):
self.flask = wiz.flask
def has(self, key):
if key in self.flask.session:
return True
return False
def delete(self, key):
self.flask.session.pop(key)
def set(self, **kwargs):
for key in kwargs:
... |
class Tracker(object):
def update(self, detections):
matches, unmatched_tracks, unmatched_detections = self._match(detections)
return matches, unmatched_tracks, unmatched_detections
def _match(self, detections):
print("father match called")
pass
class Sun(Tracker):
'''def... |
slice[ a.b : c.d ]
slice[ d :: d + 1 ]
slice[ d + 1 :: d ]
slice[ d::d ]
slice[ 0 ]
slice[ -1 ]
slice[ :-1 ]
slice[ ::-1 ]
slice[ :c, c - 1 ]
slice[ c, c + 1, d:: ]
slice[ ham[ c::d ] :: 1 ]
slice[ ham[ cheese ** 2 : -1 ] : 1 : 1, ham[ 1:2 ] ]
slice[ :-1: ]
slice[ lambda: None : lambda: None ]
slice[ lambda x, y, *args... |
def aumentar(preço = 0, taxa = 0, formato = False):
res = preço + (preço * taxa / 100)
return res if formato is False else moeda(res)
def diminuir(preço = 0, taxa = 0, formato = False):
res = preço - (preço * taxa / 100)
return res if formato is False else moeda(res)
def dobro(preço = 0, formato = Fal... |
class Solution:
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = [1] + nums + [1]
n = len(nums)
dp = [[0] * n for i in range(n)]
for j in range(2, n):
for i in range(j-2, -1, -1):
for k in range(i+1... |
"""Advent of Code 2017 Day 15."""
puzzle = [699, 124]
def main(puzzle=puzzle):
matching_pairs = compare_pairs(puzzle, 40_000_000)
print(f'Final count for 40 million pairs: {matching_pairs}')
conditions = [lambda num: is_multiply_of(num, 4),
lambda num: is_multiply_of(num, 8)]
matchi... |
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'symroot.gypi',
],
'targets': [
{
'target_name': 'prog1',
'type': 'executable',
'dependencies': [
... |
"""
__init__.py:
"""
__author__ = "Michael J. Harms"
__all__ = ["uhbd","common","pyUHBD"]
|
soma = 0
print('A seguir digite 6 números e ao fim será exibido a soma dos números pares')
for c in range(0, 6):
num = int(input('Digite o {}° número: '.format(c+1)))
if num % 2 == 0:
soma += num
print('A soma dos números pares é {}'.format(soma))
|
# Generation of 'magic' numbers for bitmasking to extract
# values from cpuid
def bitmask(mask):
'''
First element in `mask` is least-significant bit, last element is most-significant.
'''
result = 0
for index, x in enumerate(mask):
result |= x << index
return result
ways = bitmask(... |
"""CORS Middleware
A middleware for handling CORS requests.
See: https://falcon.readthedocs.io/en/stable/user/faq.html#how-do-i-implement-cors-with-falcon
"""
class CORSComponent(object):
def process_response(self, req, resp, resource, req_succeeded):
resp.set_header('Access-Control-Allow-Origin', '*')... |
"""Contains the function for calculating the crc16 value
Functions:
crc16_a2a(str) :: string to string
crc16_a2b(str) :: string to bytes
crc16_b2b(bytestr) :: bytes to bytes
"""
def crc16_a2a(str):
"""Take in a string and calculate its correct crc16 value.
Args:
... |
class Solution(object):
def tribonacci(self, n, memo = dict()):
if n in memo:
return memo[n]
if n == 0:
return 0
if n == 2 or n ==1 :
return 1
else:
var = self.tribonacci(n-1) + self.tribonacci(n-3) + self.tribonacci(n-2)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 10:16:47 2018
@author: abauville
"""
## Units
## =====================================
m = 1.0
s = 1.0
K = 1.0
kg = 1.0
cm = 0.01 * m
km = 1000.0 * m
mn = 60 * s
hour = 60 ... |
GRAB_SPIDER_CONFIG = {
'global': {
'spider_modules': ['zzz'],
},
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.