content stringlengths 7 1.05M |
|---|
# taxes.tests
# Tax tests
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sat Apr 14 16:36:54 2018 -0400
#
# ID: tests.py [20315d2] benjamin@bengfort.com $
"""
Tax tests
"""
##########################################################################
## Imports
########################################... |
#!/usr/bin/python
# 1. Retourner VRAI si N est parfait, faux sinon
# 2. Afficher la liste des nombres parfait compris entre 1 et 10 000
def est_parfait(n):
somme = 0
for i in range(1, n):
if n % i == 0:
somme += i
if somme == n:
return True
else:
return False
fo... |
class Credentials(object):
@staticmethod
def refresh(request, **kwargs):
pass
@property
def token(self):
return "PASSWORD"
def default(scopes: list, **kwargs):
return Credentials(), "myproject"
class Request(object):
pass
|
distancia = int(input('Digite a distancia da sua viagem: '))
valor1 = distancia*0.5
valor2 = distancia*0.45
if distancia <= 200:
print('O preço dessa viagem vai custar R${:.2f}'.format(valor1))
else:
print('O preço dessa viagem vai custar R${:.2f}'.format(valor2))
print('--fim--')
|
xCoordinate = [1,2,3,4,5,6,7,8,9,10]
xCdt = [1,2,3,4,5,6,7,8,9,10]
def setup():
size(500,500)
smooth()
noStroke()
for i in range(len(xCoordinate)):
xCoordinate[i] = 35*i + 90
for j in range(len(xCdt)):
xCdt[j] = 35*j + 90
def draw():
background(50)
for j in range(len(xCdt)):... |
class LostFocusEventManager(WeakEventManager):
""" Provides a System.Windows.WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the System.Windows.UIElement.LostFocus or System.Windows.ContentElement.LostFocus events. """
@staticmethod
def AddHandler(sour... |
#TeamLeague
class Team:
def __init__(self, owner, value, id1, name):
self.owner = owner
self.value = value
self.id1 = id1
self.name = name
class League:
def __init__(self, team_list, league):
self.league = league
self.team_list = team_list
def find_minimum_t... |
## Solution Challenge 10
def data_url(country):
'''
Function to build url for data retrieval
'''
BASE_URL = "http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/"
SUFFIX_URL = "-TAVG-Trend.txt"
return(BASE_URL + country + SUFFIX_URL) |
"""
The hyperexponentiation of a number
"""
def pow_mod_recursive(a, x, mod):
if x == 0 or x == 1:
return a ** x % mod
elif x % 2 == 0:
return pow_mod_recursive(a, x//2, mod) ** 2 % mod
else:
return a* pow_mod_recursive(a, x//2, mod)** 2 % mod
def pow_mod(a, x, mod):
pow_v... |
"""
ensemble module
"""
class BaseEnsembler:
def __init__(self, *args, **kwargs):
super().__init__()
def fit(self, predictions, label, identifiers, feval, *args, **kwargs):
pass
def ensemble(self, predictions, identifiers, *args, **kwargs):
pass
@classmethod
def build_en... |
class Solution(object):
def hammingDistance(self, x, y):
cnt = 0
n=x^y
while n>0:
cnt += 1
n = n&(n-1)
return cnt
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: i... |
# Faça um algoritmo que leia o salário de um funcionário e mostre seu
# novo salário com 15% de aumento.
print('-'*50)
salario = float(input('Digite o salário do funcionário: R$'))
novoSalario = salario + (salario*15/100)
print('O salário de R${:.2f}, com o aumento de 15%,\npassa a ser R${:.2f}.'.format(salario, nov... |
#
# PySNMP MIB module RFC1382-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1382-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:26:33 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( Octe... |
def main(filepath):
with open(filepath) as file:
rows = [int(x.strip()) for x in file.readlines()]
rows.append(0)
rows.sort()
rows.append(rows[-1]+3)
current_volts = 0
one_volts = 0
three_volts = 0
for i in range(len(rows)):
if ro... |
# -*- coding:utf-8 -*-
def decorator_singleton(cls):
"""
装饰器实现方式
:param cls:
:return:
"""
instances = {}
def _singleton(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return _singleton
class NewSingleton(object):
"""
需要单... |
def find_min_max(nums):
if nums[0]<nums[1]:
min = nums[0]
max = nums[1]
else:
min = nums[1]
max = nums[0]
for i in range(len(nums)-2):
if nums[i+2] < min:
min = nums[i+2]
elif nums[i+2] > max:
max = nums[i+2]
return (min, max)
de... |
def daily_sleeping_hours(hours=7):
return hours
print(daily_sleeping_hours(10))
print(daily_sleeping_hours()) |
x=1
grenais = 0
inter = 0
gremio = 0
empate = 0
while x == 1:
y = input().split()
a,b=y
a=int(a)
b=int(b)
grenais = grenais + 1
if a > b:
inter = inter + 1
if a < b:
gremio = gremio + 1
if a == b:
empate = empate + 1
while True:
x = int(input('Novo g... |
#
# PySNMP MIB module SNR-ERD-PRO-Mini (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNR-ERD-PRO-Mini
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
def test_rank():
plugin = ComputeRank("rank")
docs = [{}, {}]... |
'''
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers
in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order.
However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible... |
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
count = dict()
for words in cpdomains:
times, cpdomain = words.split(' ')
times = int(times)
keys = cpdomain.split('.')
... |
ENTITY = "<<Entity>>"
REL = 'Rel/'
ATTR = 'Attr/'
SOME = 'SOME'
ALL = 'ALL'
GRAPH = 'GRAPH'
LIST = 'LIST'
TEXT = 'TEXT'
SHAPE = 'SHAPE'
SOME_LIMIT = 15
EXACT_MATCH = 'EXACT_MATCH'
REGEX_MATCH = 'REGEX_MATCH'
SYNONYM_MATCH = 'SYNONYM_MATCH' |
def calculate(arr, index=0):
back = - 1 - index
if arr[index] != arr[back]:
return False
elif abs(back) == (index+1):
return True
return calculate(arr, index+1)
arr = [int(i) for i in input().split()]
print(calculate(arr))
|
"""
Find the parant and the node to be deleted. [0]
Deleting the node means replacing its reference by something else. [1]
For the node to be deleted, if it only has no child, just remove it from the parent. Return None. [2]
If it has one child, return the child. So its parent will directly connect to its child. [3]
... |
class IberException(Exception):
pass
class ResponseException(IberException):
def __init__(self, status_code):
super().__init__("Response error, code: {}".format(status_code))
class LoginException(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user ... |
v = 6.0 # velocity of seismic waves [km/s]
def earthquake_epicenter(x1, y1, t1, x2, y2, t2, x3, y3, t3):
x = 0
y = 0
# Your code goes here!
return x, y
|
class Logi:
def __init__(self, email, password):
self.email = email
self.password = password
|
class StringFormatFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the display and layout information for text strings.
enum (flags) StringFormatFlags,values: DirectionRightToLeft (1),DirectionVertical (2),DisplayFormatControl (32),FitBlackBox (4),LineLimit (8192),MeasureTrailingSpace... |
requestDict = {
'instances':
[
{
"Lat": 37.4434774, "Long": -122.1652269,
"Altitude": 21.0, "Date_": "7/4/17",
"Time_": "23:37:25", "dt_": "7/4/17 23:37"
#driving meet conjestion
}... |
#!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
self.parent = None
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.tx... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将每日的数据进行处理,并导出到MYSQL中,并对未生成的数据进行记录,可选择进行重跑或者手动重跑
""" |
def fizzbuzz(num):
if (num >= 0 and num % 3 == 0 and num % 5 == 0):
return "Fizz Buzz"
if (num >= 0 and num % 3 == 0):
return "Fizz"
if (num >= 0 and num % 5 == 0):
return "Buzz"
if (num >= 0):
return ""
|
dataset_paths = {
'ffhq': '',
'celeba_test': '',
'cars_train': '',
'cars_test': '',
'church_train': '',
'church_test': '',
'horse_train': '',
'horse_test': '',
'afhq_wild_train': '',
'afhq_wild_test': '',
'font_train': '/mnt/data01/AWS_S3_CONTAINER/personnel-records/1956/seg/firm/stylegan2_crops/pr',
'... |
def v(kod):
if (k == len(kod)):
print(' '.join(kod))
return
if (len(kod) != 0):
for i in range(int(kod[-1]) + 1, n + 1):
if (str(i) not in kod):
gg = kod.copy()
gg.append(str(i))
v(gg)
else:
for i in range... |
#! /usr/bin/env python3
""" Carian converter
The transliteration scheme is as follows
-------------------------------------------------------------------
| a 𐊠 | b 𐊡 | d 𐊢 | l 𐊣 | y 𐊤 | y2 𐋐 |
| r 𐊥 | L 𐊦 | L2 𐋎 | A2 𐊧 | q 𐊨 | b 𐊩 |
... |
'''
(0-1 Knapsack) example
The example solves the 0/1 Knapsack Problem:
how we get the maximum value, given our knapsack just can hold a maximum weight of w,
while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]?
i = total item
w = total weigh of knapsack can carry
'''
# a1: item value... |
list_fruits = ['🍎', '🥭', '🍊', '🍌']
# for fruit in list_fruits:
# print(fruit)
def find_average_height(list_heights):
temp = 0
for height in list_heights:
temp += height
average_height = temp / len(list_heights)
print(f'Average height is {round(average_height)}')
print(sum(list_hei... |
administrator_user_id = 403569083402158090
reaction_message_ids = [832010993542365184, 573059396259807232]
current_year = 2021
|
class NoneTypeFont(Exception):
pass
class PortraitBoolError(Exception):
pass
class NoneStringObject(Exception):
pass
class BMPvalidationError(Exception):
pass
|
""""
题目描述
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有相同长度超2的子串重复
说明:长度超过2的子串
输入描述:
一组或多组长度超过2的子符串。每组占一行
输出描述:
如果符合要求输出:OK,否则输出NG
示例1
输入
021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000
输出
OK
NG
NG
OK
"""
def isLong(s):
if len(s) > 8:
return True
else:
return False
def isMoreClass(s):
... |
n = str(input('Nome: '))
if n == 'Nicolas':
print('TOP')
elif n == 'Claudia':
print('Eca...')
else:
print('Olá!')
|
default_values = {
'mode': 'train',
'net': 'resnet32_cifar',
'device': 'cuda:0',
'num_epochs': 300,
'activation_type': 'deepBspline_explicit_linear',
'spline_init': 'leaky_relu',
'spline_size': 51,
'spline_range': 4,
'save_memory': False,
'knot_threshold': 0.,
'num_hidden_lay... |
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
k=1
m=0
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
k+=1
else:
... |
# [Newman-Conway sequence] is the one which generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7….. and follows below recursive formula.
# P(1) = 1
# P(2) = 1
# for all n > 2
# P(n) = P(P(n - 1)) + P(n - P(n - 1))
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given ... |
class Solution:
'''
如果input長度為n,那麼暴力解就是將數字兩兩相加看是不是解,
這樣的解法要算n(n-1)/2次,也就是O(n²)的時間複雜度。
'''
# def twoSum(self, nums, target):
# for i in range(len(nums)-1):
# for j in range(i+1, len(nums)):
# if nums[i] + nums[j] == target:
# return [i, j]
... |
NONE = u'none'
OTHER = u'other'
PRIMARY = u'primary'
JUNIOR_SECONDARY = u'junior_secondary'
SECONDARY = u'secondary'
ASSOCIATES = u'associates'
BACHELORS = u'bachelors'
MASTERS = u'masters'
DOCTORATE = u'doctorate'
|
RESTAURANT_LIST_GET = {
'tags': ['음식점 정보'],
'description': '음식점 목록 조회',
'parameters': [
{
'name': 'sector',
'description': '음식점 종류(선호메뉴)\n'
'음식 종류가 "아무거나"일 경우 "all"',
'in': 'path',
'type': 'str',
'required': True
... |
class SteepshotBotError(Exception):
msg = {}
def get_msg(self, locale: str = 'en') -> str:
return self.msg.get(locale, self.msg.get('en', 'Some error occurred: ')) + str(self)
class SteepshotServerError(SteepshotBotError):
msg = {
'en': 'Some Steepshot error occurred: '
}
class Stee... |
class Instrument:
insId: int
name: str
urlName: str
instrument: int
isin: str
ticker: str
yahoo: str
sectorId: int
marketId: int
branchId: int
countryId: int
listingDate: str
def __init__(self, insId, name, urlName, instrument, isin, ticker, yahoo, sectorId, marketId... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 20:34:09 2019
@author: Enrique Lopez Ortiz
"""
# ===========================
# PARÁMETROS DE CONFIGURACIÓN
# ===========================
# ¿Quieres preprocesar un fichero de nodos o de aristas?
el_input_es_un_fichero_de_nodos = True
# Nombre de... |
class WeightedUnionFind(object):
def __init__(self, n):
self.n = n
self.parents = range(n)
self.sizes = [1] * n
def find(self, p):
while p != self.parents[p]:
p = self.parents[p]
return p
def is_connected(self, p, q):
return self.find(p) == self... |
num = int(input("Enter a number: "))
iter_num = 0
pwr = 0
if num == 0:
root = 0
else:
root = 1
while root**pwr != num and root < num:
while pwr < 6:
iter_num += 1
if root**pwr == num:
print(root, "^", pwr, sep="")
break
pwr += 1
if root**pwr == num:
break
else:
pwr = 0
... |
def dict_recursive_bypass(dictionary: dict, on_node: callable) -> dict:
"""
Recursive bypass dictionary
:param dictionary:
:param on_node: callable for every node, that get value of dict end node as parameters
"""
res = {}
for k, v in dictionary.items():
if isinstance(v, dict):
... |
expected_output = {
"route-information": {
"route-table": {
"active-route-count": "1250009",
"destination-count": "1250009",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": {
"rt-announced-count": "1",
... |
#!/usr/bin/python3
# python 基础语法笔记
def choose_method(a, b):
"""
python中的if语句
python中没有switch语句
只有 if: elif: else:
判断语句
:param a:
:param b:
:return:
"""
if a > b:
print("%d>%d" % (a, b))
else:
print("%d<=%d" % (a, b))
if a > 0:
print("%d>%d" % (a, ... |
""" Summation puzzle
Example:
pot + pan = bib
dog + cat = pig
boy+ girl = baby
"""
def puzzle_solve(k, S, U, solutionSeq): # we have also passed puzzles solution samples to verify the configuarion
""" Input: an integer k : length of the subset made by combination of letters,
S: Sequence of unique letters ... |
# class MyHashSet:
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self._range = 10000
# self.list = [[]]*self._range
# def _hash(self, key: int) -> int:
# return key%self._range
# def _search(self, key: int) -> int:
#... |
SERVER_EMAIL = 'SERVER_EMAIL'
SERVER_PASSWORD = 'SERVER_PASSWORD'
WATCHED = {
'service': ['service'],
'process': ['process'],
}
NOTIFICATION_DETAILS = {
'service': [
{
'identifiers': ['identifiers'],
'to_emails': ['nimesh.aug11@gmail.com'],
'subject': 'subject'... |
x = int(input('1º numero: '))
y = int(input('2º numero: '))
z = int(input('3º numero: '))
m = x
if z < x and z < y:
m = z
if y < x and y < z :
m = y
ma = x
if z > x and z > y:
ma = z
if y > x and y > z :
ma = y
print("O maior numero foi {} e o menor foi {}".format(ma, m))
|
# -*- coding: utf-8 -*-
"""Zeigen -- find protonated waters in structures.
\b
For complete help visit https://github.com/hydrationdynamics/zeigen
\b
License: BSD-3-Clause
Copyright © 2021, GenerisBio LLC.
All rights reserved.
""" # noqa: D301
|
print("HelloWorld")
print(len("HelloWorld"))
a_string = "Hello"
b_string = "World"
print("a_string + b_string: ", a_string+b_string)
c_string = "abcdefghijklmnopqrstuvwxyz"
print("num of letters from a to z", len(c_string))
print(c_string[:3]) #abc
print(c_string[23:]) #xyz
#step count reverse
print(c_string[::-1])
#st... |
def substituter(seq, substitutions):
for item in seq:
if item in substitutions:
yield substitutions[item]
else:
yield item
|
a = input()
b = input()
ans = 0
while True:
s = a.find(b)
if s < 0:
break
ans += 1
a = a[s+len(b):]
print(ans)
|
"""Externalized strings for better structure and easier localization"""
setup_greeting = """
Dwarf - First run configuration
Insert your bot's token, or enter 'cancel' to cancel the setup:"""
not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process."
choose_prefix = """Choose a prefix. A pr... |
# Lecture 5, Problem 9
def semordnilapWrapper(str1, str2):
# A single-length string cannot be semordnilap.
if len(str1) == 1 or len(str2) == 1:
return False
# Equal strings cannot be semordnilap.
if str1 == str2:
return False
return semordnilap(str1, str2)
def semordnilap(str1, s... |
#!/usr/bin/env python
# Monitoring the Mem usage of a Sonicwall
# Herward Cooper <coops@fawk.eu> - 2012
# Uses OID 1.3.6.1.4.1.8741.1.3.1.4.0
sonicwall_mem_default_values = (35, 40)
def inventory_sonicwall_mem(checkname, info):
inventory=[]
inventory.append( (None, None, "sonicwall_mem_default_values") )
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 2017
@author: maque
Note that the demo code is from the below link:
http://interactivepython.org/courselib/static/pythonds/SortSearch/Hashing.html
and add some other operations in the exercises.
"""
class Hash_table:
'''
put(key,val) Add ... |
title = 'Projects'
class Card:
def __init__(self, section, url, name, description, image):
self.section = section; self.url = url;
self.image = image; self.name = name; self.description = description
cards = [
Card('2018', 'resources/projects/awg_highres.jpg', 'Automatic Nanomanipulation Platform'... |
class LastPassError(Exception):
def __init__(self, output):
self.output = output
class CliNotInstalledException(Exception):
pass
|
def grad_tmp(temp, lat: np.ndarray, lon: np.ndarray) -> np.ndarray:
"""grad_eqv_ptntl_tmp.
calcureta gradient of temperature [K/100km]
Args:
eqv_ptntl_t:
lat (np.ndarray): lat
lon (np.ndarray): lon
Returns:
np.ndarray:
"""
# horizontal equivalent_potential_temp... |
n=int(input())
arr=[int(x) for x in input().split()]
brr=[int(x) for x in input().split()]
my_list=[]
for i in arr[1:]:
my_list.append(i)
for i in brr[1:]:
my_list.append(i)
for i in range(1,n+1):
if i in my_list:
if i == n:
print("I become the guy.")
break
else:
... |
'''
Need 3 temporary variables to find the longest substring: start, maxLength,
and usedChars.
Start by walking through string of characters, one at a time.
Check if the current character is in the usedChars map, this would mean we
have already seen it and have stored it's corresponding index.
If it's in there and the ... |
class APICONTROLLERNAMEController(apicontrollersbase.APIOperationBase):
def __init__(self, apirequest):
super(APICONTROLLERNAMEController, self).__init__(apirequest)
return
def validaterequest(self):
logging.debug('performing custom validation..')
#validate required ... |
pesos = []
q = int(input('Analisar quantas pessoas? '))
for i in range(1, q + 1):
pesos.append(float(input(f'Peso da {i}ª pessoa: ')))
print(f'\nO maior peso lido foi de {max(pesos)}Kg')
print(f'O menor peso lido foi de {min(pesos)}Kg')
|
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
# write your code here
if nums == None or len(nums) <= 1:
return
pl = 0
pr = len(nums) - 1
i = 0
while i <= pr:
if... |
# Leo colorizer control file for c mode.
# This file is in the public domain.
# Properties for c mode.
properties = {
"commentEnd": "*/",
"commentStart": "/*",
"doubleBracketIndent": "false",
"indentCloseBrackets": "}",
"indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|... |
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key = lambda interval : interval[1])
res = 0
prev = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] < prev:
res +=1
else:
prev = intervals[i][1... |
#https://www.interviewbit.com/problems/max-distance/
def maximumGap(A):
left = [A[0]]
right = [A[-1]]
n = len(A)
for i in range(1,n):
left.append(min(left[-1], A[i]))
for i in range(n-2, -1, -1):
right.insert(0, max(right[0], A[i]))
i,j,gap = 0, 0, -1
while (i < n and j < n):... |
'''
Created on May 24, 2012
@author: newatv2user
'''
PIANO_RPC_HOST = "tuner.pandora.com"
PIANO_ONE_HOST = "internal-tuner.pandora.com"
PIANO_RPC_PATH = "/services/json/?"
class PianoUserInfo:
def __init__(self):
self.listenerId = ''
self.authToken = ''
class PianoStation:
def __init... |
class Emplacement:
"""
documentation
"""
def __init__(self, id, line, n):
self.id = id
line = line.split(' ')
distances = {}
i = 0
for elt in line:
if elt != '':
i+=1
if i != id:
distances[i] = int(e... |
"""
Streamlined python project setup and build system.
"""
__version__ = "0.2"
DESCRIPTION = __doc__
__all__ = ['__init__', '__main__', 'parsers']
|
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
class Singleton(type):
def __new__(meta, name, bases, attrs):
attrs["_instance"] = None
return super().__new__(meta, name, bases, attrs)
def __call__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: template_deploy
short_description: Manage TemplateDeploy objects of ConfigurationTemplates
description:
- Deploys... |
# -*- coding: utf-8 -*-
'''
File name: code\eight_divisors\sol_501.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #501 :: Eight Divisors
#
# For more information see:
# https://projecteuler.net/problem=501
# Problem Statement
'''
The e... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/pygictower/blob/master/NOTICE
__version__ = "0.0.1"
|
def countBits(n: int) -> list[int]:
result = [0]
for i in range(1,n+1):
count = 0
test = ~(i - 1)
while test & 1 == 0:
test >>= 1
count += 1
result.append(result[i-1] - count + 1)
return result |
class Predicate(object):
def test(self, obj):
raise NotImplementedError()
def __call__(self, obj):
return self.test(obj)
def __eq__(self, obj):
return self.test(obj)
def __ne__(self, obj):
return not self == obj
def __and__(self, other):
return And(self, ... |
usingdir = '/sys/fs/cgroup/memory/memory.max_usage_in_bytes'
totaldir = '/sys/fs/cgroup/memory/memory.limit_in_bytes'
def ram():
try:
using = int(open(usingdir).read())
total = int(open(totaldir).read())
except FileNotFoundError:
return 'Dados não encontrados'
else:
return ... |
# Copyright 2018 Jianfei Gao, Leonardo Teixeira, Bruno Ribeiro.
#
# 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
#
# Unle... |
nota1 = int(input('Digite sua nota da A1 '))
nota2 = int(input('Digite sua nota da A2 '))
media = (nota1+nota2)/2
if media < 5:
print(f'REPROVADO')
elif media == 5 or media < 7 :
print(f'RECUPERAÇÃO')
elif media == 7 or media > 7:
print(f'APROVADO') |
def increment(dictionary, k1, k2):
"""
dictionary[k1][k2]++
:param dictionary: Dictionary of dictionary of integers.
:param k1: First key.
:param k2: Second key.
:return: same dictionary with incremented [k1][k2]
"""
if k1 not in dictionary:
dictionary[k1] = {}
if 0 not in ... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
sumc = 0
cont = 0
for c in range(1, 7):
print("{}----- {} Number -----{}".format(colors["cian"], c, col... |
# -*- coding: utf-8 -*-
"""
Copyright () 2018
All rights reserved
FILE: binary_tree.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2018/5/15 上午11:06
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2018/5/15 上午11:06
"""
"""
二叉树是每个节点最多有两个子树的树结构,子树有左右之分,二叉树常被用于实现二叉查找树和二叉堆
... |
# Solution to Advent of Code 2020 day 6
# Read data
with open("input.txt") as inFile:
groups = inFile.read().split("\n\n")
# Part 1
yesAnswers = sum([len(set(group.replace("\n", ""))) for group in groups])
print("Solution for part 1:", yesAnswers)
# Part 2
yesAnswers = 0
for group in groups:
persons = group.... |
DOCARRAY_PULL_NAME = "fashion-product-images-clip-all"
DATA_DIR = "../data/images" # Where are the files?
CSV_FILE = "../data/styles.csv" # Where's the metadata?
WORKSPACE_DIR = "../embeddings"
DIMS = 512 # This should be same shape as vector embedding
|
def Instagram_scroller(driver,command):
print('In scroller function')
while True:
while True:
l0 = ["scroll up","call down","call don","scroll down","up","down","exit","roll down","croll down","roll up","croll up"]
if len([i for i in l0 if i in command]) != 0:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def _is_tensor(x):
return hasattr(x, "__len__")
|
# initial based on FreeCAD 0.17dev
#last edit: 2019-08
SourceFolder=[
("Base","Foundamental classes for FreeCAD",
"""import as FreeCAD in Python, see detailed description in later section"""),
("App","nonGUI code: Document, Property and DocumentObject",
"""import as FreeCAD in Python, see detailed description in late... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.