content
stringlengths 7
1.05M
|
---|
class Solution:
def isHappy(self, n: int) -> bool:
def squaredSum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squaredSum(n)
fast = squaredSum(squaredSum(n))
while slow != fast:
slow = squaredSum(slow)
fast = squaredSum(squaredSum(fast))
return slow == 1
|
def safeDict(elem, array_of_keys, default=""):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default |
# Those constants are used from the library only
BASE_PAL_URL = "https://pal-{}.adyen.com/pal/servlet"
PAL_LIVE_ENDPOINT_URL_TEMPLATE = "https://{}-pal-live" \
".adyenpayments.com/pal/servlet"
BASE_HPP_URL = "https://{}.adyen.com/hpp"
ENDPOINT_CHECKOUT_TEST = "https://checkout-test.adyen.com"
ENDPOINT_CHECKOUT_LIVE_SUFFIX = "https://{}-checkout-live" \
".adyenpayments.com/checkout"
API_BIN_LOOKUP_VERSION = "v50"
API_CHECKOUT_VERSION = "v67"
API_CHECKOUT_UTILITY_VERSION = "v1"
API_RECURRING_VERSION = "v49"
API_PAYMENT_VERSION = "v64"
API_PAYOUT_VERSION = "v64"
LIB_VERSION = "5.1.0"
LIB_NAME = "adyen-python-api-library"
|
# -*- coding: utf-8 -*-
"""
@file
@brief Data from INSEE
**Source**
* ``irsocsd2014_G10.xlsx``: ?
* ``fm-fecondite-age-mere.csv``: `INSEE Bilan Démographique 2016 <https://www.insee.fr/fr/statistiques/1892259?sommaire=1912926>`_
* ``pop-totale-france.xlsx``: `INED Population totale
<https://www.ined.fr/fr/tout-savoir-population/chiffres/france/evolution-population/population-totale/>`_
* ``TF00-02_D.xls``: `spac-actuaires, tables de mortalité <http://www.spac-actuaires.fr/glossaire/Table_de_mortalit%C3%A9>`_
* ``TH00-02_D.xls``: `spac-actuaires, tables de mortalité <http://www.spac-actuaires.fr/glossaire/Table_de_mortalit%C3%A9>`_
""" # pragma: no cover
|
__all__ = ['VERSION']
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
VIDEO = 'youtube#video'
YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v='
VERSION = '4.0.0'
|
# mailbox_or_url_parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list delim mailbox_or_url\n | mailbox_or_url_list delim\n | mailbox_or_urldelim : delim fwsp COMMA\n | delim fwsp SEMICOLON\n | COMMA\n | SEMICOLONmailbox_or_url : mailbox\n | urlurl : ofwsp URL ofwspmailbox : addr_spec\n | angle_addr\n | name_addrname_addr : ofwsp phrase angle_addrangle_addr : ofwsp LANGLE addr_spec RANGLE ofwspaddr_spec : ofwsp local_part AT domain ofwsplocal_part : DOT_ATOM\n | ATOM\n | quoted_stringdomain : DOT_ATOM\n | ATOM\n | domain_literalquoted_string : DQUOTE quoted_string_text DQUOTE\n | DQUOTE DQUOTEquoted_string_text : quoted_string_text QTEXT\n | quoted_string_text QPAIR\n | quoted_string_text fwsp\n | QTEXT\n | QPAIR\n | fwspdomain_literal : LBRACKET domain_literal_text RBRACKET\n | LBRACKET RBRACKETdomain_literal_text : domain_literal_text DTEXT\n | domain_literal_text fwsp\n | DTEXT\n | fwspcomment : LPAREN comment_text RPAREN\n | LPAREN RPARENcomment_text : comment_text CTEXT\n | comment_text fwsp\n | CTEXT\n | fwspphrase : phrase fwsp ATOM\n | phrase fwsp DOT_ATOM\n | phrase fwsp DOT\n | phrase fwsp quoted_string\n | phrase ATOM\n | phrase DOT_ATOM\n | phrase DOT\n | phrase quoted_string\n | ATOM\n | DOT_ATOM\n | DOT\n | quoted_stringofwsp : fwsp comment fwsp\n | fwsp comment\n | comment fwsp\n | comment\n | fwsp\n |fwsp : FWSP'
_lr_action_items = {'FWSP':([0,2,7,11,12,14,15,17,18,19,20,21,22,23,24,25,26,32,33,34,35,36,40,41,42,43,44,45,46,50,51,52,53,54,55,56,57,58,59,60,61,62,63,66,67,68,69,70,71,72,],[7,7,-61,7,7,7,7,-51,7,-52,7,-54,-53,-42,7,-38,-41,-30,-29,-28,-24,7,-48,-47,-50,-49,-40,-37,-39,7,7,7,-20,-21,-22,-27,-26,-25,-23,-44,-43,-46,-45,-36,-35,7,-32,-34,-33,-31,]),'LANGLE':([0,1,2,4,7,12,13,17,19,20,21,22,25,27,35,37,38,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,14,-61,-56,-57,-51,-52,-60,-54,-53,-38,-55,-24,-59,14,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'QPAIR':([7,18,32,33,34,36,56,57,58,],[-61,33,-30,-29,-28,57,-27,-26,-25,]),'URL':([0,1,2,4,7,12,13,25,27,45,],[-60,-59,-58,15,-61,-56,-57,-38,-55,-37,]),'QTEXT':([7,18,32,33,34,36,56,57,58,],[-61,34,-30,-29,-28,58,-27,-26,-25,]),'DTEXT':([7,52,66,67,68,70,71,],[-61,67,-36,-35,71,-34,-33,]),'DQUOTE':([0,1,2,4,7,12,13,14,17,18,19,20,21,22,25,27,28,32,33,34,35,36,37,40,41,42,43,45,56,57,58,59,60,61,62,63,],[-60,-59,-58,18,-61,-56,-57,-60,-51,35,-52,18,-54,-53,-38,-55,18,-30,-29,-28,-24,59,18,-48,-47,-50,-49,-37,-27,-26,-25,-23,-44,-43,-46,-45,]),'LBRACKET':([31,],[52,]),'DOT_ATOM':([0,1,2,4,7,12,13,14,17,19,20,21,22,25,27,28,31,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,19,-61,-56,-57,-60,-51,-52,40,-54,-53,-38,-55,47,53,-24,60,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'RPAREN':([7,11,23,24,26,44,46,],[-61,25,-42,45,-41,-40,-39,]),'AT':([16,17,19,21,35,47,48,49,59,],[31,-18,-17,-19,-24,-17,-18,-19,-23,]),'LPAREN':([0,1,7,14,15,17,19,20,21,22,35,37,40,41,42,43,50,51,53,54,55,59,60,61,62,63,69,72,],[11,11,-61,11,11,-51,-52,11,-54,-53,-24,11,-48,-47,-50,-49,11,11,-20,-21,-22,-23,-44,-43,-46,-45,-32,-31,]),'ATOM':([0,1,2,4,7,12,13,14,17,19,20,21,22,25,27,28,31,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,17,-61,-56,-57,-60,-51,-52,41,-54,-53,-38,-55,48,54,-24,61,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'RANGLE':([1,2,7,12,13,25,27,29,45,51,53,54,55,65,69,72,],[-59,-58,-61,-56,-57,-38,-55,50,-37,-60,-20,-21,-22,-16,-32,-31,]),'RBRACKET':([7,52,66,67,68,70,71,],[-61,69,-36,-35,72,-34,-33,]),'CTEXT':([7,11,23,24,26,44,46,],[-61,26,-42,46,-41,-40,-39,]),'DOT':([0,1,2,4,7,12,13,17,19,20,21,22,25,27,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,22,-61,-56,-57,-51,-52,43,-54,-53,-38,-55,-24,63,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'$end':([1,2,3,5,6,7,8,9,10,12,13,15,25,27,30,39,45,50,51,53,54,55,64,65,69,72,],[-59,-58,-13,-12,0,-61,-8,-9,-11,-56,-57,-60,-38,-55,-10,-14,-37,-60,-60,-20,-21,-22,-15,-16,-32,-31,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'fwsp':([0,2,11,12,14,15,18,20,24,36,50,51,52,68,],[1,13,23,27,1,1,32,37,44,56,1,1,66,70,]),'comment':([0,1,14,15,20,37,50,51,],[2,12,2,2,2,12,2,2,]),'domain':([31,],[51,]),'comment_text':([11,],[24,]),'name_addr':([0,],[3,]),'ofwsp':([0,14,15,20,50,51,],[4,28,30,38,64,65,]),'angle_addr':([0,20,],[5,39,]),'mailbox_or_url':([0,],[6,]),'local_part':([4,28,],[16,16,]),'domain_literal_text':([52,],[68,]),'mailbox':([0,],[8,]),'quoted_string_text':([18,],[36,]),'url':([0,],[9,]),'addr_spec':([0,14,],[10,29,]),'phrase':([4,],[20,]),'quoted_string':([4,20,28,37,],[21,42,49,62,]),'domain_literal':([31,],[55,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> mailbox_or_url","S'",1,None,None,None),
('mailbox_or_url_list -> mailbox_or_url_list delim mailbox_or_url','mailbox_or_url_list',3,'p_expression_mailbox_or_url_list','parser.py',19),
('mailbox_or_url_list -> mailbox_or_url_list delim','mailbox_or_url_list',2,'p_expression_mailbox_or_url_list','parser.py',20),
('mailbox_or_url_list -> mailbox_or_url','mailbox_or_url_list',1,'p_expression_mailbox_or_url_list','parser.py',21),
('delim -> delim fwsp COMMA','delim',3,'p_delim','parser.py',30),
('delim -> delim fwsp SEMICOLON','delim',3,'p_delim','parser.py',31),
('delim -> COMMA','delim',1,'p_delim','parser.py',32),
('delim -> SEMICOLON','delim',1,'p_delim','parser.py',33),
('mailbox_or_url -> mailbox','mailbox_or_url',1,'p_expression_mailbox_or_url','parser.py',36),
('mailbox_or_url -> url','mailbox_or_url',1,'p_expression_mailbox_or_url','parser.py',37),
('url -> ofwsp URL ofwsp','url',3,'p_expression_url','parser.py',41),
('mailbox -> addr_spec','mailbox',1,'p_expression_mailbox','parser.py',45),
('mailbox -> angle_addr','mailbox',1,'p_expression_mailbox','parser.py',46),
('mailbox -> name_addr','mailbox',1,'p_expression_mailbox','parser.py',47),
('name_addr -> ofwsp phrase angle_addr','name_addr',3,'p_expression_name_addr','parser.py',51),
('angle_addr -> ofwsp LANGLE addr_spec RANGLE ofwsp','angle_addr',5,'p_expression_angle_addr','parser.py',55),
('addr_spec -> ofwsp local_part AT domain ofwsp','addr_spec',5,'p_expression_addr_spec','parser.py',59),
('local_part -> DOT_ATOM','local_part',1,'p_expression_local_part','parser.py',63),
('local_part -> ATOM','local_part',1,'p_expression_local_part','parser.py',64),
('local_part -> quoted_string','local_part',1,'p_expression_local_part','parser.py',65),
('domain -> DOT_ATOM','domain',1,'p_expression_domain','parser.py',69),
('domain -> ATOM','domain',1,'p_expression_domain','parser.py',70),
('domain -> domain_literal','domain',1,'p_expression_domain','parser.py',71),
('quoted_string -> DQUOTE quoted_string_text DQUOTE','quoted_string',3,'p_expression_quoted_string','parser.py',75),
('quoted_string -> DQUOTE DQUOTE','quoted_string',2,'p_expression_quoted_string','parser.py',76),
('quoted_string_text -> quoted_string_text QTEXT','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',83),
('quoted_string_text -> quoted_string_text QPAIR','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',84),
('quoted_string_text -> quoted_string_text fwsp','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',85),
('quoted_string_text -> QTEXT','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',86),
('quoted_string_text -> QPAIR','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',87),
('quoted_string_text -> fwsp','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',88),
('domain_literal -> LBRACKET domain_literal_text RBRACKET','domain_literal',3,'p_expression_domain_literal','parser.py',92),
('domain_literal -> LBRACKET RBRACKET','domain_literal',2,'p_expression_domain_literal','parser.py',93),
('domain_literal_text -> domain_literal_text DTEXT','domain_literal_text',2,'p_expression_domain_literal_text','parser.py',100),
('domain_literal_text -> domain_literal_text fwsp','domain_literal_text',2,'p_expression_domain_literal_text','parser.py',101),
('domain_literal_text -> DTEXT','domain_literal_text',1,'p_expression_domain_literal_text','parser.py',102),
('domain_literal_text -> fwsp','domain_literal_text',1,'p_expression_domain_literal_text','parser.py',103),
('comment -> LPAREN comment_text RPAREN','comment',3,'p_expression_comment','parser.py',107),
('comment -> LPAREN RPAREN','comment',2,'p_expression_comment','parser.py',108),
('comment_text -> comment_text CTEXT','comment_text',2,'p_expression_comment_text','parser.py',112),
('comment_text -> comment_text fwsp','comment_text',2,'p_expression_comment_text','parser.py',113),
('comment_text -> CTEXT','comment_text',1,'p_expression_comment_text','parser.py',114),
('comment_text -> fwsp','comment_text',1,'p_expression_comment_text','parser.py',115),
('phrase -> phrase fwsp ATOM','phrase',3,'p_expression_phrase','parser.py',119),
('phrase -> phrase fwsp DOT_ATOM','phrase',3,'p_expression_phrase','parser.py',120),
('phrase -> phrase fwsp DOT','phrase',3,'p_expression_phrase','parser.py',121),
('phrase -> phrase fwsp quoted_string','phrase',3,'p_expression_phrase','parser.py',122),
('phrase -> phrase ATOM','phrase',2,'p_expression_phrase','parser.py',123),
('phrase -> phrase DOT_ATOM','phrase',2,'p_expression_phrase','parser.py',124),
('phrase -> phrase DOT','phrase',2,'p_expression_phrase','parser.py',125),
('phrase -> phrase quoted_string','phrase',2,'p_expression_phrase','parser.py',126),
('phrase -> ATOM','phrase',1,'p_expression_phrase','parser.py',127),
('phrase -> DOT_ATOM','phrase',1,'p_expression_phrase','parser.py',128),
('phrase -> DOT','phrase',1,'p_expression_phrase','parser.py',129),
('phrase -> quoted_string','phrase',1,'p_expression_phrase','parser.py',130),
('ofwsp -> fwsp comment fwsp','ofwsp',3,'p_expression_ofwsp','parser.py',139),
('ofwsp -> fwsp comment','ofwsp',2,'p_expression_ofwsp','parser.py',140),
('ofwsp -> comment fwsp','ofwsp',2,'p_expression_ofwsp','parser.py',141),
('ofwsp -> comment','ofwsp',1,'p_expression_ofwsp','parser.py',142),
('ofwsp -> fwsp','ofwsp',1,'p_expression_ofwsp','parser.py',143),
('ofwsp -> <empty>','ofwsp',0,'p_expression_ofwsp','parser.py',144),
('fwsp -> FWSP','fwsp',1,'p_expression_fwsp','parser.py',148),
]
|
"""
142. Linked List Cycle II
Medium
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
"""
# V0
# IDEA : 2 pointers + linked list basics
# https://github.com/yennanliu/CS_basics/blob/master/doc/cheatsheet/2_pointers.md
class Solution:
def detectCycle(self, head):
if not head or not head.next:
return
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
#print ("slow = " + str(slow) + " fast = " + str(fast))
### NOTE : via below condition check if is a cycle linked list
if not fast or not fast.next:
return
"""
### NOTE : re-init slow or fast as head (from starting point)
-> can init slow or head
"""
slow = head
#fast = head
"""
### NOTE : check while slow != fast
### NOTE : use the same speed
"""
while slow != fast:
fast = fast.next
slow = slow.next
return slow
# V0'
# IDEA : SET
class Solution(object):
def detectCycle(self, head):
if not head or not head.next:
return
s = set()
while head:
s.add(head)
head = head.next
if head in s:
return head
return
# V0'
# IDEA : SET
class Solution(object):
def detectCycle(self, head):
if not head: return None
visited = set()
while head:
if head in visited:
return head
visited.add(head)
head = head.next
return None
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79530638
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow, fast = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if not fast or not fast.next:
return None
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/79530638
# IDEA : SET
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return None
visited = set()
while head:
if head in visited:
return head
visited.add(head)
head = head.next
return None
# V1''
# http://bookshadow.com/weblog/2015/07/10/leetcode-linked-list-cycle-ii/
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head is None or head.next is None:
return None
slow, fast = head.next, head.next.next
while fast and fast.next and slow != fast:
fast = fast.next.next
slow = slow.next
if fast is None or fast.next is None:
return None
slow = head
while slow != fast:
slow, fast = slow.next, fast.next
return slow
# V2
# https://www.cnblogs.com/zuoyuan/p/3701877.html
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head == None or head.__next__ == None:
return None
slow = fast = head
while fast and fast.__next__:
slow = slow.__next__
fast = fast.next.__next__
if fast == slow:
break
if slow == fast:
slow = head
while slow != fast:
slow = slow.__next__
fast = fast.__next__
return slow
return None
# V3
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
if self:
return "{}".format(self.val)
else:
return None
class Solution(object):
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
fast, slow = head, head
while fast and fast.__next__:
fast, slow = fast.next.__next__, slow.__next__
if fast is slow:
fast = head
while fast is not slow:
fast, slow = fast.__next__, slow.__next__
return fast
return None |
# coding: utf8
{
'\n Ao clicar no botão "enviar" abaixo, você estará concordando com os termos de uso acima descritos': '\n Ao clicar no botão "enviar" abaixo, você estará concordando com os termos de uso acima descritos',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de um JOIN',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s rows deleted': '%s linhas apagadas',
'%s rows updated': '%s linhas atualizadas',
'<anterior': '<anterior',
'<página anterior': '<página anterior',
'A senha deve ter pelo menos 2 caracteres': 'A senha deve ter pelo menos 2 caracteres',
'A senha foi trocada': 'A senha foi trocada',
'Acesse o link de confirmação no seu e-mail para completar o cadastro': 'Acesse o link de confirmação no seu e-mail para completar o cadastro',
'Admin': 'Admin',
'Anônimo': 'Anônimo',
'Ao completar seu registro você estará concordando com os termos de uso acima.': 'Ao completar seu registro você estará concordando com os termos de uso acima.',
'Ao completar seu registro, clicando no botão "enviar", você estará concordando com os termos de uso acima.': 'Ao completar seu registro, clicando no botão "enviar", você estará concordando com os termos de uso acima.',
'Ao completar seu registro, você estará concordando com os termos de uso acima.': 'Ao completar seu registro, você estará concordando com os termos de uso acima.',
'Atenção': 'Atenção',
'Atenção:': 'Atenção:',
'Atenção: ': 'Atenção: ',
'Available databases and tables': 'Bancos de dados e tabelas disponíveis',
'Avaliação excluída com sucesso': 'Avaliação excluída com sucesso',
'Cadastro ainda não verificado': 'Cadastro ainda não verificado',
'Cannot be empty': 'Não pode ser vazio',
'Change password': 'Alterar senha',
'Check to delete': 'Marque para apagar',
'Client IP': 'Client IP',
'Clique no link http://127.0.0.1:8000/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.': 'Clique no link http://127.0.0.1:8000/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.',
'Clique no link http://dacomp.info/forca/ForCA/default/user/reset_password/%(key)s para redefinir sua senha.': 'Clique no link http://dacomp.info/forca/ForCA/default/user/reset_password/%(key)s para redefinir sua senha.',
'Clique no link http://dacomp.info/forca/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.': 'Clique no link http://dacomp.info/forca/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.',
'Clique no link http://www.dacomp.info/forca/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.': 'Clique no link http://www.dacomp.info/forca/ForCA/default/user/verify_email/%(key)s para confirmar seu cadastro.',
'Confirmação de senha': 'Confirmação de senha',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Current request': 'Requisição atual',
'Current response': 'Resposta atual',
'Current session': 'Sessão atual',
'DB Model': 'DB Model',
'Database': 'Database',
'Delete:': 'Apagar:',
'Description': 'Description',
'Desfavoritar avaliação': 'Desfavoritar avaliação',
'Deslogado': 'Deslogado',
'Disciplina': 'Disciplina',
'Disciplinas': 'Disciplinas',
'Disciplinas ministradas por ': 'Disciplinas ministradas por ',
'E-mail enviado': 'E-mail enviado',
'E-mail inválido': 'E-mail inválido',
'E-mail verificado': 'E-mail verificado',
'Edit': 'Edit',
'Edit This App': 'Edit This App',
'Edit current record': 'Editar o registro atual',
'Editar avaliação': 'Editar avaliação',
'Enviar': 'Enviar',
'Este e-mail já está cadastrado': 'Este e-mail já está cadastrado',
'Excluir avaliação': 'Excluir avaliação',
'FAQ': 'FAQ',
'Favoritar avaliação': 'Favoritar avaliação',
'ForCA - Redefinição de senha': 'ForCA - Redefinição de senha',
'ForCA - Verificação de e-mail': 'ForCA - Verificação de e-mail',
'Fórum Colaborativo de Avaliação': 'Fórum Colaborativo de Avaliação',
'Group %(group_id)s created': 'Group %(group_id)s created',
'Group ID': 'Group ID',
'Group uniquely assigned to user %(id)s': 'Group uniquely assigned to user %(id)s',
'Hello World': 'Olá Mundo',
'Import/Export': 'Importar/Exportar',
'Index': 'Index',
'Informações sobre ': 'Informações sobre ',
'Internal State': 'Estado Interno',
'Invalid Query': 'Consulta Inválida',
'Invalid password': 'Senha inválida',
'Início': 'Início',
'Layout': 'Layout',
'Lembrar-me (por 30 dias)': 'Lembrar-me (por 30 dias)',
'Logado': 'Logado',
'Login': 'Autentique-se',
'Login inválido': 'Login inválido',
'Lost Password': 'Esqueceu sua senha?',
'Main Menu': 'Main Menu',
'Mais informações sobre ': 'Mais informações sobre ',
'Marque para excluir': 'Marque para excluir',
'Marque para excluir:': 'Marque para excluir:',
'Menu Model': 'Menu Model',
'Média': 'Média',
'Média de': 'Média de',
'Média de ': 'Média de ',
'Média em': 'Média em',
'Média em ': 'Média em ',
'Name': 'Nome',
'New Record': 'Novo Registro',
'New password': 'Nova senha',
'No databases in this application': 'Sem bancos de dados nesta aplicação',
'Not authorized': 'Not authorized',
'Não foi possível enviar o e-mail': 'Não foi possível enviar o e-mail',
'O e-mail deve ser @inf.ufrgs.br': 'O e-mail deve ser @inf.ufrgs.br',
'Old password': 'Senha antiga',
'Origin': 'Origin',
'Os campos de senha não conferem': 'Os campos de senha não conferem',
'Pesquisar': 'Pesquisar',
'Por favor, preencha a sua resposta': 'Por favor, preencha a sua resposta',
'Powered by': 'Powered by',
'Professor': 'Professor',
'Professores': 'Professores',
'Professores que ministram ': 'Professores que ministram ',
'Professores que ministram essa disciplina': 'Professores que ministram essa disciplina',
'Profile': 'Profile',
'Profile updated': 'Profile updated',
'Qualificar negativamente': 'Qualificar negativamente',
'Qualificar positivamente': 'Qualificar positivamente',
'Query:': 'Consulta:',
'Record ID': 'Record ID',
'Redefinição de senha inválida': 'Redefinição de senha inválida',
'Register': 'Registre-se',
'Request reset password': 'Solicitar redefinição de senha',
'Reset password': 'Reset password',
'Resposta excluída com sucesso': 'Resposta excluída com sucesso',
'Resposta postada com sucesso': 'Resposta postada com sucesso',
'Role': 'Role',
'Rows in table': 'Linhas na tabela',
'Rows selected': 'Linhas selecionadas',
'Stylesheet': 'Stylesheet',
'Sure you want to delete this object?': 'Está certo(a) que deseja apagar esse objeto ?',
'Table name': 'Table name',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Uma "consulta" é uma condição como "db.tabela1.campo1==\'valor\'". Expressões como "db.tabela1.campo1==db.tabela2.campo2" resultam em um JOIN SQL.',
'The output of the file is a dictionary that was rendered by the view': 'The output of the file is a dictionary that was rendered by the view',
'This is a copy of the scaffolding application': 'This is a copy of the scaffolding application',
'Timestamp': 'Timestamp',
'Update:': 'Atualizar:',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir consultas mais complexas.',
'User %(id)s Logged-in': 'User %(id)s Logged-in',
'User %(id)s Logged-out': 'User %(id)s Logged-out',
'User %(id)s Password changed': 'User %(id)s Password changed',
'User %(id)s Password reset': 'User %(id)s Password reset',
'User %(id)s Profile updated': 'User %(id)s Profile updated',
'User %(id)s Registered': 'User %(id)s Registered',
'User %(id)s Verification email sent': 'User %(id)s Verification email sent',
'User ID': 'User ID',
'Ver professores que ministram essa disciplina': 'Ver professores que ministram essa disciplina',
'View': 'View',
'Você não pode editar uma avaliação respondida': 'Você não pode editar uma avaliação respondida',
'Você não pode excluir uma avaliação respondida': 'Você não pode excluir uma avaliação respondida',
'Welcome': 'Bem-vindo',
'Welcome %s': 'Bem-vindo, %s',
'Welcome to web2py': 'Bem vindo ao web2py',
'Which called the function': 'Which called the function',
'You are successfully running web2py': 'You are successfully running web2py',
'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs',
'You visited the url': 'You visited the url',
'anterior': 'anterior',
'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel',
'baixar em PDF': 'baixar em PDF',
'cache': 'cache',
'change password': 'alterar senha',
'click here for online examples': 'clique aqui para ver alguns exemplos',
'click here for the administrative interface': 'clique aqui para acessar a interface administrativa',
'customize me!': 'Personalize-me!',
'data uploaded': 'dados enviados',
'database': 'banco de dados',
'database %s select': 'Selecionar banco de dados %s',
'db': 'db',
'design': 'design',
'digite sua senha novamente': 'digite sua senha novamente',
'documentation': 'documentação',
'done!': 'concluído!',
'edit profile': 'editar perfil',
'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g',
'export as csv file': 'exportar como um arquivo csv',
'insert new': 'inserir novo',
'insert new %s': 'inserir novo %s',
'invalid request': 'requisição inválida',
'located in the file': 'located in the file',
'login': 'entrar',
'logout': 'sair',
'lost password?': 'esqueceu a senha?',
'new record inserted': 'novo registro inserido',
'next 100 rows': 'próximas 100 linhas',
'or import from csv file': 'ou importar de um arquivo csv',
'password': 'senha',
'previous 100 rows': '100 linhas anteriores',
'profile': 'perfil',
'próxima': 'próxima',
'próxima página>': 'próxima página>',
'próxima>': 'próxima>',
'record': 'registro',
'record does not exist': 'registro não existe',
'record id': 'id do registro',
'register': 'registrar',
'selected': 'selecionado',
'sem comentário': 'sem comentário',
'state': 'estado',
'table': 'tabela',
'teste': 'teste',
'unable to parse csv file': 'não foi possível analisar arquivo csv',
}
|
def sum(a, b):
"""Returns sum
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
sum -- Sum
"""
return a + b
def difference(a, b):
"""Returns difference
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
diff -- Difference
"""
return a - b
def product(a, b):
"""Returns product
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
product -- Product
"""
return a * b
def quotient(a, b):
"""Returns quotient
Arguments:
a {float} -- Input 1
b {float} -- Input 2
Returns:
quotient -- Quotient
"""
if (b == 0):
return 0
return a / b
def modulus(a, b):
"""Returns modulus
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
mod -- Modulus
"""
if (b == 0):
return 0
return a % b
def getInputs():
"""Accepts user inputs and returns them
Returns:
tuple -- set of inputs
"""
return int(input("Enter X: ")), int(input("Enter Y: "))
if __name__ == "__main__":
x, y = getInputs()
for i in range(5):
if (i == 0):
print(f"\nSum: {sum(x, y)}")
elif (i == 1):
print(f"Difference: {difference(x, y)}")
elif (i == 2):
print(f"Product: {product(x, y)}")
elif (i == 3):
print(f"Quotient: {quotient(float(x), float(y))}")
elif (i == 4):
print(f"Modulus: {modulus(x, y)}")
print("\nExiting...\n")
|
class UnionFind:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(n + 2)]
def find(self, a):
path = []
while self.parent[a] != a:
path.append(a)
a = self.parent[a]
for p in path:
self.parent[p] = a
return a
def union(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a != root_b:
self.parent[root_b] = root_a
class Solution:
"""
@param L: the length
@param W: the width
@param p: the obstacle coordinates
@return: yes or no
"""
def drivingProblem(self, L, W, p):
'''
0 1 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
是否可以从路的一侧通过不断连接路障到达路的另一侧, 并且每个连接的距离都小于车的直径+路障的直径 (在连接路沿和路障时, 距离limit为车的直径和路障的半径
'''
n = len(p)
union = UnionFind(n)
for i in range(n):
for j in range(i + 1, n):
dx = abs(p[i][0] - p[j][0])
dy = abs(p[i][1] - p[j][1])
if dx + dy <= 6:
union.union(i, j)
# edge
if p[i][1] <= 5:
union.union(i, n)
if W - p[i][1] <= 5:
union.union(i, n + 1)
return "no" if union.find(n) == union.find(n + 1) else "yes"
|
class Produto:
def __init__(self, codigo, descricao, valorUni):
self.codigo = codigo
self.descricao = descricao
self.valorUni = valorUni
class NotaFiscal:
def __init__(self, nroNF, nomeCliente, itensNF):
self.nroNF = nroNF
self.nomeCliente = nomeCliente
self.itensNF = itensNF
class CompraParcialmenteRealizada(Exception):
pass
class CompraInvalida(Exception):
pass
if __name__ == '__main__':
calça = Produto(101, 'calça', 150)
meia = Produto(102, 'meia', 10)
tenis = Produto(103, 'tenis', 500)
colar = Produto(104, 'colar', 100)
pulseira = Produto(105, 'pulseira', 100)
brinco = Produto(106, 'brinco', 50)
listaProdutos = [calça.descricao, meia.descricao, tenis.descricao, colar.descricao, pulseira.descricao, brinco.descricao]
estoque = {calça.descricao:5, meia.descricao:10, tenis.descricao:3, colar.descricao:10, pulseira.descricao:6, brinco.descricao:2}
compra1 = {calça.descricao:2, meia.descricao:3, tenis.descricao:3, colar.descricao:2, pulseira.descricao:1, brinco.descricao:0}
novoEstoque = {calça.descricao: estoque[calça.descricao] - compra1[calça.descricao],meia.descricao: estoque[meia.descricao] - compra1[meia.descricao], tenis.descricao:estoque[tenis.descricao] - compra1[tenis.descricao], colar.descricao:estoque[colar.descricao] - compra1[colar.descricao], pulseira.descricao:estoque[pulseira.descricao] - compra1[pulseira.descricao], brinco.descricao:estoque[brinco.descricao] - compra1[brinco.descricao]}
valorFinal = (compra1[calça.descricao] * calça.valorUni) + (compra1[meia.descricao] * meia.valorUni) + (compra1[tenis.descricao] * tenis.valorUni) + (compra1[colar.descricao] * colar.valorUni) + (compra1[pulseira.descricao] * pulseira.valorUni) + (compra1[brinco.descricao] * brinco.valorUni)
cliente1 = NotaFiscal(1, 'Gustavo', compra1)
print(f'Estoque inicial: {estoque}')
print(f'Carrinho de compras: {compra1}')
print(f'Estoque pós compras: {novoEstoque}')
print('======================================')
print(f'Número da nota:{cliente1.nroNF}\nNome do Cliente: {cliente1.nomeCliente}, Produto: {calça.descricao} - {calça.valorUni} reais - {compra1[calça.descricao]} vendidos')
print(f'Produto: {meia.descricao} - {meia.valorUni} reais - {compra1[meia.descricao]} vendidos')
print(f'Produto: {tenis.descricao} - {tenis.valorUni} reais - {compra1[tenis.descricao]} vendidos')
print(f'Produto: {colar.descricao} - {colar.valorUni} reais - {compra1[colar.descricao]} vendidos')
print(f'Produto: {pulseira.descricao} - {pulseira.valorUni} reais - {compra1[pulseira.descricao]} vendidos')
print(f'Produto: {brinco.descricao} - {brinco.valorUni} reais - {compra1[brinco.descricao]} vendidos')
print(f'VALOR DA COMPRA : {valorFinal}')
print('==========================================')
try:
if compra1[calça.descricao] < estoque[calça.descricao] and compra1[meia.descricao] < estoque[meia.descricao] and compra1[tenis.descricao] < estoque[tenis.descricao]and compra1[colar.descricao] < estoque[colar.descricao]and compra1[pulseira.descricao] < estoque[pulseira.descricao] and compra1[brinco.descricao] < estoque[brinco.descricao]:
raise CompraParcialmenteRealizada()
if compra1[calça.descricao] > estoque[calça.descricao] and compra1[meia.descricao] > estoque[meia.descricao] and compra1[tenis.descricao] > estoque[tenis.descricao]and compra1[colar.descricao] > estoque[colar.descricao]and compra1[pulseira.descricao] > estoque[pulseira.descricao] and compra1[brinco.descricao] > estoque[brinco.descricao]:
raise CompraInvalida()
except CompraParcialmenteRealizada:
print('Nota Fiscal parcialmente criada')
except CompraInvalida:
print('Nota fiscal não criada')
else:
print('Nota fiscal criada')
|
print(add(5, 3))
def add(x, y):
return x+y
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = []
dfs(root)
return nums[len(nums) - k]
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if self.k and root:
dfs(root.right)
self.k -= 1
if not self.k:
self.rtn = root.val
return
dfs(root.left)
self.k = k
dfs(root)
return self.rtn
|
print('----->DEAFIO 62<-----')
num = int(input('Digite o primeiro termo da PA: '))
rz = int(input('Qual a razão da PA: '))
cont = 0
while cont < 10:
num += rz
print(num)
cont += 1
mais = 1
while mais != 0:
mais = int(input('Deseja ver mais quantos termos: '))
while cont < 10 + mais:
num += rz
print(num)
cont += 1
cont = 10 |
class Solution:
# O(n) time | O(1) space - where n is the length of the input list
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
maxDuration, startTime, slowestKey = 0, 0, ''
for i in range(len(releaseTimes)):
pressTime = releaseTimes[i] - startTime
if pressTime > maxDuration:
maxDuration = pressTime
slowestKey = keysPressed[i]
elif pressTime == maxDuration and keysPressed[i] > slowestKey:
slowestKey = keysPressed[i]
startTime = releaseTimes[i]
return slowestKey
|
# -*- coding: utf-8 -*-
formatted_body_template = """<div id="vlivepy-post-html" style="width:728px;">
<p><a href="###LINK###">###LINK###</a></p>
<div style="padding:15px 0;border-bottom:1px solid #f2f2f2">
<span class="author" style="font-weight:600;color:#111;font-size:14px;display:block">###AUTHOR###</span>
<span class="createdAt" style="color:#777;font-size:12px">###TIME###</span>
</div>
<h2 class="title">###TITLE###</h2>
<div class="post_content">
###POST###
</div>
</div>"""
video_box_template = """<div style="position:relative;padding-top: 56.25%;background-color: #000;margin-bottom:10px">
<div style="position: absolute;top: 0;right: 0;bottom: 0;left: 0;z-index: 0;">
<div style="position:relative;z-index:1;height:100%;">
<div class="container" style="overflow:hidden;height:100%">###VIDEO###</div>
<div class="sizer"
style="position: absolute; inset: 0px; overflow: hidden; z-index: -1; visibility: hidden; opacity: 0;"></div>
</div>
</div>
</div>
""" |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"run_params": "000_exp_02_pretrained.ipynb",
"experiment": "000_exp_02_pretrained.ipynb",
"DatasetBuilder": "01_dataset_builder.ipynb",
"StatementClassifier": "02_statement_classifer.ipynb",
"Experiment": "03_experiment.ipynb",
"RunParams": "04_run_parameters.ipynb",
"BasicModel": "05_basic_model.ipynb",
"DataManager": "06_data_manager.ipynb",
"WikiDatabase": "08_database_proxy.ipynb",
"properties": "09_properties.ipynb"}
modules = ["exp_01.py",
"dataset_builder.py",
"statement_classifier.py",
"experiment.py",
"run_params.py",
"basic_model.py",
"data_manager.py",
"database_proxy.py",
"properties.py"]
doc_url = "https://rmorain.github.io/kirby/"
git_url = "https://github.com/rmorain/kirby/tree/master/"
def custom_doc_links(name): return None
|
A, B = map(int, input().split())
S = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No')
|
def configure_tx_chains(txChains, streamNum, mcsIdx):
txChains = txChains.lower()
RATE_MCS_ANT_A_MSK = 0x04000
RATE_MCS_ANT_B_MSK = 0x08000
RATE_MCS_ANT_C_MSK = 0x10000
RATE_MCS_HT_MSK = 0x00100
mask = 0x0
usedAntNum = 0
if "a" in txChains:
mask |= RATE_MCS_ANT_A_MSK
usedAntNum += 1
if "b" in txChains:
mask |= RATE_MCS_ANT_B_MSK
usedAntNum += 1
if "c" in txChains:
mask |= RATE_MCS_ANT_C_MSK
usedAntNum += 1
mask |= RATE_MCS_HT_MSK
if streamNum > usedAntNum:
print("Cannot use {} streams with {} antennas".format(streamNum, usedAntNum))
print("Set stream num to {}".format(usedAntNum))
streamNum = usedAntNum
mcsMask = mcsIdx
if streamNum == 2:
mcsMask += 8
elif streamNum == 3:
mcsMask += 16
mask |= mcsMask
mask = "0x{:05x}".format(mask)
print("Set TX mask: ", mask)
filePath = "/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/monitor_tx_rate"
f = open(filePath, 'w')
f.write(mask)
f.close()
def configure_rx_chains(rxChains):
rxChains = rxChains.lower()
mask = 0x0
aMask = 0x1
bMask = 0x2
cMask = 0x4
if "a" in rxChains:
mask |= aMask
if "b" in rxChains:
mask |= bMask
if "c" in rxChains:
mask |= cMask
mask = "0x{:01x}".format(mask)
print("Set RX chain mask: ", mask)
filePath = "/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/rx_chains_msk"
f = open(filePath, 'w')
f.write(mask)
f.close() |
# 19. Remove Nth Node From End of List
# Time: O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = head
fast = head
for i in range(n):
fast = fast.next
while fast:
prev = slow
slow = slow.next
fast = fast.next
if slow==head:
head = head.next
else:
prev.next = slow.next
return head
|
"""
A particular zoo determines the price of admission based on the age of the guest.
Guests 2 years of age and less are admitted without charge.
Children between 3 and 12 years of age cost $14.00.
Seniors aged 65 years and over cost $18.00.
Admission for all other guests is $23.00.
Create a program that
begins by reading the ages of all of the guests in a group from the user,
with one age entered on each line.
The user will enter a blank line to indicate that there are no more guests in the group.
Then your program should display the admission cost for the group with an appropriate message.
The cost should be displayed using two decimal places.
"""
# START Definition of FUNCTION
def valutaEntry(numero):
if numero.isdigit():
if 0 < int(numero) <= 120:
return True
return False
def computesAdmissionPrice(age):
age = int(age)
if age <= 2:
admissionPrice = 0 # no charge
elif 3 <= age <= 14:
admissionPrice = 14.00 # $14.00
elif 15 <= age <= 64:
admissionPrice = 23.00 # $23.00
else: # equal and over 65 years
admissionPrice = 18.00 # $18.00
return admissionPrice
# END Definition of FUNCTION
# Declaration of VARIABLES
groupCost = 0
# Acquisition and Control of the DATA entered by the USER
age = input("Enter the AGE of the GUEST: ")
ageValidated = valutaEntry(age)
while not(ageValidated):
print("Incorrect entry. Try again.")
age = input("Enter the AGE of the GUEST: ")
ageValidated = valutaEntry(age)
while age != "":
if ageValidated:
admissionPrice = computesAdmissionPrice(age) # ADMISSION PRICE computing
groupCost += admissionPrice # ADMISSION PRICE for the GROUP
age = input("Enter the AGE of the GUEST (or EMPTY line to QUIT): ")
ageValidated = valutaEntry(age)
else:
print("Incorrect entry. Try again.")
age = input("Enter the AGE of the GUEST (or EMPTY line to QUIT): ")
ageValidated = valutaEntry(age)
# Displaying the RESULT
print("The TOTAL ADMISSION PRICE to the ZOO for the GROUP is $ %.2f" % groupCost)
|
# Cloud Automation Services SDK for Python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class Region(object):
"""
Class for Region methods.
Used to discover regions for all fabric constructs (images, mappings,
networks and storage.)
"""
def __init__(self,
region
):
self.external_region_id = region['externalRegionId']
self.id = region['id']
self.updated_at = region['updatedAt']
self._links = region['_links']
@staticmethod
def list(session):
uri = f'/iaas/api/regions'
j = session._request(f'{session.baseurl}{uri}')
return j['content']
@classmethod
def describe(cls, session, id):
uri = f'/iaas/api/regions/{id}'
return cls(session._request(f'{session.baseurl}{uri}'))
def describe_by_name(self, session, name):
uri = f'/iaas/api/regions/?$filter=(externalRegionId eq \'{name}\')'
j = session._request(f'{session.baseurl}{uri}')
return j
|
'''
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Example 4:
Input: arr = [5]
Output: -1
Example 5:
Input: arr = [7,7,7,7,7,7,7]
Output: 7
Constraints:
1 <= arr.length <= 500
1 <= arr[i] <= 500
'''
class Solution:
def findLucky(self, arr):
counts = {}
for n in arr:
if n in counts:
counts[n] += 1
else:
counts[n] = 1
max_lucky_num = -1
for n, count in counts.items():
if n == count:
max_lucky_num = max(max_lucky_num, n)
return max_lucky_num
'''
OTHER SLOW SOLUTION
class Solution:
def findLucky(self, arr):
max_lucky_num = -1
for n in arr:
if n == arr.count(n):
max_lucky_num = max(max_lucky_num, n)
return max_lucky_num
'''
|
'''
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
leftMin = self.minDepth(root.left)
rightMin = self.minDepth(root.right)
finalMin = min(leftMin, rightMin) if leftMin and rightMin else leftMin or rightMin
return finalMin + 1
|
#string.py
str1 = "Hello"
str2 = 'John'
print(type(str1))
print("\"Good\\Job\"")
greet = "Hello John"
print(greet[1])
print(greet[-4])
print(greet[0:3])
print("bad" + "apple")
print("wt" + "d" * 5)
print(len("pine"))
print(type(str(123))) |
class DimensionError(Exception):
"""Represents an error involving matrix dimensions."""
class CoefficientError(Exception):
"""Represents an error involving transfer function coefficients."""
class StateSpaceError(Exception):
"""Represents a miscellaneous error involving `StateSpace`."""
class ResultError(Exception):
"""Represents an error involving the result of some calculation."""
|
#!/usr/bin/env python
NAME = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie(r'^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
# Now going for attack phase
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
if all(i in page for i in (b'Current session has been terminated', b'do not hesitate to contact us',
b'Access denied (403)')):
return True
return False
|
"""
Enumerated data types useful for data conversion
Created: 15 May 2018
Eva Berlot & Naveed Ejaz
"""
class BidsTags:
tSubj = 'sub-'
tSes = 'ses-'
tSesID = 'ses-id'
tParticipantID = 'participants-id'
tFunc = 'func'
tFuncEvents = 'task-{}_events'
tFuncRun = 'task-{}_run-{}_bold'
tAnat = 'anat'
tDWI = 'dwi'
tMask = 'masks'
tBehRaw = 'behavior-raw'
tSurface = 'surface'
tMovPar = 'movement-param'
tMVC = 'MVC'
tFuncPrep = 'func-preprocess'
fParticipantID = 'participants.tsv'
def __init__(self):
""" purposely left empty """ |
#
# PySNMP MIB module TIME-AGGREGATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIME-AGGREGATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:20 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, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection")
OwnerString, = mibBuilder.importSymbols("RMON-MIB", "OwnerString")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
MibIdentifier, Integer32, IpAddress, Unsigned32, Bits, Opaque, ObjectIdentity, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, experimental, TimeTicks, NotificationType, Counter64, ModuleIdentity, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Integer32", "IpAddress", "Unsigned32", "Bits", "Opaque", "ObjectIdentity", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "experimental", "TimeTicks", "NotificationType", "Counter64", "ModuleIdentity", "iso", "Counter32")
RowStatus, StorageType, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TextualConvention", "DisplayString")
tAggrMIB = ModuleIdentity((1, 3, 6, 1, 3, 124))
tAggrMIB.setRevisions(('2006-04-27 00:00',))
if mibBuilder.loadTexts: tAggrMIB.setLastUpdated('200604270000Z')
if mibBuilder.loadTexts: tAggrMIB.setOrganization('Cyber Solutions Inc. NetMan Working Group')
class TAggrMOErrorStatus(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
class TimeAggrMOValue(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
class CompressedTimeAggrMOValue(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
tAggrCtlTable = MibTable((1, 3, 6, 1, 3, 124, 1), )
if mibBuilder.loadTexts: tAggrCtlTable.setStatus('current')
tAggrCtlEntry = MibTableRow((1, 3, 6, 1, 3, 124, 1, 1), ).setIndexNames((0, "TIME-AGGREGATE-MIB", "tAggrCtlEntryID"))
if mibBuilder.loadTexts: tAggrCtlEntry.setStatus('current')
tAggrCtlEntryID = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: tAggrCtlEntryID.setStatus('current')
tAggrCtlMOInstance = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlMOInstance.setStatus('current')
tAggrCtlAgMODescr = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlAgMODescr.setStatus('current')
tAggrCtlInterval = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 4), Integer32()).setUnits('micro seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlInterval.setStatus('current')
tAggrCtlSamples = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 5), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlSamples.setStatus('current')
tAggrCtlCompressionAlgorithm = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("deflate", 2))).clone('none')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlCompressionAlgorithm.setStatus('current')
tAggrCtlEntryOwner = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 7), OwnerString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryOwner.setStatus('current')
tAggrCtlEntryStorageType = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 8), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryStorageType.setStatus('current')
tAggrCtlEntryStatus = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 9), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryStatus.setStatus('current')
tAggrDataTable = MibTable((1, 3, 6, 1, 3, 124, 2), )
if mibBuilder.loadTexts: tAggrDataTable.setStatus('current')
tAggrDataEntry = MibTableRow((1, 3, 6, 1, 3, 124, 2, 1), ).setIndexNames((0, "TIME-AGGREGATE-MIB", "tAggrCtlEntryID"))
if mibBuilder.loadTexts: tAggrDataEntry.setStatus('current')
tAggrDataRecord = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 1), TimeAggrMOValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataRecord.setStatus('current')
tAggrDataRecordCompressed = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 2), CompressedTimeAggrMOValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataRecordCompressed.setStatus('current')
tAggrDataErrorRecord = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 3), TAggrMOErrorStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataErrorRecord.setStatus('current')
tAggrConformance = MibIdentifier((1, 3, 6, 1, 3, 124, 3))
tAggrGroups = MibIdentifier((1, 3, 6, 1, 3, 124, 3, 1))
tAggrCompliances = MibIdentifier((1, 3, 6, 1, 3, 124, 3, 2))
tAggrMibCompliance = ModuleCompliance((1, 3, 6, 1, 3, 124, 3, 2, 1)).setObjects(("TIME-AGGREGATE-MIB", "tAggrMibBasicGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tAggrMibCompliance = tAggrMibCompliance.setStatus('current')
tAggrMibBasicGroup = ObjectGroup((1, 3, 6, 1, 3, 124, 3, 1, 1)).setObjects(("TIME-AGGREGATE-MIB", "tAggrCtlMOInstance"), ("TIME-AGGREGATE-MIB", "tAggrCtlAgMODescr"), ("TIME-AGGREGATE-MIB", "tAggrCtlInterval"), ("TIME-AGGREGATE-MIB", "tAggrCtlSamples"), ("TIME-AGGREGATE-MIB", "tAggrCtlCompressionAlgorithm"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryOwner"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryStorageType"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryStatus"), ("TIME-AGGREGATE-MIB", "tAggrDataRecord"), ("TIME-AGGREGATE-MIB", "tAggrDataRecordCompressed"), ("TIME-AGGREGATE-MIB", "tAggrDataErrorRecord"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tAggrMibBasicGroup = tAggrMibBasicGroup.setStatus('current')
mibBuilder.exportSymbols("TIME-AGGREGATE-MIB", tAggrCtlInterval=tAggrCtlInterval, tAggrDataEntry=tAggrDataEntry, tAggrDataTable=tAggrDataTable, tAggrCtlTable=tAggrCtlTable, tAggrGroups=tAggrGroups, tAggrDataErrorRecord=tAggrDataErrorRecord, tAggrCompliances=tAggrCompliances, tAggrCtlEntry=tAggrCtlEntry, tAggrConformance=tAggrConformance, tAggrCtlEntryOwner=tAggrCtlEntryOwner, tAggrCtlAgMODescr=tAggrCtlAgMODescr, tAggrCtlEntryStorageType=tAggrCtlEntryStorageType, tAggrCtlSamples=tAggrCtlSamples, tAggrCtlEntryStatus=tAggrCtlEntryStatus, tAggrMibBasicGroup=tAggrMibBasicGroup, tAggrMibCompliance=tAggrMibCompliance, TimeAggrMOValue=TimeAggrMOValue, tAggrMIB=tAggrMIB, PYSNMP_MODULE_ID=tAggrMIB, tAggrCtlEntryID=tAggrCtlEntryID, tAggrDataRecord=tAggrDataRecord, tAggrDataRecordCompressed=tAggrDataRecordCompressed, tAggrCtlCompressionAlgorithm=tAggrCtlCompressionAlgorithm, CompressedTimeAggrMOValue=CompressedTimeAggrMOValue, tAggrCtlMOInstance=tAggrCtlMOInstance, TAggrMOErrorStatus=TAggrMOErrorStatus)
|
class ExtendedTextAttributes(object):
def __init__(
self,
text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info
):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = description
self._title = title
self._jpeg_thumbnail = jpeg_thumbnail
self._context_info = context_info
def __str__(self):
attrs = []
if self.text is not None:
attrs.append(("text", self.text))
if self.matched_text is not None:
attrs.append(("matched_text", self.matched_text))
if self.canonical_url is not None:
attrs.append(("canonical_url", self.canonical_url))
if self.description is not None:
attrs.append(("description", self.description))
if self.title is not None:
attrs.append(("title", self.title))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[binary data]"))
if self.context_info is not None:
attrs.append(("context_info", self.context_info))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
@property
def matched_text(self):
return self._matched_text
@matched_text.setter
def matched_text(self, value):
self._matched_text = value
@property
def canonical_url(self):
return self._canonical_url
@canonical_url.setter
def canonical_url(self, value):
self._canonical_url = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
self._context_info = value
|
#!/usr/bin/env python3
"""
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?
https://projecteuler.net/problem=5
"""
|
soma = 0
cont = 0
for impar in range(1,501,2):
if impar % 3 == 0:
cont = cont + 1
soma = soma + impar
print('\33[35mA soma de todos os {} valores solicitados é {}.'.format(cont,soma))
|
_V = {}
# Stages: game, rounds
# State: probability, probability of co-operating
# Action:
# V(t,p) gives maximum expected value from starting game t with probability p of cooperating
def V(game, probability):
if game is 10:
return 0, 0
else:
if (game, probability) not in _V:
cooperate = probability * (3 + V(game + 1, min(1, probability + 0.1))[0]) + \
(1 - probability) * (0 + V(game + 1, min(1, probability + 0.1))[0])
defect = probability * (5 + V(game + 1, max(0, probability - 0.2))[0]) + \
(1 - probability) * (1 + V(game + 1, max(0, probability - 0.2))[0])
_V[game, probability] = max((cooperate, 'Co-operate'), (defect, 'Defect'))
return _V[game, probability]
print('---------------------------')
prob = 0.6
# Transitions are deterministic so we can generate sequence of actions
for games in range(10):
payoff, decision = V(games, prob)
print('|Round', games + 1, '\t|\t', decision)
prob = min(1, prob + 0.1) if decision == 'Co-operate' else max(0, prob - 0.2)
|
help = """
Your project has been created!
If you have not done so already, create a conda environment for your new
project with:
cd {{cookiecutter.repo_name}}
conda create --name {{cookiecutter.repo_name}} python=3.x
conda activate {{cookiecutter.repo_name}}
conda env export > environment.yml
Install your new project in your local conda environment with:
pip install -e .
Don't forget to sync to GitHub. Have fun!
"""
print(help)
|
# -*- coding: utf-8 -*-
# Este programa usa um loop que itera por todos os valores de 1 a N e checa se o valor não está na lista de números,
# caso o valor não esteja ele é exibido.
# Input do N
n = int(input())
# Input da lista de números que representam as peças
v = list(map(int, input().split()))
# Loop para os valores a serem checados (1 a N)
for i in range(1, n + 1):
# Caso a lista não contenha o valor i
if i not in v:
# Exibe o valor i
print(i) |
PROPER_NOUNS = {
"Αγγ",
"Ἀθῆναι",
"Αἴγυπτος",
"Ἀλέξιον",
"Ἀλέξιος",
"Ἀλεξίου",
"Ἀντιοχεία",
"Ἀντιοχείᾳ",
"Ἀντιόχεια",
"Ἀντιόχειαν",
"Ἀντιοχείας",
"Ἀραβία",
"Ἀραβίᾳ",
"Ἀσία",
"Ἀσίᾳ",
"Ἀτλαντικόν",
"Ἀφρικῇ",
"Βρεταννία",
"Βρεττανία",
"Γαλλία",
"Γαλλίᾳ",
"Γερμανία",
"Γερμανίᾳ",
"Γηργόριος",
"Γηργόριους",
"Γρη",
"Γρηγόριον",
"Γρηγόριος",
"Γρηγορίου",
"Γρηγόριου",
"Γρηγορίῳ",
"Γρηγρορίου",
"Γρηρόριος",
"Δῆλος",
"Δημήρτιος",
"Δημήτριε",
"Δημήτριον",
"Δημήτριος",
"Δημητρίου",
"Δικαιόπολις",
"Εἰρήνη",
"Εἰρήνης",
"Ἑλλάδι",
"Ἑλλάς",
"Ἑλληνικά",
"Ἑλληνικαί",
"Ἑλληνική",
"Ἑλληνικοί",
"Ἑλληνικόν",
"Ἑλληνικός",
"Εὔβοια",
"Εὐγενία",
"Εὐγενίᾳ",
"Εὐγενίαν",
"Εὐγενίας",
"Εὐρώπῃ",
"Ζεύς",
"Ἡρακλείδης",
"Θύμβρις",
"Ἱεροσόλυμα",
"Ἰησοῦς",
"Ἱσπανία",
"Ἴστρος",
"Ἰταλία",
"Ἰταλίᾳ",
"Κεφαλαῖον",
"Κεφάλαιον",
"Κίλισσα",
"Κιλίσσης",
"Κρήτη",
"Κωνσταντινούπολις",
"Λέσβος",
"Λῆμνος",
"Μακ",
"Μακάριον",
"Μακάριος",
"Μακαρίῳ",
"Μαρ",
"Μάρκος",
"Νάξος",
"Νεῖλος",
"Ξαν",
"Ξανθία",
"Ξανθίᾳ",
"Ξανθίας",
"Ὀρόντες",
"Ὀρόντης",
"Πιερίᾳ",
"Ῥαβέννα",
"Ῥῆνος",
"Ῥόδος",
"Ῥωμαϊκά",
"Ῥωμαϊκαί",
"Ῥωμαϊκή",
"Ῥωμαϊκῇ",
"Ῥωμαϊκόν",
"Ῥωμαϊκός",
"Ῥώμη",
"Ῥώμην",
"Σάμος",
"Σελεύκεια",
"Σελεύκειαν",
"Σελεύκιαν",
"Σελευκίας",
"Σικελία",
"Σοσίαν",
"Σοφία",
"Σοφίας",
"Σπαρτή",
"Σπάρτη",
"Σύρα",
"Συρία",
"Συρίᾳ",
"Συριακαί",
"Συριακή",
"Συριακός",
"Συρίας",
"Σως",
"Σωσία",
"Σωσίαν",
"Σωσίας",
"Σωσίου",
"Σωφία",
"Σωφίαν",
"Τρο",
"Τροχίλε",
"Τροχίλον",
"Τροχίλος",
"Χίος",
"Χριστιανῶν",
"Χριστός",
"Χριστοῦ",
}
SPECIAL_CASES = {
"πο-",
"-τα-",
"-μος",
"Α",
"Β",
"Γ",
"Δ",
"Αγγ",
"Γρη",
"Μακ",
"Μαρ",
"Ξαν",
"Σως",
"Τρο",
# "#",
# "ἀλλα",
# "δε",
# "καἰ",
# "στ",
}
|
BASE_DIR = './'
environ = {
'KPK_DATA': '/home/kpk/data',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
}
KPK_DATA = environ.get('KPK_DATA')
# print(KPK_DATA)
# _KPK_DATA = environ['KPK_DATA']
# print(_KPK_DATA)
# os.environ.get('KPK_DATA') or BASE_DIR
#
# os.environ.get('KPK_DATA') if os.environ.get('KPK_DATA') else BASE_DIR
# ROOT = os.environ.get('KPK_DATA') if os.environ.get('KPK_DATA') else BASE_DIR
pass
if KPK_DATA:
ROOT = KPK_DATA
else:
ROOT = BASE_DIR
print(ROOT)
pass
ROOT = KPK_DATA if KPK_DATA else BASE_DIR
print(ROOT)
pass
ROOT = KPK_DATA or BASE_DIR
print(ROOT)
|
class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified
|
NONE = 0x000000000
# Posting Permissions
CREATE_POST = 0x000000001
EDIT_POST = 0x000000002
DELETE_POST = 0x000000004
# Documents Permissions
UPLOAD_DOCUMENT = 0x000000008
EDIT_DOCUMENT = 0x000000010
DELETE_DOCUMENT = 0x000000020
# User Account Permissions
CREATE_USER = 0x000000040
EDIT_USER = 0x000000080
DELETE_USER = 0x000000100 |
class Car:
wheels = 4 # Class (Static) Variables before __init__
def __init__(self):
self.com = "BMW" # Instance Variables inside __init__
self.mil = "10"
c1 = Car()
c2 = Car()
Car.wheels = 5 # The value of all the wheels is now 5
# c1.wheels = 10 # For individual changes
# c2.wheels = 15
print(c1.com, c1.mil, c1.wheels) # print(c1.com, c1.mil, Car.wheels)
print(c2.com, c2.mil, c2.wheels) # print(c1.com, c1.mil, Car.wheels) |
"""
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
#n,m=map(int,input().split())
#n=int(input())
#a=list(map(int,input().split()[:n]))
#s=str(input())
#a,b=input().split()
n=int(input())
a=list(map(int,input().split()[:n]))
b=list(map(int,input().split()[:n]))
ans=1
for i in a:
for j in b:
if i^j in (a or b):
ans+=1
if ans%2==0:
print("Yes")
else:
print("No")
for _ in range(int(input())):
solve()
|
lista = []
valor = lista.append(int(input('Digite um valor: ')))
while True:
continuação = str(input('Quer continuar? [S/N] ')).strip()[0].upper()
if continuação in 'N':
break
elif continuação in 'S':
valor = lista.append(int(input('Digite um valor: ')))
else:
continuação1 = str(input('Opção inválida. Tente novamente com "SIM" ou "NÃO": ')).strip().upper()[0]
if continuação1 in 'S':
valor = lista.append(int(input('Digite um valor: ')))
print('=' * 30)
print(f'Você digitou {len(valor)} elementos.')
lista.sort(reverse=True)
print(f'Os valores em ordem decrescente são {lista}')
if 5 in lista:
print(f'O valor "5" faz parte da lista!')
else:
print(f'O valor "5" não faz parte da lista!')
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ThrottlingConfiguration(object):
"""Implementation of the 'ThrottlingConfiguration' model.
Specifies the throttling configuration parameters.
Attributes:
fixed_threshold (long|int): Fixed baseline threshold for throttling. This is
mandatory for any other throttling type than kNoThrottling.
pattern_type (int): Type of the throttling pattern.
"""
# Create a mapping from Model property names to API property names
_names = {
"fixed_threshold": 'fixedThreshold',
"pattern_type": 'patternType'
}
def __init__(self,
fixed_threshold=None,
pattern_type=None):
"""Constructor for the ThrottlingConfiguration class"""
# Initialize members of the class
self.fixed_threshold = fixed_threshold
self.pattern_type = pattern_type
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
fixed_threshold = dictionary.get('fixedThreshold', None)
pattern_type = dictionary.get('patternType', None)
# Return an object of this model
return cls(fixed_threshold,
pattern_type)
|
class Solution:
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
idx1, idx2 = len(words), len(words)
result = len(words)
for i in range(len(words)):
if words[i] == word1:
idx1 = i
result = min(result, abs(idx2 - idx1))
if words[i] == word2:
idx2 = i
result = min(result, abs(idx2 - idx1))
return result
|
class HParams(object):
def __init__(self,**default_param):
temp_local=self.__dict__
for key in default_param.keys():
temp_local[key]=default_param[key]
def create_hparams():
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = HParams(
total_iteration=150000,
source_feat_dim=80, #输入语音特征的维度
n_mel_channels=80, #输出mel谱的维度
################################
# Model Parameters #
################################
encoder_embedding_dim=-1, #必须等于prenet_dim,在下面赋值
# Encoder parameters
encoder_conf={
'attention_heads': 4,
'linear_units': 256,
'num_blocks': 6,
'positional_dropout_rate': 0.1,
'attention_dropout_rate': 0.1,
'input_layer': 'conv2d',
'positionwise_layer_type': 'linear',
'positionwise_conv_kernel_size': 3,
'rel_pos_type': 'latest',
'pos_enc_layer_type': 'rel_pos',
'selfattention_layer_type': 'rel_selfattn',
'activation_type': 'swish',
'zero_triu': False,
'cnn_module_kernel': 31,
'padding_idx': -1,
'concat_after': False,
'dropout_rate': 0.1,
'macaron_style': True,
'normalize_before': True,
'use_cnn_module': True,
"output_size": 512
},
# Decoder parameters
n_frames_per_step=1,
decoder_rnn_dim=512,
prenet_dim=512,
max_decoder_steps=200000,
p_attention_dropout=0.1,
p_decoder_dropout=0.1,
gate_threshold=0.5,
# Attention parameters
attention_rnn_dim=512,
attention_dim=128,
# Location Layer parameters
attention_location_n_filters=32,
attention_location_kernel_size=31,
# Mel-post processing network parameters
postnet_embedding_dim=512,
postnet_kernel_size=5,
postnet_n_convolutions=5,
################################
# Optimization Hyperparameters #
################################
use_saved_learning_rate=False,
learning_rate=1e-3,
weight_decay=1e-6,
grad_clip_thresh=1.0,
batchsize=32,
mask_padding=True # set model's padded outputs to padded values
)
hparams.encoder_embedding_dim=hparams.encoder_conf["output_size"]
return hparams
|
'''
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or change modulus 100)
Getting quarters of change (divide by 25 then convert to integer)
Getting the amount of change leftover (either change minus quarters times 25 or change modulus 25)
and so on.
Stress the use of comments to at least segment the project.
Stress the use of print statements to test regularly.
Stress the use of working it out on paper in detail to see the calculations that need to be made.
'''
#EXAMPLE SOLUTION:
#The following is not perfect but would benefit from some rounding.
bill=input("How many dollars is the bill for? ")
pay=input("How many dollars will you give the cashier? ")
change=float(pay)-float(bill)
dollars=int(change/1)
left=(change%1)
quarters=int(left/.25)
left=(left%.25)
dimes=int(left/.1)
left=left%.1
nickles=int(left%.05)
pennies=int(100*(left%.05))
left=left%.01
print("If you don't turn things into ints, you are in danger of getting this: "+str(left)+", instead of zero")
print("The bill is for $" + bill + ". You are giving the cashier $" + pay +". You will recieve $"+str(change) + " in the form of " + str(dollars) +" dollars, "+str(quarters)+" quarters, "+str(dimes)+" dimes, "+str(nickles)+" nickles and "+str(left)+" pennies. Thank you for your business")
|
class AzureCloudProviderResourceModel(object):
def __init__(self):
self.azure_application_id = '' # type: str
self.azure_mgmt_network_d = '' # type: str
self.azure_mgmt_nsg_id = '' # type: str
self.azure_application_key = '' # type: str
self.region = '' # type: str
self.vm_size = '' # type: str
self.keypairs_location = '' # type: str
self.networks_in_use = '' # type: str
self.azure_subscription_id = '' # type: str
self.azure_tenant = '' # type: str
self.storage_type = '' # type: str
self.management_group_name = '' # type: str
self.additional_mgmt_networks = '' # type: str
self.cloud_provider_name = '' # type: str
self.private_ip_allocation_method = '' # type: str
|
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. by Daniel Barrejon, UC3M. +
# All rights reserved. This file is part of the Shi-VAE, and is released under the +
# "MIT License Agreement". Please see the LICENSE file that should have been included +
# as part of this package. +
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class EarlyStopping(object):
"""
EarlyStopping scheme to finish training if model is not improving any more.
"""
def __init__(self, patience=15, min_delta=0.1):
"""
Args:
patience: (int) Patience value to stop training.
min_delta: (float) Minimum margin for improving.
"""
self.patience = patience
self.min_delta = min_delta
self.patience_cnt = 0
self.prev_loss_val = 2000000
self.patient_cum = 0
def stop(self, loss_val):
"""
Args:
loss_val: (int) Validation loss to compare and apply early stopping.
Returns:
boolean: True if stop, False if continue.
"""
if (abs(self.prev_loss_val - loss_val)> self.min_delta):
self.patience_cnt = 0
self.prev_loss_val = loss_val
else:
self.patience_cnt += 1
self.patient_cum += 1
print('Patience count: ', self.patience_cnt)
if (self.patience_cnt > self.patience or self.patient_cum > 80):
return True
else:
return False
|
# Criando um set com elementos:
# Utiliza-se de chaves, entretanto não é um dicionário, visto que não possui chave nem um índice, possuindo apenas valores.
Set1 = {1, 2, 3, 4, 5}
# Criando um set vazio
Set2 = set()
# Pode ser utilizado para remover elementos duplicados de uma lista, visto que só pode conter elementos únicos. EX:
lista1 = [1, 2, 1, 1, 3, 4, 5, 6, 6, 6, 6, 6, 7, 8, 9, 'Luiz', 'Luiz']
l1 = set(lista1)
# print(l1) # Saída: {1, 2, 3, 4, 5, 6, 7, 8, 9, 'Luiz'}
#####################################################################################################################
set1 = {1, 2, 3, 4, 5, 7}
set2 = {1, 2, 3, 4, 5, 6}
# ----------------------------------------------------------
# union ou | //unir sets
set3 = set1 | set2
# print(set3) # Saída: {1, 2, 3, 4, 5, 6, 7}
# ----------------------------------------------------------
# Intersection ou & //Coleta apenas os elementos que estão nos dois sets.
set4 = set1 & set2
# print(set4) # Saída: {1, 2, 3, 4, 5}
# ----------------------------------------------------------
# Difference ou - //Coleta os elementos do set da esquerda que não estão no set da direita.
set5 = set1 - set2
# print(set5) # Saída: {7}
# ----------------------------------------------------------
# Symmetric_difference ou ^ //Coleta elementos que estão nos dois sets mas não estão em ambos.
set6 = set1 ^ set2
# print(set6) # Saída: {6, 7}
|
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
r, s, t = -1, 0, 0
for i in range(0, len(gas)):
t = t + gas[i] - cost[i]
s = s + gas[i] - cost[i]
if s < 0:
r = -1
s = 0
else:
if r == -1:
r = i
if t < 0:
r = -1
return r
def test_can_complete_circuit():
s = Solution()
assert 3 == s.canCompleteCircuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])
assert -1 == s.canCompleteCircuit([2, 3, 4], [3, 4, 3])
assert 4 == s.canCompleteCircuit([5, 1, 2, 3, 4], [4, 4, 1, 5, 1])
|
# Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
# To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
# For example, inverting [1, 1, 0] results in [0, 0, 1].
# Example 1:
# Input: [
# [1,0,1],
# [1,1,1],
# [0,1,1]
# ]
# Output: [
# [0,1,0],
# [0,0,0],
# [0,0,1]
# ]
# Explanation: First reverse each row: [[1,0,1],[1,1,1],[1,1,0]]. Then, invert the image: [[0,1,0],[0,0,0],[0,0,1]]
def flip_invert_image(matrix):
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range((n + 1) // 2):
matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1] ^ 1, matrix[i][j] ^ 1
return matrix
print(flip_invert_image([
[1,0,1],
[1,1,1],
[0,1,1]
]))
print(flip_invert_image([
[1,1,0,0],
[1,0,0,1],
[0,1,1,1],
[1,0,1,0]
])) |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk_environment_name": "beanstalkEnvironmentName",
"block_devices_mode": "blockDevicesMode",
"capacity_unit": "capacityUnit",
"cluster_id": "clusterId",
"cluster_zone_name": "clusterZoneName",
"controller_id": "controllerId",
"cpu_credits": "cpuCredits",
"desired_capacity": "desiredCapacity",
"draining_timeout": "drainingTimeout",
"ebs_block_devices": "ebsBlockDevices",
"ebs_optimized": "ebsOptimized",
"elastic_ips": "elasticIps",
"elastic_load_balancers": "elasticLoadBalancers",
"enable_monitoring": "enableMonitoring",
"ephemeral_block_devices": "ephemeralBlockDevices",
"event_type": "eventType",
"fallback_to_ondemand": "fallbackToOndemand",
"health_check": "healthCheck",
"health_check_grace_period": "healthCheckGracePeriod",
"health_check_type": "healthCheckType",
"health_check_unhealthy_duration_before_replacement": "healthCheckUnhealthyDurationBeforeReplacement",
"iam_instance_profile": "iamInstanceProfile",
"image_id": "imageId",
"instance_types_customs": "instanceTypesCustoms",
"instance_types_ondemand": "instanceTypesOndemand",
"instance_types_preemptibles": "instanceTypesPreemptibles",
"instance_types_preferred_spots": "instanceTypesPreferredSpots",
"instance_types_spots": "instanceTypesSpots",
"instance_types_weights": "instanceTypesWeights",
"integration_codedeploy": "integrationCodedeploy",
"integration_docker_swarm": "integrationDockerSwarm",
"integration_ecs": "integrationEcs",
"integration_gitlab": "integrationGitlab",
"integration_kubernetes": "integrationKubernetes",
"integration_mesosphere": "integrationMesosphere",
"integration_multai_runtime": "integrationMultaiRuntime",
"integration_nomad": "integrationNomad",
"integration_rancher": "integrationRancher",
"integration_route53": "integrationRoute53",
"ip_forwarding": "ipForwarding",
"key_name": "keyName",
"lifetime_period": "lifetimePeriod",
"load_balancers": "loadBalancers",
"low_priority_sizes": "lowPrioritySizes",
"max_size": "maxSize",
"min_size": "minSize",
"multai_target_sets": "multaiTargetSets",
"network_interfaces": "networkInterfaces",
"node_image": "nodeImage",
"od_sizes": "odSizes",
"ondemand_count": "ondemandCount",
"persist_block_devices": "persistBlockDevices",
"persist_private_ip": "persistPrivateIp",
"persist_root_device": "persistRootDevice",
"placement_tenancy": "placementTenancy",
"preemptible_percentage": "preemptiblePercentage",
"preferred_availability_zones": "preferredAvailabilityZones",
"private_ips": "privateIps",
"resource_group_name": "resourceGroupName",
"resource_id": "resourceId",
"revert_to_spot": "revertToSpot",
"scaling_down_policies": "scalingDownPolicies",
"scaling_target_policies": "scalingTargetPolicies",
"scaling_up_policies": "scalingUpPolicies",
"scheduled_tasks": "scheduledTasks",
"security_groups": "securityGroups",
"service_account": "serviceAccount",
"shutdown_script": "shutdownScript",
"spot_percentage": "spotPercentage",
"startup_script": "startupScript",
"stateful_deallocation": "statefulDeallocation",
"subnet_ids": "subnetIds",
"target_group_arns": "targetGroupArns",
"update_policy": "updatePolicy",
"user_data": "userData",
"utilize_reserved_instances": "utilizeReservedInstances",
"wait_for_capacity": "waitForCapacity",
"wait_for_capacity_timeout": "waitForCapacityTimeout",
}
_CAMEL_TO_SNAKE_CASE_TABLE = {
"availabilityZones": "availability_zones",
"backendServices": "backend_services",
"beanstalkEnvironmentName": "beanstalk_environment_name",
"blockDevicesMode": "block_devices_mode",
"capacityUnit": "capacity_unit",
"clusterId": "cluster_id",
"clusterZoneName": "cluster_zone_name",
"controllerId": "controller_id",
"cpuCredits": "cpu_credits",
"desiredCapacity": "desired_capacity",
"drainingTimeout": "draining_timeout",
"ebsBlockDevices": "ebs_block_devices",
"ebsOptimized": "ebs_optimized",
"elasticIps": "elastic_ips",
"elasticLoadBalancers": "elastic_load_balancers",
"enableMonitoring": "enable_monitoring",
"ephemeralBlockDevices": "ephemeral_block_devices",
"eventType": "event_type",
"fallbackToOndemand": "fallback_to_ondemand",
"healthCheck": "health_check",
"healthCheckGracePeriod": "health_check_grace_period",
"healthCheckType": "health_check_type",
"healthCheckUnhealthyDurationBeforeReplacement": "health_check_unhealthy_duration_before_replacement",
"iamInstanceProfile": "iam_instance_profile",
"imageId": "image_id",
"instanceTypesCustoms": "instance_types_customs",
"instanceTypesOndemand": "instance_types_ondemand",
"instanceTypesPreemptibles": "instance_types_preemptibles",
"instanceTypesPreferredSpots": "instance_types_preferred_spots",
"instanceTypesSpots": "instance_types_spots",
"instanceTypesWeights": "instance_types_weights",
"integrationCodedeploy": "integration_codedeploy",
"integrationDockerSwarm": "integration_docker_swarm",
"integrationEcs": "integration_ecs",
"integrationGitlab": "integration_gitlab",
"integrationKubernetes": "integration_kubernetes",
"integrationMesosphere": "integration_mesosphere",
"integrationMultaiRuntime": "integration_multai_runtime",
"integrationNomad": "integration_nomad",
"integrationRancher": "integration_rancher",
"integrationRoute53": "integration_route53",
"ipForwarding": "ip_forwarding",
"keyName": "key_name",
"lifetimePeriod": "lifetime_period",
"loadBalancers": "load_balancers",
"lowPrioritySizes": "low_priority_sizes",
"maxSize": "max_size",
"minSize": "min_size",
"multaiTargetSets": "multai_target_sets",
"networkInterfaces": "network_interfaces",
"nodeImage": "node_image",
"odSizes": "od_sizes",
"ondemandCount": "ondemand_count",
"persistBlockDevices": "persist_block_devices",
"persistPrivateIp": "persist_private_ip",
"persistRootDevice": "persist_root_device",
"placementTenancy": "placement_tenancy",
"preemptiblePercentage": "preemptible_percentage",
"preferredAvailabilityZones": "preferred_availability_zones",
"privateIps": "private_ips",
"resourceGroupName": "resource_group_name",
"resourceId": "resource_id",
"revertToSpot": "revert_to_spot",
"scalingDownPolicies": "scaling_down_policies",
"scalingTargetPolicies": "scaling_target_policies",
"scalingUpPolicies": "scaling_up_policies",
"scheduledTasks": "scheduled_tasks",
"securityGroups": "security_groups",
"serviceAccount": "service_account",
"shutdownScript": "shutdown_script",
"spotPercentage": "spot_percentage",
"startupScript": "startup_script",
"statefulDeallocation": "stateful_deallocation",
"subnetIds": "subnet_ids",
"targetGroupArns": "target_group_arns",
"updatePolicy": "update_policy",
"userData": "user_data",
"utilizeReservedInstances": "utilize_reserved_instances",
"waitForCapacity": "wait_for_capacity",
"waitForCapacityTimeout": "wait_for_capacity_timeout",
}
|
# guess file size : https://softwareengineering.stackexchange.com/q/204417
# https://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
# def fsize(file_path):
# sizeof_fmt(self.size)
# if self.size > 1000000000:
# print('File is larger than 1 GB')
# else:
# print('File smaller than 1 GB')
|
# Source : https://leetcode.com/problems/rectangle-overlap/
# Author : foxfromworld
# Date : 07/04/2021
# Second attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or\
rec2[1] == rec2[3] or rec1[1] == rec1[3]:
return False
UpBound = min(rec1[3], rec2[3])
LoBound = max(rec1[1], rec2[1])
RtBound = min(rec1[2], rec2[2])
LtBound = max(rec1[0], rec2[0])
return True if UpBound > LoBound and RtBound > LtBound else False
# Date : 07/04/2021
# First attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec1[1] == rec1[3] or \
rec2[0] == rec2[2] or rec2[1] == rec2[3]:
return False # check if it's a line
return rec2[0] < rec1[2] and rec2[1] < rec1[3] and rec1[0] < rec2[2] and rec1[1] < rec2[3]
|
class Project():
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session():
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite, host, description, id_project):
self.id_session = id_session
self.index = index
self.dt_start = dt_start
self.dt_end = dt_end
self.is_active = is_active
self.is_favorite = is_favorite
self.host = host
self.description = description
self.id_project = id_project
class Epoch():
def __init__(self, id_epoch, index, metrics, time, id_session):
self.id_epoch = id_epoch
self.index = index
self.metrics = metrics
self.time = time
self.id_session = id_session |
#=======================================================================
# Author: Isai Damier
# Title: Selection Sort
# Project: geekviewpoint
# Package: algorithm.sorting
#
# Statement:
# Given a disordered list of integers (or any other items),
# rearrange the integers in natural order.
#
# Sample Input: [18,5,3,1,19,6,0,7,4,2,5]
# Sample Output: [0,1,2,3,4,5,5,6,7,18,19]
#
# Time Complexity of Solution:
# Best O(n^2); Average O(n^2); Worst O(n^2).
#
# Approach:
# Selection sort is a step up from insertion sort from a memory
# viewpoint. It only swaps elements that need to be swapped. In terms
# of time complexity, however, insertion sort is better.
#=======================================================================
def selectionsort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = 3
if a > 2:
print("H")
else:
print("L") |
"""
1720. Decode XORed Array
https://leetcode.com/problems/decode-xored-array/
There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1,
such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].
You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].
Return the original array arr. It can be proved that the answer exists and is unique.
Example:
Input: encoded = [1,2,3], first = 1
Output: [1,0,2,1]
Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
"""
# Runtime: 232ms
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
# The first element in the hidden array: first
arr = [first]
# Initialise a temp variable to keep track of each reverse XOR
temp = 0
for idx, val in enumerate(encoded):
# a ^ b = c -> b = a ^ c
# to reverse an encoded XORed array, we need to XOR either value resulting in the XORed value
# the first element in the encoded array must XOR the first element in the hidden array
if idx == 0:
temp = first ^ val
# subsequently, we can just use the temp variable which to slowly decode the arr
else:
temp ^= val
arr.append(temp)
return arr
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
m = float(raw_input());
t = m * input() /100;
x = m * input() /100;
totalCost = round(m + x + t);
print ('The total meal cost is' " " + str(int(totalCost)) + " " 'dollars.') |
# program to match key values in two dictionaries.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
|
class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print("even")
return True
def _odds_even(self):
print("not odd")
return False
a = Number(2)
a.even()
b = Number(3)
b.even()
a.even()
|
WIDTH = 87
HEIGHT = 87
FIRST = 0x20
LAST = 0x7f
_font =\
b'\x00\x4a\x5a\x02\x44\x60\x44\x52\x60\x52\x02\x44\x60\x44\x60'\
b'\x60\x44\x02\x52\x52\x52\x3e\x52\x66\x02\x44\x60\x44\x44\x60'\
b'\x60\x02\x44\x60\x44\x52\x60\x52\x02\x46\x5e\x46\x59\x5e\x4b'\
b'\x02\x4b\x59\x4b\x5e\x59\x46\x02\x52\x52\x52\x44\x52\x60\x02'\
b'\x4b\x59\x4b\x46\x59\x5e\x02\x46\x5e\x46\x4b\x5e\x59\x02\x4b'\
b'\x59\x4b\x52\x59\x52\x02\x4d\x57\x4d\x57\x57\x4d\x02\x52\x52'\
b'\x52\x4b\x52\x59\x02\x4d\x57\x4d\x4d\x57\x57\x07\x47\x52\x52'\
b'\x47\x50\x47\x4d\x48\x4a\x4a\x48\x4d\x47\x50\x47\x52\x07\x47'\
b'\x52\x47\x52\x47\x54\x48\x57\x4a\x5a\x4d\x5c\x50\x5d\x52\x5d'\
b'\x07\x52\x5d\x52\x5d\x54\x5d\x57\x5c\x5a\x5a\x5c\x57\x5d\x54'\
b'\x5d\x52\x07\x52\x5d\x5d\x52\x5d\x50\x5c\x4d\x5a\x4a\x57\x48'\
b'\x54\x47\x52\x47\x08\x44\x60\x44\x4f\x47\x51\x4b\x53\x50\x54'\
b'\x54\x54\x59\x53\x5d\x51\x60\x4f\x08\x50\x55\x55\x44\x53\x47'\
b'\x51\x4b\x50\x50\x50\x54\x51\x59\x53\x5d\x55\x60\x08\x4f\x54'\
b'\x4f\x44\x51\x47\x53\x4b\x54\x50\x54\x54\x53\x59\x51\x5d\x4f'\
b'\x60\x08\x44\x60\x44\x55\x47\x53\x4b\x51\x50\x50\x54\x50\x59'\
b'\x51\x5d\x53\x60\x55\x04\x4b\x59\x52\x4a\x59\x4e\x4b\x56\x52'\
b'\x5a\x04\x4a\x5a\x4a\x52\x4e\x4b\x56\x59\x5a\x52\x04\x4b\x59'\
b'\x4b\x56\x4b\x4e\x59\x56\x59\x4e\x04\x4a\x5a\x4c\x58\x4a\x50'\
b'\x5a\x54\x58\x4c\x16\x4a\x5a\x4a\x5d\x4c\x5d\x4f\x5c\x51\x5b'\
b'\x54\x58\x55\x56\x56\x53\x56\x4f\x55\x4c\x54\x4a\x53\x49\x51'\
b'\x49\x50\x4a\x4f\x4c\x4e\x4f\x4e\x53\x4f\x56\x50\x58\x53\x5b'\
b'\x55\x5c\x58\x5d\x5a\x5d\x16\x49\x5d\x5d\x5a\x5d\x58\x5c\x55'\
b'\x5b\x53\x58\x50\x56\x4f\x53\x4e\x4f\x4e\x4c\x4f\x4a\x50\x49'\
b'\x51\x49\x53\x4a\x54\x4c\x55\x4f\x56\x53\x56\x56\x55\x58\x54'\
b'\x5b\x51\x5c\x4f\x5d\x4c\x5d\x4a\x16\x4a\x5a\x5a\x47\x58\x47'\
b'\x55\x48\x53\x49\x50\x4c\x4f\x4e\x4e\x51\x4e\x55\x4f\x58\x50'\
b'\x5a\x51\x5b\x53\x5b\x54\x5a\x55\x58\x56\x55\x56\x51\x55\x4e'\
b'\x54\x4c\x51\x49\x4f\x48\x4c\x47\x4a\x47\x16\x47\x5b\x47\x4a'\
b'\x47\x4c\x48\x4f\x49\x51\x4c\x54\x4e\x55\x51\x56\x55\x56\x58'\
b'\x55\x5a\x54\x5b\x53\x5b\x51\x5a\x50\x58\x4f\x55\x4e\x51\x4e'\
b'\x4e\x4f\x4c\x50\x49\x53\x48\x55\x47\x58\x47\x5a\x14\x45\x5b'\
b'\x45\x50\x46\x52\x48\x54\x4a\x55\x4d\x56\x51\x56\x55\x55\x58'\
b'\x53\x5a\x50\x5b\x4e\x5a\x4c\x57\x4c\x53\x4d\x51\x4e\x4e\x50'\
b'\x4c\x53\x4b\x56\x4b\x59\x4c\x5c\x4d\x5e\x12\x45\x59\x45\x54'\
b'\x48\x56\x4b\x57\x50\x57\x53\x56\x56\x54\x58\x51\x59\x4e\x59'\
b'\x4c\x58\x4b\x56\x4b\x53\x4c\x50\x4e\x4e\x51\x4d\x54\x4d\x59'\
b'\x4e\x5c\x50\x5f\x19\x4f\x55\x51\x4f\x4f\x51\x4f\x53\x51\x55'\
b'\x53\x55\x55\x53\x55\x51\x53\x4f\x51\x4f\x20\x52\x51\x50\x50'\
b'\x51\x50\x53\x51\x54\x53\x54\x54\x53\x54\x51\x53\x50\x51\x50'\
b'\x20\x52\x52\x51\x51\x52\x52\x53\x53\x52\x52\x51\x0a\x52\x57'\
b'\x52\x4d\x53\x4d\x55\x4e\x56\x4f\x57\x51\x57\x53\x56\x55\x55'\
b'\x56\x53\x57\x52\x57\x08\x44\x60\x44\x52\x4a\x52\x20\x52\x4f'\
b'\x52\x55\x52\x20\x52\x5a\x52\x60\x52\x04\x44\x60\x44\x55\x44'\
b'\x4f\x60\x4f\x60\x55\x05\x4a\x5a\x52\x44\x4a\x52\x20\x52\x52'\
b'\x44\x5a\x52\x08\x44\x60\x44\x52\x60\x52\x20\x52\x4a\x59\x5a'\
b'\x59\x20\x52\x50\x60\x54\x60\x08\x44\x60\x44\x52\x60\x52\x20'\
b'\x52\x44\x52\x52\x62\x20\x52\x60\x52\x52\x62\x11\x4b\x59\x51'\
b'\x4b\x4e\x4c\x4c\x4e\x4b\x51\x4b\x53\x4c\x56\x4e\x58\x51\x59'\
b'\x53\x59\x56\x58\x58\x56\x59\x53\x59\x51\x58\x4e\x56\x4c\x53'\
b'\x4b\x51\x4b\x05\x4c\x58\x4c\x4c\x4c\x58\x58\x58\x58\x4c\x4c'\
b'\x4c\x04\x4b\x59\x52\x4a\x4b\x56\x59\x56\x52\x4a\x05\x4c\x58'\
b'\x52\x48\x4c\x52\x52\x5c\x58\x52\x52\x48\x0b\x4a\x5a\x52\x49'\
b'\x50\x4f\x4a\x4f\x4f\x53\x4d\x59\x52\x55\x57\x59\x55\x53\x5a'\
b'\x4f\x54\x4f\x52\x49\x05\x4b\x59\x52\x4b\x52\x59\x20\x52\x4b'\
b'\x52\x59\x52\x05\x4d\x57\x4d\x4d\x57\x57\x20\x52\x57\x4d\x4d'\
b'\x57\x08\x4d\x57\x52\x4c\x52\x58\x20\x52\x4d\x4f\x57\x55\x20'\
b'\x52\x57\x4f\x4d\x55\x22\x4e\x56\x51\x4e\x4f\x4f\x4e\x51\x4e'\
b'\x53\x4f\x55\x51\x56\x53\x56\x55\x55\x56\x53\x56\x51\x55\x4f'\
b'\x53\x4e\x51\x4e\x20\x52\x4f\x51\x4f\x53\x20\x52\x50\x50\x50'\
b'\x54\x20\x52\x51\x4f\x51\x55\x20\x52\x52\x4f\x52\x55\x20\x52'\
b'\x53\x4f\x53\x55\x20\x52\x54\x50\x54\x54\x20\x52\x55\x51\x55'\
b'\x53\x1a\x4e\x56\x4e\x4e\x4e\x56\x56\x56\x56\x4e\x4e\x4e\x20'\
b'\x52\x4f\x4f\x4f\x55\x20\x52\x50\x4f\x50\x55\x20\x52\x51\x4f'\
b'\x51\x55\x20\x52\x52\x4f\x52\x55\x20\x52\x53\x4f\x53\x55\x20'\
b'\x52\x54\x4f\x54\x55\x20\x52\x55\x4f\x55\x55\x10\x4d\x57\x52'\
b'\x4c\x4d\x55\x57\x55\x52\x4c\x20\x52\x52\x4f\x4f\x54\x20\x52'\
b'\x52\x4f\x55\x54\x20\x52\x52\x52\x51\x54\x20\x52\x52\x52\x53'\
b'\x54\x10\x4c\x55\x4c\x52\x55\x57\x55\x4d\x4c\x52\x20\x52\x4f'\
b'\x52\x54\x55\x20\x52\x4f\x52\x54\x4f\x20\x52\x52\x52\x54\x53'\
b'\x20\x52\x52\x52\x54\x51\x10\x4d\x57\x52\x58\x57\x4f\x4d\x4f'\
b'\x52\x58\x20\x52\x52\x55\x55\x50\x20\x52\x52\x55\x4f\x50\x20'\
b'\x52\x52\x52\x53\x50\x20\x52\x52\x52\x51\x50\x10\x4f\x58\x58'\
b'\x52\x4f\x4d\x4f\x57\x58\x52\x20\x52\x55\x52\x50\x4f\x20\x52'\
b'\x55\x52\x50\x55\x20\x52\x52\x52\x50\x51\x20\x52\x52\x52\x50'\
b'\x53\x0a\x52\x59\x52\x4b\x52\x59\x20\x52\x52\x4b\x59\x4e\x52'\
b'\x51\x20\x52\x53\x4d\x56\x4e\x53\x4f\x14\x49\x5b\x52\x47\x52'\
b'\x56\x20\x52\x4d\x4a\x57\x50\x20\x52\x57\x4a\x4d\x50\x20\x52'\
b'\x49\x56\x4c\x5c\x20\x52\x5b\x56\x58\x5c\x20\x52\x49\x56\x5b'\
b'\x56\x20\x52\x4c\x5c\x58\x5c\x0c\x4d\x57\x52\x4c\x52\x58\x20'\
b'\x52\x4f\x4f\x55\x4f\x20\x52\x4d\x55\x4f\x57\x51\x58\x53\x58'\
b'\x55\x57\x57\x55\x0a\x4c\x58\x52\x4c\x52\x58\x20\x52\x4c\x51'\
b'\x4d\x4f\x57\x4f\x58\x51\x20\x52\x50\x57\x54\x57\x0d\x4b\x59'\
b'\x4d\x4e\x57\x58\x20\x52\x57\x4e\x4d\x58\x20\x52\x4f\x4c\x4c'\
b'\x4f\x4b\x51\x20\x52\x55\x4c\x58\x4f\x59\x51\x11\x49\x5b\x4e'\
b'\x49\x49\x5b\x20\x52\x56\x49\x5b\x5b\x20\x52\x4d\x4d\x5b\x5b'\
b'\x20\x52\x57\x4d\x49\x5b\x20\x52\x4e\x49\x56\x49\x20\x52\x4d'\
b'\x4d\x57\x4d\x02\x4b\x59\x4b\x46\x59\x5e\x0a\x47\x5b\x4d\x4a'\
b'\x53\x56\x20\x52\x4b\x50\x53\x4c\x20\x52\x47\x5c\x5b\x5c\x5b'\
b'\x52\x47\x5c\x0d\x4c\x58\x50\x4c\x50\x50\x4c\x50\x4c\x54\x50'\
b'\x54\x50\x58\x54\x58\x54\x54\x58\x54\x58\x50\x54\x50\x54\x4c'\
b'\x50\x4c\x1f\x4b\x59\x59\x50\x58\x4e\x56\x4c\x53\x4b\x51\x4b'\
b'\x4e\x4c\x4c\x4e\x4b\x51\x4b\x53\x4c\x56\x4e\x58\x51\x59\x53'\
b'\x59\x56\x58\x58\x56\x59\x54\x20\x52\x59\x50\x57\x4e\x55\x4d'\
b'\x53\x4d\x51\x4e\x50\x4f\x4f\x51\x4f\x53\x50\x55\x51\x56\x53'\
b'\x57\x55\x57\x57\x56\x59\x54\x09\x4b\x59\x52\x4a\x4b\x56\x59'\
b'\x56\x52\x4a\x20\x52\x52\x5a\x59\x4e\x4b\x4e\x52\x5a\x21\x47'\
b'\x5d\x50\x49\x50\x47\x51\x46\x53\x46\x54\x47\x54\x49\x20\x52'\
b'\x47\x5a\x48\x58\x4a\x56\x4b\x54\x4c\x50\x4c\x4b\x4d\x4a\x4f'\
b'\x49\x55\x49\x57\x4a\x58\x4b\x58\x50\x59\x54\x5a\x56\x5c\x58'\
b'\x5d\x5a\x20\x52\x47\x5a\x5d\x5a\x20\x52\x51\x5a\x50\x5b\x51'\
b'\x5c\x53\x5c\x54\x5b\x53\x5a\x3f\x4a\x5a\x52\x4d\x52\x53\x20'\
b'\x52\x52\x53\x51\x5c\x20\x52\x52\x53\x53\x5c\x20\x52\x51\x5c'\
b'\x53\x5c\x20\x52\x52\x4d\x51\x4a\x50\x48\x4e\x47\x20\x52\x51'\
b'\x4a\x4e\x47\x20\x52\x52\x4d\x53\x4a\x54\x48\x56\x47\x20\x52'\
b'\x53\x4a\x56\x47\x20\x52\x52\x4d\x4e\x4b\x4c\x4b\x4a\x4d\x20'\
b'\x52\x50\x4c\x4c\x4c\x4a\x4d\x20\x52\x52\x4d\x56\x4b\x58\x4b'\
b'\x5a\x4d\x20\x52\x54\x4c\x58\x4c\x5a\x4d\x20\x52\x52\x4d\x50'\
b'\x4e\x4f\x4f\x4f\x52\x20\x52\x52\x4d\x50\x4f\x4f\x52\x20\x52'\
b'\x52\x4d\x54\x4e\x55\x4f\x55\x52\x20\x52\x52\x4d\x54\x4f\x55'\
b'\x52\x5d\x4a\x5a\x52\x49\x52\x4b\x20\x52\x52\x4e\x52\x50\x20'\
b'\x52\x52\x53\x52\x55\x20\x52\x52\x59\x51\x5c\x20\x52\x52\x59'\
b'\x53\x5c\x20\x52\x51\x5c\x53\x5c\x20\x52\x52\x47\x51\x49\x50'\
b'\x4a\x20\x52\x52\x47\x53\x49\x54\x4a\x20\x52\x50\x4a\x52\x49'\
b'\x54\x4a\x20\x52\x52\x4b\x50\x4e\x4e\x4f\x4d\x4e\x20\x52\x52'\
b'\x4b\x54\x4e\x56\x4f\x57\x4e\x20\x52\x4e\x4f\x50\x4f\x52\x4e'\
b'\x54\x4f\x56\x4f\x20\x52\x52\x50\x50\x53\x4e\x54\x4c\x54\x4b'\
b'\x52\x4b\x53\x4c\x54\x20\x52\x52\x50\x54\x53\x56\x54\x58\x54'\
b'\x59\x52\x59\x53\x58\x54\x20\x52\x4e\x54\x50\x54\x52\x53\x54'\
b'\x54\x56\x54\x20\x52\x52\x55\x50\x58\x4f\x59\x4d\x5a\x4c\x5a'\
b'\x4b\x59\x4a\x57\x4a\x59\x4c\x5a\x20\x52\x52\x55\x54\x58\x55'\
b'\x59\x57\x5a\x58\x5a\x59\x59\x5a\x57\x5a\x59\x58\x5a\x20\x52'\
b'\x4d\x5a\x4f\x5a\x52\x59\x55\x5a\x57\x5a\x27\x4a\x5a\x52\x59'\
b'\x51\x5c\x20\x52\x52\x59\x53\x5c\x20\x52\x51\x5c\x53\x5c\x20'\
b'\x52\x52\x59\x55\x5a\x58\x5a\x5a\x58\x5a\x55\x59\x54\x57\x54'\
b'\x59\x52\x5a\x4f\x59\x4d\x57\x4c\x55\x4d\x56\x4a\x55\x48\x53'\
b'\x47\x51\x47\x4f\x48\x4e\x4a\x4f\x4d\x4d\x4c\x4b\x4d\x4a\x4f'\
b'\x4b\x52\x4d\x54\x4b\x54\x4a\x55\x4a\x58\x4c\x5a\x4f\x5a\x52'\
b'\x59\x1f\x4a\x5a\x52\x59\x51\x5c\x20\x52\x52\x59\x53\x5c\x20'\
b'\x52\x51\x5c\x53\x5c\x20\x52\x52\x59\x56\x58\x56\x56\x58\x55'\
b'\x58\x52\x5a\x51\x5a\x4c\x59\x49\x58\x48\x56\x48\x54\x47\x50'\
b'\x47\x4e\x48\x4c\x48\x4b\x49\x4a\x4c\x4a\x51\x4c\x52\x4c\x55'\
b'\x4e\x56\x4e\x58\x52\x59\x0e\x49\x5b\x49\x50\x4b\x52\x20\x52'\
b'\x4c\x4b\x4e\x50\x20\x52\x52\x47\x52\x4f\x20\x52\x58\x4b\x56'\
b'\x50\x20\x52\x5b\x50\x59\x52\x1b\x47\x5d\x49\x49\x4a\x4b\x4b'\
b'\x4f\x4b\x55\x4a\x59\x49\x5b\x20\x52\x5b\x49\x5a\x4b\x59\x4f'\
b'\x59\x55\x5a\x59\x5b\x5b\x20\x52\x49\x49\x4b\x4a\x4f\x4b\x55'\
b'\x4b\x59\x4a\x5b\x49\x20\x52\x49\x5b\x4b\x5a\x4f\x59\x55\x59'\
b'\x59\x5a\x5b\x5b\x36\x46\x5e\x52\x52\x52\x5b\x51\x5c\x20\x52'\
b'\x52\x56\x51\x5c\x20\x52\x52\x49\x51\x48\x4f\x48\x4e\x49\x4e'\
b'\x4b\x4f\x4e\x52\x52\x20\x52\x52\x49\x53\x48\x55\x48\x56\x49'\
b'\x56\x4b\x55\x4e\x52\x52\x20\x52\x52\x52\x4e\x4f\x4c\x4e\x4a'\
b'\x4e\x49\x4f\x49\x51\x4a\x52\x20\x52\x52\x52\x56\x4f\x58\x4e'\
b'\x5a\x4e\x5b\x4f\x5b\x51\x5a\x52\x20\x52\x52\x52\x4e\x55\x4c'\
b'\x56\x4a\x56\x49\x55\x49\x53\x4a\x52\x20\x52\x52\x52\x56\x55'\
b'\x58\x56\x5a\x56\x5b\x55\x5b\x53\x5a\x52\x2d\x4a\x5a\x55\x49'\
b'\x54\x4a\x55\x4b\x56\x4a\x56\x49\x55\x47\x53\x46\x51\x46\x4f'\
b'\x47\x4e\x49\x4e\x4b\x4f\x4d\x51\x4f\x56\x52\x20\x52\x4f\x4d'\
b'\x54\x50\x56\x52\x57\x54\x57\x56\x56\x58\x54\x5a\x20\x52\x50'\
b'\x4e\x4e\x50\x4d\x52\x4d\x54\x4e\x56\x50\x58\x55\x5b\x20\x52'\
b'\x4e\x56\x53\x59\x55\x5b\x56\x5d\x56\x5f\x55\x61\x53\x62\x51'\
b'\x62\x4f\x61\x4e\x5f\x4e\x5e\x4f\x5d\x50\x5e\x4f\x5f\x1d\x4a'\
b'\x5a\x52\x46\x51\x48\x52\x4a\x53\x48\x52\x46\x20\x52\x52\x46'\
b'\x52\x62\x20\x52\x52\x51\x51\x54\x52\x62\x53\x54\x52\x51\x20'\
b'\x52\x4c\x4d\x4e\x4e\x50\x4d\x4e\x4c\x4c\x4d\x20\x52\x4c\x4d'\
b'\x58\x4d\x20\x52\x54\x4d\x56\x4e\x58\x4d\x56\x4c\x54\x4d\x37'\
b'\x4a\x5a\x52\x46\x51\x48\x52\x4a\x53\x48\x52\x46\x20\x52\x52'\
b'\x46\x52\x54\x20\x52\x52\x50\x51\x52\x53\x56\x52\x58\x51\x56'\
b'\x53\x52\x52\x50\x20\x52\x52\x54\x52\x62\x20\x52\x52\x5e\x51'\
b'\x60\x52\x62\x53\x60\x52\x5e\x20\x52\x4c\x4d\x4e\x4e\x50\x4d'\
b'\x4e\x4c\x4c\x4d\x20\x52\x4c\x4d\x58\x4d\x20\x52\x54\x4d\x56'\
b'\x4e\x58\x4d\x56\x4c\x54\x4d\x20\x52\x4c\x5b\x4e\x5c\x50\x5b'\
b'\x4e\x5a\x4c\x5b\x20\x52\x4c\x5b\x58\x5b\x20\x52\x54\x5b\x56'\
b'\x5c\x58\x5b\x56\x5a\x54\x5b\x11\x45\x5f\x52\x49\x51\x4a\x52'\
b'\x4b\x53\x4a\x52\x49\x20\x52\x49\x59\x48\x5a\x49\x5b\x4a\x5a'\
b'\x49\x59\x20\x52\x5b\x59\x5a\x5a\x5b\x5b\x5c\x5a\x5b\x59\x20'\
b'\x46\x5e\x52\x48\x4e\x4c\x4b\x50\x4a\x53\x4a\x55\x4b\x57\x4d'\
b'\x58\x4f\x58\x51\x57\x52\x55\x20\x52\x52\x48\x56\x4c\x59\x50'\
b'\x5a\x53\x5a\x55\x59\x57\x57\x58\x55\x58\x53\x57\x52\x55\x20'\
b'\x52\x52\x55\x51\x59\x50\x5c\x20\x52\x52\x55\x53\x59\x54\x5c'\
b'\x20\x52\x50\x5c\x54\x5c\x19\x46\x5e\x52\x4e\x51\x4b\x50\x49'\
b'\x4e\x48\x4d\x48\x4b\x49\x4a\x4b\x4a\x4f\x4b\x52\x4c\x54\x4e'\
b'\x57\x52\x5c\x20\x52\x52\x4e\x53\x4b\x54\x49\x56\x48\x57\x48'\
b'\x59\x49\x5a\x4b\x5a\x4f\x59\x52\x58\x54\x56\x57\x52\x5c\x13'\
b'\x46\x5e\x52\x47\x50\x4a\x4c\x4f\x49\x52\x20\x52\x52\x47\x54'\
b'\x4a\x58\x4f\x5b\x52\x20\x52\x49\x52\x4c\x55\x50\x5a\x52\x5d'\
b'\x20\x52\x5b\x52\x58\x55\x54\x5a\x52\x5d\x2f\x46\x5e\x52\x54'\
b'\x54\x57\x56\x58\x58\x58\x5a\x57\x5b\x55\x5b\x53\x5a\x51\x58'\
b'\x50\x56\x50\x53\x51\x20\x52\x53\x51\x55\x4f\x56\x4d\x56\x4b'\
b'\x55\x49\x53\x48\x51\x48\x4f\x49\x4e\x4b\x4e\x4d\x4f\x4f\x51'\
b'\x51\x20\x52\x51\x51\x4e\x50\x4c\x50\x4a\x51\x49\x53\x49\x55'\
b'\x4a\x57\x4c\x58\x4e\x58\x50\x57\x52\x54\x20\x52\x52\x54\x51'\
b'\x59\x50\x5c\x20\x52\x52\x54\x53\x59\x54\x5c\x20\x52\x50\x5c'\
b'\x54\x5c\x2f\x49\x5b\x56\x2b\x53\x2d\x51\x2f\x50\x31\x4f\x34'\
b'\x4f\x38\x50\x3c\x54\x44\x55\x47\x55\x4a\x54\x4d\x52\x50\x20'\
b'\x52\x53\x2d\x51\x30\x50\x34\x50\x38\x51\x3b\x55\x43\x56\x47'\
b'\x56\x4a\x55\x4d\x52\x50\x4e\x52\x52\x54\x55\x57\x56\x5a\x56'\
b'\x5d\x55\x61\x51\x69\x50\x6c\x50\x70\x51\x74\x53\x77\x20\x52'\
b'\x52\x54\x54\x57\x55\x5a\x55\x5d\x54\x60\x50\x68\x4f\x6c\x4f'\
b'\x70\x50\x73\x51\x75\x53\x77\x56\x79\x2f\x49\x5b\x4e\x2b\x51'\
b'\x2d\x53\x2f\x54\x31\x55\x34\x55\x38\x54\x3c\x50\x44\x4f\x47'\
b'\x4f\x4a\x50\x4d\x52\x50\x20\x52\x51\x2d\x53\x30\x54\x34\x54'\
b'\x38\x53\x3b\x4f\x43\x4e\x47\x4e\x4a\x4f\x4d\x52\x50\x56\x52'\
b'\x52\x54\x4f\x57\x4e\x5a\x4e\x5d\x4f\x61\x53\x69\x54\x6c\x54'\
b'\x70\x53\x74\x51\x77\x20\x52\x52\x54\x50\x57\x4f\x5a\x4f\x5d'\
b'\x50\x60\x54\x68\x55\x6c\x55\x70\x54\x73\x53\x75\x51\x77\x4e'\
b'\x79\x1f\x49\x5b\x56\x2e\x53\x31\x51\x34\x4f\x38\x4e\x3d\x4e'\
b'\x43\x4f\x49\x50\x4d\x53\x58\x54\x5c\x55\x62\x55\x67\x54\x6c'\
b'\x53\x6f\x51\x73\x20\x52\x53\x31\x51\x35\x50\x38\x4f\x3d\x4f'\
b'\x42\x50\x48\x51\x4c\x54\x57\x55\x5b\x56\x61\x56\x67\x55\x6c'\
b'\x53\x70\x51\x73\x4e\x76\x1f\x49\x5b\x4e\x2e\x51\x31\x53\x34'\
b'\x55\x38\x56\x3d\x56\x43\x55\x49\x54\x4d\x51\x58\x50\x5c\x4f'\
b'\x62\x4f\x67\x50\x6c\x51\x6f\x53\x73\x20\x52\x51\x31\x53\x35'\
b'\x54\x38\x55\x3d\x55\x42\x54\x48\x53\x4c\x50\x57\x4f\x5b\x4e'\
b'\x61\x4e\x67\x4f\x6c\x51\x70\x53\x73\x56\x76\x0d\x37\x5a\x3a'\
b'\x52\x41\x52\x52\x6f\x20\x52\x40\x52\x51\x6f\x20\x52\x3f\x52'\
b'\x52\x72\x20\x52\x5a\x22\x56\x4a\x52\x72\x1a\x49\x5b\x54\x4d'\
b'\x56\x4e\x58\x50\x58\x4f\x57\x4e\x54\x4d\x51\x4d\x4e\x4e\x4d'\
b'\x4f\x4c\x51\x4c\x53\x4d\x55\x4f\x57\x53\x5a\x20\x52\x51\x4d'\
b'\x4f\x4e\x4e\x4f\x4d\x51\x4d\x53\x4e\x55\x53\x5a\x54\x5c\x54'\
b'\x5e\x53\x5f\x51\x5f\x2c\x47\x5d\x4c\x4d\x4b\x4e\x4a\x50\x4a'\
b'\x52\x4b\x55\x4f\x59\x50\x5b\x20\x52\x4a\x52\x4b\x54\x4f\x58'\
b'\x50\x5b\x50\x5d\x4f\x60\x4d\x62\x4c\x62\x4b\x61\x4a\x5f\x4a'\
b'\x5c\x4b\x58\x4d\x54\x4f\x51\x52\x4e\x54\x4d\x56\x4d\x59\x4e'\
b'\x5a\x50\x5a\x54\x59\x58\x57\x5a\x55\x5b\x54\x5b\x53\x5a\x53'\
b'\x58\x54\x57\x55\x58\x54\x59\x20\x52\x56\x4d\x58\x4e\x59\x50'\
b'\x59\x54\x58\x58\x57\x5a\x44\x45\x5f\x59\x47\x58\x48\x59\x49'\
b'\x5a\x48\x59\x47\x57\x46\x54\x46\x51\x47\x4f\x49\x4e\x4b\x4d'\
b'\x4e\x4c\x52\x4a\x5b\x49\x5f\x48\x61\x20\x52\x54\x46\x52\x47'\
b'\x50\x49\x4f\x4b\x4e\x4e\x4c\x57\x4b\x5b\x4a\x5e\x49\x60\x48'\
b'\x61\x46\x62\x44\x62\x43\x61\x43\x60\x44\x5f\x45\x60\x44\x61'\
b'\x20\x52\x5f\x47\x5e\x48\x5f\x49\x60\x48\x60\x47\x5f\x46\x5d'\
b'\x46\x5b\x47\x5a\x48\x59\x4a\x58\x4d\x55\x5b\x54\x5f\x53\x61'\
b'\x20\x52\x5d\x46\x5b\x48\x5a\x4a\x59\x4e\x57\x57\x56\x5b\x55'\
b'\x5e\x54\x60\x53\x61\x51\x62\x4f\x62\x4e\x61\x4e\x60\x4f\x5f'\
b'\x50\x60\x4f\x61\x20\x52\x49\x4d\x5e\x4d\x33\x46\x5e\x5b\x47'\
b'\x5a\x48\x5b\x49\x5c\x48\x5b\x47\x58\x46\x55\x46\x52\x47\x50'\
b'\x49\x4f\x4b\x4e\x4e\x4d\x52\x4b\x5b\x4a\x5f\x49\x61\x20\x52'\
b'\x55\x46\x53\x47\x51\x49\x50\x4b\x4f\x4e\x4d\x57\x4c\x5b\x4b'\
b'\x5e\x4a\x60\x49\x61\x47\x62\x45\x62\x44\x61\x44\x60\x45\x5f'\
b'\x46\x60\x45\x61\x20\x52\x59\x4d\x57\x54\x56\x58\x56\x5a\x57'\
b'\x5b\x5a\x5b\x5c\x59\x5d\x57\x20\x52\x5a\x4d\x58\x54\x57\x58'\
b'\x57\x5a\x58\x5b\x20\x52\x4a\x4d\x5a\x4d\x35\x46\x5e\x59\x47'\
b'\x58\x48\x59\x49\x5a\x48\x5a\x47\x58\x46\x20\x52\x5c\x46\x55'\
b'\x46\x52\x47\x50\x49\x4f\x4b\x4e\x4e\x4d\x52\x4b\x5b\x4a\x5f'\
b'\x49\x61\x20\x52\x55\x46\x53\x47\x51\x49\x50\x4b\x4f\x4e\x4d'\
b'\x57\x4c\x5b\x4b\x5e\x4a\x60\x49\x61\x47\x62\x45\x62\x44\x61'\
b'\x44\x60\x45\x5f\x46\x60\x45\x61\x20\x52\x5b\x46\x57\x54\x56'\
b'\x58\x56\x5a\x57\x5b\x5a\x5b\x5c\x59\x5d\x57\x20\x52\x5c\x46'\
b'\x58\x54\x57\x58\x57\x5a\x58\x5b\x20\x52\x4a\x4d\x59\x4d\x55'\
b'\x40\x63\x54\x47\x53\x48\x54\x49\x55\x48\x54\x47\x52\x46\x4f'\
b'\x46\x4c\x47\x4a\x49\x49\x4b\x48\x4e\x47\x52\x45\x5b\x44\x5f'\
b'\x43\x61\x20\x52\x4f\x46\x4d\x47\x4b\x49\x4a\x4b\x49\x4e\x47'\
b'\x57\x46\x5b\x45\x5e\x44\x60\x43\x61\x41\x62\x3f\x62\x3e\x61'\
b'\x3e\x60\x3f\x5f\x40\x60\x3f\x61\x20\x52\x60\x47\x5f\x48\x60'\
b'\x49\x61\x48\x60\x47\x5d\x46\x5a\x46\x57\x47\x55\x49\x54\x4b'\
b'\x53\x4e\x52\x52\x50\x5b\x4f\x5f\x4e\x61\x20\x52\x5a\x46\x58'\
b'\x47\x56\x49\x55\x4b\x54\x4e\x52\x57\x51\x5b\x50\x5e\x4f\x60'\
b'\x4e\x61\x4c\x62\x4a\x62\x49\x61\x49\x60\x4a\x5f\x4b\x60\x4a'\
b'\x61\x20\x52\x5e\x4d\x5c\x54\x5b\x58\x5b\x5a\x5c\x5b\x5f\x5b'\
b'\x61\x59\x62\x57\x20\x52\x5f\x4d\x5d\x54\x5c\x58\x5c\x5a\x5d'\
b'\x5b\x20\x52\x44\x4d\x5f\x4d\x57\x40\x63\x54\x47\x53\x48\x54'\
b'\x49\x55\x48\x54\x47\x52\x46\x4f\x46\x4c\x47\x4a\x49\x49\x4b'\
b'\x48\x4e\x47\x52\x45\x5b\x44\x5f\x43\x61\x20\x52\x4f\x46\x4d'\
b'\x47\x4b\x49\x4a\x4b\x49\x4e\x47\x57\x46\x5b\x45\x5e\x44\x60'\
b'\x43\x61\x41\x62\x3f\x62\x3e\x61\x3e\x60\x3f\x5f\x40\x60\x3f'\
b'\x61\x20\x52\x5e\x47\x5d\x48\x5e\x49\x5f\x48\x5f\x47\x5d\x46'\
b'\x20\x52\x61\x46\x5a\x46\x57\x47\x55\x49\x54\x4b\x53\x4e\x52'\
b'\x52\x50\x5b\x4f\x5f\x4e\x61\x20\x52\x5a\x46\x58\x47\x56\x49'\
b'\x55\x4b\x54\x4e\x52\x57\x51\x5b\x50\x5e\x4f\x60\x4e\x61\x4c'\
b'\x62\x4a\x62\x49\x61\x49\x60\x4a\x5f\x4b\x60\x4a\x61\x20\x52'\
b'\x60\x46\x5c\x54\x5b\x58\x5b\x5a\x5c\x5b\x5f\x5b\x61\x59\x62'\
b'\x57\x20\x52\x61\x46\x5d\x54\x5c\x58\x5c\x5a\x5d\x5b\x20\x52'\
b'\x44\x4d\x5e\x4d\x13\x4c\x59\x4d\x51\x4e\x4f\x50\x4d\x53\x4d'\
b'\x54\x4e\x54\x51\x52\x57\x52\x5a\x53\x5b\x20\x52\x52\x4d\x53'\
b'\x4e\x53\x51\x51\x57\x51\x5a\x52\x5b\x55\x5b\x57\x59\x58\x57'\
b'\x15\x4c\x58\x52\x4c\x4e\x57\x58\x50\x4c\x50\x56\x57\x52\x4c'\
b'\x20\x52\x52\x52\x52\x4c\x20\x52\x52\x52\x4c\x50\x20\x52\x52'\
b'\x52\x4e\x57\x20\x52\x52\x52\x56\x57\x20\x52\x52\x52\x58\x50'\
b'\x17\x46\x5e\x49\x55\x49\x53\x4a\x50\x4c\x4f\x4e\x4f\x50\x50'\
b'\x54\x53\x56\x54\x58\x54\x5a\x53\x5b\x51\x20\x52\x49\x53\x4a'\
b'\x51\x4c\x50\x4e\x50\x50\x51\x54\x54\x56\x55\x58\x55\x5a\x54'\
b'\x5b\x51\x5b\x4f'
_index =\
b'\x00\x00\x03\x00\x0a\x00\x11\x00\x18\x00\x1f\x00\x26\x00\x2d'\
b'\x00\x34\x00\x3b\x00\x42\x00\x49\x00\x50\x00\x57\x00\x5e\x00'\
b'\x65\x00\x76\x00\x87\x00\x98\x00\xa9\x00\xbc\x00\xcf\x00\xe2'\
b'\x00\xf5\x00\x00\x01\x0b\x01\x16\x01\x21\x01\x50\x01\x7f\x01'\
b'\xae\x01\xdd\x01\x08\x02\x2f\x02\x64\x02\x7b\x02\x8e\x02\x99'\
b'\x02\xa6\x02\xb9\x02\xcc\x02\xf1\x02\xfe\x02\x09\x03\x16\x03'\
b'\x2f\x03\x3c\x03\x49\x03\x5c\x03\xa3\x03\xda\x03\xfd\x03\x20'\
b'\x04\x43\x04\x66\x04\x7d\x04\xa8\x04\xc3\x04\xda\x04\xf7\x04'\
b'\x1c\x05\x23\x05\x3a\x05\x57\x05\x98\x05\xad\x05\xf2\x05\x73'\
b'\x06\x30\x07\x81\x07\xc2\x07\xe1\x07\x1a\x08\x89\x08\xe6\x08'\
b'\x23\x09\x94\x09\xb9\x09\xfc\x09\x31\x0a\x5a\x0a\xbb\x0a\x1c'\
b'\x0b\x7d\x0b\xbe\x0b\xff\x0b\x1c\x0c\x53\x0c\xae\x0c\x39\x0d'\
b'\xa2\x0d\x0f\x0e\xbc\x0e\x6d\x0f\x96\x0f\xc3\x0f'
INDEX = memoryview(_index)
FONT = memoryview(_font)
|
#!/usr/bin/python
## Ejercicio 1 reverse Polish Notation
## Autor: Fabiola Tapara Quispe
## Description: Mediante el siguiente metodo recibe un string con datos y signos con operaciones basicas (+, -, *, /) usando una Pila como estructura.
## * Date: 15/11/21
def sum (a, b):
return a + b
def resta (a, b):
return a - b
def multipli (a, b):
return a * b
def division (a, b):
return a // b
## Funcion Notacion
def polishReverse(input):
operadores = "+-*/"
string = []
listado = input.split(" ")
for i in listado:
if (i in operadores):
num2 = string.pop()
num1 = string.pop()
if (i == "+"):
string.append(sum(num1, num2))
elif (i == "-"):
string.append(resta(num1, num2))
elif (i == "*"):
string.append(multipli(num1, num2))
else:
string.append(division(num1, num2))
else:
string.append(int(i))
continue
return string[0]
## Casos de prueba vistos en clase
input = "2 1 + 3 *"
print("Primer Input : " + input)
print(polishReverse(input))
input = "4 13 5 / +"
print("Segundo Input : " + input)
print(polishReverse(input))
input = "10 6 9 3 + -11 * / * 17 + 5 +"
print("Tercer Input : " + input)
print(polishReverse(input))
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author:nikan
@file: asyncio_utils.py
@time: 2018/5/18 下午6:06
"""
async def add_future_callback(fut, success_callback, fail_callback=None, need_fut_as_success_cb_args=True):
"""
adding a callback after future completed
:param fut:
:param callback:
:param args:
:return:
"""
try:
result = await fut
if need_fut_as_success_cb_args:
await success_callback(result)
else:
await success_callback()
except Exception:
if fail_callback:
await fail_callback()
raise
return result
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 4 23:30:51 2017
@author: coskun
Problem 1 - Paying Debt off in a Year
10.0 points possible (graded)
Write a program to calculate the credit card balance after
one year if a person only pays the minimum monthly payment
required by the credit card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
For each month, calculate statements on the monthly payment and
remaining balance. At the end of 12 months, print out the remaining balance.
Be sure to print out no more than two decimal digits of accuracy - so print
print("Remaining balance: 813.41")
"""
#test Case 1:
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
grndTotal = 0
#Test Case 2:
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
def unpaidBalance(Balance, MonthlyPaymentRate):
return Balance - (Balance * MonthlyPaymentRate)
def updatedNextMount(Unpaid, AnnualInterestRate):
return Unpaid + ((AnnualInterestRate/12.0) * Unpaid)
def annualSubDebt(balance, annualInterestRate, monthlyPaymentRate, mount = 12):
""" This Recursive Function calculates mountly interest applied debt and,
returns grand total debit.
"""
#b1 = updatedNextMount(unpaidBalance(balance, monthlyPaymentRate), annualInterestRate)
if mount == 0:
print("Month",12 - mount,"Remaining balance:",balance)
return balance
print("Month",12 - mount,"Remaining balance:",balance)
mount = mount - 1
ub = unpaidBalance(balance, monthlyPaymentRate)
return annualSubDebt(updatedNextMount(ub, annualInterestRate), annualInterestRate, monthlyPaymentRate, mount)
grndTotal = round(annualSubDebt(balance, annualInterestRate, monthlyPaymentRate), 2)
print("Remaining balance:",grndTotal) |
def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=["column_category"])[
"column_installment_value"
].sum()
return category_transactions.idxmax(), category_transactions.max()
|
# Copyright (c) 2020 Thomas Holland ([email protected])
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Refer to the LICENSE file which is part of the AdvPiStepper distribution or
# to https://opensource.org/licenses/MIT for a text of the license.
#
#
"""
Definitions used by the AdvPiStepper
CW and CCW constants defining clockwise / couterclockwise motions.
The Keys which are used as parameters to describe a motor and the driver.
* DRIVER_NAME Human readable name of the driver.
* MAX_SPEED: Maximum speed in steps per second. This is not a limit, just a recommendation.
* MAX_TORQUE_SPEED: Maximum speed at which the motor will still deliver full torque (optional, if known)
* ACCELERATION_RATE: Acceleration in steps per second squared.
* DECELERATION_RATE: Deceleration in steps per second squared.
* FULL_STEPS_PER_REV: Number of full (not micro-)steps per one revolution.
* MICROSTEP_OPTIONS: Tupel of all microsteps options.
* MICROSTEP_DEFAULT: The prefered microstep rate of the driver.
Other parameters which can be passed to the AdvPiStepper class
* PIGPIO_ADDR: The hostname of the system where the pigpio daemon is running on.
* PIGPIO_PORT: The port on which the pigpio daemon is listening on.
"""
CW: int = 1
"""Clockwise/forward rotation. Just an internal designation. True
direction may depend on the wiring of the stepper motor."""
CCW: int = -1
"""Counterclockwise/backward rotation. Just an internal designation.
True direction may depend on the wiring of the stepper motor."""
# Parameter Keys
DRIVER_NAME: str = "driver_name"
MAX_SPEED: str = "max_speed"
"""Maximum speed in steps per second. This is not a limit, just a recommendation"""
MAX_TORQUE_SPEED: str = "max_torque_speed"
"""Maximum speed at which the motor will still deliver full torque."""
ACCELERATION_RATE: str = "acceleration_rate"
"""Acceleration in steps per second squared."""
DECELERATION_RATE: str = "deceleration_rate"
"""Decelearation in steps per second squared."""
FULL_STEPS_PER_REV: str = "full_steps_per_rev"
"""Number of full (not micro-)steps per one revolution."""
MICROSTEP_OPTIONS: str = "microstep_options"
"""Tupel of all microsteps options. Default is only full steps."""
MICROSTEP_DEFAULT = "microstep_default"
"""The prefered microstep rate of the driver."""
PIGPIO_ADDR = "pigpio_addr"
"""The hostname of the system where the pigpio daemon is running on. Default is empty for the localhost."""
PIGPIO_PORT = "pigpio_port"
"""The port on which the pigpio daemon is listening on. Default is empty to use the default pigpio port (8888)."""
DIRECTION_INVERT = "direction_invert"
"""If this key exists then the direction signal is inverted by the driver,
i.e. Clockwise and Counterclockwise are swaped."""
# Paramaters of the Step/Dir Driver
DIRECTION_CHANGE_DELAY = "direction_change_delay"
"""The time between a change in direction and the first step pulse (in microseconds)"""
STEP_PULSE_LENGTH = "step_pulse_length"
"""The time for a step pulse (in microseconds)"""
STEP_PULSE_DELAY = "step_pulse_delay"
"""The minimum time between step pulses (in microseconds)"""
|
# Problem Statement
# Given an array of positive numbers and a positive number ‘S’,
# find the length of the smallest contiguous subarray
# whose sum is greater than or equal to ‘S’.
# Return 0, if no such subarray exists.
# Example 1:
# Input: [2, 1, 5, 2, 3, 2], S = 7
# Output: 2
# Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
# Example 2:
# Input: [2, 1, 5, 2, 8], S = 7
# Output: 1
# Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
# Example 3:
# Input: [3, 4, 1, 1, 6], S = 8
# Output: 3
# Explanation: Smallest subarrays with a sum greater than or equal to '8' are[3, 4, 1] or [1, 1, 6].
def smallest_subarray_sum_s(arr, s):
window_start = 0
window_sum = 0
min_length = len(arr)
for window_end in range(0, len(arr)):
window_sum += arr[window_end]
while window_sum >= s:
min_length = min(min_length, (window_end - window_start + 1))
window_sum -= arr[window_start]
window_start += 1
if min_length == len(arr):
return 0
return min_length
def main():
print(smallest_subarray_sum_s([2, 1, 5, 2, 3, 2], 7))
print(smallest_subarray_sum_s([2, 1, 5, 2, 8], 7))
print(smallest_subarray_sum_s([3, 4, 1, 1, 6], 8))
if __name__ == "__main__":
main()
|
def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
n = i * j
if is_palindrome(n) and n > largest_palindrome:
largest_palindrome = n
return largest_palindrome
if __name__ == "__main__":
print(solution())
|
''' Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and age < 24 # correct solution
'''
age = int(input("Please enter the age: "))
if age >= 18 and age <= 24:
print("You can apply for Youth Festival program")
else:
print("Sorry, you cannot apply") # Please enter the age: 20
# You can apply for Youth Festival program
# Please enter the age: 30
# Sorry, you cannot apply
|
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008/.
"""
Wyrd In: Time tracker and task manager
CC-Share Alike 2012 © The Wyrd In team
https://github.com/WyrdIn
This module implements the Deadline class.
"""
class Deadline():
"""
Deadline is an attribute of a task or a goal. It is essentially an instance
of the datetime.time class, but it can be more complex. We can have soft
deadlines too. Deadlines can have penalties associated with missing them.
A deadline always belongs to a certain task or project (goal). The history
of each deadline (how it was originally specified and later shifted,
modified or cancelled, potentially also who shifted, modified or cancelled
it) should be also stored.
"""
raise NotImplementedError("Deadline needs to be implemented yet.")
pass
|
dtypes = {
'float32': 'float',
'float64': 'double',
'complex64': 'complex_float',
'complex128': 'complex_double'
}
""" Possible dptypes for spaces and c equivalents """
compatible_dtypes = { # name: (tuple of compatible dtypes)
'float32': ('float32', 'complex64'),
'float64': ('float64', 'complex128'),
'complex64': ('complex64',),
'complex128': ('complex128',),
}
""" Compatibility between basis and result types """
# Describes available spaces and their wrapper implementation.
# Most of the characteristics (barycentric, dual...) are guessed later on.
# However, these characteristics can be specified here. The characteristics
# will be used in the actual space factories by the users.
# The default implementation is 'grid_only', eg a single constructor that takes
# a grid as its only argument.
spaces = {
'PiecewiseConstantScalarSpace': {
'doc': 'Space of piecewise constant scalar functions',
},
'PiecewiseConstantScalarSpaceBarycentric': {
'doc': 'Space of piecewise constant scalar functions',
},
'PiecewiseConstantDualGridScalarSpace': {
'doc': 'Space of piecewise constant scalar functions on the dual grid',
},
'PiecewiseLinearContinuousScalarSpace': {
'doc': 'Space of continuous, piecewise linear scalar functions',
},
'PiecewiseLinearDiscontinuousScalarSpace': {
'doc':
'Space of piecewise linear, possibly discontinuous, scalar functions',
},
'PiecewiseLinearDiscontinuousScalarSpaceBarycentric': {
'doc':
'Space of piecewise constant functions define on the dual grid',
'dual': True # According top the doxygen tag...
},
'PiecewisePolynomialContinuousScalarSpace': {
'doc':
'Space of continuous, piecewise polynomial scalar functions',
'implementation': 'polynomial'
}
}
# Guess implementation from class name
# Mostly means guessing wether space operates on the direct or dual grid,
# whether functions are continuous, whether they are constant, linear, or
# polynomial, etc. These facts are used later on in the actual space factory.
for key, description in spaces.items():
if 'implementation' not in description:
description['implementation'] = 'grid_only'
if 'header' not in description:
f = lambda x: x if x.islower() else '_' + x.lower()
description['header'] = 'bempp/space/%s.hpp' \
% (key[0].lower() + ''.join([f(u) for u in key[1:]]))
if 'scalar' not in description:
description['scalar'] = 'scalar' in key.lower()
if description['scalar'] and 'order' not in description:
if 'constant' in key.lower():
description['order'] = 'constant'
elif 'linear' in key.lower():
description['order'] = 'linear'
else:
description['order'] = 'polynomial'
if 'continuous' not in description:
description['continuous'] = 'discontinuous' not in key.lower()
if 'dual' not in description:
description['dual'] = 'dual' in key.lower()
if 'barycentric' not in description:
description['barycentric'] = 'barycentric' in key.lower()
|
# M0_C4 - Peak Volumes
def get_peak_volumes(volumes):
# Write your code here
return "not implemented"
#### DO NOT TOUCH CODE BELOW THIS LINE ####
if __name__ == '__main__':
"""This code is for manual testing and is provided for your convenience."""
test_volumes = input("Input space-separated list of volumes: ")
converted = [int(a) for a in test_volumes.split()]
print(get_peak_volumes(converted))
|
#Algorithm Case Study
def naive(a,b):
x=a; y=b
z =0
while(x > 0):
z = z+y
x = x-1
return z
def testnaive():
i=0
while(i < 10):
j=0
while(j < 10):
print(i,j)
print(naive(i,j))
j += 1
i += 1
if __name__ == "__main__":
testnaive()
|
"""
Entradas
dia-->int
mes-->int
Salidas
singno zodiacal-->float
"""
dia = int (input ('Digite el numero de dia: '))
mes = int (input ("Digite el numero de mes: "))
if (dia>=21 and mes==3) or (dia<=20 and mes==4):
print ('Aries')
if (dia>=24 and mes==9) or (dia<=23 and mes==10):
print ('Libra')
if (dia>=21 and mes==4) or (dia<=21 and mes==5):
print ('Tauro')
if (dia>=24 and mes==10) or (dia<=22 and mes==11):
print ('Escorpio')
if (dia>=22 and mes==5) or (dia<=21 and mes==6):
print ('Geminis')
if (dia>=23 and mes==11) or (dia<=21 and mes==12):
print ('Sagitario')
if (dia>=21 and mes==6) or (dia<=23 and mes==7):
print ('Cancer')
if (dia>=22 and mes==12) or (dia<=20 and mes==1):
print ('Capricornio')
if (dia>=24 and mes==7) or (dia<=23 and mes==8):
print ('Leo')
if (dia>=21 and mes==1) or (dia<=19 and mes==2):
print ('Acuario')
if (dia>=24 and mes==8) or (dia<=23 and mes==9):
print ('Virgo')
if (dia>=20 and mes==2) or (dia<=20 and mes==3):
print ('Piscis')
print () |
capacity = int(input())
income = 0
command = input()
while command != "Movie time!":
group_count = int(command)
if group_count > capacity:
print("The cinema is full.")
print(f"Cinema income - {income} lv.")
exit()
capacity -= group_count
group_tax = group_count * 5
if group_count % 3 == 0:
group_tax -= 5
income += group_tax
command = input()
print(f"There are {capacity} seats left in the cinema.")
print(f"Cinema income - {income} lv.")
|
#pretty print method
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
|
# -*- coding: utf-8 -*-
# This work is licensed under the MIT License.
# To view a copy of this license, visit https://www.gnu.org/licenses/
# Written by Taher Abbasi
# Email: [email protected]
class WrongSide(Exception):
pass |
skywater_metal1 = {"layer": 68, "datatype": 20 }
skywater_metal2 = {"layer": 69, "datatype": 20 }
skywater_metal3 = {"layer": 70, "datatype": 20 }
skywater_metal4 = {"layer": 71, "datatype": 20 }
skywater_metal5 = {"layer": 72, "datatype": 20 }
|
rc = 0
def setup():
size(600, 600)
smooth()
background(0)
font = loadFont("Gadugi-Bold-48.vlw")
textFont(font, 48)
def draw():
global rc
translate(width/2, height/2)
pushMatrix()
rotate(rc)
fill(255)
text("Black", mouseX - width/4, mouseY - height/4)
popMatrix()
pushMatrix()
rotate(-rc * 1.5)
fill(0)
text("White", width/4 - mouseX, height/4 - mouseY)
popMatrix()
rc += 0.05
|
"""
Hamming Numbers
URL: https://www.codewars.com/kata/526d84b98f428f14a60008da/python
A Hamming number is a positive integer of the form 2^i, 3^j, 5^k,
for some non-negative integers i, j, and k.
Write a function that computes the nth smallest Hamming number.
Specifically:
The first smallest Hamming number is 1 = 2^0 * 3^0 * 5^0
The second smallest Hamming number is 2 = 2^1 * 3^0 * 5^0
The third smallest Hamming number is 3 = 2^0 * 3^1 * 5^0
The fourth smallest Hamming number is 4 = 2^2 * 3^0 * 5^0
The fifth smallest Hamming number is 5 = 2^0 * 3^0 * 5^1
Your code should be able to compute all of the smallest 5,000
Hamming numbers without timing out.
----------------------------------------------------------------
From research, Hamming Numbers are the same as Natural Numbers,
which are described on Wikipedia here:
https://en.wikipedia.org/wiki/Regular_number
This article contains a section on algorithms:
Algorithms for calculating the regular numbers in ascending order were
popularized by Edsger Dijkstra. Dijkstra attributes to Hamming the
problem of building the infinite ascending sequence of all 5-smooth
numbers; this problem is now known as Hamming's problem, and the
numbers so generated are also called the Hamming numbers.
Dijkstra's ideas to compute these numbers are the following:
1) The sequence of Hamming numbers begins with the number 1.
2) The remaining values in the sequence are of the form 2h, 3h,
and 5h, where h is any Hamming number.
Therefore, the sequence H may be generated by outputting the value 1,
and then merging the sequences 2H, 3H, and 5H.
This algorithm is often used to demonstrate the power of a lazy
functional programming language, because (implicitly) concurrent
efficient implementations, using a constant number of arithmetic
operations per generated value, are easily constructed as described
above.
...
In the Python programming language, lazy functional code for generating
regular numbers is used as one of the built-in tests for correctness
of the language's implementation (it implements a lazy list). I
don't understand generators well enough to solve the problem this
way, so I'm going to try and get by with what I do know...
"""
hammings = [1]
#version 2 will try to remember where we put the lowest 'new'
#Hamming and only start from there
#version 3 uses set() and list sorting to beat extendHamming()!
last_good_index = 0
def hamming_v1(n):
global hammings
index = 0
for h in hammings:
index += 1
if index == n:
return hammings[n-1]
extendHamming(hammings, 2*h)
extendHamming(hammings, 3*h)
extendHamming(hammings, 5*h)
def hamming_v2(n):
global hammings
global last_good_index
index = last_good_index
if n-1 < index:
return hammings[n-1]
else:
for h in hammings[last_good_index:]:
index += 1
if index == n:
last_good_index = n
return hammings[n-1]
extendHamming(hammings, 2*h)
extendHamming(hammings, 3*h)
extendHamming(hammings, 5*h)
def hamming_v3(n):
global last_good_index
global hammings
index = last_good_index
if n-1 < index:
return hammings[n-1]
else:
while True:
h = hammings[index]
index += 1
if index == n:
last_good_index = n-1
return hammings[n-1]
hammings = sorted(set(hammings).update([2*h, 3*h, 5*h]))
def extendHamming(hammings, new_hamming):
if new_hamming not in hammings:
#insert the new number in the correct place
for j in range(len(hammings), 0, -1):
if hammings[j-1] < new_hamming:
hammings.insert(j, new_hamming)
return
print(hamming_v1(7)) # 8
print(hamming_v1(12)) # 16
print(hamming_v1(20)) # 36
print(hamming_v1(100)) # 1536
print(hamming_v1(1000)) # 51200000
print(hamming_v1(777)) # 10628820
print(hamming_v1(77)) # 729
print(hamming_v1(7)) # 8
print(hamming_v2(7))
print(hamming_v2(12))
print(hamming_v2(20))
print(hamming_v2(100))
print(hamming_v2(1000))
print(hamming_v2(777))
print(hamming_v2(77))
print(hamming_v2(7))
print(hamming_v3(7))
print(hamming_v3(12))
print(hamming_v3(20))
print(hamming_v3(100))
print(hamming_v3(1000))
print(hamming_v3(777))
print(hamming_v3(77))
print(hamming_v3(7))
|
class MessagesSerializer:
fields = ['id', 'topic', 'payload', 'attributes', 'bulk']
def serialize(self, messages):
return [self._serialize_fields(message) for message in messages]
def _serialize_fields(self, message):
return {field: getattr(message, field, None) for field in self.fields}
|
# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date: 2018-09-01 22:04:38
# @Last Modified by: Anderson
# @Last Modified time: 2018-09-14 15:55:53
class DS(object):
def __init__(self, N):
self.__id = list(range(0, N))
def is_connected(self, parent, child):
pid = ord(parent) - ord('A')
cid = ord(child) - ord('A')
connected = False
generation_count = 0
while not connected:
generation_count += 1
pid = self.__id[pid]
if pid == cid:
connected = True
elif pid == self.__id[pid]:
break
if connected:
result = 'child'
if generation_count > 1:
result = 'grandchild'
if generation_count > 2:
for _ in range(2, generation_count):
result = 'great-' + result
return result
else:
return '-'
def connect(self, parent, child):
if parent != '-':
self.__id[ord(parent)-ord('A')] = ord(child)-ord('A')
s = input()
n, m = s.split(' ')
n = int(n)
m = int(m)
ds = DS(26)
for _ in range(n):
child, father, mother = input()
ds.connect(father, child)
ds.connect(mother, child)
for _ in range(m):
a, b = input()
if a == b:
print('-')
else:
result = ds.is_connected(b, a)
if result == '-':
result = ds.is_connected(a, b)
result = result.replace('child', 'parent')
print(result)
|
#
# PySNMP MIB module Juniper-IPV6-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IPV6-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:03:09 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, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InetAddressIPv6, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressIPv6")
Ipv6AddressPrefix, = mibBuilder.importSymbols("IPV6-TC", "Ipv6AddressPrefix")
juniMibs, = mibBuilder.importSymbols("Juniper-MIBs", "juniMibs")
JuniName, JuniSetMap, JuniEnable = mibBuilder.importSymbols("Juniper-TC", "JuniName", "JuniSetMap", "JuniEnable")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, ModuleIdentity, Unsigned32, Counter32, NotificationType, Bits, ObjectIdentity, Gauge32, TimeTicks, IpAddress, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "ModuleIdentity", "Unsigned32", "Counter32", "NotificationType", "Bits", "ObjectIdentity", "Gauge32", "TimeTicks", "IpAddress", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
juniIpv6ProfileMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68))
juniIpv6ProfileMIB.setRevisions(('2007-07-19 18:19', '2003-09-29 17:58',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setRevisionsDescriptions(('Added ND support on dynamic interface.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setLastUpdated('200707191819Z')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setOrganization('Juniper Networks')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford MA 01886-3146 USA Tel: +1 978 589 5800 Email: [email protected]')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setDescription('The IPv6 Profile MIB for the Juniper Networks enterprise.')
juniIpv6ProfileObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1))
juniIpv6Profile = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1))
juniIpv6ProfileTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1), )
if mibBuilder.loadTexts: juniIpv6ProfileTable.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileTable.setDescription('The entries in this table describe profiles for configuring IP interfaces. Entries in this table are created/deleted as a side-effect of corresponding operations to the juniProfileNameTable in the Juniper-PROFILE-MIB.')
juniIpv6ProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1), ).setIndexNames((0, "Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileId"))
if mibBuilder.loadTexts: juniIpv6ProfileEntry.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileEntry.setDescription('A profile describing configuration of an IPv6 interface.')
juniIpv6ProfileId = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: juniIpv6ProfileId.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileId.setDescription('The integer identifier associated with this profile. A value for this identifier is determined by locating or creating a profile name in the juniProfileNameTable.')
juniIpv6ProfileSetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 2), JuniSetMap()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileSetMap.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileSetMap.setDescription("A bitmap representing which objects in this entry have been explicitly configured. See the definition of the JuniSetMap TEXTUAL-CONVENTION for details of use. The INDEX object(s) and this object are excluded from representation (i.e. their bits are never set). When a SET request does not explicitly configure JuniSetMap, bits in JuniSetMap are set as a side-effect of configuring other profile attributes in the same entry. If, however, a SET request explicitly configures JuniSetMap, the explicitly configured value overrides 1) any previous bit settings, and 2) any simultaneous 'side-effect' settings that would otherwise occur. Once set, bits can only be cleared by explicitly configuring JuniSetMap.")
juniIpv6ProfileRouterName = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 3), JuniName()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileRouterName.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileRouterName.setDescription('The virtual router to which an IPv6 interface configured by this profile will be assigned, if other mechanisms do not otherwise specify a virtual router assignment.')
juniIpv6ProfileIpv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 4), InetAddressIPv6().clone(hexValue="00000000000000000000000000000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileIpv6Addr.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileIpv6Addr.setDescription('An IPv6 address to be used by an IPv6 interface configured by this profile. This object will have a value of 0::0 for an unnumbered interface.')
juniIpv6ProfileIpv6MaskLen = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileIpv6MaskLen.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileIpv6MaskLen.setDescription('An IPv6 address mask length to be used by an IPv6 interface configured by this profile. This object will have a value of 0 for an unnumbered interface.')
juniIpv6ProfileMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1280, 10240), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileMtu.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileMtu.setDescription('The configured MTU size for this IPv6 network interface. If set to zero, the default MTU size, as determined by the underlying network media, is used.')
juniIpv6ProfileSrcAddrValidEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 7), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileSrcAddrValidEnable.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileSrcAddrValidEnable.setDescription('Enable/disable whether source addresses in received IPv6 packets are validated. Validation is performed by looking up the source IPv6 address in the routing database and determining whether the packet arrived on the expected interface; if not, the packet is discarded.')
juniIpv6ProfileInheritNumString = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileInheritNumString.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileInheritNumString.setDescription("The text identifier of the numbered interface, associated with the specified virtual router, whose IPv6 address is used as the source address when transmitting IPv6 packets on unnumbered remote access user links. Types/formats/examples for this string include: Loopback loopback <id> 'loopback 0' ATM Virtual Circuit atm <slot>/<port>.<distinguisher> 'atm 3/1.100' Ethernet { fastEthernet | gigabitEthernet } <slot>/<port> 'fastEthernet 3/0' 'gigabitEthernet 3/0' Ethernet VLAN { fastEthernet | gigabitEthernet } <slot>/<port>:<vlanID> 'fastEthernet 3/0:1000' 'gigabitEthernet 3/0:1000' Channelized Serial serial <slot>/<port>:<channelSpecifier>[/<channelSpecifier>]* 'serial 3/0:4' (T1/E1) 'serial 3/0:2/4' (T3/E3) 'serial 3/0:2/1/1/4' (OC3/OC12 - channelized DS3) 'serial 3/0:2/1/1/1/4' (OC3/OC12 - virtual tributaries) Other formats may be supported over time. An empty string indicates the referenced interface is unspecified, e.g., when this IPv6 interface is numbered.")
juniIpv6ProfileNdEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 9), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdEnabled.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdEnabled.setDescription('Enable/disable ND for this IPv6 network interface.')
juniIpv6ProfileNdManagedConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 10), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdManagedConfig.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdManagedConfig.setDescription('Enable/disable ND managed config for this IPv6 network interface.')
juniIpv6ProfileNdOtherConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 11), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdOtherConfig.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdOtherConfig.setDescription('Enable/disable ND other config for this IPv6 network interface.')
juniIpv6ProfileNdSuppressRa = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 12), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdSuppressRa.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdSuppressRa.setDescription('Enable/disable ND suppress RA for this IPv6 network interface.')
juniIpv6ProfileNdRaInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 1800)).clone(200)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdRaInterval.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdRaInterval.setDescription('The configured interval between IPv6 RA transmissions on the interface.')
juniIpv6ProfileNdRaLifeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1800)).clone(1800)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdRaLifeTime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdRaLifeTime.setDescription('The configured RA lifetime for this IPv6 network interface.')
juniIpv6ProfileNdReachableTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 15), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdReachableTime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdReachableTime.setDescription('The configured RA reachable time for this IPv6 network interface.')
juniIpv6ProfileNdPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 16), Ipv6AddressPrefix()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefix.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefix.setDescription('The prefix associated with the this interface.')
juniIpv6ProfileNdPrefixLength = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixLength.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixLength.setDescription('The length of the prefix (in bits).')
juniIpv6ProfileNdPrefixOnLinkFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 18), JuniEnable().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixOnLinkFlag.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixOnLinkFlag.setDescription("This object has the value 'true(1)', if this prefix can be used for on-link determination and the value 'false(2)' otherwise.")
juniIpv6ProfileNdPrefixAutonomousFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 19), JuniEnable().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixAutonomousFlag.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixAutonomousFlag.setDescription('Autonomous address configuration flag. When true(1), indicates that this prefix can be used for autonomous address configuration (i.e. can be used to form a local interface address). If false(2), it is not used to autoconfigure a local interface address.')
juniIpv6ProfileNdPrefixPreferredLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 20), Integer32().clone(604800)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixPreferredLifetime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixPreferredLifetime.setDescription('It is the length of time in seconds that this prefix will remain preferred, i.e. time until deprecation. A value of 4,294,967,295 represents infinity. The address generated from a deprecated prefix should no longer be used as a source address in new communications, but packets received on such an interface are processed as expected.')
juniIpv6ProfileNdPrefixValidLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 21), Integer32().clone(2592000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixValidLifetime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixValidLifetime.setDescription('It is the length of time in seconds that this prefix will remain valid, i.e. time until invalidation. A value of 4,294,967,295 represents infinity. The address generated from an invalidated prefix should not appear as the destination or source address of a packet.')
juniIpv6ProfileMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4))
juniIpv6ProfileMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1))
juniIpv6ProfileMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2))
juniIpv6ProfileCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 1)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileCompliance = juniIpv6ProfileCompliance.setStatus('obsolete')
if mibBuilder.loadTexts: juniIpv6ProfileCompliance.setDescription('Obsolete Compliance statement for systems supporting IPv6 configuration profiles. This statement became obsolete when added ND support.')
juniIpv6ProfileCompliance1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 2)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileGroup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileCompliance1 = juniIpv6ProfileCompliance1.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileCompliance1.setDescription('Compliance statement for systems supporting IPv6 configuration profiles, incorporating support of ND on dynamical interface.')
juniIpv6ProfileGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 1)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSetMap"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileRouterName"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6Addr"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6MaskLen"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileMtu"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSrcAddrValidEnable"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileInheritNumString"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileGroup = juniIpv6ProfileGroup.setStatus('obsolete')
if mibBuilder.loadTexts: juniIpv6ProfileGroup.setDescription('An obsolete collection of objects providing management of IPv6 Profile functionality in a Juniper product. This statement became obsolete when added ND support.')
juniIpv6ProfileGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 2)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSetMap"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileRouterName"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6Addr"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6MaskLen"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileMtu"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSrcAddrValidEnable"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileInheritNumString"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdEnabled"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdManagedConfig"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdOtherConfig"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdSuppressRa"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdRaInterval"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdRaLifeTime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdReachableTime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefix"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixLength"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixOnLinkFlag"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixAutonomousFlag"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixPreferredLifetime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixValidLifetime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileGroup1 = juniIpv6ProfileGroup1.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileGroup1.setDescription('The basic collection of objects providing management of IPv6 Profile functionality in a Juniper product.')
mibBuilder.exportSymbols("Juniper-IPV6-PROFILE-MIB", juniIpv6Profile=juniIpv6Profile, juniIpv6ProfileSrcAddrValidEnable=juniIpv6ProfileSrcAddrValidEnable, juniIpv6ProfileGroup=juniIpv6ProfileGroup, juniIpv6ProfileNdSuppressRa=juniIpv6ProfileNdSuppressRa, juniIpv6ProfileIpv6MaskLen=juniIpv6ProfileIpv6MaskLen, juniIpv6ProfileObjects=juniIpv6ProfileObjects, juniIpv6ProfileNdPrefixPreferredLifetime=juniIpv6ProfileNdPrefixPreferredLifetime, juniIpv6ProfileCompliance1=juniIpv6ProfileCompliance1, juniIpv6ProfileNdPrefixValidLifetime=juniIpv6ProfileNdPrefixValidLifetime, juniIpv6ProfileNdPrefixLength=juniIpv6ProfileNdPrefixLength, juniIpv6ProfileMIB=juniIpv6ProfileMIB, juniIpv6ProfileNdPrefix=juniIpv6ProfileNdPrefix, juniIpv6ProfileGroup1=juniIpv6ProfileGroup1, juniIpv6ProfileIpv6Addr=juniIpv6ProfileIpv6Addr, juniIpv6ProfileNdRaLifeTime=juniIpv6ProfileNdRaLifeTime, juniIpv6ProfileTable=juniIpv6ProfileTable, juniIpv6ProfileNdOtherConfig=juniIpv6ProfileNdOtherConfig, juniIpv6ProfileNdPrefixOnLinkFlag=juniIpv6ProfileNdPrefixOnLinkFlag, juniIpv6ProfileMtu=juniIpv6ProfileMtu, juniIpv6ProfileMIBCompliances=juniIpv6ProfileMIBCompliances, juniIpv6ProfileNdEnabled=juniIpv6ProfileNdEnabled, juniIpv6ProfileMIBConformance=juniIpv6ProfileMIBConformance, juniIpv6ProfileInheritNumString=juniIpv6ProfileInheritNumString, juniIpv6ProfileNdPrefixAutonomousFlag=juniIpv6ProfileNdPrefixAutonomousFlag, juniIpv6ProfileMIBGroups=juniIpv6ProfileMIBGroups, juniIpv6ProfileCompliance=juniIpv6ProfileCompliance, juniIpv6ProfileSetMap=juniIpv6ProfileSetMap, juniIpv6ProfileNdReachableTime=juniIpv6ProfileNdReachableTime, juniIpv6ProfileId=juniIpv6ProfileId, juniIpv6ProfileNdRaInterval=juniIpv6ProfileNdRaInterval, PYSNMP_MODULE_ID=juniIpv6ProfileMIB, juniIpv6ProfileRouterName=juniIpv6ProfileRouterName, juniIpv6ProfileEntry=juniIpv6ProfileEntry, juniIpv6ProfileNdManagedConfig=juniIpv6ProfileNdManagedConfig)
|
r'''
Copyright 2015 Google Inc. 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 law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
class TlsNotEnoughDataError(Exception):
"""Error in TLS parsing where the TLS record is so far valid but incomplete"""
pass
class TlsRecordIncompleteError(TlsNotEnoughDataError):
"""Error for when a TLS Record appears valid but is not enough data is present to parse
the record"""
def __init__(self, data_available, record_size):
self.data_available = data_available
self.record_size = record_size
class TlsMessageFragmentedError(TlsNotEnoughDataError):
"""Error for when not enough data is present to parse a TLS message because of
fragmentation"""
def __init__(self, fragment_data, data_consumed):
self.fragment_data = fragment_data
self.data_consumed = data_consumed
|
print("My name is Jessica Bonnie Ayomide")
print("JJJJJJJJJJJJJ BBBBBBBBBB A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J BBBBBBBBBB AAAAAAAAAA")
print(" J B B A A")
print(" J B B A A")
print("J J B B A A")
print(" J J B B A A")
print(" JJJJJ BBBBBBBBBB A A")
|
#!/usr/bin/env python3
def main():
arr = []
fname = sys.argv[1]
with open(fname, 'r') as f:
for line in f:
arr.append(int(line.rstrip('\r\n')))
quicksort(arr, start=0, end=len(arr)-1)
print('Sorted list is: ', arr)
return
def quicksort(arr, start, end):
if end - start < 1:
return 0
b = start + 1
for i in range(start+1, end):
if arr[i] <= arr[start]:
arr[b], arr[i] = arr[i], arr[b]
b += 1
arr[start], arr[b-1] = arr[b-1], arr[start]
quicksort(arr, start, b-1)
quicksort(arr, b, end)
if __name__ == '__main__':
main()
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"test_eq": "00_core.ipynb",
"listify": "00_core.ipynb",
"test_in": "00_core.ipynb",
"test_err": "00_core.ipynb",
"configure_logging": "00_core.ipynb",
"setup_dataframe_copy_logging": "00_core.ipynb",
"n_total_series": "00_core.ipynb",
"n_days_total": "00_core.ipynb",
"raw_dir": "00_core.ipynb",
"read_series_sample": "00_core.ipynb",
"melt_sales_series": "00_core.ipynb",
"extract_day_ids": "00_core.ipynb",
"join_w_calendar": "00_core.ipynb",
"join_w_prices": "00_core.ipynb",
"to_parquet": "00_core.ipynb",
"extract_id_columns": "00_core.ipynb",
"get_submission_template_melt": "00_core.ipynb",
"ParquetIterableDataset": "01_petastorm.ipynb",
"prepare_data_on_disk": "02_pipeline.ipynb"}
modules = ["core.py",
"petastorm.py",
"pipeline.py"]
doc_url = "https://cluePrints.github.io/kaggle-m5-nbdev/"
git_url = "https://github.com/cluePrints/kaggle-m5-nbdev/tree/master/"
def custom_doc_links(name): return None
|
# -*- coding: utf-8 -*-
"""@package Methods.Machine.SlotWind.comp_surface_wind
Slot Winding Computation of surface (Numerical) method
@date Created on Wed Jul 25 14:22:33 2018
@copyright (C) 2014-2015 EOMYS ENGINEERING.
@author pierre_b
"""
def comp_surface_wind(self):
"""Compute the Slot winding surface (by numerical computation).
Caution, the bottom of the Slot is an Arc
Parameters
----------
self : SlotWind
A SlotWind object
Returns
-------
S: float
Slot total surface [m**2]
"""
surf = self.build_geometry_wind(Nrad=1, Ntan=1)
return surf[0].comp_surface()
|
# code
'''python'''
class Solution(object):
def lengthOfLastWord(self, s):
self.s=s
string = self.s.strip().split(' ')[-1]
return len(string)
|
def clean_sentence(output, data_loader):
start_word = data_loader.dataset.vocab.start_word
end_word = data_loader.dataset.vocab.end_word
unk_word = data_loader.dataset.vocab.unk_word
words = []
for i in range(len(output)):
word_idx = output[i]
word = data_loader.dataset.vocab.idx2word.get(word_idx)
if word == end_word:
break
#elif word != start_word and word != unk_word:
elif word != unk_word:
words.append(word)
return " ".join(words)
|
#
# PySNMP MIB module TPLINK-SSH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-SSH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:53 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, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, ModuleIdentity, iso, Gauge32, Unsigned32, IpAddress, Bits, Counter32, NotificationType, ObjectIdentity, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "ModuleIdentity", "iso", "Gauge32", "Unsigned32", "IpAddress", "Bits", "Counter32", "NotificationType", "ObjectIdentity", "TimeTicks", "Integer32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt")
tplinkSshMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 5))
tplinkSshMIB.setRevisions(('2012-12-13 09:30',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: tplinkSshMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: tplinkSshMIB.setLastUpdated('201212130930Z')
if mibBuilder.loadTexts: tplinkSshMIB.setOrganization('TPLINK')
if mibBuilder.loadTexts: tplinkSshMIB.setContactInfo('www.tplink.com.cn')
if mibBuilder.loadTexts: tplinkSshMIB.setDescription('Private MIB for SSH configuration.')
tplinkSshMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1))
tplinkSshNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 2))
tpSshEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEnable.setDescription('0. disable 1. enable')
tpSshProtocolV1Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshProtocolV1Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshProtocolV1Enable.setDescription('0. disable 1. enable')
tpSshProtocolV2Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshProtocolV2Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshProtocolV2Enable.setDescription('0. disable 1. enable')
tpSshQuietPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 120))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshQuietPeriod.setStatus('current')
if mibBuilder.loadTexts: tpSshQuietPeriod.setDescription('quiet period(1-120 second)')
tpSshMaxConnections = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshMaxConnections.setStatus('current')
if mibBuilder.loadTexts: tpSshMaxConnections.setDescription('max connection(1-5)')
tpSshEncryptAlgAES128Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES128Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES128Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgAES192Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES192Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES192Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgAES256Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES256Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES256Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgBlowfishEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgBlowfishEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgBlowfishEnable.setDescription('0. disable 1. enable')
tpSshEncryptAlgCast128Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgCast128Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgCast128Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlg3DESEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlg3DESEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlg3DESEnable.setDescription('0. disable 1. enable')
tpSshInteAlgSHA1Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshInteAlgSHA1Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshInteAlgSHA1Enable.setDescription('0. disable 1. enable')
tpSshInteAlgMD5Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshInteAlgMD5Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshInteAlgMD5Enable.setDescription('0. disable 1. enable')
mibBuilder.exportSymbols("TPLINK-SSH-MIB", tpSshEncryptAlgCast128Enable=tpSshEncryptAlgCast128Enable, tplinkSshMIBObjects=tplinkSshMIBObjects, tpSshEncryptAlgBlowfishEnable=tpSshEncryptAlgBlowfishEnable, tpSshEncryptAlgAES128Enable=tpSshEncryptAlgAES128Enable, tpSshProtocolV2Enable=tpSshProtocolV2Enable, tpSshMaxConnections=tpSshMaxConnections, tpSshInteAlgMD5Enable=tpSshInteAlgMD5Enable, tpSshProtocolV1Enable=tpSshProtocolV1Enable, tpSshEncryptAlg3DESEnable=tpSshEncryptAlg3DESEnable, PYSNMP_MODULE_ID=tplinkSshMIB, tplinkSshNotifications=tplinkSshNotifications, tpSshInteAlgSHA1Enable=tpSshInteAlgSHA1Enable, tplinkSshMIB=tplinkSshMIB, tpSshEncryptAlgAES192Enable=tpSshEncryptAlgAES192Enable, tpSshEncryptAlgAES256Enable=tpSshEncryptAlgAES256Enable, tpSshEnable=tpSshEnable, tpSshQuietPeriod=tpSshQuietPeriod)
|
REGULAR_MARGIN_REQUIREMENT = 0.25
LEVERAGED_MARGIN_REQUIREMENT = 0.75
def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop,
percentage_of_regular_drop, current_loan):
leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop)
regular_value_after_drop = regular_value * (1 - percentage_of_regular_drop)
leveraged_margin_impact = (1 - LEVERAGED_MARGIN_REQUIREMENT) * leveraged_value_after_drop
regular_margin_impact = (1 - REGULAR_MARGIN_REQUIREMENT) * regular_value_after_drop
return (leveraged_margin_impact + regular_margin_impact -
current_loan) / (1 - (1 - REGULAR_MARGIN_REQUIREMENT) *
(1 - percentage_of_regular_drop))
def main():
return max_margin(20000, 10000, 0.6, 0.5, 0)
if __name__ == '__main__':
print(main())
|
def trans_char_number(text, q2b=True):
table = {ord(u'\uff41'): ord('a'), ord(u'\uff42'): ord('b'), ord(u'\uff43'): ord('c'), ord(u'\uff44'): ord('d'),
ord(u'\uff45'): ord('e'), ord(u'\uff46'): ord('f'), ord(u'\uff47'): ord('g'), ord(u'\uff48'): ord('h'),
ord(u'\uff49'): ord('i'), ord(u'\uff47'): ord('j'), ord(u'\uff4b'): ord('k'), ord(u'\uff4c'): ord('l'),
ord(u'\uff4d'): ord('m'), ord(u'\uff4e'): ord('n'), ord(u'\uff4f'): ord('o'), ord(u'\uff50'): ord('p'),
ord(u'\uff51'): ord('q'), ord(u'\uff52'): ord('r'), ord(u'\uff53'): ord('s'), ord(u'\uff54'): ord('t'),
ord(u'\uff55'): ord('u'), ord(u'\uff56'): ord('v'), ord(u'\uff57'): ord('w'), ord(u'\uff58'): ord('x'),
ord(u'\uff59'): ord('y'), ord(u'\uff5a'): ord('z'),
ord(u'\uff21'): ord('A'), ord(u'\uff22'): ord('B'), ord(u'\uff23'): ord('C'), ord(u'\uff24'): ord('D'),
ord(u'\uff25'): ord('E'), ord(u'\uff26'): ord('F'), ord(u'\uff27'): ord('G'), ord(u'\uff28'): ord('H'),
ord(u'\uff29'): ord('I'), ord(u'\uff2a'): ord('J'), ord(u'\uff2b'): ord('K'), ord(u'\uff2c'): ord('L'),
ord(u'\uff2d'): ord('M'), ord(u'\uff2e'): ord('N'), ord(u'\uff2f'): ord('O'), ord(u'\uff30'): ord('P'),
ord(u'\uff31'): ord('K'), ord(u'\uff32'): ord('R'), ord(u'\uff33'): ord('S'), ord(u'\uff35'): ord('T'),
ord(u'\uff35'): ord('U'), ord(u'\uff36'): ord('V'), ord(u'\uff37'): ord('W'), ord(u'\uff38'): ord('X'),
ord(u'\uff39'): ord('Y'), ord(u'\uff3a'): ord('Z'),
ord(u'\uff11'): ord('1'), ord(u'\uff12'): ord('2'), ord(u'\uff13'): ord('3'), ord(u'\uff14'): ord('4'),
ord(u'\uff15'): ord('5'), ord(u'\uff16'): ord('6'), ord(u'\uff17'): ord('7'), ord(u'\uff18'): ord('8'),
ord(u'\uff19'): ord('9'), ord(u'\uff10'): ord('0')
}
if not q2b:
table = {v: k for k, v in table.items()}
return text.translate(table)
def trans_punc(text, ch2en=False):
E_pun = u',.!?[]()<>"\''
C_pun = u',。!?【】()《》“‘'
table = {ord(f): ord(t) for f, t in zip(E_pun, C_pun)}
if ch2en:
table = {v: k for k, v in table.items()}
return text.translate(table)
|
class Node:
def __init__(self, idx):
self.idx = idx
self.out = set() # zbiór sąsiadów
def connect_to(self, v):
self.out.add(v)
def lex_bfs(graph):
lex_order = [1]
lex_unvisited_list = []
first_vertex_neighbours = set()
others = set()
for i in range(2, len(graph)):
if i in graph[1].out:
first_vertex_neighbours.add(i)
else:
others.add(i)
if others:
lex_unvisited_list.append(others)
if first_vertex_neighbours:
lex_unvisited_list.append(first_vertex_neighbours)
while lex_unvisited_list:
vertex = lex_unvisited_list[-1].pop()
lex_order.append(vertex)
if not lex_unvisited_list[-1]:
lex_unvisited_list.pop(-1)
new_lex_unvisited_list = []
for i in range(len(lex_unvisited_list)):
vertex_neigbours = set()
others = set()
while lex_unvisited_list[i]:
unvisited_vertex = lex_unvisited_list[i].pop()
if unvisited_vertex in graph[vertex].out:
vertex_neigbours.add(unvisited_vertex)
else:
others.add(unvisited_vertex)
if others:
new_lex_unvisited_list.append(others)
if vertex_neigbours:
new_lex_unvisited_list.append(vertex_neigbours)
lex_unvisited_list = new_lex_unvisited_list
return lex_order
|
class Solution:
def __init__(self):
pass
# o(mn)
def print_lcs(self, str1, str2):
m = len(str1)
n = len(str2)
if n == 0 or m == 0:
return 0
# declare an two dimension array store calculated dp value of lcs(str1[i]
R = [[None] * (n + 1) for i in xrange(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
R[i][j] = 0
elif str1[i - 1] == str2[j - 1]:
R[i][j] = 1 + R[i - 1][j - 1]
else:
R[i][j] = max(R[i - 1][j], R[i][j - 1])
lcs = []
i = m
j = n
while i > 0 and j > 0:
if str1[i - 1] == str2[j - 1]:
lcs.insert(0, str1[i - 1])
i -= 1
j -= 1
elif R[i - 1][j] > R[i][j - 1]:
i -= 1
else:
j -= 1
return lcs
str1 = 'AGGTAB';
str2 = 'GXTXAYB';
# print(Solution().longest_sub_sequence(str1, str2, len(str1), len(str2)));
print(Solution().print_lcs(str1, str2))
|
lines = None
with open('day07/input.txt') as f:
lines = f.readlines()
line = lines[0]
arr = list(map(lambda s: int(s), line.split(",")))
cost = []
prev = 0
q = 0
for i in range(2000):
cost.append(prev + q)
prev = prev + q
q += 1
min = 99999999999999
for pos in range(1500):
sum = 0
for x in arr:
sum += cost[abs(x - pos)]
if sum < min: min = sum
print(min)
|
target = "xilinx"
action = "synthesis"
syn_device = "xc7k325t"
syn_grade = "-2"
syn_package = "ffg900"
syn_top = "cm0_busy_wait_top"
syn_project = "cm0_busy_wait_top"
syn_tool = "vivado"
modules = {
"local" : [ "../../../top/kc705_busy_wait/verilog" ],
}
|
class DataObject:
def __init__(self, read_data=True):
if read_data:
self._run_methods('read')
self._run_methods('parse')
def _run_methods(self, method_type):
for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]:
getattr(self, method)()
def get_data(self):
raise NotImplementedError
|
def sumUpNumbers(inputString):
numbers = []
curr = ""
for i in inputString:
try:
x = int(i)
curr += i
except:
if curr != "":
numbers.append(curr)
curr = ""
if curr != "":
numbers.append(curr)
return sum([int(x) for x in numbers])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.