content stringlengths 7 1.05M |
|---|
def file_name_for_format(file_format):
names = {
'json': 'data',
'xlsx': 'catalog'
}
file_name = names[file_format]
return file_name
|
def main(request, response):
location = request.GET.first(b"location")
if request.method == u"OPTIONS":
if b"redirect_preflight" in request.GET:
response.status = 302
response.headers.set(b"Location", location)
else:
response.status = 200
response.headers.set(b"Access-Control-Allow-Methods", b"GET")
response.headers.set(b"Access-Control-Max-Age", 1)
elif request.method == u"GET":
response.status = 302
response.headers.set(b"Location", location)
if b"allow_origin" in request.GET:
response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin"))
if b"allow_header" in request.GET:
response.headers.set(b"Access-Control-Allow-Headers", request.GET.first(b"allow_header"))
|
# set random number generator
np.random.seed(2020)
# initialize step_end, t_range, v and syn
step_end = int(t_max / dt)
t_range = np.linspace(0, t_max, num=step_end)
v = el * np.ones(step_end)
syn = i_mean * (1 + 0.1 * (t_max/dt) ** (0.5) * (2 * np.random.random(step_end) - 1))
# loop for step_end - 1 steps
for step in range(1, step_end):
v[step] = v[step - 1] + (dt / tau) * (el - v[step - 1] + r * syn[step])
with plt.xkcd():
# initialize the figure
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel(r'$V_m$ (V)')
plt.plot(t_range, v, 'k.')
plt.show() |
##Patterns: E0107
def test():
a = 1
##Err: E0107
++a
##Err: E0107
--a |
#
# PySNMP MIB module BIANCA-BRICK-OSPF-ERR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-OSPF-ERR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:21:24 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")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, iso, Bits, enterprises, ModuleIdentity, Unsigned32, Gauge32, ObjectIdentity, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, NotificationType, Counter64, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "iso", "Bits", "enterprises", "ModuleIdentity", "Unsigned32", "Gauge32", "ObjectIdentity", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "NotificationType", "Counter64", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
bintec = MibIdentifier((1, 3, 6, 1, 4, 1, 272))
bibo = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4))
biboip = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4, 5))
ospfErr = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4, 5, 11))
ospfErrOspfBadVersion = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadVersion.setStatus('mandatory')
ospfErrOspfBadPacketType = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadPacketType.setStatus('mandatory')
ospfErrOspfBadChecksum = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadChecksum.setStatus('mandatory')
ospfErrIpBadDestination = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrIpBadDestination.setStatus('mandatory')
ospfErrOspfBadAreaId = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadAreaId.setStatus('mandatory')
ospfErrOspfAuthenticationFailed = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfAuthenticationFailed.setStatus('mandatory')
ospfErrOspfUnknownNeighbor = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfUnknownNeighbor.setStatus('mandatory')
ospfErrHelloNetmaskMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloNetmaskMismatch.setStatus('mandatory')
ospfErrHelloDeadTimerMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloDeadTimerMismatch.setStatus('mandatory')
ospfErrHelloTimerMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloTimerMismatch.setStatus('mandatory')
ospfErrHelloOptionMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloOptionMismatch.setStatus('mandatory')
ospfErrOspfRouterIdConfusion = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfRouterIdConfusion.setStatus('mandatory')
ospfErrOspfUnknownLsaType = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfUnknownLsaType.setStatus('mandatory')
ospfErrDdOptionMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrDdOptionMismatch.setStatus('mandatory')
ospfErrDdNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrDdNeighborStateLow.setStatus('mandatory')
ospfErrLsackBadAck = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsackBadAck.setStatus('mandatory')
ospfErrLsackDuplicateAck = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsackDuplicateAck.setStatus('mandatory')
ospfErrLsreqBadRequest = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsreqBadRequest.setStatus('mandatory')
ospfErrLsreqNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsreqNeighborStateLow.setStatus('mandatory')
ospfErrLsupdNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdNeighborStateLow.setStatus('mandatory')
ospfErrLsupdBadLsaChecksum = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdBadLsaChecksum.setStatus('mandatory')
ospfErrLsupdNewerSelfgenLsa = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdNewerSelfgenLsa.setStatus('mandatory')
ospfErrLsupdLessRecentLsa = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdLessRecentLsa.setStatus('mandatory')
mibBuilder.exportSymbols("BIANCA-BRICK-OSPF-ERR-MIB", ospfErrLsupdBadLsaChecksum=ospfErrLsupdBadLsaChecksum, ospfErrOspfBadChecksum=ospfErrOspfBadChecksum, ospfErr=ospfErr, ospfErrHelloTimerMismatch=ospfErrHelloTimerMismatch, ospfErrOspfBadVersion=ospfErrOspfBadVersion, ospfErrOspfUnknownNeighbor=ospfErrOspfUnknownNeighbor, ospfErrOspfUnknownLsaType=ospfErrOspfUnknownLsaType, ospfErrOspfRouterIdConfusion=ospfErrOspfRouterIdConfusion, ospfErrLsackBadAck=ospfErrLsackBadAck, ospfErrLsupdNewerSelfgenLsa=ospfErrLsupdNewerSelfgenLsa, bibo=bibo, ospfErrLsreqNeighborStateLow=ospfErrLsreqNeighborStateLow, ospfErrLsreqBadRequest=ospfErrLsreqBadRequest, ospfErrDdOptionMismatch=ospfErrDdOptionMismatch, ospfErrLsupdNeighborStateLow=ospfErrLsupdNeighborStateLow, ospfErrLsackDuplicateAck=ospfErrLsackDuplicateAck, ospfErrOspfBadAreaId=ospfErrOspfBadAreaId, ospfErrLsupdLessRecentLsa=ospfErrLsupdLessRecentLsa, ospfErrHelloOptionMismatch=ospfErrHelloOptionMismatch, ospfErrOspfBadPacketType=ospfErrOspfBadPacketType, ospfErrHelloDeadTimerMismatch=ospfErrHelloDeadTimerMismatch, ospfErrDdNeighborStateLow=ospfErrDdNeighborStateLow, bintec=bintec, ospfErrOspfAuthenticationFailed=ospfErrOspfAuthenticationFailed, ospfErrHelloNetmaskMismatch=ospfErrHelloNetmaskMismatch, biboip=biboip, ospfErrIpBadDestination=ospfErrIpBadDestination)
|
"""
File: complement.py
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""
def main():
"""
This App provides complement sequence of DNA
"""
dna = input('Please give me a DNA strand and I\'ll find the complement:')
dna = dna.upper()
complement_dna = find_complement(dna)
print('The complement of ' + dna + ' is ' + complement_dna)
def find_complement(dna):
"""
:param dna: str, DNA consequence provided by user to be compared
:return: str, complement DNA consequence for given DNA consequence
"""
complement = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
complement += 'T'
elif ch == 'T':
complement += 'A'
elif ch == 'C':
complement += 'G'
else:
complement += 'C'
return complement
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
main()
|
def deep_index(lst, w):
return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub]
class variable():
def __init__(self, name, val):
self.name = name
self.val = val
class variableHandler():
def __init__(self):
self.varList = []
def create(self, varName, varVal):
inList = False
for var in self.varList:
if var.name == varName:
inList = True
if not inList:
var = variable(varName, varVal)
self.varList.append(var)
return var
else:
for var in self.varList:
if var.name == varName:
var.val = varVal
return variable(varName, varVal)
def get(self, varName):
for var in self.varList:
if var.name == varName:
return var.val
return None |
#!/usr/bin/python3
# code for AdventOfCode day 1 http://adventofcode.com/2017/day/1
# get user input WITHOUT validation
# the code will fail when repeating non numeric chars
input_seq = input()
# append first algarism to the end of a new 'extended'
# that way we can use a single 'for' loop for everything
input_seq_extended = str(input_seq) + str(input_seq[0])
# initialize the output as an integer
total_output = 0
for i in range(0, len(input_seq)):
# not sure if this checking of range happens every loop.
# # maybe its inefficient
# permute all the input checking for repeated chars
if input_seq_extended[i] == input_seq_extended[i+1]:
print("Match! "+ str(i) + " Total output: " + str(total_output))
total_output += int(input_seq_extended[i])
print("Output: " + str(total_output))
|
class Player:
next_id = 1
def __init__(self, name, corp_id=None, runner_id=None):
self.id = Player.next_id
Player.next_id += 1
self.name = name
self.corp_id = corp_id
self.runner_id = runner_id
self.score = 0
self.sos = 0
self.esos = 0
self.side_bias = 0
# self.opponents is a dictionary key'd by opponent ID
# value is the side they played against the opponent
self.opponents = {}
self.byes_recieved = 0
self.dropped = False
self.is_bye = False
def __repr__(self):
return f"<Player> {self.id} : {self.name}"
def allowable_pairings(self, opp_id):
# For a given opponent return what sides they can play
# Only works in swiss
if opp_id not in self.opponents.keys():
return 0 # Sum of -1 and 1
if self.opponents[opp_id] == 0:
return None
else:
return self.opponents[opp_id] * (-1)
def games_played(self):
count = 0
for side in self.opponents.values():
if side == 0:
count += 2
else:
count += 1
return count
|
word = input('Enter a word')
letter = input('Enter a letter')
def count(word, letter):
counter = 0
for character in word:
if character == letter:
counter = counter + 1
print(counter)
count(word, letter)
|
'''
Implement a function which takes as input a string s
and returns true if s is a palindromic string.
'''
def is_palindrome(s): # Time: O(n)
# i moves forward, and j moves backward.
i, j = 0, len(s) - 1
while i < j:
# i and j both skip non-alphanumeric characters.
while not s[i].isalnum() and i < j:
i += 1
while not s[j].isalnum() and i < j:
j -= 1
if s[i].lower() != s[j].lower():
return False
i, j = i + 1, j - 1
return True
assert(is_palindrome('A man, a plan, a canal, Panama.') == True)
assert(is_palindrome('Able was I, ere I saw Elba!') == True)
assert(is_palindrome('Ray a Ray') == False)
|
def game(player1, player2):
history = []
while len(player1) != 0 and len(player2) != 0:
state = {'player1': player1.copy(), 'player2': player2.copy()}
if state in history:
return True, player1 + player2
history.append(state)
num1 = player1.pop(0)
num2 = player2.pop(0)
if num1 <= len(player1) and num2 <= len(player2):
winner, deck = game(player1[0:num1], player2[0:num2])
else:
winner = num1 > num2
if winner:
player1 += [num1, num2]
else:
player2 += [num2, num1]
return len(player1) != 0, player1 + player2
paragraph = open("input.txt", "r").read().split('\n\n')
g1 = list(map(int, paragraph[0].split('\n')[1:]))
g2 = list(map(int, paragraph[1].split('\n')[1:]))
final = game(g1, g2)[1][::-1] # get second result because is winner final deck
total = 0
for i in range(len(final)):
total += (i + 1) * final[i]
print(total)
|
#!/usr/bin/env python3
######################################################################################
# #
# Program purpose: Creates a string made of the first 2 and the last 2 chars #
# from a given string. If the string length is less than 2, #
# returns instead an empty string. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : October 10, 2019 #
# #
######################################################################################
def get_user_string(mess: str):
is_valid = False
data = ''
while is_valid is False:
try:
data = input(mess)
if len(data) == 0:
raise ValueError("Please provide a string")
is_valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return data
def process_data(main_data: str):
if len(main_data) < 2:
return ''
return main_data[:2] + main_data[-2:]
if __name__ == "__main__":
user_str = get_user_string('Enter some string: ')
print(f'Processed data: {process_data(main_data=user_str)}') |
'''
Copyright (©) 2021 Kiet Pham <kiet.riley2005@gmail.com>
This software/program has a copyright license, more information is in the 'LICENSE' file
IF YOU WANT TO USE/COPY/MODIFY/REPRODUCE/RE-DISTRIBUTE THIS PROGRAM, YOU MUST INCLUDE A COPY OF THE LICENSE
Author Name: Kiet Pham
Author Contact: kiet.riley2005@gmail.com
Discord: CaptainVietnam6#7932
Discord Server: https://discord.gg/3z76p8H5yj
GitHub: https://github.com/CaptainVietnam6
Instagram: @itz_kietttttttttt
Program Status: ACTIVE, FINALISED
'''
DIGITS = int(input("Enter how many digits of pi you want: "))
def pi_digits(x):
"""Generate x digits of Pi."""
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
print("%s.%s\n" % (digits.pop(0), "".join(digits)))
|
# Program to implement Affine Cipher for encryption and decryption
#returns gcd of two numbers
def gcd(num1, num2):
if num2 == 0:
return num1
return gcd(num2, num1 % num2)
#returns the inverse of a number if it exists, else '-1', under mod
def inverse(number, mod):
if gcd(number, mod) != 1:
return None
t1 = 0
t2 = 1
while number != 0:
quotient = mod // number
remainder = mod % number
t = t1 - quotient*t2
mod = number
number = remainder
t1 = t2
t2 = t
return t1
class AffineCipher:
def __init__(self, key1, key2):
self.key1 = key1
self.key2 = key2
self.keyInverse = inverse(self.key1, 26)
#returns index of the given alphabet
def index(self, alphabet):
return ord(alphabet.upper()) - ord('A')
# returns a cipher text by encrypting a plain text using affine cipher algorithm
def encrypt(self, plainTxt):
cipherTxt = str()
if not self.keyInverse:
return "INVERSE NOT FOUND!!"
for x in plainTxt:
if x.isalpha():
cipherTxt += chr((self.index(x)*self.key1 + self.key2)%26 + ord('A'))
else:
cipherTxt += x
return cipherTxt
# returns a plain text by decrypting a plain text using additive cipher algorithm
def decrypt(self, cipherTxt):
plainTxt = str()
if not self.keyInverse:
return "INVERSE NOT FOUND!!"
for x in cipherTxt:
if x.isalpha():
plainTxt += chr(((self.index(x)-self.key2) * self.keyInverse)%26 + ord('A'))
else:
plainTxt += x
return plainTxt
if __name__ == '__main__':
aff = AffineCipher(7,2)
print(aff.encrypt("hello"))
print(aff.decrypt(aff.encrypt("hello")))
|
# coding=utf-8
# autogenerated using ms_props_generator.py
PROPS_ID_MAP = {
"0x0001": {"data_type": "0x0102", "name": "TemplateData"},
"0x0002": {"data_type": "0x000B", "name": "AlternateRecipientAllowed"},
"0x0004": {"data_type": "0x0102", "name": "ScriptData"},
"0x0005": {"data_type": "0x000B", "name": "AutoForwarded"},
"0x000F": {"data_type": "0x0040", "name": "DeferredDeliveryTime"},
"0x0010": {"data_type": "0x0040", "name": "DeliverTime"},
"0x0015": {"data_type": "0x0040", "name": "ExpiryTime"},
"0x0017": {"data_type": "0x0003", "name": "Importance"},
"0x001A": {"data_type": "0x001F", "name": "MessageClass"},
"0x0023": {"data_type": "0x000B", "name": "OriginatorDeliveryReportRequested"},
"0x0025": {"data_type": "0x0102", "name": "ParentKey"},
"0x0026": {"data_type": "0x0003", "name": "Priority"},
"0x0029": {"data_type": "0x000B", "name": "ReadReceiptRequested"},
"0x002A": {"data_type": "0x0040", "name": "ReceiptTime"},
"0x002B": {"data_type": "0x000B", "name": "RecipientReassignmentProhibited"},
"0x002E": {"data_type": "0x0003", "name": "OriginalSensitivity"},
"0x0030": {"data_type": "0x0040", "name": "ReplyTime"},
"0x0031": {"data_type": "0x0102", "name": "ReportTag"},
"0x0032": {"data_type": "0x0040", "name": "ReportTime"},
"0x0036": {"data_type": "0x0003", "name": "Sensitivity"},
"0x0037": {"data_type": "0x001F", "name": "Subject"},
"0x0039": {"data_type": "0x0040", "name": "ClientSubmitTime"},
"0x003A": {"data_type": "0x001F", "name": "ReportName"},
"0x003B": {"data_type": "0x0102", "name": "SentRepresentingSearchKey"},
"0x003D": {"data_type": "0x001F", "name": "SubjectPrefix"},
"0x003F": {"data_type": "0x0102", "name": "ReceivedByEntryId"},
"0x0040": {"data_type": "0x001F", "name": "ReceivedByName"},
"0x0041": {"data_type": "0x0102", "name": "SentRepresentingEntryId"},
"0x0042": {"data_type": "0x001F", "name": "SentRepresentingName"},
"0x0043": {"data_type": "0x0102", "name": "ReceivedRepresentingEntryId"},
"0x0044": {"data_type": "0x001F", "name": "ReceivedRepresentingName"},
"0x0045": {"data_type": "0x0102", "name": "ReportEntryId"},
"0x0046": {"data_type": "0x0102", "name": "ReadReceiptEntryId"},
"0x0047": {"data_type": "0x0102", "name": "MessageSubmissionId"},
"0x0049": {"data_type": "0x001F", "name": "OriginalSubject"},
"0x004B": {"data_type": "0x001F", "name": "OriginalMessageClass"},
"0x004C": {"data_type": "0x0102", "name": "OriginalAuthorEntryId"},
"0x004D": {"data_type": "0x001F", "name": "OriginalAuthorName"},
"0x004E": {"data_type": "0x0040", "name": "OriginalSubmitTime"},
"0x004F": {"data_type": "0x0102", "name": "ReplyRecipientEntries"},
"0x0050": {"data_type": "0x001F", "name": "ReplyRecipientNames"},
"0x0051": {"data_type": "0x0102", "name": "ReceivedBySearchKey"},
"0x0052": {"data_type": "0x0102", "name": "ReceivedRepresentingSearchKey"},
"0x0053": {"data_type": "0x0102", "name": "ReadReceiptSearchKey"},
"0x0054": {"data_type": "0x0102", "name": "ReportSearchKey"},
"0x0055": {"data_type": "0x0040", "name": "OriginalDeliveryTime"},
"0x0057": {"data_type": "0x000B", "name": "MessageToMe"},
"0x0058": {"data_type": "0x000B", "name": "MessageCcMe"},
"0x0059": {"data_type": "0x000B", "name": "MessageRecipientMe"},
"0x005A": {"data_type": "0x001F", "name": "OriginalSenderName"},
"0x005B": {"data_type": "0x0102", "name": "OriginalSenderEntryId"},
"0x005C": {"data_type": "0x0102", "name": "OriginalSenderSearchKey"},
"0x005D": {"data_type": "0x001F", "name": "OriginalSentRepresentingName"},
"0x005E": {"data_type": "0x0102", "name": "OriginalSentRepresentingEntryId"},
"0x005F": {"data_type": "0x0102", "name": "OriginalSentRepresentingSearchKey"},
"0x0060": {"data_type": "0x0040", "name": "StartDate"},
"0x0061": {"data_type": "0x0040", "name": "EndDate"},
"0x0062": {"data_type": "0x0003", "name": "OwnerAppointmentId"},
"0x0063": {"data_type": "0x000B", "name": "ResponseRequested"},
"0x0064": {"data_type": "0x001F", "name": "SentRepresentingAddressType"},
"0x0065": {"data_type": "0x001F", "name": "SentRepresentingEmailAddress"},
"0x0066": {"data_type": "0x001F", "name": "OriginalSenderAddressType"},
"0x0067": {"data_type": "0x001F", "name": "OriginalSenderEmailAddress"},
"0x0068": {"data_type": "0x001F", "name": "OriginalSentRepresentingAddressType"},
"0x0069": {"data_type": "0x001F", "name": "OriginalSentRepresentingEmailAddress"},
"0x0070": {"data_type": "0x001F", "name": "ConversationTopic"},
"0x0071": {"data_type": "0x0102", "name": "ConversationIndex"},
"0x0072": {"data_type": "0x001F", "name": "OriginalDisplayBcc"},
"0x0073": {"data_type": "0x001F", "name": "OriginalDisplayCc"},
"0x0074": {"data_type": "0x001F", "name": "OriginalDisplayTo"},
"0x0075": {"data_type": "0x001F", "name": "ReceivedByAddressType"},
"0x0076": {"data_type": "0x001F", "name": "ReceivedByEmailAddress"},
"0x0077": {"data_type": "0x001F", "name": "ReceivedRepresentingAddressType"},
"0x0078": {"data_type": "0x001F", "name": "ReceivedRepresentingEmailAddress"},
"0x007D": {"data_type": "0x001F", "name": "TransportMessageHeaders"},
"0x007F": {"data_type": "0x0102", "name": "TnefCorrelationKey"},
"0x0080": {"data_type": "0x001F", "name": "ReportDisposition"},
"0x0081": {"data_type": "0x001F", "name": "ReportDispositionMode"},
"0x0807": {"data_type": "0x0003", "name": "AddressBookRoomCapacity"},
"0x0809": {"data_type": "0x001F", "name": "AddressBookRoomDescription"},
"0x0C04": {"data_type": "0x0003", "name": "NonDeliveryReportReasonCode"},
"0x0C05": {"data_type": "0x0003", "name": "NonDeliveryReportDiagCode"},
"0x0C06": {"data_type": "0x000B", "name": "NonReceiptNotificationRequested"},
"0x0C08": {"data_type": "0x000B", "name": "OriginatorNonDeliveryReportRequested"},
"0x0C15": {"data_type": "0x0003", "name": "RecipientType"},
"0x0C17": {"data_type": "0x000B", "name": "ReplyRequested"},
"0x0C19": {"data_type": "0x0102", "name": "SenderEntryId"},
"0x0C1A": {"data_type": "0x001F", "name": "SenderName"},
"0x0C1B": {"data_type": "0x001F", "name": "SupplementaryInfo"},
"0x0C1D": {"data_type": "0x0102", "name": "SenderSearchKey"},
"0x0C1E": {"data_type": "0x001F", "name": "SenderAddressType"},
"0x0C1F": {"data_type": "0x001F", "name": "SenderEmailAddress"},
"0x0C21": {"data_type": "0x001F", "name": "RemoteMessageTransferAgent"},
"0x0E01": {"data_type": "0x000B", "name": "DeleteAfterSubmit"},
"0x0E02": {"data_type": "0x001F", "name": "DisplayBcc"},
"0x0E03": {"data_type": "0x001F", "name": "DisplayCc"},
"0x0E04": {"data_type": "0x001F", "name": "DisplayTo"},
"0x0E06": {"data_type": "0x0040", "name": "MessageDeliveryTime"},
"0x0E07": {"data_type": "0x0003", "name": "MessageFlags"},
"0x0E08": {"data_type": "0x0014", "name": "MessageSizeExtended"},
"0x0E09": {"data_type": "0x0102", "name": "ParentEntryId"},
"0x0E0F": {"data_type": "0x000B", "name": "Responsibility"},
"0x0E12": {"data_type": "0x000D", "name": "MessageRecipients"},
"0x0E13": {"data_type": "0x000D", "name": "MessageAttachments"},
"0x0E17": {"data_type": "0x0003", "name": "MessageStatus"},
"0x0E1B": {"data_type": "0x000B", "name": "HasAttachments"},
"0x0E1D": {"data_type": "0x001F", "name": "NormalizedSubject"},
"0x0E1F": {"data_type": "0x000B", "name": "RtfInSync"},
"0x0E20": {"data_type": "0x0003", "name": "AttachSize"},
"0x0E21": {"data_type": "0x0003", "name": "AttachNumber"},
"0x0E28": {"data_type": "0x001F", "name": "PrimarySendAccount"},
"0x0E29": {"data_type": "0x001F", "name": "NextSendAcct"},
"0x0E2B": {"data_type": "0x0003", "name": "ToDoItemFlags"},
"0x0E2C": {"data_type": "0x0102", "name": "SwappedToDoStore"},
"0x0E2D": {"data_type": "0x0102", "name": "SwappedToDoData"},
"0x0E69": {"data_type": "0x000B", "name": "Read"},
"0x0E6A": {"data_type": "0x001F", "name": "SecurityDescriptorAsXml"},
"0x0E79": {"data_type": "0x0003", "name": "TrustSender"},
"0x0E84": {"data_type": "0x0102", "name": "ExchangeNTSecurityDescriptor"},
"0x0E99": {"data_type": "0x0102", "name": "ExtendedRuleMessageActions"},
"0x0E9A": {"data_type": "0x0102", "name": "ExtendedRuleMessageCondition"},
"0x0E9B": {"data_type": "0x0003", "name": "ExtendedRuleSizeLimit"},
"0x0FF4": {"data_type": "0x0003", "name": "Access"},
"0x0FF5": {"data_type": "0x0003", "name": "RowType"},
"0x0FF6": {"data_type": "0x0102", "name": "InstanceKey"},
"0x0FF7": {"data_type": "0x0003", "name": "AccessLevel"},
"0x0FF8": {"data_type": "0x0102", "name": "MappingSignature"},
"0x0FF9": {"data_type": "0x0102", "name": "RecordKey"},
"0x0FFB": {"data_type": "0x0102", "name": "StoreEntryId"},
"0x0FFE": {"data_type": "0x0003", "name": "ObjectType"},
"0x0FFF": {"data_type": "0x0102", "name": "EntryId"},
"0x1000": {"data_type": "0x001F", "name": "Body"},
"0x1001": {"data_type": "0x001F", "name": "ReportText"},
"0x1009": {"data_type": "0x0102", "name": "RtfCompressed"},
"0x1013": {"data_type": "0x0102", "name": "Html"},
"0x1014": {"data_type": "0x001F", "name": "BodyContentLocation"},
"0x1015": {"data_type": "0x001F", "name": "BodyContentId"},
"0x1016": {"data_type": "0x0003", "name": "NativeBody"},
"0x1035": {"data_type": "0x001F", "name": "InternetMessageId"},
"0x1039": {"data_type": "0x001F", "name": "InternetReferences"},
"0x1042": {"data_type": "0x001F", "name": "InReplyToId"},
"0x1043": {"data_type": "0x001F", "name": "ListHelp"},
"0x1044": {"data_type": "0x001F", "name": "ListSubscribe"},
"0x1045": {"data_type": "0x001F", "name": "ListUnsubscribe"},
"0x1046": {"data_type": "0x001F", "name": "OriginalMessageId"},
"0x1080": {"data_type": "0x0003", "name": "IconIndex"},
"0x1081": {"data_type": "0x0003", "name": "LastVerbExecuted"},
"0x1082": {"data_type": "0x0040", "name": "LastVerbExecutionTime"},
"0x1090": {"data_type": "0x0003", "name": "FlagStatus"},
"0x1091": {"data_type": "0x0040", "name": "FlagCompleteTime"},
"0x1095": {"data_type": "0x0003", "name": "FollowupIcon"},
"0x1096": {"data_type": "0x0003", "name": "BlockStatus"},
"0x10C3": {"data_type": "0x0040", "name": "ICalendarStartTime"},
"0x10C4": {"data_type": "0x0040", "name": "ICalendarEndTime"},
"0x10C5": {"data_type": "0x0040", "name": "CdoRecurrenceid"},
"0x10CA": {"data_type": "0x0040", "name": "ICalendarReminderNextTime"},
"0x10F4": {"data_type": "0x000B", "name": "AttributeHidden"},
"0x10F6": {"data_type": "0x000B", "name": "AttributeReadOnly"},
"0x3000": {"data_type": "0x0003", "name": "Rowid"},
"0x3001": {"data_type": "0x001F", "name": "DisplayName"},
"0x3002": {"data_type": "0x001F", "name": "AddressType"},
"0x3003": {"data_type": "0x001F", "name": "EmailAddress"},
"0x3004": {"data_type": "0x001F", "name": "Comment"},
"0x3005": {"data_type": "0x0003", "name": "Depth"},
"0x3007": {"data_type": "0x0040", "name": "CreationTime"},
"0x3008": {"data_type": "0x0040", "name": "LastModificationTime"},
"0x300B": {"data_type": "0x0102", "name": "SearchKey"},
"0x3010": {"data_type": "0x0102", "name": "TargetEntryId"},
"0x3013": {"data_type": "0x0102", "name": "ConversationId"},
"0x3016": {"data_type": "0x000B", "name": "ConversationIndexTracking"},
"0x3018": {"data_type": "0x0102", "name": "ArchiveTag"},
"0x3019": {"data_type": "0x0102", "name": "PolicyTag"},
"0x301A": {"data_type": "0x0003", "name": "RetentionPeriod"},
"0x301B": {"data_type": "0x0102", "name": "StartDateEtc"},
"0x301C": {"data_type": "0x0040", "name": "RetentionDate"},
"0x301D": {"data_type": "0x0003", "name": "RetentionFlags"},
"0x301E": {"data_type": "0x0003", "name": "ArchivePeriod"},
"0x301F": {"data_type": "0x0040", "name": "ArchiveDate"},
"0x340D": {"data_type": "0x0003", "name": "StoreSupportMask"},
"0x340E": {"data_type": "0x0003", "name": "StoreState"},
"0x3600": {"data_type": "0x0003", "name": "ContainerFlags"},
"0x3601": {"data_type": "0x0003", "name": "FolderType"},
"0x3602": {"data_type": "0x0003", "name": "ContentCount"},
"0x3603": {"data_type": "0x0003", "name": "ContentUnreadCount"},
"0x3609": {"data_type": "0x000B", "name": "Selectable"},
"0x360A": {"data_type": "0x000B", "name": "Subfolders"},
"0x360C": {"data_type": "0x001F", "name": "Anr"},
"0x360E": {"data_type": "0x000D", "name": "ContainerHierarchy"},
"0x360F": {"data_type": "0x000D", "name": "ContainerContents"},
"0x3610": {"data_type": "0x000D", "name": "FolderAssociatedContents"},
"0x3613": {"data_type": "0x001F", "name": "ContainerClass"},
"0x36D0": {"data_type": "0x0102", "name": "IpmAppointmentEntryId"},
"0x36D1": {"data_type": "0x0102", "name": "IpmContactEntryId"},
"0x36D2": {"data_type": "0x0102", "name": "IpmJournalEntryId"},
"0x36D3": {"data_type": "0x0102", "name": "IpmNoteEntryId"},
"0x36D4": {"data_type": "0x0102", "name": "IpmTaskEntryId"},
"0x36D5": {"data_type": "0x0102", "name": "RemindersOnlineEntryId"},
"0x36D7": {"data_type": "0x0102", "name": "IpmDraftsEntryId"},
"0x36D8": {"data_type": "0x1102", "name": "AdditionalRenEntryIds"},
"0x36D9": {"data_type": "0x0102", "name": "AdditionalRenEntryIdsEx"},
"0x36DA": {"data_type": "0x0102", "name": "ExtendedFolderFlags"},
"0x36E2": {"data_type": "0x0003", "name": "OrdinalMost"},
"0x36E4": {"data_type": "0x1102", "name": "FreeBusyEntryIds"},
"0x36E5": {"data_type": "0x001F", "name": "DefaultPostMessageClass"},
"0x3701": {"data_type": "0x000D", "name": "AttachDataObject"},
"0x3702": {"data_type": "0x0102", "name": "AttachEncoding"},
"0x3703": {"data_type": "0x001F", "name": "AttachExtension"},
"0x3704": {"data_type": "0x001F", "name": "AttachFilename"},
"0x3705": {"data_type": "0x0003", "name": "AttachMethod"},
"0x3707": {"data_type": "0x001F", "name": "AttachLongFilename"},
"0x3708": {"data_type": "0x001F", "name": "AttachPathname"},
"0x3709": {"data_type": "0x0102", "name": "AttachRendering"},
"0x370A": {"data_type": "0x0102", "name": "AttachTag"},
"0x370B": {"data_type": "0x0003", "name": "RenderingPosition"},
"0x370C": {"data_type": "0x001F", "name": "AttachTransportName"},
"0x370D": {"data_type": "0x001F", "name": "AttachLongPathname"},
"0x370E": {"data_type": "0x001F", "name": "AttachMimeTag"},
"0x370F": {"data_type": "0x0102", "name": "AttachAdditionalInformation"},
"0x3711": {"data_type": "0x001F", "name": "AttachContentBase"},
"0x3712": {"data_type": "0x001F", "name": "AttachContentId"},
"0x3713": {"data_type": "0x001F", "name": "AttachContentLocation"},
"0x3714": {"data_type": "0x0003", "name": "AttachFlags"},
"0x3719": {"data_type": "0x001F", "name": "AttachPayloadProviderGuidString"},
"0x371A": {"data_type": "0x001F", "name": "AttachPayloadClass"},
"0x371B": {"data_type": "0x001F", "name": "TextAttachmentCharset"},
"0x3900": {"data_type": "0x0003", "name": "DisplayType"},
"0x3902": {"data_type": "0x0102", "name": "Templateid"},
"0x3905": {"data_type": "0x0003", "name": "DisplayTypeEx"},
"0x39FE": {"data_type": "0x001F", "name": "SmtpAddress"},
"0x39FF": {"data_type": "0x001F", "name": "AddressBookDisplayNamePrintable"},
"0x3A00": {"data_type": "0x001F", "name": "Account"},
"0x3A02": {"data_type": "0x001F", "name": "CallbackTelephoneNumber"},
"0x3A05": {"data_type": "0x001F", "name": "Generation"},
"0x3A06": {"data_type": "0x001F", "name": "GivenName"},
"0x3A07": {"data_type": "0x001F", "name": "GovernmentIdNumber"},
"0x3A08": {"data_type": "0x001F", "name": "BusinessTelephoneNumber"},
"0x3A09": {"data_type": "0x001F", "name": "HomeTelephoneNumber"},
"0x3A0A": {"data_type": "0x001F", "name": "Initials"},
"0x3A0B": {"data_type": "0x001F", "name": "Keyword"},
"0x3A0C": {"data_type": "0x001F", "name": "Language"},
"0x3A0D": {"data_type": "0x001F", "name": "Location"},
"0x3A0F": {"data_type": "0x001F", "name": "MessageHandlingSystemCommonName"},
"0x3A10": {"data_type": "0x001F", "name": "OrganizationalIdNumber"},
"0x3A11": {"data_type": "0x001F", "name": "Surname"},
"0x3A12": {"data_type": "0x0102", "name": "OriginalEntryId"},
"0x3A15": {"data_type": "0x001F", "name": "PostalAddress"},
"0x3A16": {"data_type": "0x001F", "name": "CompanyName"},
"0x3A17": {"data_type": "0x001F", "name": "Title"},
"0x3A18": {"data_type": "0x001F", "name": "DepartmentName"},
"0x3A19": {"data_type": "0x001F", "name": "OfficeLocation"},
"0x3A1A": {"data_type": "0x001F", "name": "PrimaryTelephoneNumber"},
"0x3A1B": {"data_type": "0x101F", "name": "Business2TelephoneNumbers"},
"0x3A1C": {"data_type": "0x001F", "name": "MobileTelephoneNumber"},
"0x3A1D": {"data_type": "0x001F", "name": "RadioTelephoneNumber"},
"0x3A1E": {"data_type": "0x001F", "name": "CarTelephoneNumber"},
"0x3A1F": {"data_type": "0x001F", "name": "OtherTelephoneNumber"},
"0x3A20": {"data_type": "0x001F", "name": "TransmittableDisplayName"},
"0x3A21": {"data_type": "0x001F", "name": "PagerTelephoneNumber"},
"0x3A22": {"data_type": "0x0102", "name": "UserCertificate"},
"0x3A23": {"data_type": "0x001F", "name": "PrimaryFaxNumber"},
"0x3A24": {"data_type": "0x001F", "name": "BusinessFaxNumber"},
"0x3A25": {"data_type": "0x001F", "name": "HomeFaxNumber"},
"0x3A26": {"data_type": "0x001F", "name": "Country"},
"0x3A27": {"data_type": "0x001F", "name": "Locality"},
"0x3A28": {"data_type": "0x001F", "name": "StateOrProvince"},
"0x3A29": {"data_type": "0x001F", "name": "StreetAddress"},
"0x3A2A": {"data_type": "0x001F", "name": "PostalCode"},
"0x3A2B": {"data_type": "0x001F", "name": "PostOfficeBox"},
"0x3A2C": {
"data_type": "0x001F; PtypMultipleBinary, 0x1102",
"name": "TelexNumber",
},
"0x3A2D": {"data_type": "0x001F", "name": "IsdnNumber"},
"0x3A2E": {"data_type": "0x001F", "name": "AssistantTelephoneNumber"},
"0x3A2F": {"data_type": "0x101F", "name": "Home2TelephoneNumbers"},
"0x3A30": {"data_type": "0x001F", "name": "Assistant"},
"0x3A40": {"data_type": "0x000B", "name": "SendRichInfo"},
"0x3A41": {"data_type": "0x0040", "name": "WeddingAnniversary"},
"0x3A42": {"data_type": "0x0040", "name": "Birthday"},
"0x3A43": {"data_type": "0x001F", "name": "Hobbies"},
"0x3A44": {"data_type": "0x001F", "name": "MiddleName"},
"0x3A45": {"data_type": "0x001F", "name": "DisplayNamePrefix"},
"0x3A46": {"data_type": "0x001F", "name": "Profession"},
"0x3A47": {"data_type": "0x001F", "name": "ReferredByName"},
"0x3A48": {"data_type": "0x001F", "name": "SpouseName"},
"0x3A49": {"data_type": "0x001F", "name": "ComputerNetworkName"},
"0x3A4A": {"data_type": "0x001F", "name": "CustomerId"},
"0x3A4B": {
"data_type": "0x001F",
"name": "TelecommunicationsDeviceForDeafTelephoneNumber",
},
"0x3A4C": {"data_type": "0x001F", "name": "FtpSite"},
"0x3A4D": {"data_type": "0x0002", "name": "Gender"},
"0x3A4E": {"data_type": "0x001F", "name": "ManagerName"},
"0x3A4F": {"data_type": "0x001F", "name": "Nickname"},
"0x3A50": {"data_type": "0x001F", "name": "PersonalHomePage"},
"0x3A51": {"data_type": "0x001F", "name": "BusinessHomePage"},
"0x3A57": {"data_type": "0x001F", "name": "CompanyMainTelephoneNumber"},
"0x3A58": {"data_type": "0x101F", "name": "ChildrensNames"},
"0x3A59": {"data_type": "0x001F", "name": "HomeAddressCity"},
"0x3A5A": {"data_type": "0x001F", "name": "HomeAddressCountry"},
"0x3A5B": {"data_type": "0x001F", "name": "HomeAddressPostalCode"},
"0x3A5C": {"data_type": "0x001F", "name": "HomeAddressStateOrProvince"},
"0x3A5D": {"data_type": "0x001F", "name": "HomeAddressStreet"},
"0x3A5E": {"data_type": "0x001F", "name": "HomeAddressPostOfficeBox"},
"0x3A5F": {"data_type": "0x001F", "name": "OtherAddressCity"},
"0x3A60": {"data_type": "0x001F", "name": "OtherAddressCountry"},
"0x3A61": {"data_type": "0x001F", "name": "OtherAddressPostalCode"},
"0x3A62": {"data_type": "0x001F", "name": "OtherAddressStateOrProvince"},
"0x3A63": {"data_type": "0x001F", "name": "OtherAddressStreet"},
"0x3A64": {"data_type": "0x001F", "name": "OtherAddressPostOfficeBox"},
"0x3A70": {"data_type": "0x1102", "name": "UserX509Certificate"},
"0x3A71": {"data_type": "0x0003", "name": "SendInternetEncoding"},
"0x3F08": {"data_type": "0x0003", "name": "InitialDetailsPane"},
"0x3FDE": {"data_type": "0x0003", "name": "InternetCodepage"},
"0x3FDF": {"data_type": "0x0003", "name": "AutoResponseSuppress"},
"0x3FE0": {"data_type": "0x0102", "name": "AccessControlListData"},
"0x3FE3": {"data_type": "0x000B", "name": "DelegatedByRule"},
"0x3FE7": {"data_type": "0x0003", "name": "ResolveMethod"},
"0x3FEA": {"data_type": "0x000B", "name": "HasDeferredActionMessages"},
"0x3FEB": {"data_type": "0x0003", "name": "DeferredSendNumber"},
"0x3FEC": {"data_type": "0x0003", "name": "DeferredSendUnits"},
"0x3FED": {"data_type": "0x0003", "name": "ExpiryNumber"},
"0x3FEE": {"data_type": "0x0003", "name": "ExpiryUnits"},
"0x3FEF": {"data_type": "0x0040", "name": "DeferredSendTime"},
"0x3FF0": {"data_type": "0x0102", "name": "ConflictEntryId"},
"0x3FF1": {"data_type": "0x0003", "name": "MessageLocaleId"},
"0x3FF8": {"data_type": "0x001F", "name": "CreatorName"},
"0x3FF9": {"data_type": "0x0102", "name": "CreatorEntryId"},
"0x3FFA": {"data_type": "0x001F", "name": "LastModifierName"},
"0x3FFB": {"data_type": "0x0102", "name": "LastModifierEntryId"},
"0x3FFD": {"data_type": "0x0003", "name": "MessageCodepage"},
"0x401A": {"data_type": "0x0003", "name": "SentRepresentingFlags"},
"0x4029": {"data_type": "0x001F", "name": "ReadReceiptAddressType"},
"0x402A": {"data_type": "0x001F", "name": "ReadReceiptEmailAddress"},
"0x402B": {"data_type": "0x001F", "name": "ReadReceiptName"},
"0x4076": {"data_type": "0x0003", "name": "ContentFilterSpamConfidenceLevel"},
"0x4079": {"data_type": "0x0003", "name": "SenderIdStatus"},
"0x4082": {"data_type": "0x0040", "name": "HierRev"},
"0x4083": {"data_type": "0x001F", "name": "PurportedSenderDomain"},
"0x5902": {"data_type": "0x0003", "name": "InternetMailOverrideFormat"},
"0x5909": {"data_type": "0x0003", "name": "MessageEditorFormat"},
"0x5D01": {"data_type": "0x001F", "name": "SenderSmtpAddress"},
"0x5D02": {"data_type": "0x001F", "name": "SentRepresentingSmtpAddress"},
"0x5D05": {"data_type": "0x001F", "name": "ReadReceiptSmtpAddress"},
"0x5D07": {"data_type": "0x001F", "name": "ReceivedBySmtpAddress"},
"0x5D08": {"data_type": "0x001F", "name": "ReceivedRepresentingSmtpAddress"},
"0x5FDF": {"data_type": "0x0003", "name": "RecipientOrder"},
"0x5FE1": {"data_type": "0x000B", "name": "RecipientProposed"},
"0x5FE3": {"data_type": "0x0040", "name": "RecipientProposedStartTime"},
"0x5FE4": {"data_type": "0x0040", "name": "RecipientProposedEndTime"},
"0x5FF6": {"data_type": "0x001F", "name": "RecipientDisplayName"},
"0x5FF7": {"data_type": "0x0102", "name": "RecipientEntryId"},
"0x5FFB": {"data_type": "0x0040", "name": "RecipientTrackStatusTime"},
"0x5FFD": {"data_type": "0x0003", "name": "RecipientFlags"},
"0x5FFF": {"data_type": "0x0003", "name": "RecipientTrackStatus"},
"0x6100": {"data_type": "0x0003", "name": "JunkIncludeContacts"},
"0x6101": {"data_type": "0x0003", "name": "JunkThreshold"},
"0x6102": {"data_type": "0x0003", "name": "JunkPermanentlyDelete"},
"0x6103": {"data_type": "0x0003", "name": "JunkAddRecipientsToSafeSendersList"},
"0x6107": {"data_type": "0x000B", "name": "JunkPhishingEnableLinks"},
"0x64F0": {"data_type": "0x0102", "name": "MimeSkeleton"},
"0x65C2": {"data_type": "0x0102", "name": "ReplyTemplateId"},
"0x65E0": {"data_type": "0x0102", "name": "SourceKey"},
"0x65E1": {"data_type": "0x0102", "name": "ParentSourceKey"},
"0x65E2": {"data_type": "0x0102", "name": "ChangeKey"},
"0x65E3": {"data_type": "0x0102", "name": "PredecessorChangeList"},
"0x65E9": {"data_type": "0x0003", "name": "RuleMessageState"},
"0x65EA": {"data_type": "0x0003", "name": "RuleMessageUserFlags"},
"0x65EB": {"data_type": "0x001F", "name": "RuleMessageProvider"},
"0x65EC": {"data_type": "0x001F", "name": "RuleMessageName"},
"0x65ED": {"data_type": "0x0003", "name": "RuleMessageLevel"},
"0x65EE": {"data_type": "0x0102", "name": "RuleMessageProviderData"},
"0x65F3": {"data_type": "0x0003", "name": "RuleMessageSequence"},
"0x6619": {"data_type": "0x0102", "name": "UserEntryId"},
"0x661B": {"data_type": "0x0102", "name": "MailboxOwnerEntryId"},
"0x661C": {"data_type": "0x001F", "name": "MailboxOwnerName"},
"0x661D": {"data_type": "0x000B", "name": "OutOfOfficeState"},
"0x6622": {"data_type": "0x0102", "name": "SchedulePlusFreeBusyEntryId"},
"0x6638": {"data_type": "0x0102", "name": "SerializedReplidGuidMap"},
"0x6639": {"data_type": "0x0003", "name": "Rights"},
"0x663A": {"data_type": "0x000B", "name": "HasRules"},
"0x663B": {"data_type": "0x0102", "name": "AddressBookEntryId"},
"0x663E": {"data_type": "0x0003", "name": "HierarchyChangeNumber"},
"0x6645": {"data_type": "0x0102", "name": "ClientActions"},
"0x6646": {"data_type": "0x0102", "name": "DamOriginalEntryId"},
"0x6647": {"data_type": "0x000B", "name": "DamBackPatched"},
"0x6648": {"data_type": "0x0003", "name": "RuleError"},
"0x6649": {"data_type": "0x0003", "name": "RuleActionType"},
"0x664A": {"data_type": "0x000B", "name": "HasNamedProperties"},
"0x6650": {"data_type": "0x0003", "name": "RuleActionNumber"},
"0x6651": {"data_type": "0x0102", "name": "RuleFolderEntryId"},
"0x666A": {"data_type": "0x0003", "name": "ProhibitReceiveQuota"},
"0x666C": {"data_type": "0x000B", "name": "InConflict"},
"0x666D": {"data_type": "0x0003", "name": "MaximumSubmitMessageSize"},
"0x666E": {"data_type": "0x0003", "name": "ProhibitSendQuota"},
"0x6671": {"data_type": "0x0014", "name": "MemberId"},
"0x6672": {"data_type": "0x001F", "name": "MemberName"},
"0x6673": {"data_type": "0x0003", "name": "MemberRights"},
"0x6674": {"data_type": "0x0014", "name": "RuleId"},
"0x6675": {"data_type": "0x0102", "name": "RuleIds"},
"0x6676": {"data_type": "0x0003", "name": "RuleSequence"},
"0x6677": {"data_type": "0x0003", "name": "RuleState"},
"0x6678": {"data_type": "0x0003", "name": "RuleUserFlags"},
"0x6679": {"data_type": "0x00FD", "name": "RuleCondition"},
"0x6680": {"data_type": "0x00FE", "name": "RuleActions"},
"0x6681": {"data_type": "0x001F", "name": "RuleProvider"},
"0x6682": {"data_type": "0x001F", "name": "RuleName"},
"0x6683": {"data_type": "0x0003", "name": "RuleLevel"},
"0x6684": {"data_type": "0x0102", "name": "RuleProviderData"},
"0x668F": {"data_type": "0x0040", "name": "DeletedOn"},
"0x66A1": {"data_type": "0x0003", "name": "LocaleId"},
"0x66A8": {"data_type": "0x0003", "name": "FolderFlags"},
"0x66C3": {"data_type": "0x0003", "name": "CodePageId"},
"0x6704": {"data_type": "0x000D", "name": "AddressBookManageDistributionList"},
"0x6705": {"data_type": "0x0003", "name": "SortLocaleId"},
"0x6709": {"data_type": "0x0040", "name": "LocalCommitTime"},
"0x670A": {"data_type": "0x0040", "name": "LocalCommitTimeMax"},
"0x670B": {"data_type": "0x0003", "name": "DeletedCountTotal"},
"0x670E": {"data_type": "0x001F", "name": "FlatUrlName"},
"0x6740": {"data_type": "0x00FB", "name": "SentMailSvrEID"},
"0x6741": {"data_type": "0x00FB", "name": "DeferredActionMessageOriginalEntryId"},
"0x6748": {"data_type": "0x0014", "name": "FolderId"},
"0x6749": {"data_type": "0x0014", "name": "ParentFolderId"},
"0x674A": {"data_type": "0x0014", "name": "Mid"},
"0x674D": {"data_type": "0x0014", "name": "InstID"},
"0x674E": {"data_type": "0x0003", "name": "InstanceNum"},
"0x674F": {"data_type": "0x0014", "name": "AddressBookMessageId"},
"0x67A4": {"data_type": "0x0014", "name": "ChangeNumber"},
"0x67AA": {"data_type": "0x000B", "name": "Associated"},
"0x6800": {"data_type": "0x001F", "name": "OfflineAddressBookName"},
"0x6801": {"data_type": "0x0003", "name": "VoiceMessageDuration"},
"0x6802": {"data_type": "0x001F", "name": "SenderTelephoneNumber"},
"0x6803": {"data_type": "0x001F", "name": "VoiceMessageSenderName"},
"0x6804": {"data_type": "0x001E", "name": "OfflineAddressBookDistinguishedName"},
"0x6805": {"data_type": "0x001F", "name": "VoiceMessageAttachmentOrder"},
"0x6806": {"data_type": "0x001F", "name": "CallId"},
"0x6820": {"data_type": "0x001F", "name": "ReportingMessageTransferAgent"},
"0x6834": {"data_type": "0x0003", "name": "SearchFolderLastUsed"},
"0x683A": {"data_type": "0x0003", "name": "SearchFolderExpiration"},
"0x6841": {"data_type": "0x0003", "name": "SearchFolderTemplateId"},
"0x6842": {"data_type": "0x0102", "name": "WlinkGroupHeaderID"},
"0x6843": {"data_type": "0x000B", "name": "ScheduleInfoDontMailDelegates"},
"0x6844": {"data_type": "0x0102", "name": "SearchFolderRecreateInfo"},
"0x6845": {"data_type": "0x0102", "name": "SearchFolderDefinition"},
"0x6846": {"data_type": "0x0003", "name": "SearchFolderStorageType"},
"0x6847": {"data_type": "0x0003", "name": "WlinkSaveStamp"},
"0x6848": {"data_type": "0x0003", "name": "SearchFolderEfpFlags"},
"0x6849": {"data_type": "0x0003", "name": "WlinkType"},
"0x684A": {"data_type": "0x0003", "name": "WlinkFlags"},
"0x684B": {"data_type": "0x0102", "name": "WlinkOrdinal"},
"0x684C": {"data_type": "0x0102", "name": "WlinkEntryId"},
"0x684D": {"data_type": "0x0102", "name": "WlinkRecordKey"},
"0x684E": {"data_type": "0x0102", "name": "WlinkStoreEntryId"},
"0x684F": {"data_type": "0x0102", "name": "WlinkFolderType"},
"0x6850": {"data_type": "0x0102", "name": "WlinkGroupClsid"},
"0x6851": {"data_type": "0x001F", "name": "WlinkGroupName"},
"0x6852": {"data_type": "0x0003", "name": "WlinkSection"},
"0x6853": {"data_type": "0x0003", "name": "WlinkCalendarColor"},
"0x6854": {"data_type": "0x0102", "name": "WlinkAddressBookEID"},
"0x6855": {"data_type": "0x1003", "name": "ScheduleInfoMonthsAway"},
"0x6856": {"data_type": "0x1102", "name": "ScheduleInfoFreeBusyAway"},
"0x6868": {"data_type": "0x0040", "name": "FreeBusyRangeTimestamp"},
"0x6869": {"data_type": "0x0003", "name": "FreeBusyCountMonths"},
"0x686A": {"data_type": "0x0102", "name": "ScheduleInfoAppointmentTombstone"},
"0x686B": {"data_type": "0x1003", "name": "DelegateFlags"},
"0x686C": {"data_type": "0x0102", "name": "ScheduleInfoFreeBusy"},
"0x686D": {"data_type": "0x000B", "name": "ScheduleInfoAutoAcceptAppointments"},
"0x686E": {"data_type": "0x000B", "name": "ScheduleInfoDisallowRecurringAppts"},
"0x686F": {"data_type": "0x000B", "name": "ScheduleInfoDisallowOverlappingAppts"},
"0x6890": {"data_type": "0x0102", "name": "WlinkClientID"},
"0x6891": {"data_type": "0x0102", "name": "WlinkAddressBookStoreEID"},
"0x6892": {"data_type": "0x0003", "name": "WlinkROGroupType"},
"0x7001": {"data_type": "0x0102", "name": "ViewDescriptorBinary"},
"0x7002": {"data_type": "0x001F", "name": "ViewDescriptorStrings"},
"0x7006": {"data_type": "0x001F", "name": "ViewDescriptorName"},
"0x7007": {"data_type": "0x0003", "name": "ViewDescriptorVersion"},
"0x7C06": {"data_type": "0x0003", "name": "RoamingDatatypes"},
"0x7C07": {"data_type": "0x0102", "name": "RoamingDictionary"},
"0x7C08": {"data_type": "0x0102", "name": "RoamingXmlStream"},
"0x7C24": {"data_type": "0x000B", "name": "OscSyncEnabled"},
"0x7D01": {"data_type": "0x000B", "name": "Processed"},
"0x7FF9": {"data_type": "0x0040", "name": "ExceptionReplaceTime"},
"0x7FFA": {"data_type": "0x0003", "name": "AttachmentLinkId"},
"0x7FFB": {"data_type": "0x0040", "name": "ExceptionStartTime"},
"0x7FFC": {"data_type": "0x0040", "name": "ExceptionEndTime"},
"0x7FFD": {"data_type": "0x0003", "name": "AttachmentFlags"},
"0x7FFE": {"data_type": "0x000B", "name": "AttachmentHidden"},
"0x7FFF": {"data_type": "0x000B", "name": "AttachmentContactPhoto"},
"0x8004": {"data_type": "0x001F", "name": "AddressBookFolderPathname"},
"0x8005": {"data_type": "0x001F", "name": "AddressBookManagerDistinguishedName"},
"0x8006": {"data_type": "0x001E", "name": "AddressBookHomeMessageDatabase"},
"0x8008": {"data_type": "0x001E", "name": "AddressBookIsMemberOfDistributionList"},
"0x8009": {"data_type": "0x000D", "name": "AddressBookMember"},
"0x800C": {"data_type": "0x000D", "name": "AddressBookOwner"},
"0x800E": {"data_type": "0x000D", "name": "AddressBookReports"},
"0x800F": {"data_type": "0x101F", "name": "AddressBookProxyAddresses"},
"0x8011": {"data_type": "0x001F", "name": "AddressBookTargetAddress"},
"0x8015": {"data_type": "0x000D", "name": "AddressBookPublicDelegates"},
"0x8024": {"data_type": "0x000D", "name": "AddressBookOwnerBackLink"},
"0x802D": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute1"},
"0x802E": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute2"},
"0x802F": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute3"},
"0x8030": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute4"},
"0x8031": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute5"},
"0x8032": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute6"},
"0x8033": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute7"},
"0x8034": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute8"},
"0x8035": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute9"},
"0x8036": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute10"},
"0x803C": {"data_type": "0x001F", "name": "AddressBookObjectDistinguishedName"},
"0x806A": {"data_type": "0x0003", "name": "AddressBookDeliveryContentLength"},
"0x8073": {
"data_type": "0x000D",
"name": "AddressBookDistributionListMemberSubmitAccepted",
},
"0x8170": {"data_type": "0x101F", "name": "AddressBookNetworkAddress"},
"0x8C57": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute11"},
"0x8C58": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute12"},
"0x8C59": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute13"},
"0x8C60": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute14"},
"0x8C61": {"data_type": "0x001F", "name": "AddressBookExtensionAttribute15"},
"0x8C6A": {"data_type": "0x1102", "name": "AddressBookX509Certificate"},
"0x8C6D": {"data_type": "0x0102", "name": "AddressBookObjectGuid"},
"0x8C8E": {"data_type": "0x001F", "name": "AddressBookPhoneticGivenName"},
"0x8C8F": {"data_type": "0x001F", "name": "AddressBookPhoneticSurname"},
"0x8C90": {"data_type": "0x001F", "name": "AddressBookPhoneticDepartmentName"},
"0x8C91": {"data_type": "0x001F", "name": "AddressBookPhoneticCompanyName"},
"0x8C92": {"data_type": "0x001F", "name": "AddressBookPhoneticDisplayName"},
"0x8C93": {"data_type": "0x0003", "name": "AddressBookDisplayTypeExtended"},
"0x8C94": {
"data_type": "0x000D",
"name": "AddressBookHierarchicalShowInDepartments",
},
"0x8C96": {"data_type": "0x101F", "name": "AddressBookRoomContainers"},
"0x8C97": {
"data_type": "0x000D",
"name": "AddressBookHierarchicalDepartmentMembers",
},
"0x8C98": {"data_type": "0x001E", "name": "AddressBookHierarchicalRootDepartment"},
"0x8C99": {
"data_type": "0x000D",
"name": "AddressBookHierarchicalParentDepartment",
},
"0x8C9A": {
"data_type": "0x000D",
"name": "AddressBookHierarchicalChildDepartments",
},
"0x8C9E": {"data_type": "0x0102", "name": "ThumbnailPhoto"},
"0x8CA0": {"data_type": "0x0003", "name": "AddressBookSeniorityIndex"},
"0x8CA8": {
"data_type": "0x001F",
"name": "AddressBookOrganizationalUnitRootDistinguishedName",
},
"0x8CAC": {"data_type": "0x101F", "name": "AddressBookSenderHintTranslations"},
"0x8CB5": {"data_type": "0x000B", "name": "AddressBookModerationEnabled"},
"0x8CC2": {"data_type": "0x0102", "name": "SpokenName"},
"0x8CD8": {"data_type": "0x000D", "name": "AddressBookAuthorizedSenders"},
"0x8CD9": {"data_type": "0x000D", "name": "AddressBookUnauthorizedSenders"},
"0x8CDA": {
"data_type": "0x000D",
"name": "AddressBookDistributionListMemberSubmitRejected",
},
"0x8CDB": {
"data_type": "0x000D",
"name": "AddressBookDistributionListRejectMessagesFromDLMembers",
},
"0x8CDD": {
"data_type": "0x000B",
"name": "AddressBookHierarchicalIsHierarchicalGroup",
},
"0x8CE2": {"data_type": "0x0003", "name": "AddressBookDistributionListMemberCount"},
"0x8CE3": {
"data_type": "0x0003",
"name": "AddressBookDistributionListExternalMemberCount",
},
"0xFFFB": {"data_type": "0x000B", "name": "AddressBookIsMaster"},
"0xFFFC": {"data_type": "0x0102", "name": "AddressBookParentEntryId"},
"0xFFFD": {"data_type": "0x0003", "name": "AddressBookContainerId"},
}
|
try:
with open("input.txt", "r") as fileContent:
segments = [[segment.split(" -> ")]
for segment in fileContent.readlines()]
segments = [tuple([int(axis) for axis in coordinate.strip().split(",")])
for segment in segments for coordinates in segment for coordinate in coordinates]
segments = [segments[index:index + 2]
for index in range(0, len(segments), 2)]
except FileNotFoundError:
print("[!] The input file was not found. The program will not continue.")
exit(-1)
highestX = 0
highestY = 0
for segment in segments:
for coordinates in segment:
x, y = coordinates[0], coordinates[1]
highestX = x if x > highestX else highestX
highestY = y if y > highestY else highestY
grid = [[0 for _ in range(highestX + 1)] for _ in range(highestY + 1)]
for segment in segments:
start, end = segment[0], segment[1]
x1, y1, x2, y2 = start[0], start[1], end[0], end[1]
if x1 == x2:
for row in range(y1 if y1 < y2 else y2, (y2 + 1) if y1 < y2 else (y1 + 1)):
grid[row][x1] += 1
elif y1 == y2:
for col in range(x1 if x1 < x2 else x2, (x2 + 1) if x1 < x2 else (x1 + 1)):
grid[y1][col] += 1
dangerousAreas = sum([1 for row in grid for cell in row if cell >= 2])
print(dangerousAreas)
|
def return_rate_limit(github):
rate_limit = github.get_rate_limit()
rate = rate_limit.rate
return rate.remaining
|
# https://leetcode.com/problems/count-and-say/description/
#
# algorithms
# Hard (27.1%)
# Total Accepted: 165.2k
# Total Submissions: 609.6k
# beats 100.0% of python submissions
# 我的方法是采用位运算来做,用bit串的每一位来指代一个positive num
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
bit = 0
for n in nums:
if n > 0:
bit |= 1 << (n - 1)
flag = 0
while bit != 0:
if (bit & 1 == 0):
break
flag += 1
bit >>= 1
return flag + 1
# 查看Discuss,发现还有一种巧妙的解法,交换数组中的元素使得nums[i]存放i + 1
# 最后遍历即可得到缺失的正整数
class Solution:
def firstMissingPositive(self, nums):
for i in range(len(nums)):
while nums[i] > 0 and nums[i] <= len(nums) and nums[nums[i]-1] != nums[i]:
target_idx = nums[i]-1
nums[i], nums[target_idx] = nums[target_idx], nums[i]
for i in range(len(nums)):
if nums[i] != i+1:
return i+1
return len(nums)+1
class Solution1(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length == 0:
return 1
if length == 1:
return 1 if nums[0] != 1 else 2
for i in xrange(length):
while nums[i] >= 0 and nums[i] < length and nums[i] != i:
if nums[nums[i]] == nums[i]:
break
tmp = nums[nums[i]]
nums[nums[i]] = nums[i]
nums[i] = tmp
for i in xrange(1, length):
if nums[i] != i:
return i
return length if nums[0] != length else length + 1
|
"""
Determine whether an integer is a palindrome. Do this without extra space.
A palindrome integer is an integer x for which reverse(x) = x where reverse(x) is x with its digit reversed.
Negative numbers are not palindromic.
Example :
Input : 12121
Output : True
Input : 123
Output : False
"""
class Solution:
def palindromeNumber(self, n):
if n < 0:
return False
else:
n = str(n)
return n == n[::-1]
def method_02(self, n):
r, o = 0, n
if n < 0:
return 0
else:
while(n > 0):
r = r*10 + (n%10)
n //=10
print(r)
if r == o:
return 1
else:
return 0
s = Solution()
print(s.palindromeNumber(12121))
print(s.method_02(12121))
|
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def __str__(self):
return str(self.key)
def print_path(path):
s = ""
for p in path:
s += str(p) + " "
print(f"{s}\n---")
def paths_with_sum(root, total):
return _paths_with_sum(root, total)
def _paths_with_sum(root, total, curr_total=0, curr_path=[]):
if not root:
return []
paths = []
curr_path.append(root)
curr_total += root.key
if curr_total == total:
paths.append(curr_path)
# look for paths continuing with the curr_path
l_paths = _paths_with_sum(root.left, total, curr_total, curr_path.copy())
r_paths = _paths_with_sum(root.right, total, curr_total, curr_path.copy())
paths += l_paths + r_paths
# look for paths using children as root
l_paths = _paths_with_sum(root.left, total, 0, [])
r_paths = _paths_with_sum(root.right, total, 0, [])
paths += l_paths + r_paths
return paths
if __name__ == '__main__':
root = Node(2)
x0 = Node(0)
x0.left = Node(1)
x3 = Node(3)
x3.right = x0
x1 = Node(1)
x1.right = Node(4, None, Node(1))
x1.left = x3
root.left = x1
x5 = Node(5)
x5.right = Node(0, Node(-1), None)
root.right = x5
paths = paths_with_sum(root, 6)
for path in paths:
print_path(path)
|
a = 35
b = 7
print("a % b =", a % b)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 09:42:41 2020
@author: sv
"""
#num_obj = 4
#for idx in range(1,num_obj):
# print('idx = ', idx)
path = 'assets/obj_name.txt'
objname_list = []
count = 0
objfile = open(path, 'r')
Lines = objfile.readlines()
for line in Lines:
objname_list.append(line.strip())
count = count + 1
print('line' , count, ' : ' , line.strip())
print('objname_list : ' , objname_list)
count_obj = 0
for obj in objname_list:
count_obj = count_obj + 1
print('count_obj = ', count_obj)
# now create obj_name file save all obj's dot ply |
class Car:
"""
Docstring describing the class
"""
def __init__(self, car_name) -> None:
self.car_name = car_name
def __str__(self) -> str:
return f"Soh uma string mano {self.car_name}"
def anda(self):
return f"Anda {self.car_name}"
car = Car("ecosport")
print(car.anda())
print(car)
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
{
"name": "Panama - Accounting",
"description": """
Panamenian accounting chart and tax localization.
Plan contable panameño e impuestos de acuerdo a disposiciones vigentes
Con la Colaboración de
- AHMNET CORP http://www.ahmnet.com
""",
"author": "Cubic ERP",
'category': 'Accounting/Localizations/Account Charts',
"depends": ["account"],
"data": [
"data/l10n_pa_chart_data.xml",
"data/account_data.xml",
"data/account_tax_data.xml",
"data/account_chart_template_data.xml",
],
}
|
def valid_parentheses(s):
if not s:
return True
elif len(s) == 1:
return False
d = {"(": ")", "{": "}", "[": "]"}
stack = []
for bracket in s:
if bracket in d:
stack.append(bracket)
elif d[stack.pop()] != bracket:
return False
return len(stack) == 0
if __name__ == "__main__":
string = "[[{{}}]](())([])"
print(valid_parentheses(string)) |
#!/usr/bin/env python3
#
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
DOH_URI = '/.well-known/dns-query'
DOH_MEDIA_TYPE = 'application/dns-udpwireformat'
DOH_CONTENT_TYPE_PARAM = 'ct'
DOH_BODY_PARAM = 'body'
DOH_H2_NPN_PROTOCOLS = ['h2']
|
""""
Practice File 3
Created By David Story
Description: All about bit operators!
"""
# Some basic examples of hex, dec, and bin in Python
print("Example Using 0xAA:")
hexvalue = 0xAA
print(hex(hexvalue))
print(int(hexvalue))
print(bin(hexvalue))
print("Example Using decimal 65:")
decimal = 65
print(int(decimal))
print(hex(decimal))
print(bin(decimal))
print("Converting decimal 65 to ASCII:", chr(decimal))
# The following are examples of bit operators in Python
# Shifting bits to the right
value = 0xF0
print("Value before right shift by 4 bits:", bin(value))
newvalue = value >> 4
print("Value after right shift by 4 bits:", bin(newvalue))
# Shifting bits to the left
value = 0x01
print("Value before left shift by 4 bits:", bin(value))
newvalue = value << 4
print("Value after right shift by 4 bits:", bin(newvalue))
# We will now do bit AND, OR, XOR, and complement
x = 0xFF
y = 0xAA
print("Values to AND:", bin(x), "and'd with", bin(y))
z = x & y
print(bin(z))
x = 0xAA
y = 0x55
print("Values to OR:", bin(x), "or'd with", bin(y))
z = x | y
print(bin(z))
x = 0xFF
y = 0xAA
print("Values to XOR:", bin(x), "xor'd with", bin(y))
z = x ^ y
print(bin(z))
val = 0x00
print("Values to complement:", bin(val))
complement = ~val
print(bin(complement))
|
class Complex(object):
"""Class to save the complex file"""
def __init__(self, id, filename):
"""Creator of Complex class
Arguments:
- id - string, the id of the complex
- filename - string, the file name of the complex
"""
self.id = id
self.chain_dict = {}
self.filename = filename
def get_chain_list(self):
"""Return a list of the child chains"""
return list(self.chain_dict.values())
def complementary_chain(self, chain):
"""Return the complementary chain"""
# We supose that every complex has two chain childs
for chain_item in self.chain_dict.values():
if chain_item != chain:
return chain_item
return None
def __str__(self):
complex_id = self.id
filename = self.filename.split("/")[-1]
complex_chains = [str(chain) for chain in self.chain_dict.values()]
return 'complex_id: '+complex_id+', filename: '+filename+', complex_chains: '+", ".join(complex_chains) |
load("//ruby/private:constants.bzl", "RULES_RUBY_WORKSPACE_NAME")
load("//ruby/private:providers.bzl", "RubyRuntimeContext")
DEFAULT_BUNDLER_VERSION = "2.1.2"
BUNDLE_BIN_PATH = "bin"
BUNDLE_PATH = "lib"
SCRIPT_INSTALL_BUNDLER = "download_bundler.rb"
SCRIPT_ACTIVATE_GEMS = "activate_gems.rb"
SCRIPT_BUILD_FILE_GENERATOR = "create_bundle_build_file.rb"
# Runs bundler with arbitrary arguments
# eg: run_bundler(runtime_ctx, [ "lock", " --gemfile", "Gemfile.rails5" ])
def run_bundler(runtime_ctx, bundler_arguments):
# Now we are running bundle install
args = [
runtime_ctx.interpreter, # ruby
"-I",
".",
"-I", # Used to tell Ruby where to load the library scripts
BUNDLE_PATH, # Add vendor/bundle to the list of resolvers
"bundler/gems/bundler-{}/exe/bundle".format(runtime_ctx.bundler_version), # our binary
] + bundler_arguments
kwargs = {}
if "BUNDLER_TIMEOUT" in runtime_ctx.ctx.os.environ:
timeout_in_secs = runtime_ctx.ctx.os.environ["BUNDLER_TIMEOUT"]
if timeout_in_secs.isdigit():
kwargs["timeout"] = int(timeout_in_secs)
else:
fail("'%s' is invalid value for BUNDLER_TIMEOUT. Must be an integer." % (timeout_in_secs))
return runtime_ctx.ctx.execute(
args,
quiet = False,
# Need to run this command with GEM_HOME set so tgat the bin stubs can load the correct bundler
environment = {"GEM_HOME": "bundler", "GEM_PATH": "bundler"},
**kwargs
)
def install_bundler(runtime_ctx):
args = [
runtime_ctx.interpreter,
SCRIPT_INSTALL_BUNDLER,
runtime_ctx.bundler_version,
]
result = runtime_ctx.ctx.execute(args, environment = runtime_ctx.environment, quiet = False)
if result.return_code:
fail("Error installing bundler: {} {}".format(result.stdout, result.stderr))
def bundle_install(runtime_ctx):
result = run_bundler(
runtime_ctx,
[
"install", # bundle install
"--standalone", # Makes a bundle that can work without depending on Rubygems or Bundler at runtime.
"--binstubs={}".format(BUNDLE_BIN_PATH), # Creates a directory and place any executables from the gem there.
"--path={}".format(BUNDLE_PATH), # The location to install the specified gems to.
"--jobs=10", # run a few jobs to ensure no gem install is blocking another
],
)
if result.return_code:
fail("bundle install failed: %s%s" % (result.stdout, result.stderr))
def generate_bundle_build_file(runtime_ctx):
# Create the BUILD file to expose the gems to the WORKSPACE
# USAGE: ./create_bundle_build_file.rb BUILD.bazel Gemfile.lock repo-name [excludes-json] workspace-name
args = [
runtime_ctx.interpreter, # ruby interpreter
SCRIPT_BUILD_FILE_GENERATOR, # The template used to created bundle file
"BUILD.bazel", # Bazel build file (can be empty)
"Gemfile.lock", # Gemfile.lock where we list all direct and transitive dependencies
runtime_ctx.ctx.name, # Name of the target
repr(runtime_ctx.ctx.attr.excludes),
RULES_RUBY_WORKSPACE_NAME,
runtime_ctx.bundler_version,
]
result = runtime_ctx.ctx.execute(
args,
# The build file generation script requires bundler so we add this to make
# the correct version of bundler available
environment = {"GEM_HOME": "bundler", "GEM_PATH": "bundler"},
quiet = False,
)
if result.return_code:
fail("build file generation failed: %s%s" % (result.stdout, result.stderr))
def _rb_bundle_impl(ctx):
ctx.symlink(ctx.attr.gemfile, "Gemfile")
ctx.symlink(ctx.attr.gemfile_lock, "Gemfile.lock")
ctx.symlink(ctx.attr._create_bundle_build_file, SCRIPT_BUILD_FILE_GENERATOR)
ctx.symlink(ctx.attr._install_bundler, SCRIPT_INSTALL_BUNDLER)
ctx.symlink(ctx.attr._activate_gems, SCRIPT_ACTIVATE_GEMS)
# Setup this provider that we pass around between functions for convenience
runtime_ctx = RubyRuntimeContext(
ctx = ctx,
interpreter = ctx.path(ctx.attr.ruby_interpreter),
environment = {"RUBYOPT": "--enable-gems"},
bundler_version = ctx.attr.bundler_version,
)
# 1. Install the right version of the Bundler Gem
install_bundler(runtime_ctx)
# Create label for the Bundler executable
bundler = Label("//:bundler/gems/bundler-{}/exe/bundle".format(runtime_ctx.bundler_version))
# Run bundle install
bundle_install(runtime_ctx)
# Generate the BUILD file for the bundle
generate_bundle_build_file(runtime_ctx)
rb_bundle = repository_rule(
implementation = _rb_bundle_impl,
attrs = {
"ruby_sdk": attr.string(
default = "@org_ruby_lang_ruby_toolchain",
),
"ruby_interpreter": attr.label(
default = "@org_ruby_lang_ruby_toolchain//:ruby",
),
"gemfile": attr.label(
allow_single_file = True,
mandatory = True,
),
"gemfile_lock": attr.label(
allow_single_file = True,
),
"version": attr.string(
mandatory = False,
),
"bundler_version": attr.string(
default = DEFAULT_BUNDLER_VERSION,
),
"excludes": attr.string_list_dict(
doc = "List of glob patterns per gem to be excluded from the library",
),
"_install_bundler": attr.label(
default = "%s//ruby/private/bundle:%s" % (
RULES_RUBY_WORKSPACE_NAME,
SCRIPT_INSTALL_BUNDLER,
),
allow_single_file = True,
),
"_create_bundle_build_file": attr.label(
default = "%s//ruby/private/bundle:%s" % (
RULES_RUBY_WORKSPACE_NAME,
SCRIPT_BUILD_FILE_GENERATOR,
),
doc = "Creates the BUILD file",
allow_single_file = True,
),
"_activate_gems": attr.label(
default = "%s//ruby/private/bundle:%s" % (
RULES_RUBY_WORKSPACE_NAME,
SCRIPT_ACTIVATE_GEMS,
),
allow_single_file = True,
),
},
)
|
# Designing window for login
def login():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Login")
login_screen.geometry("300x250")
Label(login_screen, text="Please enter details below to login").pack()
Label(login_screen, text="").pack()
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry
Label(login_screen, text="Username * ").pack()
username_login_entry = Entry(login_screen, textvariable=username_verify)
username_login_entry.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password * ").pack()
password_login_entry = Entry(login_screen, textvariable=password_verify, show= '*')
password_login_entry.pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login", width=10, height=1, command = login_verify).pack()
def login_sucess():
global login_success_screen
login_success_screen = Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login Success").pack()
Button(login_success_screen, text="OK", command=delete_login_success).pack()
# Designing popup for login invalid password
def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen = Toplevel(login_screen)
password_not_recog_screen.title("Success")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen, text="Invalid Password ").pack()
Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()
# Designing popup for user not found
def user_not_found():
global user_not_found_screen
user_not_found_screen = Toplevel(login_screen)
user_not_found_screen.title("Success")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen, text="User Not Found").pack()
Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()
# Deleting popups
def delete_login_success():
login_success_screen.destroy()
def delete_password_not_recognised():
password_not_recog_screen.destroy()
def delete_user_not_found_screen():
user_not_found_screen.destroy()
|
def solution(n, times):
leftLim = 1; rightLim = max(times) * n; answer = max(times) * n
while leftLim <= rightLim:
# print(leftLim, rightLim)
lim = (leftLim + rightLim)//2; check = sum([lim//time for time in times])
if check >= n:
answer = min(answer, lim)
rightLim = lim - 1
elif check < n:
leftLim = lim + 1
return answer |
def resta(num_1, num_2):
print('Restando:', num_1, '-', num_2)
resta_total = num_1 - num_2
print('El resultado es:',resta_total)
return resta_total
def app_resta():
inp_1 = None # Can be used 'None' instead of 0 too
inp_2 = None
while inp_1 == None:
try:
inp_1 = int(input('Numero 1?: '))
except ValueError:
print('Numero invalido, intenta de nuevo')
while inp_2 == None:
try:
inp_2 = int(input('Numero 2?: '))
except ValueError:
print('Numero invalido, intenta de nuevo')
resta(inp_1, inp_2)
#app_resta()
|
"""
pyifc.compress._exceptions
--------------------------
Exceptions used in pyifc.compress module.
"""
class FileExtensionError(Exception):
"""
Raised when extension of the file is not correct.
"""
pass
|
class User:
"""
Class that generates new instances of contacts
"""
def __init__(self,user_name, password):
"""
This will construct an object of the instance of the class user
"""
self.user_name = user_name
self.password = password
user_list = [] #This is the list of the users
def save_user(self):
"""
This will add a new user to the user list
"""
User.user_list.append(self)
def delete_user(self):
"""
This will remove a user from the user list
"""
User.user_list.remove(self)
@classmethod
def display_users(cls):
"""
This will return all the users in the users list
"""
return User.user_list
@classmethod
def find_user(cls,name):
"""
Method that takes in a user's name and returns the users information
Args:
name: This is the user's name that is to be found
Returns:
user details of the person that matches the name
"""
for user in cls.user_list:
if user.user_name == name:
return user
@classmethod
def user_found(cls,name):
"""
Method that searches the user list for the user and returns either true or false depending on whether the user is found
Args:
name: This is the user's name being searched for
"""
user_names = []
for user in cls.user_list:
user_names.append(user.user_name)
if name in user_names:
return True
return False
@classmethod
def user_auth(cls,name,password):
"""
This returns a boolean on whether the credentials given during logging in are correct
"""
for user in cls.user_list:
if user.user_name == name and user.password == password:
return True
return False |
def cycleSort(array, *args):
for cycle_start in range(0, len(array) - 1):
item = array[cycle_start]
pos = cycle_start
for i in range(cycle_start + 1, len(array)):
if array[i] < item:
pos += 1
if pos == cycle_start:
continue
while array[pos] == item:
pos += 1
yield array, cycle_start, pos, -1, -1
array[pos], item = item, array[pos]
while pos != cycle_start:
pos = cycle_start
for i in range(cycle_start + 1, len(array)):
if array[i] < item:
pos += 1
while array[pos] == item:
pos += 1
yield array, cycle_start, pos, -1, -1
array[pos], item = item, array[pos]
|
class FileStream(Stream,IDisposable):
"""
Exposes a System.IO.Stream around a file,supporting both synchronous and asynchronous read and write operations.
FileStream(path: str,mode: FileMode)
FileStream(path: str,mode: FileMode,access: FileAccess)
FileStream(path: str,mode: FileMode,access: FileAccess,share: FileShare)
FileStream(path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int)
FileStream(path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int,options: FileOptions)
FileStream(path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int,useAsync: bool)
FileStream(path: str,mode: FileMode,rights: FileSystemRights,share: FileShare,bufferSize: int,options: FileOptions,fileSecurity: FileSecurity)
FileStream(path: str,mode: FileMode,rights: FileSystemRights,share: FileShare,bufferSize: int,options: FileOptions)
FileStream(handle: IntPtr,access: FileAccess)
FileStream(handle: IntPtr,access: FileAccess,ownsHandle: bool)
FileStream(handle: IntPtr,access: FileAccess,ownsHandle: bool,bufferSize: int)
FileStream(handle: IntPtr,access: FileAccess,ownsHandle: bool,bufferSize: int,isAsync: bool)
FileStream(handle: SafeFileHandle,access: FileAccess)
FileStream(handle: SafeFileHandle,access: FileAccess,bufferSize: int)
FileStream(handle: SafeFileHandle,access: FileAccess,bufferSize: int,isAsync: bool)
"""
def BeginRead(self,array,offset,numBytes,userCallback,stateObject):
"""
BeginRead(self: FileStream,array: Array[Byte],offset: int,numBytes: int,userCallback: AsyncCallback,stateObject: object) -> IAsyncResult
Begins an asynchronous read.
array: The buffer to read data into.
offset: The byte offset in array at which to begin reading.
numBytes: The maximum number of bytes to read.
userCallback: The method to be called when the asynchronous read operation is completed.
stateObject: A user-provided object that distinguishes this particular asynchronous read
request from other requests.
Returns: An object that references the asynchronous read.
"""
pass
def BeginWrite(self,array,offset,numBytes,userCallback,stateObject):
"""
BeginWrite(self: FileStream,array: Array[Byte],offset: int,numBytes: int,userCallback: AsyncCallback,stateObject: object) -> IAsyncResult
Begins an asynchronous write.
array: The buffer containing data to write to the current stream.
offset: The zero-based byte offset in array at which to begin copying bytes to the
current stream.
numBytes: The maximum number of bytes to write.
userCallback: The method to be called when the asynchronous write operation is completed.
stateObject: A user-provided object that distinguishes this particular asynchronous write
request from other requests.
Returns: An object that references the asynchronous write.
"""
pass
def CreateWaitHandle(self,*args):
"""
CreateWaitHandle(self: Stream) -> WaitHandle
Allocates a System.Threading.WaitHandle object.
Returns: A reference to the allocated WaitHandle.
"""
pass
def Dispose(self):
"""
Dispose(self: FileStream,disposing: bool)
Releases the unmanaged resources used by the System.IO.FileStream and
optionally releases the managed resources.
disposing: true to release both managed and unmanaged resources; false to release only
unmanaged resources.
"""
pass
def EndRead(self,asyncResult):
"""
EndRead(self: FileStream,asyncResult: IAsyncResult) -> int
Waits for the pending asynchronous read to complete.
asyncResult: The reference to the pending asynchronous request to wait for.
Returns: The number of bytes read from the stream,between 0 and the number of bytes you
requested. Streams only return 0 at the end of the stream,otherwise,they
should block until at least 1 byte is available.
"""
pass
def EndWrite(self,asyncResult):
"""
EndWrite(self: FileStream,asyncResult: IAsyncResult)
Ends an asynchronous write,blocking until the I/O operation has completed.
asyncResult: The pending asynchronous I/O request.
"""
pass
def Flush(self,flushToDisk=None):
"""
Flush(self: FileStream,flushToDisk: bool)
Clears buffers for this stream and causes any buffered data to be written to
the file,and also clears all intermediate file buffers.
flushToDisk: true to flush all intermediate file buffers; otherwise,false.
Flush(self: FileStream)
Clears buffers for this stream and causes any buffered data to be written to
the file.
"""
pass
def FlushAsync(self,cancellationToken=None):
""" FlushAsync(self: FileStream,cancellationToken: CancellationToken) -> Task """
pass
def GetAccessControl(self):
"""
GetAccessControl(self: FileStream) -> FileSecurity
Gets a System.Security.AccessControl.FileSecurity object that encapsulates the
access control list (ACL) entries for the file described by the current
System.IO.FileStream object.
Returns: An object that encapsulates the access control settings for the file described
by the current System.IO.FileStream object.
"""
pass
def Lock(self,position,length):
"""
Lock(self: FileStream,position: Int64,length: Int64)
Prevents other processes from reading from or writing to the
System.IO.FileStream.
position: The beginning of the range to lock. The value of this parameter must be equal
to or greater than zero (0).
length: The range to be locked.
"""
pass
def MemberwiseClone(self,*args):
"""
MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject
Creates a shallow copy of the current System.MarshalByRefObject object.
cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which
will cause the object to be assigned a new identity when it is marshaled across
a remoting boundary. A value of false is usually appropriate. true to copy the
current System.MarshalByRefObject object's identity to its clone,which will
cause remoting client calls to be routed to the remote server object.
Returns: A shallow copy of the current System.MarshalByRefObject object.
MemberwiseClone(self: object) -> object
Creates a shallow copy of the current System.Object.
Returns: A shallow copy of the current System.Object.
"""
pass
def ObjectInvariant(self,*args):
"""
ObjectInvariant(self: Stream)
Provides support for a System.Diagnostics.Contracts.Contract.
"""
pass
def Read(self,array,offset,count):
"""
Read(self: FileStream,offset: int,count: int) -> (int,Array[Byte])
Reads a block of bytes from the stream and writes the data in a given buffer.
offset: The byte offset in array at which the read bytes will be placed.
count: The maximum number of bytes to read.
Returns: The total number of bytes read into the buffer. This might be less than the
number of bytes requested if that number of bytes are not currently available,
or zero if the end of the stream is reached.
"""
pass
def ReadAsync(self,buffer,offset,count,cancellationToken=None):
""" ReadAsync(self: FileStream,buffer: Array[Byte],offset: int,count: int,cancellationToken: CancellationToken) -> Task[int] """
pass
def ReadByte(self):
"""
ReadByte(self: FileStream) -> int
Reads a byte from the file and advances the read position one byte.
Returns: The byte,cast to an System.Int32,or -1 if the end of the stream has been
reached.
"""
pass
def Seek(self,offset,origin):
"""
Seek(self: FileStream,offset: Int64,origin: SeekOrigin) -> Int64
Sets the current position of this stream to the given value.
offset: The point relative to origin from which to begin seeking.
origin: Specifies the beginning,the end,or the current position as a reference point
for origin,using a value of type System.IO.SeekOrigin.
Returns: The new position in the stream.
"""
pass
def SetAccessControl(self,fileSecurity):
"""
SetAccessControl(self: FileStream,fileSecurity: FileSecurity)
Applies access control list (ACL) entries described by a
System.Security.AccessControl.FileSecurity object to the file described by the
current System.IO.FileStream object.
fileSecurity: An object that describes an ACL entry to apply to the current file.
"""
pass
def SetLength(self,value):
"""
SetLength(self: FileStream,value: Int64)
Sets the length of this stream to the given value.
value: The new length of the stream.
"""
pass
def Unlock(self,position,length):
"""
Unlock(self: FileStream,position: Int64,length: Int64)
Allows access by other processes to all or part of a file that was previously
locked.
position: The beginning of the range to unlock.
length: The range to be unlocked.
"""
pass
def Write(self,array,offset,count):
"""
Write(self: FileStream,array: Array[Byte],offset: int,count: int)
Writes a block of bytes to this stream using data from a buffer.
array: The buffer containing data to write to the stream.
offset: The zero-based byte offset in array at which to begin copying bytes to the
current stream.
count: The number of bytes to be written to the current stream.
"""
pass
def WriteAsync(self,buffer,offset,count,cancellationToken=None):
""" WriteAsync(self: FileStream,buffer: Array[Byte],offset: int,count: int,cancellationToken: CancellationToken) -> Task """
pass
def WriteByte(self,value):
"""
WriteByte(self: FileStream,value: Byte)
Writes a byte to the current position in the file stream.
value: A byte to write to the stream.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type,path: str,mode: FileMode)
__new__(cls: type,path: str,mode: FileMode,access: FileAccess)
__new__(cls: type,path: str,mode: FileMode,access: FileAccess,share: FileShare)
__new__(cls: type,path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int)
__new__(cls: type,path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int,options: FileOptions)
__new__(cls: type,path: str,mode: FileMode,access: FileAccess,share: FileShare,bufferSize: int,useAsync: bool)
__new__(cls: type,path: str,mode: FileMode,rights: FileSystemRights,share: FileShare,bufferSize: int,options: FileOptions,fileSecurity: FileSecurity)
__new__(cls: type,path: str,mode: FileMode,rights: FileSystemRights,share: FileShare,bufferSize: int,options: FileOptions)
__new__(cls: type,handle: IntPtr,access: FileAccess)
__new__(cls: type,handle: IntPtr,access: FileAccess,ownsHandle: bool)
__new__(cls: type,handle: IntPtr,access: FileAccess,ownsHandle: bool,bufferSize: int)
__new__(cls: type,handle: IntPtr,access: FileAccess,ownsHandle: bool,bufferSize: int,isAsync: bool)
__new__(cls: type,handle: SafeFileHandle,access: FileAccess)
__new__(cls: type,handle: SafeFileHandle,access: FileAccess,bufferSize: int)
__new__(cls: type,handle: SafeFileHandle,access: FileAccess,bufferSize: int,isAsync: bool)
"""
pass
CanRead=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the current stream supports reading.
Get: CanRead(self: FileStream) -> bool
"""
CanSeek=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the current stream supports seeking.
Get: CanSeek(self: FileStream) -> bool
"""
CanWrite=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the current stream supports writing.
Get: CanWrite(self: FileStream) -> bool
"""
Handle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the operating system file handle for the file that the current FileStream object encapsulates.
Get: Handle(self: FileStream) -> IntPtr
"""
IsAsync=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the FileStream was opened asynchronously or synchronously.
Get: IsAsync(self: FileStream) -> bool
"""
Length=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length in bytes of the stream.
Get: Length(self: FileStream) -> Int64
"""
Name=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the name of the FileStream that was passed to the constructor.
Get: Name(self: FileStream) -> str
"""
Position=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the current position of this stream.
Get: Position(self: FileStream) -> Int64
Set: Position(self: FileStream)=value
"""
SafeFileHandle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file handle for the file that the current System.IO.FileStream object encapsulates.
Get: SafeFileHandle(self: FileStream) -> SafeFileHandle
"""
|
aI, aO, aT, aJ, aL, aS, aZ = map(int, input().split())
ans = aO
p = [aI, aJ, aL]
for i in range(3):
if p[i] >= 2:
if p[i] % 2 == 0:
ans += (p[i] - 2) // 2 * 2
p[i] = 2
else:
ans += p[i] // 2 * 2
p[i] = 1
p.sort()
if sum(p) >= 5:
ans += sum(p) // 2 * 2
elif sum(p) == 4:
if p == [1, 1, 2]:
ans += 3
elif p == [0, 2, 2]:
ans += 4
else:
assert(False)
elif sum(p) == 3:
if p == [0, 1, 2]:
ans += 2
elif p == [1, 1, 1]:
ans += 3
else:
assert(False)
elif sum(p) == 2:
if p == [0, 0, 2]:
ans += 2
elif p == [0, 1, 1]:
pass
else:
assert(False)
else:
assert(sum(p) <= 1)
print(ans)
|
class Solution:
def twoSum(self, nums , target) :
# a python dictionary(hash)
# key is number
# value is index of list: nums
number_dictionary = dict()
for index, number in enumerate(nums):
# put every number into dictionary with index
number_dictionary[ number ] = index
# a list for index storage for i, index_of_dual that nums[i] + nums[index_of_dual] = target
solution = list()
for i in range( len(nums) ):
value = nums[i]
# compute the dual that makes value + dual = target
dual = target - value
index_of_dual = number_dictionary.get( dual, None)
if index_of_dual is not None and index_of_dual != i:
# Note: we can't use the same element twice, thus return empty list
# make a list for solution list
solution = list([i, index_of_dual])
break
else:
# if index_of_dual is None, keeps going to next iteration
# Problem description says that each input would have exactly one solution
continue
# return index of nums that makes the sum equal to target
return solution |
"""
0693. Binary Number with Alternating Bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
"""
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
return '00' not in bin(n) and '11' not in bin(n)
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
return not (n * 3) & (n * 3 + 1) & (n * 3 + 2)
|
"""
Anfang des Algorithmus
"""
def mergeSort(list):
# überprüft, ob die Länge der übergebenen Liste größer als 1 ist
if len(list) > 1:
# länge der Liste
n = len(list)
# mitte der Liste
mitte = n //2
# linke hälfte der Liste
linke_haelfte = list[:mitte]
# rechte hälfte der Liste
rechte_haelfte = list[mitte:]
# ruft die Funktion mit der linke Hälfte der Liste auf und sortiert diese
mergeSort(linke_haelfte)
# ruft die Funktion mit der linken Hälfte der Liste auf und sortiert diese
mergeSort(rechte_haelfte)
# initialisiert die vairablen i, j und k und setzt den Startwert dieser auf 0
i = j = k = 0
# erste Schleife
# Diese Schleife wir solange durchlaufen, bis i größer oder gleich der Länge von der
# linken Hälfte ist oder bis j größer oder gleich der Länge von der rechten Hälfte ist
while i < len(linke_haelfte) and j < len(rechte_haelfte):
# Wenn das Element, welches sich an der i Stelle von der linken Hälfte befindet
# größer ist als das Element an der j Stelle der rechten Hälfte, bekommt unsere
# übergebene Liste an der Stelle k den Wert zugewiesen, der sich an der i Stelle von der linken Hälfte befindet
# und der Wert i erhöht sich um 1
if linke_haelfte[i] < rechte_haelfte[j]:
list[k] = linke_haelfte[i]
i += 1
# Ansonsten bekommt unsere übergebene Liste an der Stelle k den Wert zugewiesen,
# der sich an der j Stelle von der rechten Hälfte befindet und der Wert j erhöht sich um 1
else:
list[k] = rechte_haelfte[j]
j += 1
# Nach jedem Schleifendurchlauf wird der Wert k um 1 erhöht
k += 1
# zweite Schleife
# Hierdurch wird überprüft, ob sich noch ein Element in der linken Hälfte befindet,
# welches noch nicht bei unserer übergebenen List einsortiert wurde
while i < len(linke_haelfte):
list[k] = linke_haelfte[i]
k += 1
i += 1
# dritte Schleife
# Hierdurch wird überprüft, ob sich noch ein Element in der rechten Hälfte befindet,
# welches noch nicht bei unserer übergebenen List einsortiert wurde
while j < len(rechte_haelfte):
list[k] = rechte_haelfte[j]
k += 1
j += 1
"""
Ende des Algorithmus
"""
# Wir erstellen eine Liste die sortiert werden soll
list = [20, 21, 13, 6, 85, 16]
# Hier geben wir unsere unsortierte liste in der Konsole aus
print("Unsortierte Liste: " + str(list))
# ruft unsere Funktion mit der zu sortierenden Liste auf
mergeSort(list)
# Hier geben wir unsere sortierte liste in der Konsole aus
print("Sortierte Liste: " + str(list))
|
n = int(input("Enter the number : "))
fact = 1
for i in range(1,n + 1):
fact = fact * i
print("Factorial of {} is {}".format(n,fact)) |
"""
This module contains all the string constants defined for this repo.
"""
"""
Regex declarations used in Web Info module.
"""
RE_VISITORS = "^> (.*?) visitors per day <$"
RE_IP_V6 = "IPv6.png'><a href='\/info\/whois6\/(.*?)'>"
RE_IP_LOCATION = "IP Location: <\/td> <td class='vmiddle'><span class='cflag (.*?)'><\/span><a href='\/view\/countries\/(.*?)\/Internet_Usage_Statistics_(.*?).html'>(.*?)<\/a>"
RE_REVERSE_DNS = "IP Reverse DNS (.*?)<\/b><\/div><div class='sval'>(.*?)<\/div>"
RE_HOSTING_COMPANY = "Hosting Company: <\/td><td valign='middle' class='bold'> <span class='nounderline'><a title='(.*?)"
RE_HOSTING_COMPANY_IP_OWNER_1 = "Hosting Company \/ IP Owner: <\/td><td valign='middle' class='bold'> <span class='cflag (.*?)'><\/span> <a href='\/view\/web_hosting\/(.*?)'>(.*?)<\/a>"
RE_HOSTING_COMPANY_IP_OWNER_2 = "Hosting Company \/ IP Owner: <\/td><td valign='middle' class='bold'> <span class='nounderline'><a title='(.*?)"
RE_HOSTING_COMPANY_IP_OWNER = RE_HOSTING_COMPANY_IP_OWNER_1
RE_HOSTING_IP_RANGE = "IP Range <b>(.*?) - (.*?)<\/b><br>have <b>(.*?)<\/b>"
RE_HOSTING_ADDRESS = "Hosting Address: <\/td><td>(.*?)<\/td><\/tr>"
RE_OWNER_ADDRESS = "Owner Address: <\/td><td>(.*?)<\/td>"
RE_HOSTING_COUNTRY = "Hosting Country: <\/td><td><span class='cflag (.*?)'><\/span><a href='\/view\/countries\/(.*?)\/(.*?)'>(.*?)<\/a>"
RE_OWNER_COUNTRY = "Owner Country: <\/td><td><span class='cflag (.*?)'><\/span><a href='\/view\/countries\/(.*?)\/(.*?)'>(.*?)<\/a>"
RE_HOSTING_PHONE = "Hosting Phone: <\/td><td>(.*?)<\/td><\/tr>"
RE_OWNER_PHONE = "Owner Phone: <\/td><td>(.*?)<\/td><\/tr>"
RE_HOSTING_WEBSITE = "Hosting Website: <img class='cursor-help noprint left10' border='0' width='12' height='10' src='\/images\/tooltip.gif'><\/td><td><a href='\/(.*?)'>(.*?)<\/a><\/td>"
RE_OWNER_WEBSITE = "Owner Website: <img class='cursor-help noprint left10' border='0' width='12' height='10' src='\/(.*?)'><\/td><td><a href='\/(.*?)'>(.*?)<\/a>"
RE_CIDR = "CIDR:<\/td><td> (.*?)<\/td><\/tr>"
RE_OWNER_CIDR = """Owner CIDR: <\/td><td><span class='(.*?)'><a href="\/view\/ip_addresses\/(.*?)">(.*?)<\/a>\/(.*?)<\/span><\/td><\/tr>"""
RE_HOSTING_CIDR = """Hosting CIDR: <\/td><td><span class='(.*?)'><a href="\/view\/ip_addresses\/(.*?)">(.*?)<\/a>\/(.*?)<\/span><\/td><\/tr>""" |
pkgname = "lua5.4-zlib"
pkgver = "1.2"
pkgrel = 0
build_style = "makefile"
make_build_target = "linux"
hostmakedepends = ["pkgconf"]
makedepends = ["lua5.4-devel", "zlib-devel"]
pkgdesc = "Zlib streaming interface for Lua (5.4)"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "https://github.com/brimworks/lua-zlib"
source = f"{url}/archive/v{pkgver}.tar.gz"
sha256 = "26b813ad39c94fc930b168c3418e2e746af3b2e80b92f94f306f6f954cc31e7d"
# no test suite
options = ["!check"]
def init_configure(self):
tcflags = self.get_cflags(["-shared"], shell = True)
eargs = [
f"LIBS={tcflags} -lz -llua5.4 -lm",
"INCDIR=-I/usr/include -I/usr/include/lua5.4",
"LIBDIR=-L/usr/lib",
"LUACPATH=/usr/lib/lua/5.4",
"LUAPATH=/usr/share/lua/5.4",
]
self.make_build_args += eargs
self.make_install_args += eargs
self.make_check_args += eargs
self.tools["LD"] = self.get_tool("CC")
def do_install(self):
self.install_license("README")
self.install_file("zlib.so", "usr/lib/lua/5.4", mode = 0o755)
|
# TempConv.py
# Celcius to Fahreinheit
def Fahreinheit(temp):
temp = float(temp)
temp = (temp*9/5)+32
return temp
# Fahreinheit to Celcius
def Celcius(temp):
temp = float(temp)
temp = (temp-32)*5/9
return temp
|
friends = ["Sam","Samantha","Saurab"]
start_with_s = [x for x in friends if x.startswith("S")]
#compare list friends and start_with_s, bot are same value but result should be false.
#Because two are different list
print(friends is start_with_s)
print("friends : ", id(friends)," start_with_s : ",id(start_with_s))
#if we compare data then output will be true
print(friends[0] is start_with_s[0])
|
# La longitud de la lista es N-1. Entonces, la suma de todos los N elementos, es decir, la suma de los números de 1 a N
# se puede calcular usando la fórmula n * (n + 1) / 2. Encontramos la suma de todos los elementos de la lista y la
# restamos de la suma de los primeros N números naturales, el resultado de la resta será el valor del elemento faltante.
def findMissingNumber(Q):
N = len(Q)
sum_total = (N + 1) * (N + 2) // 2
sum_de_Q = sum(Q)
return sum_total - sum_de_Q
Q = [10, 18, 11, 3, 6, 15, 7, 14, 2, 8, 1, 4, 16, 12, 5, 17, 13]
print(findMissingNumber(Q))
|
# -*- coding: UTF-8 -*-
def value_judge(request, *args): # 查看客户端有没有漏传字段
for i in args:
if i not in request.data or request.data.get(i) == '' or request.data.get(i) is None:
return False
return True
|
#!/usr/bin/python3
# 100-weight_average.py
def weight_average(my_list=[]):
"""Return the weighted average of all integers in a list of tuples."""
if not isinstance(my_list, list) or len(my_list) == 0:
return (0)
avg = 0
size = 0
for tup in my_list:
avg += (tup[0] * tup[1])
size += tup[1]
return (avg / size)
|
""""
entradas
preciocomputador-->P-->float
valorcuotas-->T-->float
salidas
porcentajerecargo-->por-->float
"""
#entradas
P=float(input("Ingrese el precio del computador: "))
T=float(input("Ingrese el valor de las cuotas: "))
#caja negra
tc=T*12
r=tc-P
por=(r*100)/P
#salidas
print("El porcentaje de recargo es del ", por, "%") |
class MSDocument(object):
def setZoomValue(self, zoomLevel):
"""
Zoom the document. 1.0 represents actual size, 2.0 means 200% etc.
"""
# Not implemented
pass
def export(self):
"""
Takes you to the the export tool. Pass nil as the argument.
"""
pass
def exportPDFBook(self):
"""
A nice method not exposed in the UI at the moment; exports each slice on each page to a
multi-page PDF file. Pass nil as the argument.
"""
# Not implemented
pass
def showMessage(self, displayString):
"""
Pass a string to be displayed at the top of the canvas momentarily. The same method used
for displaying the current zoom level and other tips.
"""
# Not implemented
pass
def artboards(self):
"""
Both return an array representing the artboards and slices on the current page. Artboards
are of type MSArtboardGroup and slices are of MSSliceLayer type.
"""
pass
def children(self):
"""
Returns an array containing all layers (including slices and artboards) on the current page.
"""
pass
def pages(self):
"""
Returns an array of all pages in the document. Each page is an MSPage object.
"""
pass
def askForUserInput(self, dialogLabel, initialValue):
"""
Asks for user input and returns the value they chosen. The first argument is the label for
the dialog panel, the second argument can be used to provide a default value. See the User
Input & Feedback section for examples.
(http://www.bohemiancoding.com/sketch/support/developer/02-common-tasks/05.html)
"""
# Not implemented
pass
def saveArtboardOrSlice(self, exportItem, toFile):
"""
Saves an area of the canvas to an image file. The first argument is a GKRect, MSSliceLayer
or MSArtboardGroup and the image gets written to the file specified in the second argument.
The file format is derived from the extension. See the Exporting section for examples.
"""
pass
def currentView(self):
"""
Returns an MSContentDrawView subclass that represents the visible Canvas
"""
# Not implemented
pass
def addBlankPage(self):
"""
Adds a new MSPage object to the document, inserting it below the current page, copying its
grid and ruler position too.
"""
# Not implemented
pass
def removePage(self, page):
"""
Removes the given page from the document. The argument is an MSPage object.
"""
# Not implemented
pass
def allExportableLayers(self):
"""
Returns an array of all exportable layers in the document
"""
pass
|
#Escreva um programa que leia um inteiro não negativo n e
#imprima a soma dos n primeiros números primos.
primo=[]
n=int(input("Informe um numero: "))
if(n>0):
for c in range(1,n+1):
i=0
for u in range(1,c+1):
if(c%u==0):
i+=1
if(i<=2):
print(c)
primo.append(c)
print(sum(primo))
|
# -*- coding: utf-8 -*-
"""
pygments.console
~~~~~~~~~~~~~~~~
Format colored console output.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
esc = "\x1b["
codes = {}
codes[""] = ""
codes["reset"] = esc + "39;49;00m"
codes["bold"] = esc + "01m"
codes["faint"] = esc + "02m"
codes["standout"] = esc + "03m"
codes["underline"] = esc + "04m"
codes["blink"] = esc + "05m"
codes["overline"] = esc + "06m"
dark_colors = ["black", "darkred", "darkgreen", "brown", "darkblue",
"purple", "teal", "lightgray"]
light_colors = ["darkgray", "red", "green", "yellow", "blue",
"fuchsia", "turquoise", "white"]
x = 30
for d, l in zip(dark_colors, light_colors):
codes[d] = esc + "%im" % x
codes[l] = esc + "%i;01m" % x
x += 1
del d, l, x
codes["darkteal"] = codes["turquoise"]
codes["darkyellow"] = codes["brown"]
codes["fuscia"] = codes["fuchsia"]
codes["white"] = codes["bold"]
def reset_color():
return codes["reset"]
def colorize(color_key, text):
return codes[color_key] + text + codes["reset"]
def ansiformat(attr, text):
"""
Format ``text`` with a color and/or some attributes::
color normal color
*color* bold color
_color_ underlined color
+color+ blinking color
"""
result = []
if attr[:1] == attr[-1:] == '+':
result.append(codes['blink'])
attr = attr[1:-1]
if attr[:1] == attr[-1:] == '*':
result.append(codes['bold'])
attr = attr[1:-1]
if attr[:1] == attr[-1:] == '_':
result.append(codes['underline'])
attr = attr[1:-1]
result.append(codes[attr])
result.append(text)
result.append(codes['reset'])
return ''.join(result)
|
## Given a position, write a function to
## find if that position is within 5 points of a monster:
a_treasure_map = {
"45,46": "sea monster",
"55,38": "air monster",
"33,78": "lava monster",
"22,23": "shining castle",
"64,97": "shield of truth",
"97,3": "sword of power",
}
def near_monster(position, a_treasure_map):
x,y = position.split(",")
playerX = int(x)
playerY = int(y)
for key, value in a_treasure_map.items():
if value.endswith('monster'):
monsterX, monsterY = map(int, key.split(","))
distance = ((monsterX - playerX)**2 + (monsterY - playerY)**2)**0.5
if distance <= 5:
return True
return False
print(near_monster("44,48", a_treasure_map))
print(near_monster("3,7", a_treasure_map))
## Given your current position, are you closer to the secret gem,
## or the hidden springs? Write a function that returns the closest treasure to you
a_treasure_map = {
"38.2859417,-122.3599983": "secret_gem",
"34.3183327,-118.1399376": "hidden_springs"
}
def closest_treasure(position,a_treasure_map):
positionX, positionY = map(float, position.split(","))
min_distance = 1000000
min_value = ""
for key, value in a_treasure_map.items():
treasureX, treasureY = map(float, key.split(","))
distance = ((treasureX - positionX)**2 + (treasureY - positionY)**2)**0.5
if distance < min_distance:
min_distance = distance
min_value = value
return min_value
print(closest_treasure("5,6", a_treasure_map))
print(closest_treasure("36,-122", a_treasure_map))
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
""" Constants file for wiating backend
"""
AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID'
AUTH0_DOMAIN = 'AUTH0_DOMAIN'
AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET'
AUTH0_CALLBACK_URL = 'AUTH0_CALLBACK_URL'
AUTH0_AUDIENCE = 'AUTH0_AUDIENCE'
SECRET_KEY = 'SECRET_KEY'
S3_BUCKET = 'S3_BUCKET'
ES_CONNECTION_STRING = 'ES_CONNECTION_STRING'
INDEX_NAME = 'INDEX_NAME'
IMAGE_RESIZER_QUEUE = 'IMAGE_RESIZER_QUEUE'
DASHBOARD_CONFIG_FILE_PATH = 'DASHBOARD_CONFIG_FILE_PATH'
APP_METADATA_KEY = 'https://mapa.wiating.eu/app_metadata'
MODERATOR = 'moderator'
FLASK_STATIC_PATH = 'FLASK_STATIC_PATH'
FLASK_STATIC_FOLDER = 'FLASK_STATIC_FOLDER'
REDIS_HOST = 'REDIS_HOST'
REDIS_PORT = 'REDIS_PORT'
|
def cuberoot2(x0):
x = x0
i = 0
while True:
nextIt = (1/3)*(2*x+2/(x**2))
if (abs(nextIt - x) <= 10**-7):
break
else:
i += 1
x = nextIt
print("The sequence starting at", x0, "converges to", x,"in", i, "iterations.")
cuberoot2(20)
def nesty(x):
f = (x - 1) ** 5
g = x ** 5 - 5 * x ** 4 + 10 * x ** 3 - 10 * x ** 2 + 5 * x -1
h = x * (5 - x * (10 - x * (10 - x * (5 - x)))) - 1
print("x =", x, ", f(x) =", f, ", g(x) =", g, ", h(x) =", h)
for i in range(1,8):
nesty(1 + 10 ** -i)
#the answer *should* be (10^-n)^5 = 10 ^ -5n. With n ranging from 1 to 7, that goes as low as 10 ^ -35! This means that we want to minimize our loss of significance or face massive relative error
#f minimized the number of operations (in particular subtraction) to the answer, thereby minimizing loss of significance and the relative error
#therefore f output the best results
#on the other hand, g and h had more subtraction, resulting in greater loss of significance, worse relative error, and worse results |
"""
Module: 'machine' on micropython-rp2-1.15
"""
# MCU: {'family': 'micropython', 'sysname': 'rp2', 'version': '1.15.0', 'build': '', 'mpy': 5637, 'port': 'rp2', 'platform': 'rp2', 'name': 'micropython', 'arch': 'armv7m', 'machine': 'Raspberry Pi Pico with RP2040', 'nodename': 'rp2', 'ver': '1.15', 'release': '1.15.0'}
# Stubber: 1.3.9
class ADC:
''
CORE_TEMP = 4
def read_u16():
pass
class I2C:
''
def init():
pass
def readfrom():
pass
def readfrom_into():
pass
def readfrom_mem():
pass
def readfrom_mem_into():
pass
def readinto():
pass
def scan():
pass
def start():
pass
def stop():
pass
def write():
pass
def writeto():
pass
def writeto_mem():
pass
def writevto():
pass
class PWM:
''
def deinit():
pass
def duty_ns():
pass
def duty_u16():
pass
def freq():
pass
PWRON_RESET = 1
class Pin:
''
ALT = 3
IN = 0
IRQ_FALLING = 4
IRQ_RISING = 8
OPEN_DRAIN = 2
OUT = 1
PULL_DOWN = 2
PULL_UP = 1
def high():
pass
def init():
pass
def irq():
pass
def low():
pass
def off():
pass
def on():
pass
def toggle():
pass
def value():
pass
class SPI:
''
LSB = 0
MSB = 1
def deinit():
pass
def init():
pass
def read():
pass
def readinto():
pass
def write():
pass
def write_readinto():
pass
class Signal:
''
def off():
pass
def on():
pass
def value():
pass
class SoftI2C:
''
def init():
pass
def readfrom():
pass
def readfrom_into():
pass
def readfrom_mem():
pass
def readfrom_mem_into():
pass
def readinto():
pass
def scan():
pass
def start():
pass
def stop():
pass
def write():
pass
def writeto():
pass
def writeto_mem():
pass
def writevto():
pass
class SoftSPI:
''
LSB = 0
MSB = 1
def deinit():
pass
def init():
pass
def read():
pass
def readinto():
pass
def write():
pass
def write_readinto():
pass
class Timer:
''
ONE_SHOT = 0
PERIODIC = 1
def deinit():
pass
def init():
pass
class UART:
''
INV_RX = 2
INV_TX = 1
def any():
pass
def read():
pass
def readinto():
pass
def readline():
pass
def sendbreak():
pass
def write():
pass
class WDT:
''
def feed():
pass
WDT_RESET = 3
def bootloader():
pass
def deepsleep():
pass
def disable_irq():
pass
def enable_irq():
pass
def freq():
pass
def idle():
pass
def lightsleep():
pass
mem16 = None
mem32 = None
mem8 = None
def reset():
pass
def reset_cause():
pass
def soft_reset():
pass
def time_pulse_us():
pass
def unique_id():
pass
|
# add a key to a dicitonary
# Sample dictionary: {0:10,1:20}
# Expected Result: {0:10,1:20,2:30}
a={0:10,1:20}
a[2]=30
print(a) |
# 이 코드의 오류를 수정하고 아래 설명에 따라 테스트하세요.
# 2.00을 입력하면 "Tax rate is : 0.07" 을 출력하세요.
# 1.00을 입력하면 "Tax rate is : 0.07" 을 출력하세요.
# 0.50을 입력하면 "Tax rate is : 0" 을 출력하세요.
price = input('how much did you pay? ')
price = float(price)
if price >= 1.00:
tax = .07
print('Tax rate is: ' + str(tax))
else:
tax = 0
print('Tax rate is: ' + str(tax))
|
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Scott Burns <sburns@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
def parse_config(fname):
"""Parse a config file (like .ave and .cov files)
Parameters
----------
fname : string
config file name
Returns
-------
conditions : list of dict
Each condition is indexed by the event type.
A condition contains as keys::
tmin, tmax, name, grad_reject, mag_reject,
eeg_reject, eog_reject
"""
reject_params = read_reject_parameters(fname)
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
cat_ind = [i for i, x in enumerate(lines) if "category {" in x]
event_dict = dict()
for ind in cat_ind:
for k in range(ind + 1, ind + 7):
words = lines[k].split()
if len(words) >= 2:
key = words[0]
if key == 'event':
event = int(words[1])
break
else:
raise ValueError('Could not find event id.')
event_dict[event] = dict(**reject_params)
for k in range(ind + 1, ind + 7):
words = lines[k].split()
if len(words) >= 2:
key = words[0]
if key == 'name':
name = ' '.join(words[1:])
if name[0] == '"':
name = name[1:]
if name[-1] == '"':
name = name[:-1]
event_dict[event]['name'] = name
if key in ['tmin', 'tmax', 'basemin', 'basemax']:
event_dict[event][key] = float(words[1])
return event_dict
def read_reject_parameters(fname):
"""Read rejection parameters from .cov or .ave config file
Parameters
----------
fname : str
Filename to read.
"""
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
reject_names = ['gradReject', 'magReject', 'eegReject', 'eogReject',
'ecgReject']
reject_pynames = ['grad', 'mag', 'eeg', 'eog', 'ecg']
reject = dict()
for line in lines:
words = line.split()
if words[0] in reject_names:
reject[reject_pynames[reject_names.index(words[0])]] = \
float(words[1])
return reject
def read_flat_parameters(fname):
"""Read flat channel rejection parameters from .cov or .ave config file"""
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
reject_names = ['gradFlat', 'magFlat', 'eegFlat', 'eogFlat', 'ecgFlat']
reject_pynames = ['grad', 'mag', 'eeg', 'eog', 'ecg']
flat = dict()
for line in lines:
words = line.split()
if words[0] in reject_names:
flat[reject_pynames[reject_names.index(words[0])]] = \
float(words[1])
return flat
|
add_user_permissions_response = {
'user': 'enterprise_search',
'permissions': ['permission1']
}
|
#
# Function for program annotation-to-outline. Responsible for writing the
# LaTex structure to file.
#
def writeToLatex(fileName, outlineContents, defContents, titleContents):
# Write contents to .tex file
f = open(fileName, 'w') # file object
# write LaTex preamble to file
f.write("\\documentclass[10pt,a4paper,draft]{report}\n\
\\usepackage{geometry}\\geometry{a4paper,\
left=22mm,\n\
right=22mm,\n\
top=25mm,\n\
bottom=30mm,\n\
}\n\
\\usepackage[utf8]{inputenc}\n\
\\usepackage[english]{babel}\n\
\\usepackage{amsmath}\n\
\\usepackage{amsfonts}\n\
\\usepackage{amssymb}\n\
\\usepackage{textcomp}\n\
\\setlength\\parindent{0pt}\n\
\\begin{document}\n\n")
if titleContents:
f.write("\\begin{center}\n\\section*{Summary -- %s}\n\\end{center}\n\n" % titleContents)
if defContents:
f.write("\n\\subsection*{Definitions}\n\n%s\n\n" % defContents)
if outlineContents:
f.write("\\subsection*{Outline}\n\n%s" % outlineContents)
f.write("\n\n\\end{document}") # end LaTex document
f.close() # close file
|
dist1={0: 460146, 1: 211769, 2: 89768, 3: 41207, 4: 21465, 5: 10368, 6: 6336, 7: 3640, 8: 2378, 9: 1440, 10: 1068, 11: 694, 12: 483, 13: 336, 14: 237, 15: 155, 16: 153, 17: 128, 18: 94, 19: 81, 20: 123, 21: 71, 22: 89, 23: 40, 24: 44, 25: 43, 26: 25, 27: 15, 28: 19, 29: 19, 30: 23, 31: 19, 32: 6, 33: 13, 34: 8, 35: 3, 36: 11, 37: 5, 38: 7, 39: 7, 40: 4, 41: 6, 42: 4, 43: 3, 44: 4, 45: 3, 46: 2, 47: 2, 48: 2, 49: 2, 50: 1, 51: 3, 52: 1, 53: 2, 54: 3, 56: 1, 57: 1, 58: 3, 59: 3, 60: 1, 61: 1, 62: 1, 63: 3, 64: 3, 65: 4, 66: 4, 67: 2, 68: 1, 69: 1, 70: 2, 71: 1, 72: 3, 73: 1, 74: 3, 75: 2, 77: 2, 78: 3, 79: 3, 80: 2, 83: 1, 84: 4, 85: 2, 86: 1, 88: 1, 89: 1, 90: 1, 91: 3, 92: 1, 93: 1}
dist2={0: 494751, 1: 205874, 2: 84597, 3: 45342, 4: 22439, 5: 11599, 6: 5925, 7: 3157, 8: 2042, 9: 1089, 10: 698, 11: 363, 12: 292, 13: 167, 14: 95, 15: 85, 16: 69, 17: 45, 18: 50, 19: 20, 20: 30, 21: 26, 22: 13, 23: 13, 24: 11, 25: 11, 26: 12, 27: 11, 28: 10, 29: 12, 30: 4, 31: 8, 32: 12, 33: 9, 34: 6, 35: 4, 36: 8, 37: 5, 38: 3, 39: 5, 40: 5, 41: 5, 42: 2, 43: 2, 44: 3, 45: 2, 46: 3, 47: 3, 48: 7, 49: 2, 50: 3, 51: 3, 52: 3, 53: 3, 54: 4, 55: 1, 56: 3, 58: 2, 59: 1, 60: 1, 61: 3, 62: 1, 63: 1, 64: 2, 65: 1, 67: 1, 68: 1, 69: 7, 72: 1, 74: 5, 75: 1, 77: 1, 78: 1, 80: 1, 83: 1, 84: 1, 87: 1, 88: 2, 91: 1, 92: 1, 93: 1}
dist3={0: 512229, 1: 219168, 2: 90981, 3: 48682, 4: 24545, 5: 11873, 6: 6081, 7: 3215, 8: 2252, 9: 1134, 10: 815, 11: 412, 12: 300, 13: 140, 14: 91, 15: 64, 16: 50, 17: 39, 18: 22, 19: 8, 20: 29, 21: 12, 22: 11, 23: 8, 24: 5, 25: 4, 26: 6, 27: 3, 28: 3, 29: 7, 30: 2, 31: 3, 32: 2, 33: 1, 34: 2, 38: 4, 39: 1, 40: 1, 41: 1, 43: 2, 45: 1, 47: 1, 48: 1, 50: 1, 52: 2, 57: 1, 63: 1, 79: 1, 80: 2, 93: 1}
dist1={k: v / total for total in (sum(dist1.values()),) for k, v in dist1.items()}
dist2={k: v / total for total in (sum(dist2.values()),) for k, v in dist2.items()}
dist3={k: v / total for total in (sum(dist3.values()),) for k, v in dist3.items()}
dist1_plus_dist2={ k: dist1.get(k, 0) + dist2.get(k, 0) for k in set(dist1) | set(dist2) }
# print (dist1_plus_dist2)
dist1_plus_dist2_plus_dist3={ k: dist1_plus_dist2.get(k, 0) + dist3.get(k, 0) for k in set(dist3) | set(dist1_plus_dist2) }
# dist1_plus_dist2_plus_dist3 = {k: v / total for total in (sum(dist1_plus_dist2_plus_dist3.values()),) for k, v in dist1_plus_dist2_plus_dist3.items()}
for key, value in dist1_plus_dist2_plus_dist3.items():
dist1_plus_dist2_plus_dist3[key] = value / 3
print(dist1_plus_dist2_plus_dist3)
|
a = str(input('Digite: '))
def temLetra_a(a):
if('a' in a):
return True
else:
return False
variavel = temLetra_a(a)
if variavel == True:
print('tem letra A')
elif variavel == False:
print('Não tem letra {}'.format(a))
else:
print('...')
'''
testando outros módulos
'''
def funcao(x = 10, j = 0):
i = x * j
print(i)
c = int(input(': '))
u = int(input(': '))
funcao(c, u)
|
# def get_words(sentence):
# return list(filter((lambda x: len(str(x)) > 0), str(sentence).split(sep=' ')))
#
#
# def get_word_count(sentence):
# return get_words(sentence).count()
def get_word_freq_in_sentences(word, sentences):
"""
:param word: the word which frequency we calculate
:param sentences: a list of the sentences, representing the document / search space
:return: the number of occurrences of the given word in the search space. Letter case is ignored
"""
freq = 0
for sentence in sentences:
for w in sentence:
if str(word).lower() == str(w).lower():
freq += 1
return freq
def get_most_popular_word(sentences):
"""
Returns the most widely-used word among the given sentences
"""
word_map = {}
for sentence in sentences:
for word in sentence:
if word not in word_map:
word_map[word] = 1
word_map[word] = word_map[word] + 1
max_freq = 0
max_freq_word = ''
for key in word_map:
if word_map.get(key) > max_freq:
max_freq = word_map.get(key)
max_freq_word = key
return max_freq_word
def get_symbol_freq_in_senteces(symbol, sentences):
"""
:param symbol: The symbol which frequency we calculater
:param sentences: a list of the sentences, representing the document / search space
:return: the number of occurrences of the given symbol among the words in the search space.
"""
freq = 0
for sentence in sentences:
for w in sentence:
for char in w:
if char == symbol:
freq += 1
return freq
def get_punct_symbols():
return [',', '.', '!', '?', '-', ':', ';']
|
class SpaceAge:
def __init__(self, seconds: float):
self.seconds = seconds
def _space_age(self, ratio: float = 1.0, ndigits: int = 2) -> float:
return round(self.seconds / 31557600.0 / ratio, ndigits)
def on_mercury(self) -> float:
return self._space_age(0.2408467)
def on_venus(self) -> float:
return self._space_age(0.61519726)
def on_earth(self) -> float:
return self._space_age()
def on_mars(self) -> float:
return self._space_age(1.8808158)
def on_jupiter(self) -> float:
return self._space_age(11.862615)
def on_saturn(self) -> float:
return self._space_age(29.447498)
def on_uranus(self) -> float:
return self._space_age(84.016846)
def on_neptune(self) -> float:
return self._space_age(164.79132)
|
# This program demonstrates the repetition operator.
def main():
# Print nine rows increasing in length.
for count in range(1, 10):
print('Z' * count)
# Print nine rows decreasing in length.
for count in range(8, 0, -1):
print('Z' * count)
# Call the main function.
main()
|
"""Definitions for using tools like saved_model_cli."""
load("//tensorflow:tensorflow.bzl", "clean_dep", "if_xla_available")
load("//tensorflow:tensorflow.bzl", "tfcompile_target_cpu")
load("//tensorflow/compiler/aot:tfcompile.bzl", "target_llvm_triple")
def _maybe_force_compile(args, force_compile):
if force_compile:
return args
else:
return if_xla_available(args)
def saved_model_compile_aot(
name,
directory,
filegroups,
cpp_class,
checkpoint_path = None,
tag_set = "serve",
signature_def = "serving_default",
variables_to_feed = "",
target_triple = None,
target_cpu = None,
multithreading = False,
force_without_xla_support_flag = True,
tags = None):
"""Compile a SavedModel directory accessible from a filegroup.
This target rule takes a path to a filegroup directory containing a
SavedModel and generates a cc_library with an AOT compiled model.
For extra details, see the help for saved_model_cli's aot_compile_cpu help.
**NOTE** Any variables passed to `variables_to_feed` *must be set by the
user*. These variables will NOT be frozen and their values will be
uninitialized in the compiled object (this applies to all input
arguments from the signature as well).
Example usage:
```
saved_model_compile_aot(
name = "aot_compiled_x_plus_y",
cpp_class = "tensorflow::CompiledModel",
directory = "//tensorflow/cc/saved_model:testdata/x_plus_y_v2_debuginfo",
filegroups = [
"//tensorflow/cc/saved_model:saved_model_half_plus_two",
]
)
cc_test(
name = "test",
srcs = ["test.cc"],
deps = [
"//tensorflow/core:test_main",
":aot_compiled_x_plus_y",
"//tensorflow/core:test",
"//tensorflow/core/platform:logging",
]),
)
In "test.cc":
#include "third_party/tensorflow/python/tools/aot_compiled_x_plus_y.h"
TEST(Test, Run) {
tensorflow::CompiledModel model;
CHECK(model.Run());
}
```
Args:
name: The rule name, and the name prefix of the headers and object file
emitted by this rule.
directory: The bazel directory containing saved_model.pb and variables/
subdirectories.
filegroups: List of `filegroup` targets; these filegroups contain the
files pointed to by `directory` and `checkpoint_path`.
cpp_class: The name of the C++ class that will be generated, including
namespace; e.g. "my_model::InferenceRunner".
checkpoint_path: The bazel directory containing `variables.index`. If
not provided, then `$directory/variables/` is used
(default for SavedModels).
tag_set: The tag set to use in the SavedModel.
signature_def: The name of the signature to use from the SavedModel.
variables_to_feed: (optional) The names of the variables to feed, a comma
separated string, or 'all'. If empty, all variables will be frozen and none
may be fed at runtime.
**NOTE** Any variables passed to `variables_to_feed` *must be set by
the user*. These variables will NOT be frozen and their values will be
uninitialized in the compiled object (this applies to all input
arguments from the signature as well).
target_triple: The LLVM target triple to use (defaults to current build's
target architecture's triple). Similar to clang's -target flag.
target_cpu: The LLVM cpu name used for compilation. Similar to clang's
-mcpu flag.
multithreading: Whether to compile multithreaded AOT code.
Note, this increases the set of dependencies for binaries using
the AOT library at both build and runtime. For example,
the resulting object files may have external dependencies on
multithreading libraries like nsync.
force_without_xla_support_flag: Whether to compile even when
`--define=with_xla_support=true` is not set. If `False`, and the
define is not passed when building, then the created `cc_library`
will be empty. In this case, downstream targets should
conditionally build using macro `tfcompile.bzl:if_xla_available`.
This flag is used by the TensorFlow build to avoid building on
architectures that do not support XLA.
tags: List of target tags.
"""
saved_model = "{}/saved_model.pb".format(directory)
target_triple = target_triple or target_llvm_triple()
target_cpu = target_cpu or tfcompile_target_cpu() or ""
variables_to_feed = variables_to_feed or "''"
if checkpoint_path:
checkpoint_cmd_args = (
"--checkpoint_path \"$$(dirname $(location {}/variables.index))\" "
.format(checkpoint_path)
)
checkpoint_srcs = ["{}/variables.index".format(checkpoint_path)]
else:
checkpoint_cmd_args = ""
checkpoint_srcs = []
native.genrule(
name = "{}_gen".format(name),
srcs = filegroups + [saved_model] + checkpoint_srcs,
outs = [
"{}.h".format(name),
"{}.o".format(name),
"{}_metadata.o".format(name),
"{}_makefile.inc".format(name),
],
cmd = (
"$(location {}) aot_compile_cpu ".format(
clean_dep("//tensorflow/python/tools:saved_model_cli"),
) +
"--dir \"$$(dirname $(location {}))\" ".format(saved_model) +
checkpoint_cmd_args +
"--output_prefix $(@D)/{} ".format(name) +
"--cpp_class {} ".format(cpp_class) +
"--variables_to_feed {} ".format(variables_to_feed) +
"--signature_def_key {} ".format(signature_def) +
"--multithreading {} ".format(multithreading) +
"--target_triple " + target_triple + " " +
("--target_cpu " + target_cpu + " " if target_cpu else "") +
"--tag_set {} ".format(tag_set)
),
tags = tags,
tools = [
"//tensorflow/python/tools:saved_model_cli",
],
)
native.cc_library(
name = name,
srcs = _maybe_force_compile(
[
":{}.o".format(name),
":{}_metadata.o".format(name),
],
force_compile = force_without_xla_support_flag,
),
hdrs = _maybe_force_compile(
[
":{}.h".format(name),
],
force_compile = force_without_xla_support_flag,
),
tags = tags,
deps = _maybe_force_compile(
[
"//tensorflow/compiler/tf2xla:xla_compiled_cpu_runtime_standalone",
],
force_compile = force_without_xla_support_flag,
),
)
|
#num = 1
#
#while num < 10:
# print(num)
# num = num+1
#nome = 'cecilia'
#
#for letra in nome:
# print(letra)
#for num in range(1,6):
# print(num)
lista = [1,2,3,4,5,6]
for num in lista:
print(num) |
s = input('as: ')
print(s)
|
class Solution:
def match(self, pattern, strs):
words = strs.split()
patterns = list(pattern)
patternList = self.getPattern(patterns)
wordList = self.getPattern(words)
return patternList == wordList
def getPattern(self, strList):
index = 1
tmpDict = {}
ptnList = []
for i, v in enumerate(strList):
if not v in tmpDict:
tmpDict[v] = index
index += 1
ptnList.append(tmpDict[v])
return ptnList
if __name__ == "__main__":
solution = Solution()
print(solution.match("1212c", "hello world hello world ychost"))
|
def getAverageOverPercentage(n, score):
avg = sum(score) / n
std = 0
for i in score:
if i > avg: std += 1
return round(std / n * 100, 3)
for _ in range(int(input())):
data = list(map(int, input().split()))
result = getAverageOverPercentage(data[0], data[1:])
print("%.3f"%result + '%')
|
# We explicitly test here that the constructor is not included in the signatures.
@abstract
class Abstract:
x: int
def __init__(self, x: int) -> None:
self.x = x
__book_url__ = "dummy"
__book_version__ = "dummy"
|
# • Define una clase Estudiante en el que almacenamos
# el nombre y un diccionario cuyas claves son
# asignaturas a las que asociamos calificaciones.
# • Un estudiante recibe nombre al ser construido,
# pero nada más.
# • Si e es un estudiante, con e.califica(‘EI1022’, 10) le
# asignamos un 10 a la asignatura EI1022. Con
# e.nota(‘EI1022’) obtenemos la nota de esa
# asignatura. Con e.media() obtenemos su nota
# media (o None si no ha cursado nada). Con
# e.muestra_expediente() vemos su nombre y una
# tabla con sus asignaturas y notas.
class Estudiante:
__slots__ = ('nombre', 'notas')
def __init__(self, nombreEstudiante):
self.nombre = nombreEstudiante
self.notas = {}
def califica(self, asignatura, calificacion):
self.notas[asignatura] = calificacion
def nota(self, asignatura):
return self.notas[asignatura]
def media(self):
if len(self.notas) > 0:
return sum(self.notas.values()) / len(self.notas)
return None
def muestra_expediente(self):
return '{}: {}'.format(self.nombre, self.notas)
e = Estudiante('Victor')
e.califica('EI1022', 10)
e.califica('EI1011', 5)
print('Media: {}'.format(e.media()))
print('La nota de EI1022 es {}'.format(e.nota('EI1022')))
print(e.muestra_expediente())
|
__author__ = 'chira'
# for-loop : when number of iterations known
# while-loop : when iteration depends on condition
for i in range(5,10):
print(i)
print("------------");
i = 5
while i < 10:
print(i)
i += 1
print("------------"); |
class keyBox:
def __init__(self):
self.wallet_addresses = []
self.private_keys = []
#for testing
self.private_keys.append(b'p.Oids\xedb\xa3\x93\xc5\xad\xb9\x8d\x92\x94\x00\x06\xb9\x82\xde\xb9\xbdBg\\\x82\xd4\x90W\xd0\xd5')
self.private_keys.append(b'\x16\xc3\xb37\xb8\x8aG`\xdf\xad\xe3},\x9a\xb4~\xff7&?\xab\x80\x03\xf8\x9fo/:c\x18\xaa>')
# test = keyBoxClass()
# print(test.private_keys[b"\xdbL\xa4&\xd5;Y\xf6\x03p'O\xfb\x19\xf2&\x8d\xc3=\xdf"]) |
"""Dude Middleware."""
class ClacksOverhead(object):
"""Inject HTTP headers into your response."""
def __init__(self, app, *headers, **kwargs):
"""Initialize the header injector."""
self.app = app
self.headers = (headers or (
('X-Clacks-Overhead', 'GNU'),
)) + tuple(kwargs.items())
self.__start_response = None
def __call__(self, environ, start_response):
"""Handle our part of the request."""
self.__start_response = start_response
return self.app(environ, self.start_response)
def start_response(self, status, headers, exc_info=None):
"""Handle our part of the response."""
headers.extend(self.headers)
return self.__start_response(status, headers, exc_info)
|
for i in range(1, 6):
for j in range(1, i + 1):
print('* ', end='')
print()
for i in range(4, 0, -1):
for j in range(1, i + 1):
print('* ', end='')
print()
|
class Node:
def __init__(self, val):
self.val = val
self.next = None
# Single List, without sentinel node
# class MyLinkedList:
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.header = None
# self.size = 0
#
# def get(self, index: int) -> int:
# """
# Get the value of the index-th node in the linked list. If the index is invalid, return -1.
# """
# if index < 0 or index >= self.size:
# return -1
# cur_node = self.header
# # while cur_node:
# # cur_node = cur_node.next
# # for i in range(index - 1): // wrong
# for i in range(index):
# cur_node = cur_node.next
# return cur_node.val
#
#
# def addAtHead(self, val: int) -> None:
# """
# Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
# """
# new_node = Node(val)
# new_node.next = self.header
# self.header = new_node
# self.size += 1
#
#
# def addAtTail(self, val: int) -> None:
# """
# Append a node of value val to the last element of the linked list.
# """
# tail_node = self.header
# for i in range(self.size - 1):
# tail_node = tail_node.next
# new_node = Node(val)
# if tail_node:
# tail_node.next = new_node
# else:
# self.header = new_node
# self.size += 1
#
#
# def addAtIndex(self, index: int, val: int) -> None:
# """
# Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
# """
# # if index == self.size:
# # self.addAtTail(val)
# # return
# # if index > self.size:
# # return
# # if index < 0:
# # self.addAtHead(val)
# # return
# if index <= 0:
# self.addAtHead(val)
# return
# if index == self.size:
# self.addAtTail(val)
# return
# if index > self.size:
# return
#
# cur_node = self.header
# for i in range(index - 1):
# cur_node = cur_node.next
# new_node = Node(val)
# new_node.next = cur_node.next
# cur_node.next = new_node
# self.size += 1
#
#
# def deleteAtIndex(self, index: int) -> None:
# """
# Delete the index-th node in the linked list, if the index is valid.
# """
# if index < 0 or index >= self.size:
# return
# if index >= 1:
# cur_node = self.header
# for i in range(index - 1):
# cur_node = cur_node.next
# cur_node.next = cur_node.next.next
# else:
# self.header = self.header.next
# self.size -= 1
# Single List, with sentinel node
# class MyLinkedList:
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.size = 0
# self.sentinel = Node(0)
#
#
# def get(self, index: int) -> int:
# """
# Get the value of the index-th node in the linked list. If the index is invalid, return -1.
# """
# if index < 0 or index >= self.size:
# return -1
# cur_node = self.sentinel
# for i in range(index + 1):
# cur_node = cur_node.next
# return cur_node.val
#
#
# def addAtHead(self, val: int) -> None:
# """
# Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
# """
# self.addAtIndex(0, val)
#
#
# def addAtTail(self, val: int) -> None:
# """
# Append a node of value val to the last element of the linked list.
# """
# self.addAtIndex(self.size, val)
#
#
# def addAtIndex(self, index: int, val: int) -> None:
# """
# Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
# """
# if index > self.size:
# return
# if index < 0:
# index = 0 # add to head
# pre_node = self.sentinel
# for i in range(index):
# pre_node = pre_node.next
# new_node = Node(val)
# new_node.next = pre_node.next
# pre_node.next = new_node
# self.size += 1
#
#
# def deleteAtIndex(self, index: int) -> None:
# """
# Delete the index-th node in the linked list, if the index is valid.
# """
# if index < 0 or index >= self.size:
# return
# pre_node = self.sentinel
# for i in range(index):
# pre_node = pre_node.next
# pre_node.next = pre_node.next.next
# self.size -= 1
class Node:
def __init__(self, val):
self.val = val
self.next = None
self.pre = None
# double List
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 0
self.sentinel_head = Node(0)
self.sentinel_tail = Node(0)
self.sentinel_head.next = self.sentinel_tail
self.sentinel_tail.pre = self.sentinel_head
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
if index < 0 or index >= self.size:
return -1
head_step = index + 1
tail_step = self.size - head_step + 1
# if index <= self.size // 2:
if head_step <= tail_step:
cur_node = self.sentinel_head
for i in range(head_step):
cur_node = cur_node.next
return cur_node.val
else:
cur_node = self.sentinel_tail
for i in range(tail_step):
cur_node = cur_node.pre
return cur_node.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
"""
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
"""
if index > self.size:
return
if index < 0:
index = 0
head_step = index - 1 + 1
tail_step = self.size - head_step + 1
if head_step <= tail_step:
pre_node = self.sentinel_head
for i in range(head_step):
pre_node = pre_node.next
else:
pre_node = self.sentinel_tail
for i in range(tail_step):
pre_node = pre_node.pre
new_node = Node(val)
new_node.next = pre_node.next
new_node.pre = pre_node
pre_node.next.pre = new_node
pre_node.next = new_node
self.size += 1
def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
if index < 0 or index >= self.size:
return
head_step = index - 1 + 1
tail_step = self.size - head_step + 1
if head_step <= tail_step:
pre_node = self.sentinel_head
for i in range(head_step):
pre_node = pre_node.next
else:
pre_node = self.sentinel_tail
for i in range(tail_step):
pre_node = pre_node.pre
pre_node.next.next.pre = pre_node
pre_node.next = pre_node.next.next
self.size -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
# if __name__ == "__main__":
# # Your MyLinkedList object will be instantiated and called as such:
# linkedList = MyLinkedList()
# # linkedList.addAtHead(1)
# # linkedList.addAtTail(3)
# linkedList.addAtIndex(0, 10)
# linkedList.addAtIndex(0, 20)
# linkedList.addAtIndex(1, 30)
# linkedList.get(0)
# linkedList.deleteAtIndex(1)
# linkedList.get(1) |
class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
l, r = 0, len(num)-1
while l < r:
m = (l+r) / 2
if m == 0 or num[m] > num[m-1]:
if m == r or num[m] > num[m+1]:
return m
l = m + 1
else:
r = m - 1
return l
|
OPENSEARCH_GIT_RAW = "gits"
OPENSEARCH_GIT_GITHUB_CLEAN = "git_github_clean"
OPENSEARCH_INDEX_GITHUB_COMMITS = "github_commits"
OPENSEARCH_INDEX_GITHUB_ISSUES = "github_issues"
OPENSEARCH_INDEX_GITHUB_ISSUES_COMMENTS = "github_issues_comments"
OPENSEARCH_INDEX_GITHUB_ISSUES_TIMELINE = "github_issues_timeline"
OPENSEARCH_INDEX_CHECK_SYNC_DATA = "check_sync_data"
OPENSEARCH_INDEX_GITHUB_PULL_REQUESTS = "github_pull_requests"
OPENSEARCH_INDEX_GITHUB_PROFILE = "github_profile"
OPENSEARCH_INDEX_MAILLISTS = "maillists"
|
Dataset_Path = dict(
CULane = "/workspace/CULANE_DATASET",
Tusimple = "/workspace/TUSIMPLE_DATASET",
bdd100k = "/workspace/BDD100K_DATASET"
)
|
"""Routes config."""
def includeme(config):
"""All routes for the app."""
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('results', '/results/{id:\w+}')
config.add_route('about', '/about')
|
code = [input() for _ in range(610)]
for i in range(len(code)-1):
if code[i][:3] == 'jmp':
code[i] = 'nop' + code[i][3:]
elif code[i][:3] == 'nop':
code[i] = 'jmp' + code[i][3:]
instr_idx = 0
acc_value = 0
executed_ops = set()
while instr_idx not in executed_ops and instr_idx < len(code):
executed_ops.add(instr_idx)
operation = code[instr_idx]
if operation[:3] == 'acc':
acc_value += int(operation[4:])
instr_idx += 1
if operation[:3] == 'jmp':
instr_idx += int(operation[4:])
if operation[:3] == 'nop':
instr_idx += 1
if instr_idx >= len(code):
print(acc_value)
if code[i][:3] == 'jmp':
code[i] = 'nop' + code[i][3:]
elif code[i][:3] == 'nop':
code[i] = 'jmp' + code[i][3:] |
class Solution:
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
mx, sm = 0, sum(A)
for i in range(len(A)):
mx += i * A[i]
curr = mx
for i in range(1, len(A)):
curr = curr - sm + A[i - 1] * len(A)
mx = max(mx, curr)
return mx |
"""Multiplication Table, by Al Sweigart al@inventwithpython.com
Print a multiplication table.
This and other games are available at https://nostarch.com/XX
Tags: tiny, beginner, math"""
__version__ = 0
print('Multiplication Table, by Al Sweigart al@inventwithpython.com')
# Print the horizontal number labels:
print(' | 0 1 2 3 4 5 6 7 8 9 10 11 12')
print('--+---------------------------------------------------')
# Display each row of products:
for number1 in range(0, 13):
# Print the vertical numbers labels:
print(str(number1).rjust(2), end='')
# Print a separating bar:
print('|', end='')
for number2 in range(0, 13):
# Print the product:
print(str(number1 * number2).rjust(3), end='')
# Print a separating space:
print(' ', end='')
print() # Finish the row by printing a newline.
|
array = [1,2,3,4,5]
result = [5,1,4,2,3]
# in-place replacement
def rearrange_sorted_max_min_2(arr):
max_index = len(arr) - 1
min_index = 0
max_elem = arr[max_index] + 1
# orig element of stored as remainder, max or min element stored
# as multiplier, this allows to swap numbers in place, finally
# divide each element by max element to get output array
for i in range(len(arr)):
if i%2 is 0:
arr[i] += (arr[max_index] % max_elem) * max_elem
max_index -= 1
else:
arr[i] += (arr[min_index] % max_elem) * max_elem
min_index += 1
for i in range(len(arr)):
arr[i] = arr[i] // max_elem
return arr
def main():
print("Input: " + str(array))
print("Expected: " + str(result))
print("Output: " + str(rearrange_sorted_max_min_2(array)))
if __name__ == '__main__':
main()
|
n = int(input())
sv = sq = 0
for i in range(n):
sv += float(input())
q = len(str(input()).split())
sq += q
print('day {}: {} kg'.format(i + 1, q))
print('{:.2f} kg by day'.format(float(sq / n)))
print('R$ {:.2f} by day'.format(float(sv / n)))
|
#Print PY
print("teste")
print("RR", 1, "RRR", 3, sep="\n")
print("RR", 3, "RRR", 3, end="\n")
#sep é o separador entre os valores, por padrão o separador é um espaço em branco.
#end é o que acontecerá ao final da função, por padrão há uma quebra de linha, uma nova linha (\n).
#O Python utiliza por convenção o padrão Snake_Case para nomes de variáveis (ou identificadores).
valor_da_compra = 20
nome_cliente = 'João José'
parcelas_a_receber = 5
x = 10
y = 20
print("Cliente:", nome_cliente, "\n", "Valor:", valor_da_compra, "\n", "Parcelas:", parcelas_a_receber)
print(x+y)
print(y-x)
print(x*y)
print(x/y) |
# variables dependent on your setup
boardType = "atmega2560" # atmega168 | atmega328p | atmega2560 | atmega1280 | atmega32u4
comPort = "COM3" # com4 for atmega328 com8 for mega2560
SHIFT = 47
LATCH = 48
DATA = 49
# start Arduino service named arduino
arduino = Runtime.createAndStart("arduino", "Arduino")
arduino.setBoard(boardType) # atmega168 | mega2560 | etc
arduino.connect(comPort)
# set pinMode
arduino.pinMode(SHIFT, Arduino.OUTPUT)
arduino.pinMode(LATCH, Arduino.OUTPUT)
arduino.pinMode(DATA, Arduino.OUTPUT)
# Create shiftOut fonction
def shiftOut(value):
arduino.digitalWrite(LATCH, arduino.LOW) # Stop the copy
for byte in value:
if byte == 1 :
arduino.digitalWrite(DATA,arduino.HIGH)
else :
arduino.digitalWrite(DATA,arduino.LOW)
arduino.digitalWrite(SHIFT, arduino.HIGH)
arduino.digitalWrite(SHIFT, arduino.LOW)
arduino.digitalWrite(LATCH, arduino.HIGH) # copy
def smile():
shiftOut([1,1,0,1,1,1,0,0]) # send data
def notHappy():
shiftOut([0,0,1,1,1,1,1,0]) # send data
def speechLess():
shiftOut([1,0,1,1,1,1,0,0]) # send data
def talk():
shiftOut([0,0,0,0,0,0,0,0]) # send data
sleep(0.05)
shiftOut([0,0,0,0,0,1,0,0]) # send data
sleep(0.05)
shiftOut([0,0,0,1,1,1,0,0]) # send data
sleep(0.05)
shiftOut([0,0,0,0,0,1,0,0]) # send data
sleep(0.05)
x = 0
while (x<2) :
x=x+1
smile()
sleep(1)
notHappy()
sleep(1)
speechLess()
for i in range(0,10) :
talk()
|
airline = pd.read_csv('data/international-airline-passengers.csv', parse_dates=['Month'], sep=';')
airline.set_index('Month', inplace=True)
ax = airline.plot(legend=False)
ax.set_xlabel('Date')
ax.set_ylabel('Passengers') |
n=int(input())
if n>=0:
sum=int((n*(n+1))/2)
print(sum)
else:
print("Invalid Input") |
"""InterviewBit.
Programming > Arrays > Min Steps In Infinite Grid.
"""
class Solution:
"""Solution."""
# @param A : list of integers
# @param B : list of integers
# @return an integer
def coverPoints(self, A, B):
"""Cover points."""
x, y = A[0], B[0]
steps = 0
for xf, yf in zip(A, B):
dx, dy = abs(x - xf), abs(y - yf)
steps += max(dx, dy)
x, y = xf, yf
return steps
|
def moving_average(timeseries, k):
result = []
for begin_index in range(0, len(timeseries) - k):
end_index = begin_index + k
current_sum = 0
for v in timeseries[begin_index:end_index]:
current_sum += v
current_avg = current_sum / k
result.append(current_avg)
return result
def main():
ts = list(map(int, input().split()))
k = int(input())
print(moving_average(ts, k))
if __name__ == '__main__':
main()
|
# Array
# Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
#
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
# Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
# Example 2:
# Input: [2,2,2,2,2]
# Output: 1
# Explanation: The longest continuous increasing subsequence is [2], its length is 1.
# Note: Length of the array will not exceed 10,000.
class Solution:
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Solution 1
output, temp = 0, 0
for i in range(len(nums)):
if nums[i-1] >= nums[i]:
temp = i
output = max(output, i-temp+1)
return output
## Solution 2
# if nums == []: return 0
# maxCount, count = 1, 1
# i = 0
# while i < len(nums) - 1:
# if nums[i+1] > nums[i]:
# count = 2
# for j in range(i+1, len(nums)-1):
# if nums[j+1] > nums[j]:
# count += 1
# else:
# i = j
# break
# maxCount = max(maxCount, count);
# i += 1
# return maxCount
|
class Cord:
homepage = ( 1, 42, 529,984 )
question = ( 42,317,519,426 )
answer1 = ( 48,487,510,558 )
answer2 = ( 48,573,510,645 )
answer3 = ( 48,660,510,732 )
answer1_clk = ( 94,524 )
answer2_clk = ( 94,609 )
answer3_clk = ( 94,694 ) |
#Exercise 4-2 - Animals
animals = ['lion', 'tiger', 'cat']
for animal in animals:
print(animal.title(), "it's a feline.")
print('Only one is a great pet.')
|
class ICustomFactory:
""" Enables users to write activation code for managed objects that extend System.MarshalByRefObject. """
def CreateInstance(self, serverType):
"""
CreateInstance(self: ICustomFactory,serverType: Type) -> MarshalByRefObject
Creates a new instance of the specified type.
serverType: The type to activate.
Returns: A System.MarshalByRefObject associated with the specified type.
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
|
PICTURE_DEFAULT = {
"image": {
"url": str,
"name": str
},
"thumbnail": {
"url": str,
"name": str
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.