content stringlengths 7 1.05M |
|---|
class User:
'''
Class that generates new instances of Users
'''
user_list=[]
def __init__(self,username,password):
self.username=username
self.password=password
def save_user(self):
'''
save_user method saves user objects to the user_list
'''
User.user_list.append(self)
@classme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: fenc=utf-8:et:ts=4:sts=4:sw=4:fdm=marker
# Algorithm based on https://github.com/ogham/rust-term-grid/ which is MIT
# licensed.
"""
A grid is an mutable datastructure whose items can be printed in a grid in
such a way as to minimize the number of lines.
"""
class G... |
"""
An unweighted, undirected node in a graph.
"""
class UnweightedNode:
def __init__(self, data):
self.data = data
self.__neighbor_nodes = []
def add_neighbor(self, node):
self.__neighbor_nodes.append(node)
def get_neighbors_in_order(self):
return self.__neighbor_nodes
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 25 13:57:59 2022
@author: ranusingh1993
"""
|
#deleting a element from list
# deleting one or more element at same time from list is possible using the keyword del. It can also delete the list entirely.
list_pri=[1,3,5,7,8,11,13,17,19,23]
del list_pri[4]
print(list_pri)
#[1,3,5,7,11,13,17,19,23]
del list_pri[0:9]
print(list_pri)
del list_pri
print(list_pr... |
# Category description for the widget registry
NAME = "SOLEIL SRW Light Sources"
DESCRIPTION = "Widgets for SOLEIL SRW"
BACKGROUND = "#b8bcdb"
ICON = "icons/source.png"
PRIORITY = 210
|
_base_ = '../htc/htc_r50_fpn_1x_coco_1280.py'
# optimizer
optimizer = dict(lr=0.005)
model = dict(
pretrained=\
'./checkpoints/lesa_pretrained_imagenet/'+\
'lesa_wrn50_pretrained/'+\
'lesa_wrn50/'+\
'checkpoint.pth',
backbone=dict(
type='ResNet',
depth=50,
num... |
# -*- coding: utf-8 -*-
def list_remove_duplicates(dup_list):
"""Remove duplicates from a list.
Args:
dup_list (list): List.
Returns:
list: Return a list of unique values.
"""
return list(set(dup_list))
|
class GitHubRequestException(BaseException):
pass
class GithubDecodeError(BaseException):
pass |
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-10-07 00:36
# @Author : Fabrice LI
# @File : 480_binary_tree_paths.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a binary tree, return all root-to-leaf paths.
#Reference:**********************... |
#Editor do ambiente Python (IDLE)
print("Olá pessoal!")
print("Exemplo de código em Python")
print("Para rodar o programa, pressione a tecla F5")
#Experimente pressionar F5; o ambiente abrirá uma janela de execução.
|
tests = int(input())
def solve(C, R):
c = C//9
r = R//9
if not C%9 ==0:
c += 1
if not R%9 == 0:
r += 1
if c < r:
return [0, c]
else:
return [1, r]
for t in range(tests):
C, R = map(int, input().split())
ans = solve(C, R)
print(ans[0], ans[1])
|
#!/usr/bin/env python3
s = input()
i = 0
while i < len(s):
print(s[i:])
i = i + 1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Exception handle.
"""
|
def greeting(name):
print("Hello " + name + "!")
def goodbye(name):
print("Goodbye " + name + "!")
|
def soma(a, b):
print(f'A = {a} e B = {b}')
s = a + b
print(f'A soma A + B = {s}')
#Programa Principal
soma(b=4, a=5)
soma(7, 2)
# soma(3, 9, 5) -> não pode ser calculado nessa função pois passa 3 parametros e a função só trabalha com 2
|
'''
The Models folder consists of files representing trained/retrained models as
part of build jobs, etc. The model names can be appropriately set as
projectname_date_time or project_build_id (in case the model is created as part
of build jobs). Another approach is to store the model files in a separate storage
such as... |
x=int(input("lungima saritura initiala"))
n=int(input("numar sarituri pana scade"))
p=int(input("cu cate procente scade"))
m=int(input("numar sarituri totale"))
s=0
for i in range (m):
s+=x
if i+1 == n:
k=p*x//100
x-=k
n*=2
print(s)
|
# Number of classes
N_CLASSES = 1000
# Root directory of the `MS-ASL` dataset
_MSASL_DIR = 'D:/datasets/msasl'
# Directory of the `MS-ASL` dataset specification files
_MSASL_SPECS_DIR = f'{_MSASL_DIR}/specs'
# Directory of the filtered `MS-ASL` dataset specification files
_MSASL_FILTERED_SPECS_DIR = f'{_MSASL_DIR}/f... |
class StorageError(Exception):
pass
class RegistrationError(Exception):
pass
|
class SetupMaster(object):
def check_os():
if 'CentOS Linux' in platform.linux_distribution():
redhat_setup()
else:
debian_setup()
|
'''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Outp... |
class HandlerOperator:
"""Handler operator.
"""
def __init__(self, allow_fail=False, should_rerun=False):
"""Constructor.
"""
self.allow_fail = allow_fail
self.should_rerun = should_rerun
def execute(self, handler):
"""Execute.
"""
raise NotImple... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 09:51:45 2021
@author: Rakin Shahriar
"""
#h,m,s = map(int,input().split())
try:
h,m,s = map(int,input().split())
if(h<12 and h>0 and m<60 and s<60):
print((12-h),":",(60-m),":",(60-s))
elif(h==12):
print(12,":",(60-m),":",(60-s))
else... |
def get_parameters(code_header):
begin = -1
end = -1
for i in range(0, len(code_header)):
if code_header[i] == '(':
begin = i
for i in reversed(range(0, len(code_header))):
if code_header[i] == ')':
end = i
if begin == -1 or end == -1:
parameter = None... |
class MockGetResponse(object):
def __init__(self, text):
self.text = text
class MockSession(object):
def get(self, url):
if url.find('login') < 0:
return MockGetResponse("""
<ajax_response_xml_root>
<IF_ERRORPARAM>SUCC</IF_ERRORPARAM>
... |
cmdlist = [
("ViewerFramework","customizationCommands","setUserPreference",""" Command providing a GUI to allow the user to set available\n userPreference."""),
("ViewerFramework","customizationCommands","setOnAddObjectCommands","""Command to specify commands that have to be carried out when an object\n is added ... |
class RenguMapPass:
def __call__(self, obj: dict):
return obj
|
fiboarr=[0,1]
def fibonacci(n):
if n<=0:
print("Invalid input")
elif n<=len(fiboarr):
return fiboarr[n-1]
else:
for i in range(len(fiboarr)-1,n-1):
fiboarr.append(fiboarr[i]+fiboarr[i-1])
print(fiboarr)
return fiboarr[n-1]
print(fibonacci(10))
|
dec = int(input("Enter any Number: "))
print (" The decimal value of" ,dec, "is:")
print (bin(dec)," In binary.")
print (oct(dec),"In octal.")
print (hex(dec),"In hexadecimal.")
|
__author__ = "Andrea de Marco <andrea.demarco@buongiorno.com>"
__version__ = '0.2'
__classifiers__ = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
... |
def of_codon():
pass
def of_rna():
pass
|
def daily_stock_price_update(target_table, sleep_sec, to_date = None):
# 1. Get current updated date
def get_current_updated_date():
conn_params = {
"host" : "localhost",
"database" : "Fin_proj",
"user" : "postgres",
"password" : "nckumark"
}
sql = "SELECT... |
if __name__ == '__main__':
a = int(input("Enter a number : "))
if sum([pow(int(d), 3) for d in str(a)]) == a:
print(a, " is an armstrong number")
else:
print(a, " is not an armstrong number")
|
nums = list(map(int, input().split(' ')))
odd_num_list = [num for num in nums if num % 2 == 1]
print(len(odd_num_list))
|
posActu = int(input())
nbVillages = int(input())
nbVillagesProches = 0
for i in range(nbVillages):
posVillage = int(input())
diff = posActu - posVillage
if (diff <= 50 and diff >= -50):
nbVillagesProches += 1
print(nbVillagesProches) |
######################################
######### O(n^2) algorithm #########
######################################
# def get_single_max_profit(prices: list[int]) -> int:
# lowest = sys.maxsize
# max_profit = 0
# for price in prices:
# if price < lowest:
# lowest = price
#
# pro... |
print('=====Calculo de Aumento de Salário=====')
salario = float(input('Entre com o valor do salário Atual: R$'))
porc = float(input('Qual o valor em (%) de aumento: '))
calc = salario + (salario * porc / 100)
print(' Salário informado: R${:.2f}\n Porcentagem de aumento: {}%\n Salário com aumento: R$ {:.2f}'.format(sa... |
# Copyright 2018 Johns Hopkins University (author: Daniel Povey)
# Apache 2.0
class CoreConfig:
"""
A class to store certain configuration information that is needed
by core parts of Waldo, and read and write this information from
a config file on disk.
"""
def __init__(self):
... |
child1 = {"name": "Emil", "year": 2004}
child2 = {"name": "Tobias", "year": 2007}
child3 = {"name": "Linus", "year": 2011}
myfamily = {"child1": child1, "child2": child2, "child3": child3}
print(myfamily)
|
async def test_clear_shopping_cart_should_be_a_success(client):
resp = await client.post('/v1/shopping_cart/items', json={
'id': '5',
'quantity': 2
})
assert resp.status == 201
assert (await resp.json()) == {
'id': '5',
'name': 'Playstation 5',
'price': 3000
... |
"""
This is a lazy way to avoid opening a json, simply import this file to collect your BIDS sidecar templates instead.
:param sidecar_template_full: a dictionary containing every field specified in the BIDS standard for PET imaging data
:param sidecar_template_short: a dictionary containing only the required fields i... |
class Solution:
def removeDuplicates(self, S: str) -> str:
a = []
for i in S:
if len(a) == 0:
a.append(i)
elif a[-1] == i:
a.pop()
else:
a.append(i)
return ''.join(str(i) for i in a) |
"""
Copyright 2016 Rackspace
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 writing, software
dist... |
#!/usr/bin/env python
h = 'Hello!'
if __name__ == '__main__':
print(h.upper())
|
# height: Number of edges in longest path from the node to a leaf node.
# So,
# height of a tree = height of root node
# height of a tree with 1 node = 0
# depth:
# depth is no of edges in path from root to that node
# depth of root node = 0
class Node:
def __init__(self, data) ... |
# Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols
# ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
def ficha(nome='<desconhecido>', gols=0):
print(f'J... |
nome = str(input("Qual é seu nome? "))
if nome == 'Gabi':
print("Que nome lindo")
else:
print("Nome normal")
print("Bom dia {}".format(nome))
|
"""
Author: Kagaya john
Tutorial 14 : functions
"""
"""
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
E... |
# Implement cat and dog queue for animal shelter
class AnimalShelter:
def __init__(self) -> None:
self.cats=[]
self.dogs=[]
def enqueue(self,animal,type):
if type=='cat':
self.cats.append(animal)
else:
self.dogs.append(animal)
def dequeueCat(self):
... |
class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
def isOverlap(x1, x2, x3, x4):
if x1 == x3 and x2 == x4:
return True
elif x1 < x3 < x2 or x1 < x4 < x2 or... |
#!/usr/bin/env python3
def pkcs7_padding(msg, block_size):
padding_length = block_size - (len(msg) % block_size)
if padding_length == 0:
padding_length = block_size
padding = bytes([padding_length] * padding_length)
return msg + padding
if __name__ == '__main__':
print(pkcs7_padding(b'YELLOW S... |
print("Olá, seja muito bem vindo, peço que você digite um comprimento em jardas e iremos lhe apresentar convertido em metros.")
J = float(input("Número em Jardas: "))
M = 0.91 * J
print ("{} Jardas, convertido em metros é: {} metros.".format(J,M)) |
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1 and not t2:
return None
if not t1 or not t2:
return t1 or t2
t1.val += t2.val
q = deque([(t1, t2)])
while q:
n1, n2 = q.popleft()
if n1.left... |
"""This module contains data for UI menu items."""
# =============================================================================
# GLOBALS
# =============================================================================
DEFAULT_VALUES = {
"componentexport": False,
"lightexport": "",
"quantize": "half",
... |
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(6)
evenOdd(5)
#######################
String ="Monerah Balhareth"
print(String)
######################
def table(num):
for x in range(1,11):
print (num," * ", x,"=",num*x)
table(19)
###################... |
# -*- coding: utf-8 -*-
#BEGIN_HEADER
#END_HEADER
class RESKESearchDemo:
'''
Module Name:
RESKESearchDemo
Module Description:
A KBase module: RESKESearchDemo
'''
######## WARNING FOR GEVENT USERS ####### noqa
# Since asynchronous IO can lead to methods - even the same method -
# ... |
class LabeledBox:
def __init__(self, x1: int, y1: int, x2: int, y2: int, label: str):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.label = label
|
class BlockType:
Empty = 1 << 0
OutBound = 1 << 1
# Wall = 2
RedApple = 1 << 2
BlueApple = 1 << 3
# Agents
Self = 1 << 4
# RedAgent = 1 << 5
BlueAgent = 1 << 6
GreenAgent = 1 << 7
OrangeAgent = 1 << 8
PurpleAgent = 1 << 9
# Effects
Punish = 1 << 20
# Num... |
class UserController(object):
def getUser(self):
return "GET user"
def postUser(self):
return "POST user" |
"""
Iterables vs Iterator
- Iterables is an object implements the iterable protocol
+ __iter__ => return the iterator
- Iterator is an object implements the iterator protocol
+ __iter__ => return itself
+ __next__ => return next item or StopIteration
- This solves the exhaustion problem
"""
class Cities:
... |
class AtlasData:
texture_dict = None
border = 1
width = 0
height = 0
color_mode = ""
file_type = ""
name = ""
def __init__(self, name, width=512, height=512, border=1, color_mode="RGBA", file_type="tga"):
self.texture_dict = {}
self.name = name
self.border = bord... |
# Armstrong Number - Burak Karabey
def armstrong(x):
input_number = list(str(x))
i = 0
u = 0
while i < len(input_number):
u = u + (int(input_number[i]) ** len(input_number))
i += 1
u = str(u)
armstrong_number = []
for n in range(0, len(u)):
armstrong_number.append(u[n... |
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# Find kth node from left
l = r = head
for _ in range(k-1):
l = l.next
# Find kth node from right
# by finding tail node
tail = l
while tail.next:
... |
#!/usr/bin/env python
NAME = 'Sabre Firewall (Sabre)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, responsepage = r
if any(i in responsepage for i in (b'dxsupport@sabre.com', b'<title>Application Firewall Error</title>',
... |
"""
Views for statusapp.
Views are divided into views that dynamically draw graphs, views
that create .csv files, and views that render a webpage to response.
"""
|
valores = [[],[]] #Valor[0] = par
for v in range (1,8):
valor = int(input(f'Digite o {v}º valor: '))
if valor % 2 == 0:
while valor in valores[0]:
print ('Valor ja adicioanado')
valor = int(input(f'Digite o {v}º valor: '))
else:
valores[0].append(valor)
el... |
''' this module contains functions needed to access flood risks'''
# this function checks if current water level is over the threshold
def stations_level_over_threshold(stations, tol):
list_of_stations= []
for station in stations:
water_level= station.relative_water_level()
if water_level != None... |
#!/usr/bin/env python3
def main():
with open("./inputs/day2.txt") as file:
raw_input = file.read()
instructions = parse_intcode_into_instructions(raw_input)
mutated_instructions = run_instructions(instructions)
print(get_answer(mutated_instructions))
def parse_intcode_into_instructions(raw_b... |
def binary_search(nums,l,r,val)->int:
if nums[0] > val:
return 0
elif nums[r] < val:
return r+1
elif r>=l:
mid = l+ (r-l)//2
if nums[mid] == val:
return mid
elif nums[mid] > val:
return binary_search(nums,l,mid-1,val)
else:
... |
#!-*- coding:utf-8 -*-
"""
CentOS查看系统信息
1:查看CPU
more /proc/cpuinfo | grep "model name"
grep "model name" /proc/cpuinfo
grep "model name" /proc/cpuinfo | cut -f2 -d:
2:查看内存
grep MemTotal /proc/meminfo
grep MemTotal /proc/meminfo | cut -f2 -d:
free -m |grep "Mem" | awk '{print $2}'
3:查看当前linux的版本
cat /proc/version
red... |
def main():
a = {1, 2, 3, 4}
b = {4, 5, 6}
b.add(7)
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
print(a.issubset(b))
print(a.issuperset(b))
if __name__ == '__main__':
main()
|
# vim: expandtab:tabstop=4:shiftwidth=4
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCLabel(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
name,
name... |
"""
@file msg.py
@author Bowen Zheng
@University of California Riverside
@date 2016-10-27
This file defines messages for intersection management
"""
class Message(object):
"""The base calss for all messages"""
def __init__(self, sender, sendTime, resource, time_range, send_type):
se... |
name = "opensubdiv"
version = "3.2.0"
build_requires = [
'glfw-3'
]
requires = [
'tbb-4'
]
variants = [
["platform-linux", "arch-x86_64", "os-CentOS-7"]
]
tools = [
'far_perf'
'far_regression'
'hbr_baseline'
'hbr_regression'
'stringify'
'tutorials'
]
uuid = "opensubdiv"
def c... |
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# 大小
print(len(the_count))
# 正向取值
print(the_count[3])
# 逆向取值
print(the_count[-1])
# 增加
the_count.append(6)
print(the_count)
# 赋值
the_count[2] = 10
print(the_count)
# 5
# 4
# 5
# [1, 2, ... |
expected_output = {
"bgp_id": 65109,
"vrf": {
"VRF1": {
"neighbor": {
"192.168.10.253": {
"address_family": {
"vpnv4 unicast": {
"version": 4,
"as": 65555,
... |
i = input('digite um numero inteiro: ')
for k in range(11):
l = int(i)*int(k)
print(i,' * ',k,' = ',l) |
self.description = "Replace a package with a file in 'backup' (local modified)"
# FS#24543
lp = pmpkg("dummy")
lp.files = ["etc/dummy.conf*", "bin/dummy"]
lp.backup = ["etc/dummy.conf"]
self.addpkg2db("local", lp)
sp = pmpkg("replacement")
sp.replaces = ["dummy"]
sp.files = ["etc/dummy.conf", "bin/dummy*"]
sp.backup ... |
# 대문자로 전부 만드세요.
# sentences = "My Name is John"
# # 출력 예시
# # MY NAME IS JOHN
sentences = "My Name is John"
print(sentences.upper())
# 문장의 양 끝의 공백을 제거해주세요.
# 문장 = " ○ 사업개시일 현재 만18세 이상의 합천군민 중 재산이 2억원 이하인자 -
# 실업자 또는 정기적인 소득이 없는 일용근로자로서 구직등록을 한 자 - 행정기관 또는 행정기관이 인정한 기관에서 노숙자임을 증명한 자 ○ 재학생을 제외한 18세 이상의 미취업자 "
문장 = '''... |
a=int(input("Enter no of input = "))
for i in range (a):
b=int(input("Enter the 1 or 2= "))
if (b==1):
class A:
def odd(self):
oddInteger=int(input("Enter odd integer = "))
for i in range (oddInteger*2):
if(i%2!=0):
... |
# Solfec-2.0 input command test: GRAVITY
spl = SPLINE ([0, 0, -5, 1, 2, -9.81, 3, -9.81])
def call(t): return 0.0
GRAVITY (0.0, call, spl)
print_GRAVITY()
|
"""
A module of mass 14 requires 2 fuel.
This fuel requires no further fuel
(2 divided by 3 and rounded down is 0, which would call for a negative fuel),
so the total fuel required is still just 2.
At first, a module of mass 1969 requires 654 fuel.
Then, this fuel requires 216 more fuel (654 / 3 - 2).
216 then... |
#!/usr/bin/python3
with open('./input.txt', 'r') as input:
lines = input.read()
input.close()
lines = lines.split("\n\n")
rules = lines[0].split("\n")
rule_list = []
for rule in rules:
resp_dict = {}
for parsed_rule in rule.split(": ")[1].split(" or "):
rule_list.append({'start': int(parsed_rul... |
#!/usr/bin/python3
def is_palindrome(s: str) -> (bool):
return s == s[::-1]
def solve() -> (int):
solution = int(0)
for i in reversed(range(100, 1000)):
for j in reversed(range(100, 1000)):
product = i * j
if is_palindrome(str(product)):
if product > solut... |
'''
Given an integer array, find three numbers whose product is maximum and
output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and
all elements are in the range [-1000, 1000].
Multiplication of a... |
class Solution:
def diStringMatch(self, S: str) -> List[int]:
small = 0
large = len(S)
result = []
for s in S:
if s == "I":
result.append(small)
small += 1
elif s == "D":
result.append(large)
larg... |
'''def saudacao (msg, nome):
nome = nome.replace("a", "é")
return f'{msg} {nome}'
var = saudacao("Boa tarde", "Natalia")
print (var)'''
def divisao(n1, n2):
if n1 == 0 or n2 == 0:
return
return n1/n2
divide = divisao(8,5)
if divide:
print(divide)
else:
print("não existe divisão por 0,... |
# Faça um Programa que peça dois números e imprima o menor deles.
n1 = float(input("Primeiro valor: "))
n2 = float(input("Segundo valor: "))
if (n1 < n2):
print("O numero "+str(n1)+" é o menor")
elif (n2 < n1) :
print("O numero "+str(n2)+" é o menor")
else:
print("Os dois são iguais.") |
def array_not(arr):
r = []
for item in arr:
if item == 0:
r.append(1)
else:
r.append(0)
return r
def bin2int(arr):
r = 0
for i in range(len(arr)):
if arr[len(arr) - 1 - i] == 1:
r += 2**i
return r
with open('input.txt') as f:
a = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for 'biblio.isbn', using nose.
"""
### IMPORTS ###
## CONSTANTS & DEFINES ###
### TESTS ###
### END ####################################################################
|
class ValidateImports:
type_of_connections = []
type_of_imports=[]
def get_types_of_nodes(self, content, node_val):
self.type_of_connections.clear()
for node in node_val:
nodes = content["topology_template"]["node_templates"][node]["requirements"]
for n in range(len(... |
class BinaryExploder(object):
def __init__(self, num):
self.num = num
def __iter__(self):
num = self.num
if num != 0:
value, length = num & 1, 1
num >>= 1
while num != 0:
if num & 1 != value:
yield value, length
... |
"""
The __init__.py file lets the Python interpreter know that a directory contains code
for a Python module. An __init__.py file can be blank. Without one, you cannot
import modules from another folder into your project.
@see https://careerkarma.com/blog/what-is-init-py/
"""
|
class PokemonNotFound(Exception):
def __init__(self, value):
super().__init__()
self.value = value
def __str__(self):
return "{} was not found in PokeAPI".format(self.value)
|
######################### Common settings ################################
# Number of files that need to generate.
current_file_num = 300
# Size of each file. Only the 'current_file_size' will be read, and its unit is byte.
current_file_size_mib = 25 # Size unit is MiB
current_file_size_unit = int(10 ** 6)
current_... |
#!/usr/bin/python3
#!/usr/bin/env python3
def isValidSequence(seq):
check_array = ['A','T','G','C']
for i in seq:
if i not in check_array:
return False
return True
#To check if Sequence consists of only A,T,G,C
def inputSequence():
seq = str(raw_input("Please Enter Your Sequence: "))
print(seq)
return seq
... |
# -*- coding: utf-8 -*-
# author: Phan Minh Tâm
# source has refer to java source of BURL method: http://web.informatik.uni-mannheim.de/AnyBURL/IJCAI/ijcai19.html file ScoreTree.java
class ScoreTree(object):
lower_bound = 10
upper_bound = 10
epsilon = 1e-4
def __init__(self):
self.score = 0.0
self.ch... |
def build_placements(shoes):
""" (list of str) -> dict of {str: list of int}
Return a dictionary where each key is a company
and each value is a
list of placements by people wearing shoes
made by that company.
>>> result = build_placements(['Saucony', 'Asics', \
'Asics', 'NB... |
class UnknownUser(Exception):
pass
class UnknownRole(Exception):
pass
class UnknownAccessLevel(Exception):
pass
class UserNotAssignedToRole(Exception):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.