content stringlengths 7 1.05M |
|---|
def trace_wire(wire_dirs):
last_pos = [0, 0]
grid_dict = {}
length = 0
for direction in wire_dirs:
way = direction[0]
amount = int(direction[1:])
if way == 'R':
for x in range(1,amount+1):
grid_pos = '{}_{}'.format(last_pos[0]+x, last_pos[1])
length += 1
if grid_pos not in grid_dict:
grid_dict[grid_pos] = length
last_pos[0] += amount
elif way == 'L':
for x in range(1,amount+1):
grid_pos = '{}_{}'.format(last_pos[0]-x, last_pos[1])
length += 1
if grid_pos not in grid_dict:
grid_dict[grid_pos] = length
last_pos[0] -= amount
elif way == 'U':
for y in range(1,amount+1):
grid_pos = '{}_{}'.format(last_pos[0], last_pos[1]+y)
length += 1
if grid_pos not in grid_dict:
grid_dict[grid_pos] = length
last_pos[1] += amount
elif way == 'D':
for y in range(1,amount+1):
grid_pos = '{}_{}'.format(last_pos[0], last_pos[1]-y)
length += 1
if grid_pos not in grid_dict:
grid_dict[grid_pos] = length
last_pos[1] -= amount
return grid_dict
def main():
with open('input.txt', 'r') as f:
first, second = f.read().split('\n')
first_grid = trace_wire(first.split(','))
second_grid = trace_wire(second.split(','))
intersection_grid = set(first_grid.keys()) & set(second_grid.keys())
# print(intersection_grid)
part_1 = min([abs(int(i.split('_')[0])) + abs(int(i.split('_')[1])) for i in intersection_grid])
part_2 = min([second_grid[i] + first_grid[i] for i in intersection_grid])
print(part_1, part_2)
if __name__ == '__main__':
main()
|
#Linear Seach Algorithm
def linearSearch(data, number):
found = False
for index in range(0, len(data)):
if (data[index] == number):
found = True
break
if found:
print("Element is present in the array", index)
else:
print("Element is not present in the array.")
|
i = 1 # valor inicial de I
j = aux = 7 # valor inicial de J
while i < 10: # equanto for menor que 10:
for x in range(3): # loop: mostra as linhas consecutivas
print('I={} J={}' .format(i,j)) # mostra os valores
j -= 1 # diminui 1 no J (7,6,5)
i += 2 # altera I
aux += 2 # altera a aux
j = aux # novo J = aux |
IOSXE_TEST = {
"host": "172.18.0.11",
"username": "vrnetlab",
"password": "VR-netlab9",
"device_type": "cisco_xe",
"test_commands": ["show run", "show version"],
}
NXOS_TEST = {
"host": "172.18.0.12",
"username": "vrnetlab",
"password": "VR-netlab9",
"device_type": "cisco_nxos",
"test_commands": ["show run", "show version"],
}
IOSXR_TEST = {
"host": "172.18.0.13",
"username": "vrnetlab",
"password": "VR-netlab9",
"device_type": "cisco_iosxr",
"test_commands": ["show run", "show version"],
}
# need to get arista_eos image in vrnetlab for testing + fix libssh2 keyboard interactive auth issue
# EOS_TEST = {
# "host": "172.18.0.14",
# "username": "vrnetlab",
# "password": "VR-netlab9",
# "device_type": "arista_eos",
# "test_commands": ["show run", "show version"],
# }
JUNOS_TEST = {
"host": "172.18.0.15",
"username": "vrnetlab",
"password": "VR-netlab9",
"device_type": "juniper_junos",
"test_commands": ["show configuration", "show version"],
}
|
def rotate_left(list_f, step):
for _ in range(step):
list_f.append(list_f.pop(0))
list_s = list_f[:]
return list_s
|
times = [{'writing_data': 6.627535581588745, 'ndvi_pc10': 27.36231303215027, 'loading_data': 109.62806057929993, 'ndvi_pc90': 21.421257734298706, 'ndvi_pc50': 27.33169937133789},
{'writing_data': 6.443411588668823, 'ndvi_pc10': 39.16243243217468, 'loading_data': 123.19368815422058, 'ndvi_pc90': 38.72961163520813, 'ndvi_pc50': 36.39958381652832},
{'writing_data': 6.733800649642944, 'ndvi_pc10': 32.248281955718994, 'loading_data': 56.15437984466553, 'ndvi_pc90': 31.813125610351562, 'ndvi_pc50': 35.00871157646179},
{'writing_data': 6.484926462173462, 'ndvi_pc10': 30.538794994354248, 'loading_data': 72.27108573913574, 'ndvi_pc90': 31.11927819252014, 'ndvi_pc50': 30.832648038864136},
{'writing_data': 6.359814405441284, 'ndvi_pc10': 46.55086040496826, 'loading_data': 59.67847752571106, 'ndvi_pc90': 39.096333265304565, 'ndvi_pc50': 42.16282844543457},
{'writing_data': 6.564153432846069, 'ndvi_pc10': 45.175180196762085, 'loading_data': 87.63148283958435, 'ndvi_pc90': 49.379384994506836, 'ndvi_pc50': 45.34032440185547},
{'writing_data': 6.604489326477051, 'ndvi_pc10': 32.93318557739258, 'loading_data': 78.88174366950989, 'ndvi_pc90': 31.08031392097473, 'ndvi_pc50': 29.89056134223938},
{'writing_data': 6.4211084842681885, 'ndvi_pc10': 41.337995767593384, 'loading_data': 82.0915629863739, 'ndvi_pc90': 39.3358314037323, 'ndvi_pc50': 39.409401655197144},
{'writing_data': 6.546594858169556, 'ndvi_pc10': 35.091548681259155, 'loading_data': 47.397238969802856, 'ndvi_pc90': 34.05122685432434, 'ndvi_pc50': 33.63374209403992},
{'writing_data': 6.11034631729126, 'ndvi_pc10': 43.16675114631653, 'loading_data': 63.00188064575195, 'ndvi_pc90': 40.11013221740723, 'ndvi_pc50': 40.178325176239014},
{'writing_data': 6.267251491546631, 'ndvi_pc10': 36.879666328430176, 'loading_data': 59.68582105636597, 'ndvi_pc90': 35.762709617614746, 'ndvi_pc50': 36.186012506484985},
{'writing_data': 6.086328744888306, 'ndvi_pc10': 34.747477531433105, 'loading_data': 51.13255739212036, 'ndvi_pc90': 33.50469946861267, 'ndvi_pc50': 33.493101358413696},
{'writing_data': 6.232825517654419, 'ndvi_pc10': 37.161699056625366, 'loading_data': 72.47414040565491, 'ndvi_pc90': 36.648998975753784, 'ndvi_pc50': 38.17262291908264},
{'writing_data': 6.4867870807647705, 'ndvi_pc10': 22.58499264717102, 'loading_data': 50.658077239990234, 'ndvi_pc90': 23.183380842208862, 'ndvi_pc50': 23.05723762512207},
{'writing_data': 6.315629243850708, 'ndvi_pc10': 24.482516288757324, 'loading_data': 52.54269289970398, 'ndvi_pc90': 23.933518171310425, 'ndvi_pc50': 23.647018909454346},
{'writing_data': 6.466713190078735, 'ndvi_pc10': 33.10160160064697, 'loading_data': 39.69579243659973, 'ndvi_pc90': 35.594271183013916, 'ndvi_pc50': 33.5105459690094},
{'writing_data': 6.146531581878662, 'ndvi_pc10': 41.39342451095581, 'loading_data': 82.68737983703613, 'ndvi_pc90': 40.2240526676178, 'ndvi_pc50': 42.00848603248596},
{'writing_data': 6.4085304737091064, 'ndvi_pc10': 24.061297178268433, 'loading_data': 65.79187154769897, 'ndvi_pc90': 24.270387649536133, 'ndvi_pc50': 23.630946397781372},
{'writing_data': 5.905577898025513, 'ndvi_pc10': 37.23882865905762, 'loading_data': 55.112420082092285, 'ndvi_pc90': 36.291778326034546, 'ndvi_pc50': 36.75375556945801},
{'writing_data': 6.305130481719971, 'ndvi_pc10': 35.108429193496704, 'loading_data': 56.73119306564331, 'ndvi_pc90': 35.175426959991455, 'ndvi_pc50': 35.82203245162964},
{'writing_data': 5.938111066818237, 'ndvi_pc10': 36.650582790374756, 'loading_data': 55.64810013771057, 'ndvi_pc90': 36.924052238464355, 'ndvi_pc50': 36.689247369766235},
{'writing_data': 5.939232587814331, 'ndvi_pc10': 34.53633236885071, 'loading_data': 64.5890371799469, 'ndvi_pc90': 32.73802304267883, 'ndvi_pc50': 35.01725482940674},
{'writing_data': 6.481805801391602, 'ndvi_pc10': 15.486124753952026, 'loading_data': 44.980570793151855, 'ndvi_pc90': 16.636183738708496, 'ndvi_pc50': 19.395575284957886},
{'writing_data': 6.364058494567871, 'ndvi_pc10': 34.192909955978394, 'loading_data': 41.18637776374817, 'ndvi_pc90': 33.94004559516907, 'ndvi_pc50': 32.72668814659119},
{'writing_data': 6.19329047203064, 'ndvi_pc10': 21.083044290542603, 'loading_data': 54.03144335746765, 'ndvi_pc90': 18.876606702804565, 'ndvi_pc50': 20.58382821083069},
{'writing_data': 6.390938997268677, 'ndvi_pc10': 17.885555505752563, 'loading_data': 64.85111451148987, 'ndvi_pc90': 17.912266969680786, 'ndvi_pc50': 16.847716808319092},
{'writing_data': 6.0089945793151855, 'ndvi_pc10': 37.12860655784607, 'loading_data': 80.22634196281433, 'ndvi_pc90': 36.44176435470581, 'ndvi_pc50': 37.66867637634277},
{'writing_data': 5.877416372299194, 'ndvi_pc10': 37.55026960372925, 'loading_data': 67.21783351898193, 'ndvi_pc90': 34.27371907234192, 'ndvi_pc50': 33.92675566673279},
{'writing_data': 6.228186845779419, 'ndvi_pc10': 31.5383403301239, 'loading_data': 61.13664984703064, 'ndvi_pc90': 30.51774287223816, 'ndvi_pc50': 30.585197687149048},
{'writing_data': 6.655982971191406, 'ndvi_pc10': 10.241628408432007, 'loading_data': 41.03610324859619, 'ndvi_pc90': 8.946972131729126, 'ndvi_pc50': 10.193110942840576},
{'writing_data': 6.053949356079102, 'ndvi_pc10': 34.719430446624756, 'loading_data': 69.46687150001526, 'ndvi_pc90': 31.912947416305542, 'ndvi_pc50': 34.160250186920166},
{'writing_data': 5.863107919692993, 'ndvi_pc10': 35.627281665802, 'loading_data': 58.374780893325806, 'ndvi_pc90': 35.16462683677673, 'ndvi_pc50': 35.169331073760986},
{'writing_data': 6.245217323303223, 'ndvi_pc10': 26.947230339050293, 'loading_data': 37.8329381942749, 'ndvi_pc90': 28.4262912273407, 'ndvi_pc50': 26.491452932357788},
{'writing_data': 6.1906843185424805, 'ndvi_pc10': 10.243769407272339, 'loading_data': 47.66607213020325, 'ndvi_pc90': 10.901005268096924, 'ndvi_pc50': 9.574926376342773},
{'writing_data': 6.27140212059021, 'ndvi_pc10': 9.982360601425171, 'loading_data': 52.55823802947998, 'ndvi_pc90': 9.319277286529541, 'ndvi_pc50': 9.227921962738037},
{'writing_data': 6.332434177398682, 'ndvi_pc10': 4.836212396621704, 'loading_data': 32.75589728355408, 'ndvi_pc90': 5.307963848114014, 'ndvi_pc50': 4.731549501419067},
{'writing_data': 6.2034995555877686, 'ndvi_pc10': 36.06976509094238, 'loading_data': 81.16117906570435, 'ndvi_pc90': 35.752469539642334, 'ndvi_pc50': 37.97353792190552},
{'writing_data': 6.317094087600708, 'ndvi_pc10': 6.397157907485962, 'loading_data': 32.58416557312012, 'ndvi_pc90': 7.095927000045776, 'ndvi_pc50': 6.454242944717407},
{'writing_data': 6.197620153427124, 'ndvi_pc10': 11.273391008377075, 'loading_data': 38.74477291107178, 'ndvi_pc90': 10.42611837387085, 'ndvi_pc50': 11.03548288345337},
{'writing_data': 6.481883764266968, 'ndvi_pc10': 3.8671746253967285, 'loading_data': 26.47277569770813, 'ndvi_pc90': 3.9668197631835938, 'ndvi_pc50': 3.716965675354004},
{'writing_data': 6.128786563873291, 'ndvi_pc10': 16.900771617889404, 'loading_data': 45.50841689109802, 'ndvi_pc90': 19.169956922531128, 'ndvi_pc50': 16.847289562225342},
{'writing_data': 6.797720909118652, 'ndvi_pc10': 4.179133892059326, 'loading_data': 24.04671049118042, 'ndvi_pc90': 4.420083284378052, 'ndvi_pc50': 4.485124349594116},
{'writing_data': 6.50871467590332, 'ndvi_pc10': 5.876180410385132, 'loading_data': 35.49396777153015, 'ndvi_pc90': 5.70380973815918, 'ndvi_pc50': 5.584086894989014},
{'writing_data': 6.459113836288452, 'ndvi_pc10': 4.990781784057617, 'loading_data': 42.639532804489136, 'ndvi_pc90': 4.918926239013672, 'ndvi_pc50': 4.503567218780518}]
|
#!/usr/bin/env python3
class InitializationException(Exception):
"""Raise when initialization errors occur."""
class ChallengeNotFound(Exception):
"""Raise when challenge not found."""
class ChallengeNotCovered(Exception):
"""Raise when challenge not found."""
class TestNotFound(Exception):
"""Raise when test not found."""
class NotEmptyDirectory(Exception):
"""Raise when test not found."""
class IncorrectTestNameFormat(Exception):
"""Raise when test name doesn't match format."""
|
fname = input("Enter file name: ")
fh = open(fname)
total = 0.0
count = 0.0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
total += float(line[line.find(":") + 1:])
count += 1
lf = total/count
else:
continue
print('Average spam confidence: ',"{0:.12f}".format(round(lf,12)))
|
def selectmenuitem(window,object):
#log("{} :not implemented yet".format(sys._getframe().f_code.co_name))
object = object.split(";")
if len(object) == 2:
objectHandle = getobjecthandle(window,object[0])['handle']
mousemove(window,object[0],handle=objectHandle)
ldtp_extend_mouse_click_here()
time.sleep(1)
objectHandle = getobjecthandle(window,object[1])['handle']
mousemove(window,object[1],handle=objectHandle)
ldtp_extend_mouse_click_here()
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def kAltReverse(head, k) :
current = head
next = None
prev = None
count = 0
#1) reverse first k nodes of the linked list
while (current != None and count < k) :
next = current.next
current.next = prev
prev = current
current = next
count = count + 1;
# 2) Now head pos to the kth node.
# So change next of head to (k+1)th node
if(head != None):
head.next = current
# 3) We do not want to reverse next k
# nodes. So move the current
# poer to skip next k nodes
count = 0
while(count < k - 1 and current != None ):
current = current.next
count = count + 1
# 4) Recursively call for the list
# starting from current.next. And make
# rest of the list as next of first node
if(current != None):
current.next = kAltReverse(current.next, k)
# 5) prev is new head of the input list
return prev
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def solve(self, A, B):
return kAltReverse(A,B);
|
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/cat"
DATASETS = dict(TRAIN=("lm_pbr_cat_train",), TEST=("lm_real_cat_test",))
# bbnc5
# objects cat Avg(1)
# ad_2 19.26 19.26
# ad_5 62.48 62.48
# ad_10 91.52 91.52
# rete_2 78.24 78.24
# rete_5 99.60 99.60
# rete_10 100.00 100.00
# re_2 79.74 79.74
# re_5 99.60 99.60
# re_10 100.00 100.00
# te_2 97.70 97.70
# te_5 100.00 100.00
# te_10 100.00 100.00
# proj_2 83.63 83.63
# proj_5 99.10 99.10
# proj_10 100.00 100.00
# re 1.45 1.45
# te 0.01 0.01
|
def main():
with open('input.txt') as f:
inputs = [line.split() for line in f.readlines()]
pos = (0, 0) # horiz, depth
for cmd, amount in inputs:
amount = int(amount)
match cmd:
case 'forward':
pos = (pos[0] + amount, pos[1])
case 'down':
pos = (pos[0], pos[1] + amount)
case 'up':
pos = (pos[0], pos[1] - amount)
case _: print(f'invalid direction: {cmd}')
print(f'final coord: {pos}')
print(f'answer 1: {pos[0] * pos[1]}')
pos = (0, 0, 0) # horiz, depth, aim
for cmd, amount in inputs:
amount = int(amount)
match cmd:
case 'forward':
pos = (pos[0] + amount, pos[1] + pos[2] * amount, pos[2])
case 'down':
pos = (pos[0], pos[1], pos[2] + amount)
case 'up':
pos = (pos[0], pos[1], pos[2] - amount)
case _: print(f'invalid direction: {cmd}')
print(f'final coord: {pos}')
print(f'answer 2: {pos[0] * pos[1]}')
if __name__ == '__main__':
main()
|
# Python Lists
# @IdiotInside_
print ("Creating List:")
colors = ['red', 'blue', 'green']
print (colors[0]) ## red
print (colors[1]) ## blue
print (colors[2]) ## green
print (len(colors)) ## 3
print ("Append to the List")
colors.append("orange")
print (colors[3]) ##orange
print ("Insert to the List")
colors.insert(3, "yellow")
print (colors[3]) ##yellow
print (colors[4]) ##orange
print ("Remove from the List")
print (colors[1]) ## blue
colors.remove("blue") ## deletes blue and shifts elements to the left
print (colors[1]) ## green
print ("Sorting Ascending order using sorted")
nums = [98,22,45,30]
numsAsc = sorted(nums)
print (numsAsc[0]) ## 22
print (numsAsc[1]) ## 30
print (numsAsc[2]) ## 45
print ("Sorting Descending order using sorted")
numsDesc = sorted(nums,reverse=True)
print (numsDesc[0]) ## 98
print (numsDesc[1]) ## 45
print (numsDesc[2]) ## 30
|
class Solution:
def find_averages(self, k, arr):
result = []
window_sum = 0
window_start = 0
for window_end in range(len(arr)):
window_sum += arr[window_end]
if window_end >= k - 1:
result.append(window_sum / k)
window_sum -= arr[window_start]
window_start += 1
return result
def main():
solution = Solution()
print(solution.find_averages(5, [1, 3, 2, 6, -1, 4, 1, 8, 2]))
if __name__ == '__main__':
main() |
# calculting factorial using recursion
def Fact(n):
return (n * Fact(n-1) if (n > 1) else 1.0)
#main
num = int(input("n = "))
print(Fact(num)) |
# https://www.hackerrank.com/challenges/ctci-lonely-integer
def lonely_integer(a):
bitArray = 0b0
for ele in a:
bitArray = bitArray ^ ele
# print(ele, bin(bitArray))
return int(bitArray) |
"""
MiniAuth
~~~~~~~~
Simple program and library for local user authentication.
:license: This software is released under the terms of MIT license.
See LICENSE file for more details.
"""
__version__ = '0.2.0'
|
# -*- coding: utf-8 -*-
"""
File Name: 02metaclass.py
Author : jynnezhang
Date: 2020/12/1 9:52 上午
Description:
"""
|
class StatusesHelper(object):
"""
An helper on statuses operations
"""
values = {
0: ('none','Not Moderated',),
1: ('moderated','Being Moderated',),
2: ('accepted','Accepted',),
3: ('refused','Refused',),
}
@classmethod
def encode(_class, enc_status_name):
"""
Encode a status string to integer
"""
for status_id, status_data in _class.values.iteritems():
if enc_status_name == status_data[0]: return status_id
return 0
@classmethod
def reverse(_class, rev_status_id):
"""
Reverse a status integer to string
"""
assert type(rev_status_id) is int
if rev_status_id in _class.values:
return _class.values[rev_status_id]
return None
@classmethod
def as_tuples(_class):
"""
Return the list of statuses in tuples
"""
return [(key, value.title()) for key, value in CONTENT_LEVELS.items()] |
andmed = []
nimekiri = open("nimekiri.txt", encoding="UTF-8")
for rida in nimekiri:
f = open(rida.strip() + ".txt", encoding="UTF-8")
kirje = {}
for attr in f:
osad = attr.strip().split(": ")
kirje[osad[0]] = osad[1]
f.close()
andmed.append(kirje)
nimekiri.close()
uus_failinimi = input("Sisesta uue faili nimi: ")
veerud = input("Sisesta attribuutide nimed: ")
uus = open(uus_failinimi, mode="w", encoding="utf-8")
uus.write(veerud + "\n")
for isik in andmed:
atts = []
for veerg in veerud.split(","):
if veerg in isik:
atts.append(isik[veerg])
else:
atts.append("")
uus.write(",".join(atts) + "\n")
uus.close() |
# window's attributes
TITLE = 'Arkanoid.py'
WIDTH = 640
HEIGHT = 400
ICON = 'images/ball.png'
|
elemDictInv = {
100:'TrivialElement',
101:'PolyElement',
102:'NullElement',
110:'DirichletNode',
111:'DirichletNodeLag',
112:'zeroVariable',
120:'NodalForce',
121:'NodalForceLine',
130:'setMaterialParam',
131:'setDamageParam',
132:'IncrementVariables',
133:'insertDeformation',
134:'insertDeformationGeneral',
140:'posProcElem',
141:'posProcElemOld',
142:'Cell2Point',
143:'PosProcElemNew',
150:'Viscosity',
200:'FSgen',
201:'FSgenMixedStab',
203:'FSgen_newDamage',
210:'NeumannFiniteStrain',
211:'NeumannFiniteStrainSpatial',
212:'NeumannRefTraction',
300:'damageEvolution',
400:'StressHom',
410:'TotalDisp',
4410:'TotalDisp3D',
420:'minRestrictionBC2DExact',
421:'minRestrictionRVE',
422:'enforcePeriodic2D',
423:'MRmeanVolRVE',
424:'enforcePeriodic2D_inc',
425:'enforcePeriodic2D_inc_copy',
430:'canonicalProblem',
431:'computeTangent',
432:'TangentHom',
433:'computeMinDetQ',
434:'computeMinDetQNew',
440:'DecisionBifurcation',
441:'LocDomainBC',
442:'MarkLocPoint',
443:'LocPointsBC',
500:'nonlinearFibres',
501:'nonlinearFibresDamage',
502:'nonlinearFibresDamage_localised',
503:'NonLinFibresGen',
504:'NonlinearFibresQuang',
505:'nonlinearFibresDamage_viscous',
5505:'nonlinearFibresDamage_viscous3D',
506:'torsionalSpring',
507:'networkConstraintGen_pureInc',
5507:'networkConstraintGen_pureInc3D',
508:'networkConstraintLinear',
5508:'networkConstraintLinear3D',
509:'networkConstraintGen',
5509:'networkConstraintGen3D',
510:'networkConstraint',
511:'networkConstraint_noVolume',
512:'affineBoundary',
513:'networkConstraint_delta',
514:'networkConstraint_RVEnormal_new_gen',
515:'networkConstraintTheta',
516:'affineBoundaryTheta',
517:'networkConstraint_RVEnormal',
518:'networkConstraint_RVEnormal_',
519:'networkConstraint_RVEnormal_new',
520:'computeAnisotropyTensor',
521:'computeAnisotropyTensorInv',
530:'damageEvolutionFibres',
540:'initParamFibres',
5550:'posProcFibres3D',
550:'posProcFibres',
560:'canonicalProblemFibres',
561:'tangentHomFibres',
601:'zeroVariable_arcLength',
602:'computeCoeficientsCilindrical_arcLength',
603:'incrementIncrementEstimation',
604:'chooseIncrementLambda',
605:'incrementDisplacementsArcLength',
606:'enforcePeriodic2D_arcLength',
607:'incrementBoundaryMultipliersArcLength',
608:'IncrementVariables_Conditional',
609:'IncrementVariablesArcLength',
610:'arcLengthConsistent',
611:'incrementLambda',
612:'incrementLambdaArcLength',
613:'computeCoeficientsSpherical_arcLength',
614:'PosProcElem_arcLength',
615:'zeroVariable_arcLength2',
616:'zeroVariable_arcLength_generic',
617:'computeCoeficientsArcLength_generic',
700:'arcLength_simple',
701:'zeroVariable_arcLength_simple',
702:'computeCoeficientsCilindrical_arcLength_simple',
703:'computeIncrementEstimation_simple',
704:'chooseIncrementLambda_simple',
705:'incrementDisplacementsArcLength_simple',
706:'computeCoeficientsSpherical_arcLength_simple'}
elemDict = dict(zip(elemDictInv.values(),elemDictInv.keys()))
|
"""
Problem: Find the number of 1s in the binary representation of a number.
For example:
num_ones(2) = 1 --> since "10" is the binary representation of the number "2".
num_ones(5) = 2 --> since "101" is the binary representation of the number "5"
etc.
"""
# num = 2
num = 5
# num = 11
print(bin(num))
# Approach 1 (using Python's "bin" function):
one_sum = 0
bin_rep = bin(num)[2:]
for i in bin_rep:
one_sum += int(i)
print(one_sum)
# Approach to whithout "bin" function
# Use &: and, and >>: shift operators
one_sum = 0
while num:
one_sum += num & 1
num >>= 1
print(one_sum) |
class Error(Exception):
"""Base class"""
pass
class TokenGenerateError(Error):
"""
토큰 생성 에러
:param: message: 에러 메세지
"""
def __init__(self, message):
self.message = message
class ConnectedIdGenerateError(Error):
"""
커넥티드 아이디 생성 에러
:param: message: 에러 메세지
"""
def __init__(self, message):
self.message = message
class UseApiError(Error):
def __init__(self, message):
self.message = message
|
"""Handler class. All handlers must inherit from it."""
class Handler:
def __init__(self, alert: str):
self.broker = None
self.alert = alert
def alert_on(self):
"""Will be run when alert pops up."""
pass
def alert_off(self):
"""Will be run when alert disappears."""
pass
def alert_ongoing(self):
"""Will be run every second when the alert is up."""
pass
|
tupla = ('python', 'estudar', 'linguagem', 'curso', 'viajar',
'cinema', 'pipoca', 'futuro', 'programador', 'mercado')
for c in tupla:
print(f'\nNa palavra {c} temos as vogais:', end=' ')
for vogais in c:
if vogais.lower() in 'aeiou':
print(vogais, end=' ')
|
#!/usr/bin/env python3
# encoding: utf-8
# author: cappyclearl
class Solution(object):
r_min = -2147483648
r_max = 2147483647
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
r_int = 0
sign = 1
str = str.lstrip()
if str.isdigit():
return self.judgeRange(int(str))
else:
for i, c in enumerate(str):
if i == 0:
if c == '-':
sign = -1
continue
if c == '+':
sign = 1
continue
if c.isdigit():
# 一个数乘上所在位的权
r_int = r_int * 10 + int(c)
else:
return self.judgeRange(sign* r_int)
return self.judgeRange(sign* r_int)
def judgeRange(self, result):
if result > self.r_max:
return self.r_max
if result < self.r_min:
return self.r_min
return result
if __name__ == '__main__':
s = Solution()
assert s.myAtoi('123') == 123
assert s.myAtoi('-123') == -123
|
# Funcion de evaluacion de calidad de codigo. Devuelve un entero con un numero que representa la calidad. Cuanto mas cercano a 0 esten los valores, mayor sera la calidad.
def evaluateCode(listOfRefactors):
# Good code -> Close to 0
# Bad code -> Far from 0
codeQuality = 0
for refactor in listOfRefactors:
codeQuality = refactor['nPriority'] + codeQuality
return codeQuality
|
# Beden kütle indeksi - Sağlık göstergesi hesaplama
# TBY414 03.03.2020
# ADIM 1 - Kullanıcı girdilerinden indeksi hesaplamak
# ağırlık (kg) boy (metre) olacak şekilde bki = a/(b*b)
agirlik = float( input("Lütfen ağırlığınızı giriniz (kg): ") )
# ^ bir sayı olması gereken bir girdi alıyoruz.
boy = float( input("Lütfen boyunuzu giriniz (cm):") )
boy = boy / 100.0 # metreye çevirdik
bki = agirlik / (boy * boy)
print("BKİ değeri: ", bki)
# ADIM 2 - Kullanıcının sınıflandırmasını yapmak
# <18.5 <25 <30 <35 <40 --
# zayıf sağlıklı az kilolu 1. obez 2. obez 3. obez
if bki <18.5:
print("Zayıfsınız")
print("Sağlıklı biçimde kilo alabilirsiniz")
if boy<1.40:
# Belki de çocuk?
print("Çocuklar için BKİ formülü farklıdır.")
elif bki < 25:
print("Sağlıklısınız")
elif bki <30:
print("Az kilolusunuz")
elif bki<35:
print("Dikkat! 1. Obez")
elif bki<40:
print("Dikkat! 2. Obez")
else:
print("Dikkat 3. Obez")
# ADIM 3 - Bir kilo alma/verme hedefi oluşturmak
# Bu aynı zamanda ikinci ödevin bir parçası.
# Not: Birinci ödev github hesabı açamak idi.
|
# ==== Modos de apertura: ====
# default (read mode): 'r'
# write mode: 'w'
# append mode: 'a'
# read and write: 'r+'
filename = 'programming_languages.txt'
# with open(filename, 'w') as f_obj:
# f_obj.write('PHP\n')
# f_obj.write('Python\n')
# f_obj.write('Javascript\n')
# ==== Append Mode: ====
# with open(filename, 'a') as f_obj:
# f_obj.write('C++\n')
# f_obj.write('Rust\n')
# f_obj.write('C#\n')
# ==== Un ejemplo más chido! ====
languages = ['PHP\n', 'Python\n', 'Javascript\n', 'C++\n', 'Rust\n', 'C#\n' ]
with open(filename, 'w') as f_obj:
for language in languages:
f_obj.write(language)
|
DIRECTIONS = {
"U": (0, 1),
"D": (0, -1),
"L": (-1, 0),
"R": (1, 0)
}
def wire_to_point_set(wire):
s = set()
d = dict()
x, y, steps = 0, 0, 0
for w in wire:
dx, dy = DIRECTIONS[w[0]]
dist = int(w[1:])
for _ in range(dist):
x += dx
y += dy
s.add((x, y))
steps += 1
if (x, y) not in d:
d[(x, y)] = steps
return s, d
if __name__ == "__main__":
with open('3.txt') as f:
wires = [line.strip().split(',') for line in f.readlines()]
w1, w2 = wires
s1, d1 = wire_to_point_set(w1)
s2, d2 = wire_to_point_set(w2)
intersections = s1 & s2
p1_intersections = [(abs(x) + abs(y), (x, y)) for (x, y) in intersections]
p1_intersections.sort()
print("Part 1: {}".format(p1_intersections[0][0]))
p2_intersections = [(d1[p] + d2[p], p) for p in intersections]
p2_intersections.sort()
print("Part 2: {}".format(p2_intersections[0][0]))
|
def main():
print("Welcome To play Ground")
# Invocation
if __name__ == "__main__":
main()
myInt = 5
myFloat = 13.2
myString = "Hello"
myBool = True
myList = [0, 1, "Two", 3.4, 78, 89, 45, 67]
myTuple = (0, 1, 2)
myDict = {"one": 1, "Two": 2}
# Random print Statements
print(myDict)
print(myTuple)
print(myInt)
print(myList)
print(myFloat)
print(myString)
# Slicing in list
print(myList)
print(myList[2:5])
print(myList[::-1])
print(myList[:5])
print(myList[5])
# Dicts Accessing via keys
print(myDict["Two"])
# Error : Variables of Different Types can't be Combined
print("String" + str(123))
# Global vs Local Variables
def some():
myString = "inside function"
print(myString)
def addition(arg1, arg2): # for default args we can use like => function(arg1, arg2=x) :
result = 1
for i in range(arg2):
result = result * arg1
return result
def multiArg(*args): # we can have multiple args with multi, but it should always atLast
result = 0
for x in args:
result = result + x
return result
def conditionals():
x, y = 10, 100
result = "x is greater" if x > y else "y is greater"
value = "three"
match value:
case "one":
result = 1
case "two":
result = 2
case "three" | "four":
result = (3, 4)
case _:
result = -1
print(result)
print("---------")
x = 0
while x < 5:
print(x)
x = x + 1
print("---------")
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
for day in days:
print(day)
print("---------")
for x in range(5, 10):
# if x == 7:
# break
if x % 2 == 0:
continue
print(x)
print("---------")
for i, d in enumerate(days):
print(i, d)
print("---------")
some()
print("============")
print(myString)
print("============")
print(some())
print("============")
print(addition(2, 10))
print("============")
print(multiArg(2, 3, 4, 5, 6, 4))
print("============")
conditionals()
print("============")
|
expected_output = {
"version": 3,
"interfaces": {
"GigabitEthernet1/0/9": {
"interface": "GigabitEthernet1/0/9",
"max_start": 3,
"pae": "supplicant",
"credentials": "switch4",
"supplicant": {"eap": {"profile": "EAP-METH"}},
"timeout": {"held_period": 60, "start_period": 30, "auth_period": 30},
}
},
"system_auth_control": True,
}
|
#!/usr/bin/ python
# -*- coding: utf-8 -*-
__author__ = 'mtianyan'
__date__ = '2018/11/6 18:18'
"""
┏┓ ┏┓+ +
┏┛┻━━━┛┻┓ + +
┃ ┃
┃ ━ ┃ ++ + + +
████━████ ┃+
┃ ┃ +
┃ ┻ ┃
┃ ┃ + +
┗━┓ ┏━┛
┃ ┃
┃ ┃ + + + +
┃ ┃ Code is far away from bug with the animal protecting
┃ ┃ + 神兽保佑,代码无bug
┃ ┃
┃ ┃ +
┃ ┗━━━┓ + +
┃ ┣┓
┃ ┏┛
┗┓┓┏━┳┓┏┛ + + + +
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛+ + + +
"""
# 1. 可以被赋值给变量
def ask(name='mtianyan'):
print(name)
my_func = ask
my_func("hello")
class Person():
def __init__(self):
print("init")
my_class = Person
my_class()
# 2. 可以放入集合中
print("*" * 20)
obj_list = [ask, Person]
for item in obj_list:
print(item())
# 4. 可以当做函数的返回值
print("^" * 20)
def decorator_func():
print("dec start")
return ask
my_ask = decorator_func()
my_ask("tom")
|
country_entities={
"Q1000": {
"description": "equatorial country in West Africa",
"label": "Gabon"
},
"Q1005": {
"description": "sovereign state in West Africa",
"label": "The Gambia"
},
"Q1006": {
"description": "sovereign state in West Africa",
"label": "Guinea"
},
"Q1007": {
"description": "sovereign state in Western Africa",
"label": "Guinea-Bissau"
},
"Q1008": {
"description": "sovereign state in West Africa",
"label": "Ivory Coast"
},
"Q1009": {
"description": "sovereign state in West Africa",
"label": "Cameroon"
},
"Q1011": {
"description": "sovereign state comprising ten islands off the Western coast of Africa",
"label": "Cape Verde"
},
"Q1013": {
"description": "sovereign state in southern Africa",
"label": "Lesotho"
},
"Q1014": {
"description": "sovereign state in West Africa",
"label": "Liberia"
},
"Q1016": {
"description": "sovereign state in north Africa",
"label": "Libya"
},
"Q1019": {
"description": "island sovereign state off the coast of Southeast Africa, in the Indian Ocean",
"label": "Madagascar"
},
"Q1020": {
"description": "sovereign state in Africa",
"label": "Malawi"
},
"Q1025": {
"description": "sovereign state in Africa",
"label": "Mauritania"
},
"Q1027": {
"description": "island sovereign state in the Indian Ocean",
"label": "Mauritius"
},
"Q1028": {
"description": "sovereign state in North Africa",
"label": "Morocco"
},
"Q1029": {
"description": "sovereign state in Africa",
"label": "Mozambique"
},
"Q1030": {
"description": "sovereign state in southern Africa",
"label": "Namibia"
},
"Q1032": {
"description": "sovereign state in Western Africa",
"label": "Niger"
},
"Q1033": {
"description": "sovereign state in West Africa",
"label": "Nigeria"
},
"Q1034173": {
"description": "Peasant rebellion then the decentralized Imperial dynasty in Vietnam, 1778 to 1802.",
"label": "Tây Sơn Dynasty"
},
"Q1036": {
"description": "sovereign state in East Africa",
"label": "Uganda"
},
"Q1037": {
"description": "sovereign state in Africa",
"label": "Rwanda"
},
"Q1039": {
"description": "island sovereign state in Africa",
"label": "São Tomé and Príncipe"
},
"Q1041": {
"description": "sovereign state in Western Africa",
"label": "Senegal"
},
"Q1042": {
"description": "island sovereign state off the eastern coast of Africa",
"label": "Seychelles"
},
"Q1044": {
"description": "sovereign state in West Africa",
"label": "Sierra Leone"
},
"Q1045": {
"description": "sovereign state in Africa",
"label": "Somalia"
},
"Q1049": {
"description": "sovereign state in Northeast Africa",
"label": "Sudan"
},
"Q1050": {
"description": "Kingdom in southern Africa",
"label": "Eswatini"
},
"Q114": {
"description": "sovereign state in East Africa",
"label": "Kenya"
},
"Q115": {
"description": "country in East Africa",
"label": "Ethiopia"
},
"Q117": {
"description": "sovereign state in West Africa",
"label": "Ghana"
},
"Q11703": {
"description": "group of islands in the Caribbean",
"label": "United States Virgin Islands"
},
"Q1183": {
"description": "unincorporated territory of the United States",
"label": "Puerto Rico"
},
"Q1246": {
"description": "partially recognized country in southeastern Europe",
"label": "Kosovo"
},
"Q12585": {
"description": "region of the Americas where Romance languages are primarily spoken",
"label": "Latin America"
},
"Q126125": {
"description": "French overseas collectivity, part of the island of Saint Martin in the Lesser Antilles",
"label": "Saint Martin (French part)"
},
"Q132959": {
"description": "area of the continent of Africa that lies south of the Sahara Desert",
"label": "Sub-Saharan Africa"
},
"Q1410": {
"description": "British Overseas Territory",
"label": "Gibraltar"
},
"Q142": {
"description": "country in Western Europe",
"label": "France"
},
"Q1433120": {
"description": "Developing countries with high levels of poverty and debt",
"label": "Heavily Indebted Poor Countries"
},
"Q143487": {
"description": "geographic and cultural region; collective term for the Arabic-speaking countries of Asia and Africa, or of Asia only",
"label": "Arab world"
},
"Q145": {
"description": "country in Western Europe",
"label": "United Kingdom"
},
"Q14773": {
"description": "Special Administrative Region of China",
"label": "Macau"
},
"Q148": {
"description": "socialist state in East Asia",
"label": "People's Republic of China"
},
"Q15180": {
"description": "federal socialist country in Eastern Europe and Northern Asia (1922–1991)",
"label": "Soviet Union"
},
"Q155": {
"description": "country in South America",
"label": "Brazil"
},
"Q159": {
"description": "sovereign state in Eastern Europe and Northern Asia",
"label": "Russia"
},
"Q16": {
"description": "sovereign state in North America",
"label": "Canada"
},
"Q16502": {
"description": "planet Earth and all life upon it, including human civilization",
"label": "world"
},
"Q16635": {
"description": "island territory of the United States of America",
"label": "Guam"
},
"Q16641": {
"description": "US territory in the Pacific",
"label": "American Samoa"
},
"Q16644": {
"description": "American-dependent insular area in the western Pacific",
"label": "Northern Mariana Islands"
},
"Q17": {
"description": "sovereign state in East Asia",
"label": "Japan"
},
"Q17050654": {
"description": "old name for Poland",
"label": "Lechia"
},
"Q17054": {
"description": "island in the Lesser Antilles, overseas region and department of France",
"label": "Martinique"
},
"Q17070": {
"description": "island in the Indian Ocean, overseas region of France",
"label": "Réunion"
},
"Q18221": {
"description": "British Overseas Territory in the Caribbean",
"label": "Turks and Caicos Islands"
},
"Q183": {
"description": "country in Central Europe",
"label": "Germany"
},
"Q184": {
"description": "country in eastern Europe",
"label": "Belarus"
},
"Q189": {
"description": "sovereign state in Northern Europe, situated on an island in the far North Atlantic Ocean",
"label": "Iceland"
},
"Q191": {
"description": "sovereign state in northeastern Europe",
"label": "Estonia"
},
"Q20": {
"description": "country in northern Europe",
"label": "Norway"
},
"Q211": {
"description": "sovereign state in northeastern Europe",
"label": "Latvia"
},
"Q212": {
"description": "sovereign state in eastern Europe",
"label": "Ukraine"
},
"Q21203": {
"description": "island country in the Caribbean, part of the Kingdom of the Netherlands",
"label": "Aruba"
},
"Q213": {
"description": "country in Central Europe",
"label": "Czech Republic"
},
"Q214": {
"description": "country in Central Europe",
"label": "Slovakia"
},
"Q215": {
"description": "country in Central Europe",
"label": "Slovenia"
},
"Q217": {
"description": "sovereign state in southeastern Europe",
"label": "Moldova"
},
"Q218": {
"description": "country in Central and Eastern Europe",
"label": "Romania"
},
"Q219": {
"description": "sovereign state in southeastern Europe",
"label": "Bulgaria"
},
"Q219060": {
"description": "de jure sovereign state in the Middle East, recognized as such by several countries and international organizations, and as an observer member in the United Nations and for most other countries",
"label": "State of Palestine"
},
"Q221": {
"description": "country in southeastern Europe",
"label": "North Macedonia"
},
"Q222": {
"description": "country in southeastern Europe",
"label": "Albania"
},
"Q223": {
"description": "autonomous country within the Kingdom of Denmark",
"label": "Greenland"
},
"Q224": {
"description": "country in southeastern Europe",
"label": "Croatia"
},
"Q225": {
"description": "country in southeastern Europe",
"label": "Bosnia and Herzegovina"
},
"Q227": {
"description": "sovereign state in Western Asia and Eastern Europe",
"label": "Azerbaijan"
},
"Q228": {
"description": "sovereign microstate between France and Spain, in Western Europe",
"label": "Andorra"
},
"Q229": {
"description": "sovereign state situated on an island in the Eastern Mediterranean Sea",
"label": "Cyprus"
},
"Q230": {
"description": "country in the Caucasus between Europe and Asia",
"label": "Georgia"
},
"Q232": {
"description": "sovereign state in Eastern Europe and Central Asia",
"label": "Kazakhstan"
},
"Q233": {
"description": "sovereign state in Southern Europe situated on an archipelago in the Mediterranean Sea",
"label": "Malta"
},
"Q235": {
"description": "sovereign city-state on the French Riviera",
"label": "Monaco"
},
"Q236": {
"description": "country in southeastern Europe",
"label": "Montenegro"
},
"Q23635": {
"description": "British overseas territory in the North Atlantic Ocean",
"label": "Bermuda"
},
"Q23681": {
"description": "limited-recognition state on the Island of Cyprus",
"label": "Turkish Republic of Northern Cyprus"
},
"Q237": {
"description": "independent city-state enclaved within Rome, Italy under the sovereignty of the Holy See; world's smallest sovereign state",
"label": "Vatican City"
},
"Q238": {
"description": "sovereign state in Southern Europe, enclaved within Italy",
"label": "San Marino"
},
"Q241": {
"description": "sovereign state situated on an island in the Caribbean Sea",
"label": "Cuba"
},
"Q242": {
"description": "sovereign state in Central America",
"label": "Belize"
},
"Q244": {
"description": "sovereign state situated on an island in the Western Atlantic Ocean",
"label": "Barbados"
},
"Q252": {
"description": "sovereign state in Southeast Asia situated on more than 17,000 islands",
"label": "Indonesia"
},
"Q25227": {
"description": "former country within the Kingdom of the Netherlands",
"label": "Netherlands Antilles"
},
"Q25228": {
"description": "British Overseas Territory in the Caribbean",
"label": "Anguilla"
},
"Q25279": {
"description": "island country in the Caribbean, part of the Kingdom of the Netherlands",
"label": "Curaçao"
},
"Q25305": {
"description": "British overseas territory in the Caribbean",
"label": "British Virgin Islands"
},
"Q258": {
"description": "sovereign state in Southern Africa",
"label": "South Africa"
},
"Q262": {
"description": "sovereign country in North Africa",
"label": "Algeria"
},
"Q26273": {
"description": "country on the Caribbean island of Saint Martin, part of the Kingdom of the Netherlands",
"label": "Sint Maarten"
},
"Q265": {
"description": "sovereign state in Central Asia",
"label": "Uzbekistan"
},
"Q26988": {
"description": "state in the South Pacific Ocean",
"label": "Cook Islands"
},
"Q27": {
"description": "sovereign state in northwestern Europe covering five-sixths of the island of Ireland",
"label": "Ireland"
},
"Q27275": {
"description": "core region of the Asian continent",
"label": "Central Asia"
},
"Q28": {
"description": "country in Central Europe",
"label": "Hungary"
},
"Q29": {
"description": "country in southwestern Europe",
"label": "Spain"
},
"Q298": {
"description": "sovereign state in South America",
"label": "Chile"
},
"Q29999": {
"description": "sovereign state, constitutional monarchy",
"label": "Kingdom of the Netherlands"
},
"Q30": {
"description": "sovereign state in North America",
"label": "United States of America"
},
"Q30971": {
"description": "French overseas country in the Southern Pacific ocean",
"label": "French Polynesia"
},
"Q31": {
"description": "country in western Europe",
"label": "Belgium"
},
"Q3111454": {
"description": "Vietnamese monarchs that ruled from 1226 to 1400.",
"label": "Tran dynasty"
},
"Q32": {
"description": "country in Western Europe",
"label": "Luxembourg"
},
"Q33": {
"description": "country in northern Europe",
"label": "Finland"
},
"Q334": {
"description": "sovereign city-state in Southeast Asia",
"label": "Singapore"
},
"Q33788": {
"description": "special collectivity of France in the southwest Pacific Ocean",
"label": "New Caledonia"
},
"Q33946": {
"description": "sovereign state in Central Europe (1918-1992)",
"label": "Czechoslovakia"
},
"Q34": {
"description": "sovereign state in northern Europe",
"label": "Sweden"
},
"Q34020": {
"description": "island country in the South Pacific Ocean",
"label": "Niue"
},
"Q347": {
"description": "country in Central Europe",
"label": "Liechtenstein"
},
"Q35": {
"description": "country in northern Europe",
"label": "Denmark"
},
"Q36": {
"description": "country in Central Europe",
"label": "Poland"
},
"Q37": {
"description": "sovereign state in northeastern Europe",
"label": "Lithuania"
},
"Q3769": {
"description": "overseas French department in the Guianas region",
"label": "French Guiana"
},
"Q38": {
"description": "country in Southern Europe",
"label": "Italy"
},
"Q39": {
"description": "federal state in Western Europe",
"label": "Switzerland"
},
"Q392770": {
"description": "inter-governmental organization",
"label": "Organisation of Eastern Caribbean States"
},
"Q398": {
"description": "sovereign state in Southwest Asia",
"label": "Bahrain"
},
"Q399": {
"description": "sovereign state in the South Caucasus region of Eurasia",
"label": "Armenia"
},
"Q40": {
"description": "country in Central Europe",
"label": "Austria"
},
"Q403": {
"description": "country in southeastern Europe",
"label": "Serbia"
},
"Q407199": {
"description": "West Bank, excluding East Jerusalem annexed to the State of Israel, in the status of belligerent occupation, supported by international public law and the High Court of Justice of Israel",
"label": "Palestinian territories"
},
"Q408": {
"description": "country in the Southern Hemisphere",
"label": "Australia"
},
"Q41": {
"description": "country in southeastern Europe",
"label": "Greece"
},
"Q414": {
"description": "sovereign state in South America",
"label": "Argentina"
},
"Q419": {
"description": "sovereign state in South America",
"label": "Peru"
},
"Q423": {
"description": "sovereign state in East Asia",
"label": "North Korea"
},
"Q42314": {
"description": "archipelago in the English Channel",
"label": "Channel Islands"
},
"Q424": {
"description": "sovereign state in Southeast Asia",
"label": "Cambodia"
},
"Q43": {
"description": "sovereign state straddling Southeastern Europe and Western Asia",
"label": "Turkey"
},
"Q45": {
"description": "country in southwestern Europe",
"label": "Portugal"
},
"Q458": {
"description": "economic and political union of 27 states mostly located in Europe",
"label": "European Union"
},
"Q4628": {
"description": "autonomous constituent country of the Kingdom of Denmark",
"label": "Faroe Islands"
},
"Q49": {
"description": "continent on the Earth's northwestern quadrant",
"label": "North America"
},
"Q574": {
"description": "sovereign state situated on several islands in Southeast Asia",
"label": "East Timor"
},
"Q5785": {
"description": "British Overseas Territory in the Caribbean",
"label": "Cayman Islands"
},
"Q657": {
"description": "sovereign state in central Africa",
"label": "Chad"
},
"Q664": {
"description": "sovereign state in Oceania, situated on two main and around 600 smaller islands in the southwestern Pacific Ocean",
"label": "New Zealand"
},
"Q664609": {
"description": "region to the center-east of America composed of many islands / coastal regions surrounding the Caribbean Sea",
"label": "Caribbean"
},
"Q668": {
"description": "sovereign state in South Asia",
"label": "India"
},
"Q672": {
"description": "island sovereign state in Oceania",
"label": "Tuvalu"
},
"Q678": {
"description": "sovereign state in Oceania, situated on an archipelago",
"label": "Tonga"
},
"Q683": {
"description": "sovereign state made up of six islands in the Pacific Ocean",
"label": "Samoa"
},
"Q685": {
"description": "island sovereign state in Oceania",
"label": "Solomon Islands"
},
"Q686": {
"description": "sovereign state situated on an archipelago in the South Pacific Ocean",
"label": "Vanuatu"
},
"Q691": {
"description": "island sovereign state in Oceania",
"label": "Papua New Guinea"
},
"Q695": {
"description": "island sovereign state in Oceania",
"label": "Palau"
},
"Q697": {
"description": "island sovereign state in Oceania",
"label": "Nauru"
},
"Q702": {
"description": "island sovereign state in Oceania",
"label": "Federated States of Micronesia"
},
"Q709": {
"description": "island sovereign state in Oceania",
"label": "Marshall Islands"
},
"Q710": {
"description": "island sovereign state in the central Pacific Ocean",
"label": "Kiribati"
},
"Q711": {
"description": "sovereign state in East Asia",
"label": "Mongolia"
},
"Q712": {
"description": "island sovereign state in Oceania",
"label": "Fiji"
},
"Q717": {
"description": "sovereign state in northern South America",
"label": "Venezuela"
},
"Q7184": {
"description": "intergovernmental military alliance of Western states",
"label": "NATO"
},
"Q730": {
"description": "sovereign state in South America",
"label": "Suriname"
},
"Q733": {
"description": "sovereign state in South America",
"label": "Paraguay"
},
"Q734": {
"description": "sovereign state in South America",
"label": "Guyana"
},
"Q736": {
"description": "sovereign state in South America",
"label": "Ecuador"
},
"Q739": {
"description": "sovereign state in South America",
"label": "Colombia"
},
"Q750": {
"description": "sovereign state in South America",
"label": "Bolivia"
},
"Q752401": {
"description": "list of countries that exhibits the lowest indicators of socioeconomic development",
"label": "Least Developed Countries"
},
"Q754": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Trinidad and Tobago"
},
"Q756617": {
"description": "Denmark proper and its two autonomous territories: the Faroe Islands and Greenland",
"label": "Danish Realm"
},
"Q757": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Saint Vincent and the Grenadines"
},
"Q760": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Saint Lucia"
},
"Q763": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Saint Kitts and Nevis"
},
"Q766": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Jamaica"
},
"Q769": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Grenada"
},
"Q77": {
"description": "sovereign state in South America",
"label": "Uruguay"
},
"Q771405": {
"description": "southern region of Asia",
"label": "South Asia"
},
"Q774": {
"description": "sovereign state in Central America",
"label": "Guatemala"
},
"Q778": {
"description": "island sovereign state in the West Indies",
"label": "The Bahamas"
},
"Q781": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Antigua and Barbuda"
},
"Q783": {
"description": "sovereign state in Central America",
"label": "Honduras"
},
"Q784": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Dominica"
},
"Q785": {
"description": "British Crown dependency in the Channel Islands",
"label": "Jersey"
},
"Q786": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Dominican Republic"
},
"Q79": {
"description": "sovereign state in North Africa and Asia",
"label": "Egypt"
},
"Q790": {
"description": "island sovereign state in the Caribbean Sea",
"label": "Haiti"
},
"Q792": {
"description": "sovereign state in Central America",
"label": "El Salvador"
},
"Q794": {
"description": "sovereign state in Western Asia",
"label": "Iran"
},
"Q796": {
"description": "sovereign state in Western Asia",
"label": "Iraq"
},
"Q800": {
"description": "sovereign state in Central America",
"label": "Costa Rica"
},
"Q801": {
"description": "sovereign state in western Asia",
"label": "Israel"
},
"Q804": {
"description": "sovereign state in Central America",
"label": "Panama"
},
"Q805": {
"description": "sovereign state in Western Asia",
"label": "Yemen"
},
"Q810": {
"description": "sovereign state in Western Asia",
"label": "Jordan"
},
"Q811": {
"description": "sovereign state in Central America",
"label": "Nicaragua"
},
"Q813": {
"description": "sovereign state in Central Asia",
"label": "Kyrgyzstan"
},
"Q817": {
"description": "sovereign state in Western Asia",
"label": "Kuwait"
},
"Q819": {
"description": "sovereign state in Southeast Asia",
"label": "Laos"
},
"Q822": {
"description": "sovereign state in Western Asia",
"label": "Lebanon"
},
"Q826": {
"description": "sovereign state in South Asia, situated on an archipelago in the Arabian Sea",
"label": "Maldives"
},
"Q8268": {
"description": "region of EU countries using the Euro",
"label": "Eurozone"
},
"Q833": {
"description": "sovereign state in Southeast Asia",
"label": "Malaysia"
},
"Q836": {
"description": "sovereign state in Southeast Asia",
"label": "Myanmar"
},
"Q837": {
"description": "sovereign state in South Asia",
"label": "Nepal"
},
"Q842": {
"description": "sovereign state in Western Asia",
"label": "Oman"
},
"Q843": {
"description": "sovereign state in South Asia",
"label": "Pakistan"
},
"Q846": {
"description": "sovereign state in western Asia",
"label": "Qatar"
},
"Q851": {
"description": "sovereign state in Western Asia",
"label": "Saudi Arabia"
},
"Q854": {
"description": "sovereign state in South Asia, situated on an island in the Indian Ocean",
"label": "Sri Lanka"
},
"Q858": {
"description": "sovereign state in Western Asia",
"label": "Syria"
},
"Q863": {
"description": "sovereign state in Central Asia",
"label": "Tajikistan"
},
"Q8646": {
"description": "special administrative region of China",
"label": "Hong Kong"
},
"Q865": {
"description": "democratic republic in East Asia, also known as the Republic of China",
"label": "Taiwan"
},
"Q869": {
"description": "sovereign state in Southeast Asia",
"label": "Thailand"
},
"Q874": {
"description": "sovereign state in Central Asia",
"label": "Turkmenistan"
},
"Q878": {
"description": "sovereign state in Southwest Asia",
"label": "United Arab Emirates"
},
"Q878309": {
"description": "Vietnam's monarch that ruled from 1009 to 1226.",
"label": "Ly dynasty"
},
"Q881": {
"description": "sovereign state in Southeast Asia",
"label": "Vietnam"
},
"Q884": {
"description": "sovereign state in East Asia",
"label": "South Korea"
},
"Q889": {
"description": "sovereign state situated at the confluence of Western, Central, and South Asia",
"label": "Afghanistan"
},
"Q902": {
"description": "sovereign state in South Asia",
"label": "Bangladesh"
},
"Q912": {
"description": "sovereign state in West Africa",
"label": "Mali"
},
"Q916": {
"description": "sovereign state in Africa",
"label": "Angola"
},
"Q917": {
"description": "sovereign state in South Asia",
"label": "Bhutan"
},
"Q921": {
"description": "sovereign state in Southeast Asia",
"label": "Brunei"
},
"Q924": {
"description": "sovereign state in Africa",
"label": "Tanzania"
},
"Q928": {
"description": "sovereign state in Southeast Asia",
"label": "Philippines"
},
"Q929": {
"description": "sovereign state in Africa",
"label": "Central African Republic"
},
"Q945": {
"description": "sovereign state in Africa",
"label": "Togo"
},
"Q948": {
"description": "sovereign state in Northern Africa",
"label": "Tunisia"
},
"Q953": {
"description": "sovereign state in Southern Africa",
"label": "Zambia"
},
"Q954": {
"description": "sovereign state in southern Africa",
"label": "Zimbabwe"
},
"Q958": {
"description": "sovereign state in Africa",
"label": "South Sudan"
},
"Q96": {
"description": "sovereign state in North America",
"label": "Mexico"
},
"Q962": {
"description": "sovereign state in Africa",
"label": "Benin"
},
"Q963": {
"description": "sovereign state in Southern Africa",
"label": "Botswana"
},
"Q965": {
"description": "sovereign state in Africa",
"label": "Burkina Faso"
},
"Q967": {
"description": "sovereign state in Africa",
"label": "Burundi"
},
"Q9676": {
"description": "British Crown dependency",
"label": "Isle of Man"
},
"Q970": {
"description": "sovereign state situated on an archipelago in the Indian Ocean off the eastern coast of Africa",
"label": "Comoros"
},
"Q971": {
"description": "sovereign state in Central Africa",
"label": "Republic of the Congo"
},
"Q974": {
"description": "sovereign state in Central Africa",
"label": "Democratic Republic of the Congo"
},
"Q977": {
"description": "sovereign state in Africa",
"label": "Djibouti"
},
"Q983": {
"description": "sovereign state in Africa",
"label": "Equatorial Guinea"
},
"Q986": {
"description": "sovereign state in the Horn of Africa",
"label": "Eritrea"
}
}
|
def isintersect(a,b):
for i in a:
for j in b:
if i==j:
return True
return False
class RopChain(object):
def __init__(self):
self.chains = []
self.dump_str = None
self.payload = b""
self.base_addr = 0
self.next_call = None
self.is_noreturn = False
def merge_ropchain(self, ropchain):
assert not self.is_noreturn, "can't merge ropchain, this chain is no-return"
assert isinstance(ropchain, RopChain), "not RopChain instance"
if self.next_call:
self.append(self.next_call)
for chain in ropchain.chains:
self.append(chain)
self.next_call = ropchain.next_call
def __add__(self, ropchain):
self.merge_ropchain(ropchain)
return self
def set_next_call(self, addr, type_val=0, comment=""):
chain = Chain()
chain.set_chain_values([ChainItem(addr, type_val, comment)])
self.next_call = chain
def set_base_addr(self, addr):
self.base_addr = addr
def insert(self, idx, chain):
self.chains.insert(idx, chain)
def append(self, chain):
self.chains.append(chain)
def insert_chain(self, chain):
intersect = False
if isintersect(chain.written_regs, set(self.get_solved_regs())):
intersect = True
if intersect and len(self.chains) > 0:
for i in range(len(self.chains)-1, -1, -1):
solved_before = set(self.get_solved_regs(0,i+1))
written_before = set(self.get_written_regs(0, i+1))
if isintersect(chain.solved_regs, self.chains[i].written_regs) and not isintersect(solved_before, chain.written_regs):
self.insert(i+1, chain)
break
if i == 0:
regs_used_after = set(self.get_written_regs())
depends_regs_after = set(self.get_depends_regs())
if not isintersect(chain.solved_regs, regs_used_after) and not isintersect(chain.written_regs, depends_regs_after):
self.insert(0, chain)
else:
return False
else:
self.append(chain)
return True
def get_solved_regs(self, start_chain=None, end_chain=None):
regs_solved = set()
chains = self.chains[start_chain:end_chain]
for chain in chains:
regs_solved.update(chain.solved_regs)
return regs_solved
def get_written_regs(self, start_chain=None, end_chain=None):
regs_written = set()
chains = self.chains[start_chain:end_chain]
for chain in chains:
regs_written.update(chain.written_regs)
return regs_written
def get_depends_regs(self, start_chain=None, end_chain=None):
regs_depends = set()
chains = self.chains[start_chain:end_chain]
for chain in chains:
regs_depends.update(chain.depends_regs)
return regs_depends
def get_chains(self):
chains = []
for chain in self.chains:
chains.extend(chain.get_chains())
return chains
def get_comment(self):
comments = []
for chain in self.chains:
comments.extend(chain.comment)
return comments
def dump(self):
next_sp = 0
for chain in self.chains:
next_sp = chain.dump(next_sp, self.base_addr)
if self.next_call:
self.next_call.dump(next_sp, self.base_addr)
print("")
def payload_str(self):
payload = b""
for chain in self.chains:
payload += chain.payload_str(self.base_addr)
if self.next_call:
payload += self.next_call.payload_str(self.base_addr)
return payload
CHAINITEM_TYPE_VALUE = 0
CHAINITEM_TYPE_ADDR = 1
class ChainItem(object):
def __init__(self, value=0, idx_chain=-1, comment="", type_val=0):
self.value = value
self.type_val = type_val
self.comment = comment
self.idx_chain = idx_chain
def parseFromModel(chain_value_model, comment="", type_val=0):
chain_item = chain_value_model[0]
alias = chain_item.getVariable().getAlias()
idxchain = int(alias.replace("STACK", "")) + 1
chain_value = chain_item.getValue()
return ChainItem(chain_value, idxchain, comment, type_val)
def getValue(self, base_addr=0):
if base_addr and self.type_val == 1: # check if value is address
return self.value + base_addr
return self.value
class Chain(object):
def __init__(self):
self.written_regs = set()
self.solved_regs = set()
self.depends_regs = set()
self.gadget = None
self.chain_values = []
def set_chain_values(self, chain_values):
self.chain_values = chain_values
def set_solved(self, gadget, values, regs=set(), written_regs=set(), depends_regs=set()):
self.solved_regs.update(regs)
self.written_regs.update(gadget.written_regs)
self.written_regs.update(written_regs)
self.depends_regs.update(depends_regs)
self.gadget = gadget
depends_chain_values = []
chain_values = [ChainItem(0)]*(gadget.diff_sp//8 + 1)
chain_values[0] = ChainItem(gadget.addr, 0, str(gadget), CHAINITEM_TYPE_ADDR)
for chain_item in values:
if isinstance(chain_item, RopChain):
self.written_regs.update(chain_item.get_written_regs())
self.depends_regs.update(chain_item.get_depends_regs())
depends_chain_values += chain_item.get_chains()
continue
if chain_item:
chain_values[chain_item.idx_chain] = chain_item
self.chain_values += depends_chain_values + chain_values
if gadget.end_gadget:
self.written_regs.update(gadget.end_gadget.written_regs)
def get_chains(self):
return self.chain_values
def get_written_regs(self):
return self.written_regs
def get_solved_regs(self):
return self.solved_regs
def dump(self, sp, base_addr=0):
chains = self.get_chains()
dump_str = ""
for i in range(len(chains)):
chain = chains[i]
com = ""
if chain.comment:
com = " # {}".format(chain.comment)
dump_str += "$RSP+0x{:04x} : 0x{:016x}{}\n".format(sp, chain.getValue(base_addr), com)
sp += 8
print(dump_str, end="")
return sp
def payload_str(self, base_addr=0):
chains = self.get_chains()
payload = b""
for i in range(len(chains)):
chain = chains[i]
payload += chain.getValue(base_addr).to_bytes(8, 'little')
return payload
def __repr__(self):
return "written_regs : {}\nsolved_regs: {}\n".format(self.written_regs, self.solved_regs)
def __str__(self):
return "written_regs : {}\nsolved_regs: {}\n".format(self.written_regs, self.solved_regs)
|
def triplets_with_sum(number):
triplets = []
for a in range(1, number // 3):
l = a + 1
r = (number - a - 1) // 2
while l <= r:
b = (l + r) // 2
c = number - a - b
if a * a + b * b < c * c:
l = b + 1
elif a * a + b * b > c * c:
r = b - 1
else:
triplets.append([a, b, c])
break
return triplets
|
# Exercicio 003 int
print ('Faça um calculo')
p1= int (input('Primeiro numero'))
p2= int (input('Segundo numero'))
s0= p1+p2
print('O resultado de', (p1), '+', p2, 'é igual a', s0)
# BOOL
pergunta01= bool (input('Digite um numero boleano:'))
pergunta02= bool (input('Digite outro numero boleano:'))
print ('O primeirio numero é', pergunta01 ,'o segundo é', pergunta02)
# Float
pergunta03= float (input('Digite um numero real:'))
pergunta04= float (input('Digite outro numero real:'))
print ('O primeiro numero é', pergunta03, 'o segundo é', pergunta04)
# str
pergunta05= str (input('Digite um valor str:'))
pergunta06= str (input('Digite outro valor str:'))
print ('O primeiro numeor é', pergunta05, 'o segundo numero é', pergunta06)
|
class ChangeTextState:
def __init__(self):
self.prev_tail = ''
self.context = None
_change_text_state = None
def init():
global _change_text_state
_change_text_state = ChangeTextState()
init()
def get_state() -> ChangeTextState:
global _change_text_state
if _change_text_state is None:
_change_text_state = ChangeTextState()
return _change_text_state
|
"""
flask-wow
~~~~~~~~~
A simple CLI Generator to create flask app.
:copyright: 2020 Cove
:license: BSD 3-Clause License
"""
__version__ = '0.2.1'
# def demo():
#
# if args.cmd == 'addapp':
# print(f'Will create Flask app with name "{args.name}"')
# dir_name = os.path.dirname(__file__)
# source_dir = os.path.join(dir_name, 'templates', 'app_tmp')
# dist_dir = os.path.join(os.getcwd(), args.name)
# if dist_dir_check(dist_dir):
# shutil.copytree(source_dir, dist_dir,
# ignore=lambda src, names: [name for name in names if name == '__pycache__'])
# format_dir(dist_dir, args.name, args.name)
# print(f'Create app at {dist_dir} Success!')
# else:
# print(f'The directory {dist_dir} was not empty, Can\'t create app.')
|
Size = (512, 748)
ScaleFactor = 0.33
ZoomLevel = 1.0
Orientation = -90
Mirror = True
NominalPixelSize = 0.002325
filename = ''
ImageWindow.Center = (680, 512)
ImageWindow.ViewportCenter = (1.1904, 1.5774772727272726)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [[0.062775, -0.5417249999999999], [0.9044249999999999, -0.5324249999999999]]
ImageWindow.show_scale = False
ImageWindow.scale_color = (255, 0, 255)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.299925, -0.5905499999999999], [0.3999, 0.19529999999999997]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'xy'
ImageWindow.grid_color = (98, 98, 98)
ImageWindow.grid_x_spacing = 0.1
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
camera.use_multicast = False
camera.IP_addr = u'id14b-prosilica1.cars.aps.anl.gov'
|
"""Constants defining gameplay."""
# dimensions
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 1024
PLAYER_SPRITE_HEIGHT = 20
PLAYER_SPRITE_HOVER = 100
PLAYER_SPRITE_PADDING = 20
CLOSE_CALL_POSITION = (200, 200)
# display
TARGET_FRAMERATE = 60
GAME_TITLE = "Dodge"
SCORE_POSITION = (20, SCREEN_HEIGHT - 50)
# colors
SCREEN_FILL_COLOR = (0, 0, 0)
PLAYER_SPRITE_COLOR = (255, 255, 255)
OBSTACLE_SPRITE_COLOR = (255, 0, 0)
SCORE_COLOR = (128, 128, 255)
CLOSE_CALL_COLOR = (255, 160, 56)
# gameplay
DEFAULT_LANE_COUNT = 3
DEFAULT_OBSTACLES_PER_SECOND = 0.5
OBSTACLE_MIN_SPEED = 150
OBSTACLE_MAX_SPEED = 500
CLOSE_CALL_THRESHOLD = 10
CLOSE_CALL_POINTS = 5
|
#! /usr/bin/env python3
def analyse_pattern(ls) :
corresponds = {2:1,7:8,4:4,3:7}
dct = {corresponds[len(i)]:i for i in ls if len(i) in [2, 3, 4, 7]}
for i in range(10) :
s = len(ls[i])
if s == 6 : #0 6 9
if sum(ls[i][j] in dct[4] for j in range(s)) == 3 :
if sum(ls[i][j] in dct[1] for j in range(s)) == 2 :
dct[0] = ls[i]
else :
dct[6] = ls[i]
else :
dct[9] = ls[i]
elif s == 5 : #2 3 5
if sum(ls[i][j] in dct[7] for j in range(s)) == 3 :
dct[3] = ls[i]
elif sum(ls[i][j] in dct[4] for j in range(s)) == 3 :
dct[5] = ls[i]
else :
dct[2] = ls[i]
return dct
def get_number(dct, n) :
return int([i for i in range(10) if len(n) == len(dct[i]) and all(c in dct[i] for c in n)][0])
numbers = [tuple(map(lambda x:x.split(), line.split("|"))) for line in open("input")]
print(sum(sum(10**(len(signals)-i-1) * get_number(analyse_pattern(patterns), signals[i]) for i in range(len(signals))) for patterns, signals in numbers)) |
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder:
return
root = TreeNode(postorder[-1])
rootpos = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:rootpos], postorder[:rootpos])
root.right = self.buildTree(inorder[rootpos + 1 :], postorder[rootpos : -1])
return root |
class Node:
def __init__(self, data=None, next=None):
self.__data = data
self.__next = next
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
def next(self, ptr):
self.__next = ptr
def equals(node1, node2):
if node1 is None and node2 is None:
return True
elif node1 is None or node2 is None:
return False
else:
return (node1.data == node2.data) and (equals(node1.next, node2.next))
|
def y():
raise TypeError
def x():
y()
try:
x()
except TypeError:
print("x")
|
# nominal reactor positions
data = dict([
('YJ1', [52.5]),
('YJ2', [52.5]),
('YJ3', [52.5]),
('YJ4', [52.5]),
('YJ5', [52.5]),
('YJ6', [52.5]),
('TS1', [52.5]),
('TS2', [52.5]),
('TS3', [52.5]),
('TS4', [52.5]),
('DYB', [215.0]),
('HZ', [265.0]),
])
|
class Summary:
def __init__(self, total_income, net_income, income_tax, employees_ni,
employers_ni):
self._total_income = total_income
self._net_income = net_income
self._income_tax = income_tax
self._employees_ni = employees_ni
self._employers_ni = employers_ni
@property
def total_income(self):
return self._total_income
@property
def net_income(self):
return self._net_income
@property
def income_tax(self):
return self._income_tax
@property
def employees_ni(self):
return self._employees_ni
@property
def employers_ni(self):
return self._employers_ni
|
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
def isChar(c):
return True if ord('z')>=ord(c)>=ord('a') or ord('Z')>=ord(c)>=ord('A') else False
right = len(s)-1
left = 0
charArray = [c for c in s]
while left<right:
print(charArray,right)
while right>-1 and isChar(charArray[right])==False:
right -= 1
if(not right>left):
break
while isChar(charArray[left])==False:
left += 1
if(right>-1 and left < right):
charArray[left],charArray[right] = charArray[right],charArray[left]
left += 1
right -= 1
return ''.join(charArray)
|
def fp(i,n) :
i /= 100
return (1+i)**n
def pf(i,n) :
i /= 100
return 1/((1+i)**n)
def fa(i,n) :
i /= 100
return (((1+i)**n)-1)/i
def af(i,n) :
i /= 100
return i/(((1+i)**n)-1)
def pa(i,n) :
i /= 100
return (((1+i)**n)-1)/(i*((1+i)**n))
def ap(i,n) :
i /= 100
return (i*((1+i)**n))/(((1+i)**n)-1)
def pg(i,n) :
i /= 100
return (((1+i)**n)-(1+n*i))/((i**2)*((1+i)**n))
def ag(i,n) :
i /= 100
return (1/i)-(n/(((1+i)**n)-1))
|
"""utility functions to read in and parse a file efficiently
"""
def gen_file_line(text):
with open(text) as fp:
for line in fp:
yield line |
'''
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
'''
# https://leetcode.com/problems/invert-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.extend([node.left, node.right])
return root
|
"""
给出n对括号,求括号排列的所有可能性。
"""
"""
回溯法三要素:
1、选择。在这个例子中,解就是一个合法的括号组合形式,而选择无非是放入左括号,还是放入右括号;
2、条件。在这个例子中,选择是放入左括号,还是放入右括号,是有条件约束的,不是随便放的。
而这个约束就是括号的数量。只有剩下的右括号比左括号多,才能放右括号。只有左括号数量大于0才能放入左括号。这里if的顺序会影响输出的顺序,但是不影响最终解;
3、结束。这里的结束条件很显然就是,左右括号都放完了。
"""
def BackTracking(sublist,results,left_brackets,right_brackets):
if left_brackets==0 and right_brackets == 0:
results.append(sublist)
if left_brackets > 0:
BackTracking(sublist+'(',results,left_brackets-1,right_brackets)
if right_brackets>left_brackets:
BackTracking(sublist+")",results,left_brackets,right_brackets-1)
if __name__ == '__main__':
num = 1
left_brackets = right_brackets = num # 左括号、右括号各有num个
results = []
BackTracking("",results,left_brackets,right_brackets)
for result in results:
print(result)
|
# Copyright (c) 2018 Turysaz <turysaz@posteo.org>
class IoCContainer():
def __init__(self):
self.__constructors = {} # {"service_key" : service_ctor}
self.__dependencies = {} # {"service_key" : ["dep_key_1", "dep_key_2", ..]} constructor parameters
self.__quantity = {} # {"service_key" : "singleton" | "multiple"}
self.__singletons = {}
def register_on_demand(self,
service_name_string,
service,
*dependencies):
self.__register_internal(service_name_string, service, "multiple", dependencies)
def register_singleton(self,
service_name_string,
service,
*dependencies):
self.__register_internal(service_name_string, service, "singleton", dependencies)
def get_instance(self, service_name_string):
if service_name_string not in self.__constructors:
raise Exception()
if self.__quantity[service_name_string] == "multiple":
return __create_instance_recursive(service_name_string)
elif self.__quantity[service_name_string] == "singleton":
if service_name_string in self.__singletons:
return self.__singletons[service_name_string]
singleton = self.__create_instance_recursive(service_name_string)
self.__singletons[service_name_string] = singleton
return singleton
def __register_internal(self,
service_name_string,
service,
quantity,
dependencies):
if service_name_string in self.__constructors:
raise Exception() # already registered
self.__constructors[service_name_string] = service
self.__dependencies[service_name_string] = dependencies
self.__quantity[service_name_string] = quantity
def __create_instance_recursive(self, service_name_string):
deps = [self.get_instance(d)
for d in self.__dependencies[service_name_string]]
return self.__constructors[service_name_string](*deps)
|
# def isIPv4Address(inputString):
# return len([num for num in inputString.split(".") if num != "" and 0 <= int(num) < 255]) == 4
# def isIPv4Address(inputString):
# return len([int(num) for num in inputString.split(".") if num != "" and not num.islower() and 0 <= int(num) <= 255]) == 4
# def isIPv4Address(inputString):
# print([num.isdigit() for num in inputString.split(".")])
# print(inputString.count("."))
# numbers = [int(num) for num in inputString.split(".") if num != "" and not num.islower() and 0 <= int(num) <= 255 and len(num) == len(str(int(num)))]
# print(numbers)
# print(len(numbers))
# return len(numbers) == 4
def isIPv4Address(inputString):
if inputString.count(".") != 3:
return False
return len([int(num) for num in inputString.split(".") if num != "" and not num.islower() and 0 <= int(num) <= 255 and len(num) == len(str(int(num)))]) == 4
# 172.16.254.1 => True
# 172.316.254.1 => False
# .254.255.0 => False
print(isIPv4Address("0..1.0.0")) |
class UrlManager():
def __init__(self):
"""
初始化url
"""
# 职位 url
self.positon_url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city={}&needAddtionalResult=false'
def get_position_url(self):
"""
返回职位url
:return:
"""
return self.positon_url
|
n = int(input())
s = input()
xo = "XO"
ox = "OX"
count_x = s.count("X")
#print(count_xo)
dst = s.replace("X", "")
o_length = len(s)
# Oの数
x_length = n - o_length
count_o = s.count("O")
#print(count_ox)
dst = s.replace("O","")
if count_xo == 0:
print(1)
count = 0
elif count_ox == 0:
print(2)
count = 0
elif count_ox == count_xo:
print(3)
count = count_ox
else:
print(4)
count = count_ox + count_xo
print(count)
#if count_o == 0:
# count = 0
#elif count_x == 0:
# count = 0
#elif count_o == count_x:
# count = count_o
#elif count_o > count_x:
# count = count_x
#else:
# count = count_o
#dst = s.replace("OX", "",1)
#ans = len(dst)
#
## 文字列に検索したい文字列が含まれているか
#for ox in s:
# count = s.count(ox)
# dst = s.replace(ox,"-",count)
# for xo in s:
# dst = s.replace("XO", "-",1)
# count = count + 1
|
def validTime(time):
tokens = time.split(":")
hours, mins = tokens[0], tokens[1]
if int(hours) < 0 or int(hours) > 23:
return False
if int(mins) < 0 or int(mins) > 59:
return False
return True
|
#
# PySNMP MIB module AT-IGMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-IGMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:30:12 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)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint")
modules, = mibBuilder.importSymbols("AT-SMI-MIB", "modules")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ObjectIdentity, Counter32, iso, IpAddress, ModuleIdentity, Counter64, Bits, Unsigned32, NotificationType, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "ObjectIdentity", "Counter32", "iso", "IpAddress", "ModuleIdentity", "Counter64", "Bits", "Unsigned32", "NotificationType", "MibIdentifier", "Integer32")
DisplayString, TruthValue, MacAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "MacAddress", "TextualConvention")
igmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139))
igmp.setRevisions(('2007-08-08 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: igmp.setRevisionsDescriptions(('Initial version, to support IGMP membership status polling.',))
if mibBuilder.loadTexts: igmp.setLastUpdated('200708080000Z')
if mibBuilder.loadTexts: igmp.setOrganization('Allied Telesis, Inc.')
if mibBuilder.loadTexts: igmp.setContactInfo(' Stan Xiang,Hamish Kellahan Allied Telesis EMail: support@alliedtelesis.co.nz')
if mibBuilder.loadTexts: igmp.setDescription('The MIB module for IGMP Management.')
igmpIntInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1))
igmpIntMember = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9))
igmpSnooping = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10))
igmpInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1), )
if mibBuilder.loadTexts: igmpInterfaceTable.setStatus('current')
if mibBuilder.loadTexts: igmpInterfaceTable.setDescription('The (conceptual) table listing IGMP capable IP interfaces.')
igmpInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpInterface"))
if mibBuilder.loadTexts: igmpInterfaceEntry.setStatus('current')
if mibBuilder.loadTexts: igmpInterfaceEntry.setDescription('An entry (conceptual row) in the igmpInterfaceTable.')
igmpInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInterface.setStatus('current')
if mibBuilder.loadTexts: igmpInterface.setDescription('The index value of the interface for which IGMP is enabled. This table is indexed by this value.')
igmpInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInterfaceName.setStatus('current')
if mibBuilder.loadTexts: igmpInterfaceName.setDescription('The name of the interface for which IGMP or MLD is enabled.')
igmpQueryTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpQueryTimeout.setStatus('current')
if mibBuilder.loadTexts: igmpQueryTimeout.setDescription('It represents the maximum expected time interval, in seconds, between successive IGMP general query messages arriving on the interface. A vlaue of zero means there is no limits.')
igmpProxy = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("off", 0), ("upstream", 1), ("downstream", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpProxy.setStatus('current')
if mibBuilder.loadTexts: igmpProxy.setDescription('The object represents states of igmp proxy. When it has a value of 0 then it means the inteface proxy is currently disabled. When it has a value of 1 then it means IGMP is performing upstream inteface proxying. When it has a value of 2 then it means IGMP is performing downstream inteface proxying.')
igmpIntStatsTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2), )
if mibBuilder.loadTexts: igmpIntStatsTable.setStatus('current')
if mibBuilder.loadTexts: igmpIntStatsTable.setDescription('The (conceptual) table listing statistics for IGMP capable IP interfaces.')
igmpIntStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpInterface"))
if mibBuilder.loadTexts: igmpIntStatsEntry.setStatus('current')
if mibBuilder.loadTexts: igmpIntStatsEntry.setDescription('An entry (conceptual row) in the igmpIntStatsTable.')
igmpInQuery = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInQuery.setStatus('current')
if mibBuilder.loadTexts: igmpInQuery.setDescription('The number of IGMP Query messages received by the interface.')
igmpInReportV1 = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInReportV1.setStatus('current')
if mibBuilder.loadTexts: igmpInReportV1.setDescription('The number of IGMP version 1 Report messages received by the interface.')
igmpInReportV2 = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInReportV2.setStatus('current')
if mibBuilder.loadTexts: igmpInReportV2.setDescription('The number of IGMP version 2 Report messages received by the interface.')
igmpInLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInLeave.setStatus('current')
if mibBuilder.loadTexts: igmpInLeave.setDescription('The number of IGMP Leave Group messages received by the interface.')
igmpInTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpInTotal.setStatus('current')
if mibBuilder.loadTexts: igmpInTotal.setDescription('The total number of IGMP messages received by the interface.')
igmpOutQuery = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpOutQuery.setStatus('current')
if mibBuilder.loadTexts: igmpOutQuery.setDescription('The total number of IGMP Query messages that were transmitted by the switch over the interface.')
igmpOutTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 7), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpOutTotal.setStatus('current')
if mibBuilder.loadTexts: igmpOutTotal.setDescription('The total number of IGMP messages that were transmitted by the switch over the interface.')
igmpBadQuery = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 8), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpBadQuery.setStatus('current')
if mibBuilder.loadTexts: igmpBadQuery.setDescription('The number of IGMP membership query messages with errors that were received by the interface.')
igmpBadReportV1 = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 9), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpBadReportV1.setStatus('current')
if mibBuilder.loadTexts: igmpBadReportV1.setDescription('The number of IGMP Version 1 membership report messages with errors that were received by the interface.')
igmpBadReportV2 = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 10), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpBadReportV2.setStatus('current')
if mibBuilder.loadTexts: igmpBadReportV2.setDescription('The number of IGMP Version 2 membership report messages with errors that were received by the interface.')
igmpBadLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 11), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpBadLeave.setStatus('current')
if mibBuilder.loadTexts: igmpBadLeave.setDescription('The number of IGMP Leave Group messages with errors that were received by the interface.')
igmpBadTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 1, 2, 1, 12), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpBadTotal.setStatus('current')
if mibBuilder.loadTexts: igmpBadTotal.setDescription('The total number of IGMP messages with errors that were received by the interface..')
igmpIntGroupTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9, 1), )
if mibBuilder.loadTexts: igmpIntGroupTable.setStatus('current')
if mibBuilder.loadTexts: igmpIntGroupTable.setDescription('The (conceptual) table listing the IP multicast groups of which there are members on a particular interface.')
igmpIntGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9, 1, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpInterface"))
if mibBuilder.loadTexts: igmpIntGroupEntry.setStatus('current')
if mibBuilder.loadTexts: igmpIntGroupEntry.setDescription('An entry (conceptual row) in the igmpGroupTable.')
igmpIntGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpIntGroupAddress.setStatus('current')
if mibBuilder.loadTexts: igmpIntGroupAddress.setDescription('The IP multicast group address for which this entry contains information.')
igmpLastHost = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9, 1, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpLastHost.setStatus('current')
if mibBuilder.loadTexts: igmpLastHost.setDescription('The IP address of the last host reporting a membership. If it is static, then 0.0.0.0 presents.')
igmpRefreshTime = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 9, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpRefreshTime.setStatus('current')
if mibBuilder.loadTexts: igmpRefreshTime.setDescription('The time in seconds until the membership group is deleted if another membership report is not received. A value of 0xffffffff means infinity.')
igmpSnoopAdminInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 1))
igmpSnoopAdminEnabled = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 1, 1), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopAdminEnabled.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopAdminEnabled.setDescription('Indicates whether IGMP Snooping is globally enabled.')
igmpSnoopVlanTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2), )
if mibBuilder.loadTexts: igmpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopVlanTable.setDescription('The (conceptual) table listing the layer 2 interfaces performing IGMP snooping.')
igmpSnoopVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpSnoopVID"))
if mibBuilder.loadTexts: igmpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopVlanEntry.setDescription('An entry (conceptual row) in the IGMP Snooping Vlan Table.')
igmpSnoopVID = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopVID.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopVID.setDescription('The 802.1 VLAN ID of the layer 2 interface performing IGMP snooping.')
igmpSnoopVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopVlanName.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopVlanName.setDescription('The name of the layer 2 interface performing IGMP snooping.')
igmpSnoopFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("off", 0), ("single", 1), ("multi", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopFastLeave.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopFastLeave.setDescription('Indicates whether FastLeave is enabled, and operating in Single-Host or Multi-Host mode.')
igmpSnoopQuerySolicit = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1, 4), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopQuerySolicit.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopQuerySolicit.setDescription('Indicates whether query solicitation is on')
igmpSnoopStaticRouterPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 2, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopStaticRouterPorts.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopStaticRouterPorts.setDescription('Indicates the configured static multicast router ports.')
igmpSnoopGroupTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 3), )
if mibBuilder.loadTexts: igmpSnoopGroupTable.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopGroupTable.setDescription('The (conceptual) table of IGMP Groups snooped on a layer 2 interface.')
igmpSnoopGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 3, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpSnoopVID"), (0, "AT-IGMP-MIB", "igmpSnoopGroupAddress"))
if mibBuilder.loadTexts: igmpSnoopGroupEntry.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopGroupEntry.setDescription('A (conceptual) row in the IGMP Snooping Group table.')
igmpSnoopGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 3, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopGroupAddress.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopGroupAddress.setDescription('The Multicast Group IP Address detected on a layer 2 interface.')
igmpSnoopGroupTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 3, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopGroupTimer.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopGroupTimer.setDescription('The time remaining before the multicast group is deleted from the layer 2 interface.')
igmpSnoopPortTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 4), )
if mibBuilder.loadTexts: igmpSnoopPortTable.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopPortTable.setDescription('A (conceptual) table of ports in a layer 2 interface that are currently members of a multicast group.')
igmpSnoopPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 4, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpSnoopVID"), (0, "AT-IGMP-MIB", "igmpSnoopGroupAddress"), (0, "AT-IGMP-MIB", "igmpSnoopPortNumber"))
if mibBuilder.loadTexts: igmpSnoopPortEntry.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopPortEntry.setDescription('A (conceptual) row in the IGMP Snooping Port Table.')
igmpSnoopPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 4, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopPortNumber.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopPortNumber.setDescription('Provides the number of a port in a multicast group.')
igmpSnoopPortIsStatic = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 4, 1, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopPortIsStatic.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopPortIsStatic.setDescription('Indicates whether a port has been administratively added to a multicast group.')
igmpSnoopPortTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 4, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopPortTimer.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopPortTimer.setDescription('Indicates the time remaining before the port is removed.')
igmpSnoopHostTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 5), )
if mibBuilder.loadTexts: igmpSnoopHostTable.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopHostTable.setDescription('A (conceptual) table of hosts receiving multicast data.')
igmpSnoopHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 5, 1), ).setIndexNames((0, "AT-IGMP-MIB", "igmpSnoopVID"), (0, "AT-IGMP-MIB", "igmpSnoopGroupAddress"), (0, "AT-IGMP-MIB", "igmpSnoopPortNumber"), (0, "AT-IGMP-MIB", "igmpSnoopHostMAC"))
if mibBuilder.loadTexts: igmpSnoopHostEntry.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopHostEntry.setDescription('A (conceptual) row in the IGMP Snooping Host Table.')
igmpSnoopHostMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 5, 1, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopHostMAC.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopHostMAC.setDescription('Provides the Media Access Control Address of an IGMP Host.')
igmpSnoopHostIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 5, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopHostIpAddress.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopHostIpAddress.setDescription('Provides the Internet Protocol Address of an IGMP Host.')
igmpSnoopHostTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 139, 10, 5, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: igmpSnoopHostTimer.setStatus('current')
if mibBuilder.loadTexts: igmpSnoopHostTimer.setDescription('Indicates the time remaining before the host times out.')
mibBuilder.exportSymbols("AT-IGMP-MIB", igmpInReportV1=igmpInReportV1, igmpSnoopQuerySolicit=igmpSnoopQuerySolicit, igmpBadQuery=igmpBadQuery, igmpOutQuery=igmpOutQuery, igmpInterfaceEntry=igmpInterfaceEntry, igmpIntStatsTable=igmpIntStatsTable, igmpProxy=igmpProxy, igmpIntGroupTable=igmpIntGroupTable, igmpSnoopAdminEnabled=igmpSnoopAdminEnabled, igmpSnoopFastLeave=igmpSnoopFastLeave, igmpIntMember=igmpIntMember, igmpRefreshTime=igmpRefreshTime, igmpSnoopPortTimer=igmpSnoopPortTimer, igmpIntInfo=igmpIntInfo, igmpSnoopGroupAddress=igmpSnoopGroupAddress, igmpSnoopVlanName=igmpSnoopVlanName, igmpIntGroupEntry=igmpIntGroupEntry, igmpSnoopAdminInfo=igmpSnoopAdminInfo, igmpInQuery=igmpInQuery, igmpBadTotal=igmpBadTotal, igmpBadReportV1=igmpBadReportV1, igmp=igmp, igmpSnoopGroupEntry=igmpSnoopGroupEntry, igmpBadReportV2=igmpBadReportV2, igmpInterface=igmpInterface, igmpIntGroupAddress=igmpIntGroupAddress, PYSNMP_MODULE_ID=igmp, igmpSnoopVlanTable=igmpSnoopVlanTable, igmpSnoopGroupTimer=igmpSnoopGroupTimer, igmpSnoopHostTable=igmpSnoopHostTable, igmpSnoopHostIpAddress=igmpSnoopHostIpAddress, igmpIntStatsEntry=igmpIntStatsEntry, igmpBadLeave=igmpBadLeave, igmpSnoopPortEntry=igmpSnoopPortEntry, igmpLastHost=igmpLastHost, igmpQueryTimeout=igmpQueryTimeout, igmpSnoopGroupTable=igmpSnoopGroupTable, igmpSnoopHostMAC=igmpSnoopHostMAC, igmpSnoopPortIsStatic=igmpSnoopPortIsStatic, igmpInTotal=igmpInTotal, igmpInterfaceName=igmpInterfaceName, igmpSnoopPortNumber=igmpSnoopPortNumber, igmpSnoopHostEntry=igmpSnoopHostEntry, igmpSnoopStaticRouterPorts=igmpSnoopStaticRouterPorts, igmpSnoopVID=igmpSnoopVID, igmpSnoopHostTimer=igmpSnoopHostTimer, igmpSnoopPortTable=igmpSnoopPortTable, igmpInReportV2=igmpInReportV2, igmpInLeave=igmpInLeave, igmpSnooping=igmpSnooping, igmpSnoopVlanEntry=igmpSnoopVlanEntry, igmpOutTotal=igmpOutTotal, igmpInterfaceTable=igmpInterfaceTable)
|
#!/usr/bin/env python
#
# Copyright (c) 2018 10X Genomics, Inc. All rights reserved.
#
MULTI_REFS_PREFIX = 'multi'
# Constants for metasamples
GENE_EXPRESSION_LIBRARY_TYPE = 'Gene Expression'
VDJ_LIBRARY_TYPE = 'VDJ'
ATACSEQ_LIBRARY_TYPE = 'Peaks'
ATACSEQ_LIBRARY_DERIVED_TYPE = 'Motifs'
DEFAULT_LIBRARY_TYPE = GENE_EXPRESSION_LIBRARY_TYPE
|
n = total = maior = media = cont = 0
menor = 9999999999
opcao = 'S'
while opcao == 'S':
n = int(input('Digite um número: '))
total += n
cont += 1
if n > maior:
maior = n
if n < menor:
menor = n
opcao = str(input('Quer continuar? [S/N]: ').strip().upper()[0])
media = total / cont
print('\033[32mVocê digitou {} números e a média foi {:.1f}.'.format(cont, media))
print('\033[31mO maior valor foi {} e o menor valor foi {}.'.format(maior, menor)) |
"""
File: rocket.py
Name: 黃科諺
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
# This constant determines rocket size.
SIZE = 3
def main():
"""
This program draws a rocket composed of six parts; its size changes proportionately to the constant SIZE
"""
head()
belt()
upper()
lower()
belt()
head()
def head():
"""
This function draws the head with a length equal to SIZE and a width of SIZE*2+2
"""
for i in range(SIZE):
for j in range(SIZE+1):
if (i+j)>(SIZE-1):
print('/', end='')
else:
print(' ', end='')
for j in range(SIZE+1,SIZE*2+2):
if (j-i)>(SIZE+1):
print(' ', end='')
else:
print('\\', end='')
print('')
def belt():
"""
This function draws the belt with a length of 1 and a width of SIZE*2+2
"""
for i in range(SIZE*2+2):
if i==0:
print('+', end='')
elif i==SIZE*2+1:
print('+', end='')
else:
print('=', end='')
print('')
def upper():
"""
This function draws the upper part of the body with a length equal to SIZE and a width of SIZE*2+2
"""
for i in range(SIZE):
for j in range(SIZE+1):
if j==0:
print('|', end='')
elif (i+j)<SIZE:
print('.', end='')
else:
if SIZE%2==1:
if (i + j) % 2 == 1:
print('/', end='')
else:
print('\\', end='')
else:
if (i + j) % 2 == 1:
print('\\', end='')
else:
print('/', end='')
for j in range(SIZE+1,SIZE*2+2):
if j == SIZE * 2 + 1:
print('|', end='')
elif (j-i) > SIZE+1:
print('.', end='')
else:
if SIZE % 2 == 1:
if (i + j) % 2 == 1:
print('/', end='')
else:
print('\\', end='')
else:
if (i + j) % 2 == 1:
print('\\', end='')
else:
print('/', end='')
print('')
def lower():
"""
This function draws the lower part of the body with a length equal to SIZE and a width of SIZE*2+2
"""
for i in range(SIZE):
for j in range(SIZE+1):
if j==0:
print('|', end='')
elif (j-i)<1:
print('.', end='')
else:
if (i + j) % 2 == 1:
print('\\', end='')
else:
print('/', end='')
for j in range(SIZE+1,SIZE*2+2):
if j == SIZE * 2 + 1:
print('|', end='')
elif (i+j) > SIZE*2:
print('.', end='')
else:
if (i + j) % 2 == 1:
print('\\', end='')
else:
print('/', end='')
print('')
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main() |
def noOfwords(strs):
l = strs.split(' ')
return len(l)
string = input()
count = noOfwords(string)
print(count)
|
def modular_exp(b, e, mod):
if e == 0:
return 1
res = modular_exp(b, e//2, mod)
res = (res * res ) % mod
if e%2 == 1:
res = (res * b) % mod
return res
|
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for Skia.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def _CheckChangeHasEol(input_api, output_api, source_file_filter=None):
"""Checks that files end with atleast one \n (LF)."""
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
# Check that the file ends in atleast one newline character.
if len(contents) > 1 and contents[-1:] != '\n':
eof_files.append(f.LocalPath())
if eof_files:
return [output_api.PresubmitPromptWarning(
'These files should end in a newline character:',
items=eof_files)]
return []
def _CommonChecks(input_api, output_api):
"""Presubmit checks common to upload and commit."""
results = []
sources = lambda x: (x.LocalPath().endswith('.h') or
x.LocalPath().endswith('.gypi') or
x.LocalPath().endswith('.gyp') or
x.LocalPath().endswith('.py') or
x.LocalPath().endswith('.sh') or
x.LocalPath().endswith('.cpp'))
results.extend(
_CheckChangeHasEol(
input_api, output_api, source_file_filter=sources))
return results
def CheckChangeOnUpload(input_api, output_api):
"""Presubmit checks for the change on upload.
The following are the presubmit checks:
* Check change has one and only one EOL.
"""
results = []
results.extend(_CommonChecks(input_api, output_api))
return results
def _CheckTreeStatus(input_api, output_api, json_url):
"""Check whether to allow commit.
Args:
input_api: input related apis.
output_api: output related apis.
json_url: url to download json style status.
"""
tree_status_results = input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api, json_url=json_url)
if not tree_status_results:
# Check for caution state only if tree is not closed.
connection = input_api.urllib2.urlopen(json_url)
status = input_api.json.loads(connection.read())
connection.close()
if 'caution' in status['message'].lower():
short_text = 'Tree state is: ' + status['general_state']
long_text = status['message'] + '\n' + json_url
tree_status_results.append(
output_api.PresubmitPromptWarning(
message=short_text, long_text=long_text))
return tree_status_results
def CheckChangeOnCommit(input_api, output_api):
"""Presubmit checks for the change on commit.
The following are the presubmit checks:
* Check change has one and only one EOL.
* Ensures that the Skia tree is open in
http://skia-tree-status.appspot.com/. Shows a warning if it is in 'Caution'
state and an error if it is in 'Closed' state.
"""
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(
_CheckTreeStatus(input_api, output_api, json_url=(
'http://skia-tree-status.appspot.com/banner-status?format=json')))
return results
|
# coding=utf-8
"""
下一个排列
描述:给定一个整数数组来表示排列,找出其之后的一个排列
思路: 和寻找上一个类似
这个就是找到上升点, 然后从上升点开始算从右到左找到第一个也是最小的那个比上升点前那个数大的数
然后交换位置, 然后倒置从上升点开始的那一片
"""
class Solution:
"""
@param nums: An array of integers
@return: nothing
"""
def nextPermutation(self, nums):
# write your code here
if nums is None or len(nums) == 0:
return []
n = len(nums) - 1
# 找到第一个上升点
while n > 0 and nums[n] <= nums[n - 1]:
n -= 1
# 如果n为0 则已经为降序了,下一个就是升序
if n == 0:
nums[:] = nums[:: -1]
return
# 然后找到第一个比 nums[n-1]大的数
for i in range(len(nums) - 1, n - 1, -1):
if nums[i] > nums[n -1]:
nums[n - 1], nums[i] = nums[i], nums[n - 1]
break
nums[n:] = nums[n:][::-1] |
#!C:\Python27\python.exe
# EASY-INSTALL-SCRIPT: 'docutils==0.12','rst2odt_prepstyles.py'
__requires__ = 'docutils==0.12'
__import__('pkg_resources').run_script('docutils==0.12', 'rst2odt_prepstyles.py')
|
"""
FIT1008 Prac 6 Task 1
Loh Hao Bin 25461257, Tan Wen Jie 25839063
@purpose: Knight in Chess
File: The columns
Rank: The rows
@created 20140831
@modified 20140903
"""
class Tour:
def __init__(self,y,x):
self.board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
]
self.knight_history = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
]
self.current_pos = [y,x]
self.knight_history[y][x] = 1
self.board[y][x] = 1
def display(self,n):
"""
@purpose To display the current chess board state
@complexity:
Best & Worst Case: O(n^2) where n is the dimension of the board
@parameter none
@precondition The Tour class has been initialised
@postcondition prints out the current board state
"""
print('')
for i in range(n):
for j in range(n):
if (self.board[i][j] == 1) and (self.knight_history[i][j] == 1):
print("K", end=" ")
elif self.knight_history[i][j] == 1 and (self.board[i][j] == 0):
print("*", end=" ")
else:
print("0", end=" ")
print('')
def move(self,x,y):
"""
@purpose To display the current chess board state
@complexity: O(1)
@parameter
x: the File to move to
y: the Rank to move to
@precondition The Tour class has been initialised, and a valid x/y value passed
@postcondition current_pos is modified to new Knight position, and Knight's move history
is left in knight_history, and the current board is printed out
"""
if (x >= 0 and x <= 7) and (y >= 0 and y <= 7):
#remember current Knight position
old_x = self.current_pos[1]
old_y = self.current_pos[0]
self.board[old_y][old_x] = 0
#set new Knight Position
self.current_pos = [y,x]
self.board[y][x] = 1
self.knight_history[y][x] = 1
else:
#throw a ValueError to ask for valid x/y
raise ValueError
#FUNCTIONS
def menu():
"""
@purpose To display the menu
@complexity: O(1)
@parameter None
@precondition None
@postcondition displays the menu and allows for user input
"""
try:
print("\n1. Position")
print("2. Quit")
ans = int(input("Command: "))
if ans == 1:
try:
posX = int(input("X (File): "))
posY = int(input("Y (Rank): "))
board.move(posX,posY)
except ValueError:
print("Please input a valid File and Rank.")
elif ans == 2:
#if Quit
print("User stopped the program.")
global quit
quit = True
else:
#throw error to ask for valid command
raise ValueError
except ValueError:
print("Please input a valid command.")
if __name__ == "__main__":
try:
quit = False #set flag
board = Tour(0,1) #initialise class Tour
print("Welcome to Knight Tour. " +
"\nPosition: [Rank y, File x]")
while not quit:
print("-"*30)
board.display(8)
menu()
except KeyboardInterrupt:
print("\nUser stopped the program.")
|
"""
union operation
"""
def union(set1: list, set2: list) -> list:
result = []
for s1 in set1:
for s2 in set2:
if s1 == s2:
result.append(s1)
return result
if __name__ == "__main__":
cases = [
{"s1": [1, 2, 3], "s2": [3, 4, 5], "ans": [3]},
{"s1": [1], "s2": [3], "ans": []},
{"s1": [], "s2": [], "ans": []},
]
for case in cases:
print(case)
assert union(case["s1"], case["s2"]) == case["ans"]
|
"""Module focussing on the `format` command.
Contains the task and helpers to format the codebase given a specific formatter.
"""
# import pathlib
#
#
# def bob_format(options, cwd):
# folders = ['src', 'include']
# filetypes = ['*.c', '*.h', '*.cpp', '*.hpp']
#
# files = []
# for f in folders:
# base = cwd / f
# for type in filetypes:
# files += base.rglob(type)
#
# steps = []
# for file in files:
# steps.append(container_command(BuildTarget.Linux, cwd) + [
# "clang-format",
# "-style=file",
# "-i",
# "-fallback-style=none",
# str(pathlib.PurePosixPath(file.relative_to(cwd)))
# ])
# return steps
|
template = """
module rom32x4 (
input [4:0] addr,
input clk,
output [4:0] data);
wire [7:0] rdata;
wire [15:0] RDATA;
wire RCLK;
wire [10:0] RADDR;
SB_RAM40_4KNR #( // negative edge readclock so we can apply and addres on the positive edge and guarantee data is available on the next posedge
.WRITE_MODE(1),
.READ_MODE(1),
.INIT_0(256'h{init[0][0]:04x}{init[0][1]:04x}{init[0][2]:04x}{init[0][3]:04x}{init[0][4]:04x}{init[0][5]:04x}{init[0][6]:04x}{init[0][7]:04x}{init[0][8]:04x}{init[0][9]:04x}{init[0][10]:04x}{init[0][11]:04x}{init[0][12]:04x}{init[0][13]:04x}{init[0][14]:04x}{init[0][15]:04x}),
.INIT_1(256'h{init[1][0]:04x}{init[1][1]:04x}{init[1][2]:04x}{init[1][3]:04x}{init[1][4]:04x}{init[1][5]:04x}{init[1][6]:04x}{init[1][7]:04x}{init[1][8]:04x}{init[1][9]:04x}{init[1][10]:04x}{init[1][11]:04x}{init[1][12]:04x}{init[1][13]:04x}{init[1][14]:04x}{init[1][15]:04x}),
.INIT_2(256'h{init[2][0]:04x}{init[2][1]:04x}{init[2][2]:04x}{init[2][3]:04x}{init[2][4]:04x}{init[2][5]:04x}{init[2][6]:04x}{init[2][7]:04x}{init[2][8]:04x}{init[2][9]:04x}{init[2][10]:04x}{init[2][11]:04x}{init[2][12]:04x}{init[2][13]:04x}{init[2][14]:04x}{init[2][15]:04x}),
.INIT_3(256'h{init[3][0]:04x}{init[3][1]:04x}{init[3][2]:04x}{init[3][3]:04x}{init[3][4]:04x}{init[3][5]:04x}{init[3][6]:04x}{init[3][7]:04x}{init[3][8]:04x}{init[3][9]:04x}{init[3][10]:04x}{init[3][11]:04x}{init[3][12]:04x}{init[3][13]:04x}{init[3][14]:04x}{init[3][15]:04x}),
.INIT_4(256'h{init[4][0]:04x}{init[4][1]:04x}{init[4][2]:04x}{init[4][3]:04x}{init[4][4]:04x}{init[4][5]:04x}{init[4][6]:04x}{init[4][7]:04x}{init[4][8]:04x}{init[4][9]:04x}{init[4][10]:04x}{init[4][11]:04x}{init[4][12]:04x}{init[4][13]:04x}{init[4][14]:04x}{init[4][15]:04x}),
.INIT_5(256'h{init[5][0]:04x}{init[5][1]:04x}{init[5][2]:04x}{init[5][3]:04x}{init[5][4]:04x}{init[5][5]:04x}{init[5][6]:04x}{init[5][7]:04x}{init[5][8]:04x}{init[5][9]:04x}{init[5][10]:04x}{init[5][11]:04x}{init[5][12]:04x}{init[5][13]:04x}{init[5][14]:04x}{init[5][15]:04x}),
.INIT_6(256'h{init[6][0]:04x}{init[6][1]:04x}{init[6][2]:04x}{init[6][3]:04x}{init[6][4]:04x}{init[6][5]:04x}{init[6][6]:04x}{init[6][7]:04x}{init[6][8]:04x}{init[6][9]:04x}{init[6][10]:04x}{init[6][11]:04x}{init[6][12]:04x}{init[6][13]:04x}{init[6][14]:04x}{init[6][15]:04x}),
.INIT_7(256'h{init[7][0]:04x}{init[7][1]:04x}{init[7][2]:04x}{init[7][3]:04x}{init[7][4]:04x}{init[7][5]:04x}{init[7][6]:04x}{init[7][7]:04x}{init[7][8]:04x}{init[7][9]:04x}{init[7][10]:04x}{init[7][11]:04x}{init[7][12]:04x}{init[7][13]:04x}{init[7][14]:04x}{init[7][15]:04x}),
.INIT_8(256'h{init[8][0]:04x}{init[8][1]:04x}{init[8][2]:04x}{init[8][3]:04x}{init[8][4]:04x}{init[8][5]:04x}{init[8][6]:04x}{init[8][7]:04x}{init[8][8]:04x}{init[8][9]:04x}{init[8][10]:04x}{init[8][11]:04x}{init[8][12]:04x}{init[8][13]:04x}{init[8][14]:04x}{init[8][15]:04x}),
.INIT_9(256'h{init[9][0]:04x}{init[9][1]:04x}{init[9][2]:04x}{init[9][3]:04x}{init[9][4]:04x}{init[9][5]:04x}{init[9][6]:04x}{init[9][7]:04x}{init[9][8]:04x}{init[9][9]:04x}{init[9][10]:04x}{init[9][11]:04x}{init[9][12]:04x}{init[9][13]:04x}{init[9][14]:04x}{init[9][15]:04x}),
.INIT_A(256'h{init[10][0]:04x}{init[10][1]:04x}{init[10][2]:04x}{init[10][3]:04x}{init[10][4]:04x}{init[10][5]:04x}{init[10][6]:04x}{init[10][7]:04x}{init[10][8]:04x}{init[10][9]:04x}{init[10][10]:04x}{init[10][11]:04x}{init[10][12]:04x}{init[10][13]:04x}{init[10][14]:04x}{init[10][15]:04x}),
.INIT_B(256'h{init[11][0]:04x}{init[11][1]:04x}{init[11][2]:04x}{init[11][3]:04x}{init[11][4]:04x}{init[11][5]:04x}{init[11][6]:04x}{init[11][7]:04x}{init[11][8]:04x}{init[11][9]:04x}{init[11][10]:04x}{init[11][11]:04x}{init[11][12]:04x}{init[11][13]:04x}{init[11][14]:04x}{init[11][15]:04x}),
.INIT_C(256'h{init[12][0]:04x}{init[12][1]:04x}{init[12][2]:04x}{init[12][3]:04x}{init[12][4]:04x}{init[12][5]:04x}{init[12][6]:04x}{init[12][7]:04x}{init[12][8]:04x}{init[12][9]:04x}{init[12][10]:04x}{init[12][11]:04x}{init[12][12]:04x}{init[12][13]:04x}{init[12][14]:04x}{init[12][15]:04x}),
.INIT_D(256'h{init[13][0]:04x}{init[13][1]:04x}{init[13][2]:04x}{init[13][3]:04x}{init[13][4]:04x}{init[13][5]:04x}{init[13][6]:04x}{init[13][7]:04x}{init[13][8]:04x}{init[13][9]:04x}{init[13][10]:04x}{init[13][11]:04x}{init[13][12]:04x}{init[13][13]:04x}{init[13][14]:04x}{init[13][15]:04x}),
.INIT_E(256'h{init[14][0]:04x}{init[14][1]:04x}{init[14][2]:04x}{init[14][3]:04x}{init[14][4]:04x}{init[14][5]:04x}{init[14][6]:04x}{init[14][7]:04x}{init[14][8]:04x}{init[14][9]:04x}{init[14][10]:04x}{init[14][11]:04x}{init[14][12]:04x}{init[14][13]:04x}{init[14][14]:04x}{init[14][15]:04x}),
.INIT_F(256'h{init[15][0]:04x}{init[15][1]:04x}{init[15][2]:04x}{init[15][3]:04x}{init[15][4]:04x}{init[15][5]:04x}{init[15][6]:04x}{init[15][7]:04x}{init[15][8]:04x}{init[15][9]:04x}{init[15][10]:04x}{init[15][11]:04x}{init[15][12]:04x}{init[15][13]:04x}{init[15][14]:04x}{init[15][15]:04x})
) rom(
.RDATA(RDATA),
.RCLKN(RCLK), // negative edge readclock has an N appended
.RCLKE(1),
.RE(1),
.RADDR(RADDR),
.WCLK(0),
.WCLKE(0),
.WE(0),
.WADDR(11'hxxxx),
.MASK(16'hxxxx),
.WDATA(8'hxx)
);
assign rdata = {{RDATA[14],RDATA[12],RDATA[10],RDATA[8],RDATA[6],RDATA[4],RDATA[2],RDATA[0]}};
assign data = rdata[4:0];
assign RADDR = {{6'b0, addr}};
assign RCLK = clk;
endmodule
"""
# https://github.com/jamesbowman/swapforth/blob/master/j1a/mkrom.py
# https://stackoverflow.com/questions/41499494/how-can-i-use-ice40-4k-block-ram-in-512x8-read-mode-with-icestorm
def fanbits(byt):
f = 0
for i in range(8):
if byt & (1 << i):
f += 1 << i*2+1
return f
def genrom(data):
init = a=[[0] * 16 for i in range(16)]
for i,d in enumerate(data):
row = (i % 256) // 16
col = 15 - i % 16
bits= fanbits(d)
bits= (bits >> 1) if i < 256 else bits
init[row][col] |= bits
return template.format(init = init)
START = 0; # next is START unless overruled
FETCH = 1; # next state is always WAIT
DECODE = 2; # next is FETCH unless overruled
OPLOAD = 3; # next state is always DECODE
ECHO = 4; # next state is always ECHO1
ECHO1 = 5; # next is ECHO1 unless overruled
WAIT = 6; # next state is always OPLOAD
WAIT2 = 7; # next state is always OPLOAD2
OPLOAD2 = 8; # next state is always DECODE2
DECODE2 = 9; # next is FETCH unless overruled
WAIT3 = 10; # next state is always MEMLOAD
MEMLOAD = 11; # next state is always FETCH
READ = 12; # next is READ unless overruled
STACKPUSH = 13; # next state is always STACKPUSH2
STACKPUSH2= 14; # next state is always FETCH
CALL1 = 15; # next state is always CALL2
CALL2 = 16; # next state is always CALL3
CALL3 = 17; # next state is always CALL4
CALL4 = 18; # next state is always CALL5
CALL5 = 19; # next state is always FETCH
RETURN1 = 20; # next state is always RETURN2
RETURN2 = 21; # next state is always RETURN3
RETURN3 = 22; # next state is always RETURN4
RETURN4 = 23; # next state is always RETURN5
RETURN5 = 24; # next state is always FETCH
STIDPWAIT = 25; # next state is always STIDPWAIT1
WAITBASER = 26; # next state is always WAITBASER1
WAITBASER1= 27; # next state is always FETCH
STIDPWAIT1= 31; # next state is always FETCH
data = {
START :START,
FETCH :WAIT,
DECODE :FETCH,
OPLOAD :DECODE,
ECHO :ECHO1,
ECHO1 :ECHO1,
WAIT :OPLOAD,
WAIT2 :OPLOAD2,
OPLOAD2 :DECODE2,
DECODE2 :FETCH,
WAIT3 :MEMLOAD,
MEMLOAD :FETCH,
READ :READ,
STACKPUSH :STACKPUSH2,
STACKPUSH2:FETCH,
CALL1 :CALL2,
CALL2 :CALL3,
CALL3 :CALL4,
CALL4 :CALL5,
CALL5 :FETCH,
RETURN1 :RETURN2,
RETURN2 :RETURN3,
RETURN3 :RETURN4,
RETURN4 :RETURN5,
RETURN5 :FETCH,
STIDPWAIT :STIDPWAIT1,
WAITBASER :WAITBASER1,
WAITBASER1:FETCH,
STIDPWAIT1:FETCH,
}
data = [data[k] for k in sorted(data)]
nbytes = len(data)
data = data + [0] * (512 - nbytes)
print(genrom(data))
|
#!/usr/bin/env python3
def raw_limit_ranges(callback_values):
data = {
'__meta': {
'chart': 'cisco-sso/raw',
'version': '0.1.0'
},
'resources': [{
'apiVersion': 'v1',
'kind': 'LimitRange',
'metadata': {
'name': 'limits'
},
'spec': {
'limits': [{
'default': {
'cpu': '100m',
'memory': '256Mi'
},
'defaultRequest': {
'cpu': '100m',
'memory': '256Mi'
},
'type': 'Container'
}]
}
}]
}
callback_values.update(data)
return callback_values
|
#definir variables y otros
print("Ejemplo 01-Area de un triangulo")
#Datos de entrada - Ingresados mediante dispositivos de entrada
b=int(input("Ingrese Base:"))
h=int(input("Ingrese altura"))
#proceso de calculo de Area
area=(b*h)/2
#Datos de salida
print("El area del triangulo es:", area) |
def handle_request(response):
if response.error:
print("Error:", response.error)
else:
print('called')
print(response.body)
|
# CPP Program of Prim's algorithm for MST
inf = 65000
# To add an edge
def addEdge(adj, u, v, wt):
adj[u].append([v, wt])
adj[v].append([u, wt])
def primMST(adj, V):
# Create a priority queue to store vertices that
# are being preinMST.
pq = []
src = 0 # Taking vertex 0 as source
# Create a vector for keys and initialize all keys as infinite (INF)
key = [inf for i in range(V)]
# To store parent array which in turn store MST
parent = [-1 for i in range(V)]
# To keep track of vertices included in MST
inMST = [False for i in range(V)]
# Insert source itself in priority queue and initialize its key as 0.
pq.append([0, src])
key[src] = 0
# Looping till priority queue becomes empty
while len(pq) != 0:
# The first vertex in pair is the minimum key
# vertex, extract it from priority queue.
# vertex label is stored in second of pair (it
# has to be done this way to keep the vertices
# sorted key (key must be first item
# in pair)
u = pq[0][1]
del pq[0]
# Different key values for same vertex may exist in the priority queue.
# The one with the least key value is always processed first.
# Therefore, ignore the rest.
if inMST[u] == True:
continue
inMST[u] = True # Include vertex in MST
# Traverse all adjacent of u
for x in adj[u]:
# Get vertex label and weight of current adjacent of u.
v = x[0]
weight = x[1]
# If v is not in MST and weight of (u,v) is smaller
# than current key of v
if inMST[v] == False and key[v] > weight:
# Updating key of v
key[v] = weight
pq.append([key[v], v])
pq.sort()
parent[v] = u
for i in range(1, V):
print(parent[i], "-", i)
# Driver code
V = 9
adj = [[] for i in range(V)]
addEdge(adj, 0, 1, 4)
addEdge(adj, 0, 7, 8)
addEdge(adj, 1, 2, 8)
addEdge(adj, 1, 7, 11)
addEdge(adj, 2, 3, 7)
addEdge(adj, 2, 8, 2)
addEdge(adj, 2, 5, 4)
addEdge(adj, 3, 4, 9)
addEdge(adj, 3, 5, 14)
addEdge(adj, 4, 5, 10)
addEdge(adj, 5, 6, 2)
addEdge(adj, 6, 7, 1)
addEdge(adj, 6, 8, 6)
addEdge(adj, 7, 8, 7)
print("Edges of MST are")
primMST(adj, V)
# Output:
# Edges of MST are
# 0 - 1
# 1 - 2
# 2 - 3
# 3 - 4
# 2 - 5
# 5 - 6
# 6 - 7
# 2 - 8
|
n,m,k = map(int,input().split())
d = list(map(int,input().split()))
m = list(map(int,input().split()))
ans = []
check = 10**18
for i in range(len(d)):
frog=d[i]
c=0
for j in range(len(m)):
if m[j]%frog==0:
c+=1
if c<check:
ans.clear()
ans.append(i+1)
check=c
elif c==check:
ans.append(i+1)
c=check
print(len(ans))
print(*ans) |
'''
位1的个数
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。
'''
'''
思路:输入的整数右移32位,统计其1的个数。可以用n&(n-1)的技巧,更快的统计。
'''
class Solution:
def hammingWeight(self, n: int) -> int:
cnt = 0
while n > 0:
n &= (n - 1)
cnt += 1
return cnt
s = Solution()
print(s.hammingWeight(3))
print(s.hammingWeight(1))
print(s.hammingWeight(0))
print(s.hammingWeight(7))
print(s.hammingWeight(-1))
|
# Variables
age = 20 # declaring int variable
temperature = 89.8 # declaring float variable
name = 'John' # declaring str variable, Note: we use single quotes to store the text.
model = "SD902" # declaring str variable
print(model)
model = 8890 # now re-declaring model variable as int
# In Python this is allowed, anywhere you can change the type of variable
# just be re declaring with new value of any type.
print(model)
# Another way of declaring variables
# also the variable names are case sensitive
msg = str("Big Brother is in town")
Msg = str("Case sensitive variable")
print(f"msg = {msg}")
print(f"Msg = {Msg}")
|
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014
@author: Marat Khayrullin <xmm.dev@gmail.com>
'''
API_VERSION_V0 = 0
API_VERSION = API_VERSION_V0
bp_name = 'api_v0'
api_v0_prefix = '{prefix}/v{version}'.format(
prefix='/api', # current_app.config['URL_PREFIX'],
version=API_VERSION_V0
)
|
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
def float_dec2bin(n):
neg = False
if n < 0:
n = -n
neg = True
hx = float(n).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])
return (('1' if neg else '0') + bn.strip('0') + hx[p:p+2]
+ bin(int(hx[p+2:]))[2:])
|
# basicpackage/foo.py
a = 10
class Foo(object):
pass
print("inside 'basicpackage/foo.py' with a variable in it")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定制类
__call__
"""
class Student(object):
def __init__(self, name):
self._name = name
def __call__(self):
print('My name is %s.' % self._name)
s = Student('Walker')
s() |
print('{:=^90}'.format(' Desafio 008 '))
print('{:=^90}'.format(' Escrevendo um valor em metros e convertendo em centímetros e milímetros '))
print('='*90)
n = float(input('Metros: '))
print('{} metro(s): \n{}km \n{}hm \n{}dam \n{:.0f}dm \n{:.0f}cm \n{:.0f}mm '.format(n, n/1000, n/100, n/10, n*10, n*100, n*1000))
#km. hm. dam. m. dm. cm. mm.
|
famous_people = []
with open("/Users/coco/Documents/GitHub/python-side-projects/wikipedia-crawler/year1902-2020.txt",'r') as foo:
for line in foo.readlines():
if '``' in line:
famous_people.append(line)
with open("famous_people.txt", "a") as f:
for person in famous_people:
f.write(person) |
class no_deps(object):
pass
class one_dep(object):
def __init__(self, dependency):
self.dependency = dependency
class two_deps(object):
def __init__(self, first_dep, second_dep):
self.first_dep = first_dep
self.second_dep = second_dep
|
#
# PySNMP MIB module HP-ICF-ARP-PROTECT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-ARP-PROTECT
# Produced by pysmi-0.3.4 at Mon Apr 29 19:20:43 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)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
hpSwitch, = mibBuilder.importSymbols("HP-ICF-OID", "hpSwitch")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
VlanIndex, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanIndex")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
NotificationType, Integer32, ModuleIdentity, MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Counter64, Gauge32, IpAddress, Bits, Counter32, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Integer32", "ModuleIdentity", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Counter64", "Gauge32", "IpAddress", "Bits", "Counter32", "iso", "TimeTicks")
DisplayString, TextualConvention, MacAddress, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "MacAddress", "TruthValue")
hpicfArpProtect = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37))
hpicfArpProtect.setRevisions(('2007-08-29 00:00', '2006-05-03 00:27',))
if mibBuilder.loadTexts: hpicfArpProtect.setLastUpdated('200708290000Z')
if mibBuilder.loadTexts: hpicfArpProtect.setOrganization('HP Networking')
hpicfArpProtectNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 0))
hpicfArpProtectErrantReply = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 0, 1)).setObjects(("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantCnt"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcMac"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcIpType"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcIp"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestMac"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestIpType"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestIp"))
if mibBuilder.loadTexts: hpicfArpProtectErrantReply.setStatus('current')
hpicfArpProtectObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1))
hpicfArpProtectConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1))
hpicfArpProtectGlobalCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 1))
hpicfArpProtectEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 1, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfArpProtectEnable.setStatus('current')
hpicfArpProtectVlanEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(512, 512)).setFixedLength(512)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfArpProtectVlanEnable.setStatus('current')
hpicfArpProtectValidation = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 1, 3), Bits().clone(namedValues=NamedValues(("srcMac", 0), ("dstMac", 1), ("ip", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfArpProtectValidation.setStatus('current')
hpicfArpProtectErrantNotifyEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfArpProtectErrantNotifyEnable.setStatus('current')
hpicfArpProtectPortTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 2), )
if mibBuilder.loadTexts: hpicfArpProtectPortTable.setStatus('current')
hpicfArpProtectPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hpicfArpProtectPortEntry.setStatus('current')
hpicfArpProtectPortTrust = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 1, 2, 1, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfArpProtectPortTrust.setStatus('current')
hpicfArpProtectStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2))
hpicfArpProtectVlanStatTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1), )
if mibBuilder.loadTexts: hpicfArpProtectVlanStatTable.setStatus('current')
hpicfArpProtectVlanStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1), ).setIndexNames((0, "HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatIndex"))
if mibBuilder.loadTexts: hpicfArpProtectVlanStatEntry.setStatus('current')
hpicfArpProtectVlanStatIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 1), VlanIndex())
if mibBuilder.loadTexts: hpicfArpProtectVlanStatIndex.setStatus('current')
hpicfArpProtectVlanStatForwards = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatForwards.setStatus('current')
hpicfArpProtectVlanStatBadPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatBadPkts.setStatus('current')
hpicfArpProtectVlanStatBadBindings = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatBadBindings.setStatus('current')
hpicfArpProtectVlanStatBadSrcMacs = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatBadSrcMacs.setStatus('current')
hpicfArpProtectVlanStatBadDstMacs = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatBadDstMacs.setStatus('current')
hpicfArpProtectVlanStatBadIpAddrs = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 2, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfArpProtectVlanStatBadIpAddrs.setStatus('current')
hpicfArpProtectErrantCnt = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 3), Counter32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantCnt.setStatus('current')
hpicfArpProtectErrantSrcMac = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 4), MacAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantSrcMac.setStatus('current')
hpicfArpProtectErrantSrcIpType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 5), InetAddressType()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantSrcIpType.setStatus('current')
hpicfArpProtectErrantSrcIp = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 6), InetAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantSrcIp.setStatus('current')
hpicfArpProtectErrantDestMac = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 7), MacAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantDestMac.setStatus('current')
hpicfArpProtectErrantDestIpType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 8), InetAddressType()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantDestIpType.setStatus('current')
hpicfArpProtectErrantDestIp = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 1, 9), InetAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hpicfArpProtectErrantDestIp.setStatus('current')
hpicfArpProtectConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2))
hpicfArpProtectGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2, 1))
hpicfArpProtectBaseGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2, 1, 1)).setObjects(("HP-ICF-ARP-PROTECT", "hpicfArpProtectEnable"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanEnable"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectValidation"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectPortTrust"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatForwards"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatBadPkts"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatBadBindings"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatBadSrcMacs"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatBadDstMacs"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectVlanStatBadIpAddrs"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcMac"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcIp"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestMac"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantSrcIpType"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestIpType"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantDestIp"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantCnt"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantNotifyEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfArpProtectBaseGroup = hpicfArpProtectBaseGroup.setStatus('current')
hpicfArpProtectionNotifications = NotificationGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2, 1, 2)).setObjects(("HP-ICF-ARP-PROTECT", "hpicfArpProtectErrantReply"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfArpProtectionNotifications = hpicfArpProtectionNotifications.setStatus('current')
hpicfArpProtectCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2, 2))
hpicfArpProtectCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 37, 2, 2, 1)).setObjects(("HP-ICF-ARP-PROTECT", "hpicfArpProtectBaseGroup"), ("HP-ICF-ARP-PROTECT", "hpicfArpProtectionNotifications"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfArpProtectCompliance = hpicfArpProtectCompliance.setStatus('current')
mibBuilder.exportSymbols("HP-ICF-ARP-PROTECT", hpicfArpProtectVlanStatBadDstMacs=hpicfArpProtectVlanStatBadDstMacs, hpicfArpProtectErrantSrcMac=hpicfArpProtectErrantSrcMac, hpicfArpProtectErrantDestIp=hpicfArpProtectErrantDestIp, hpicfArpProtectStatus=hpicfArpProtectStatus, hpicfArpProtectVlanStatBadSrcMacs=hpicfArpProtectVlanStatBadSrcMacs, hpicfArpProtectNotifications=hpicfArpProtectNotifications, hpicfArpProtectionNotifications=hpicfArpProtectionNotifications, hpicfArpProtectGroups=hpicfArpProtectGroups, hpicfArpProtectVlanStatIndex=hpicfArpProtectVlanStatIndex, hpicfArpProtectVlanStatBadBindings=hpicfArpProtectVlanStatBadBindings, hpicfArpProtectEnable=hpicfArpProtectEnable, PYSNMP_MODULE_ID=hpicfArpProtect, hpicfArpProtectValidation=hpicfArpProtectValidation, hpicfArpProtectVlanStatForwards=hpicfArpProtectVlanStatForwards, hpicfArpProtectErrantSrcIpType=hpicfArpProtectErrantSrcIpType, hpicfArpProtectErrantNotifyEnable=hpicfArpProtectErrantNotifyEnable, hpicfArpProtectCompliances=hpicfArpProtectCompliances, hpicfArpProtectBaseGroup=hpicfArpProtectBaseGroup, hpicfArpProtectErrantReply=hpicfArpProtectErrantReply, hpicfArpProtectConfig=hpicfArpProtectConfig, hpicfArpProtectVlanStatBadPkts=hpicfArpProtectVlanStatBadPkts, hpicfArpProtectErrantCnt=hpicfArpProtectErrantCnt, hpicfArpProtectGlobalCfg=hpicfArpProtectGlobalCfg, hpicfArpProtectVlanStatEntry=hpicfArpProtectVlanStatEntry, hpicfArpProtectObjects=hpicfArpProtectObjects, hpicfArpProtectErrantDestIpType=hpicfArpProtectErrantDestIpType, hpicfArpProtectErrantSrcIp=hpicfArpProtectErrantSrcIp, hpicfArpProtectVlanStatBadIpAddrs=hpicfArpProtectVlanStatBadIpAddrs, hpicfArpProtectCompliance=hpicfArpProtectCompliance, hpicfArpProtectConformance=hpicfArpProtectConformance, hpicfArpProtectPortTable=hpicfArpProtectPortTable, hpicfArpProtectVlanEnable=hpicfArpProtectVlanEnable, hpicfArpProtectPortTrust=hpicfArpProtectPortTrust, hpicfArpProtectVlanStatTable=hpicfArpProtectVlanStatTable, hpicfArpProtectErrantDestMac=hpicfArpProtectErrantDestMac, hpicfArpProtect=hpicfArpProtect, hpicfArpProtectPortEntry=hpicfArpProtectPortEntry)
|
pkgname = "libuninameslist"
pkgver = "20211114"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf", "automake", "libtool"]
pkgdesc = "Library of Unicode names and annotation data"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-3-Clause"
url = "https://github.com/fontforge/libuninameslist"
source = f"{url}/archive/{pkgver}.tar.gz"
sha256 = "c089c6164f2cef361c3419a07408be72d6b58d6ef224ec226724a9fa93c0d46e"
def pre_configure(self):
self.do("autoreconf", "-if")
def post_install(self):
self.install_license("LICENSE")
@subpackage("libuninameslist-devel")
def _devel(self):
return self.default_devel()
|
POSTGRESQL = 'PostgreSQL'
MYSQL = 'MySQL'
DEV = 'Development'
STAGE = 'Staging'
TEST = 'Testing'
PROD = 'Production' |
# 10001st prime
# The nth prime number
def isPrime(n):
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
def nthPrime(n):
num = 2
nums = []
while len(nums) < n:
if isPrime(num) == True:
nums.append(num)
num += 1
return nums[-1]
|
class IntervalNum:
def __init__(self,a,b):
if a > b:
a,b = b,a
self.a = a
self.b = b
def __str__(self):
return f"[{self.a};{self.b}]"
def __add__(self,other):
return IntervalNum(self.a+other.a, self.b+other.b)
def __sub__(self,other):
return IntervalNum(self.a-other.b, self.b-other.a)
def __mul__(self,other):
sa, sb = self.a, self.b
oa, ob = other.a, other.b
a = min([sa*oa,sa*ob,sb*oa,sb*ob])
b = max([sa*oa,sa*ob,sb*oa,sb*ob])
return IntervalNum(a,b)
if __name__ == '__main__':
x = IntervalNum(-2,3)
print(f"x = {x}")
print(f"x+x = {x+x}")
print(f"x-x = {x-x}")
print(f"x*x = {x*x}") |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'cv.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'maintenance.middleware.MaintenanceMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'maintenance.tests.test_urls'
SITE_ID = 1
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.flatpages',
'maintenance',
)
|
vehicles = {
'dream': 'Honda 250T',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia 1.4',
'roadster': 'Triumph Street Triple'
}
vehicles["starfighter"] = "Lockhead F-104"
vehicles ["learjet"] = "Bombardier Learjet 75"
vehicles["toy"] = "Glider"
# upgrade Virago
vehicles["virago"] = "Yamaha XV535"
del vehicles['starfighter']
result = vehicles.pop('f1', "You wish! Sell the Learjet and you might afford a racing car.")
print(result)
plane = vehicles.pop('learjet')
print(plane)
bike = vehicles.pop("tenere", "not present")
print(bike)
print()
# for key in vehicles:
# print(key, vehicles[key], sep=", ")
for key, value in vehicles.items():
print(key, value, sep=", ")
|
class DpiChangedEventArgs(RoutedEventArgs):
# no doc
NewDpi=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: NewDpi(self: DpiChangedEventArgs) -> DpiScale
"""
OldDpi=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: OldDpi(self: DpiChangedEventArgs) -> DpiScale
"""
|
#!/usr/bin/env python
def start():
print("Hello, world.")
if __name__ == '__main__':
start()
|
numbers = [3, 6, 2, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max) |
class StateMachineException(Exception):
def __init__(self, message_format, **kwargs):
if kwargs:
self.message = message_format.format(**kwargs)
else:
self.message = message_format
self.__dict__.update(**kwargs)
def __str__(self):
return self.message
class IncorrectInitialState(StateMachineException):
pass
class StateChangedElsewhere(StateMachineException):
pass
class MultipleMachineAncestors(StateMachineException):
pass
class IncorrectSummary(StateMachineException):
pass
class InheritedFromState(StateMachineException):
pass
class CannotInferOutputState(StateMachineException):
pass
class DuplicateStateNames(StateMachineException):
pass
class DuplicateOutputStates(StateMachineException):
pass
class UnknownOutputState(StateMachineException):
pass
class ReturnedInvalidState(StateMachineException):
pass
class GetStateDidNotReturnState(StateMachineException):
pass
class DjangoStateAttrNameWarning(Warning):
pass
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class DataSet:
def __init__(self,
src_channels_url: str,
injection_file_name: str,
out_file_name: str,
out_file_encoding: str,
out_file_first_line: str,
out_file_format: str,
filter_file_name: str,
clean_filter: bool) -> None:
self._src_channels_url: str = src_channels_url
self._injection_file_name: str = injection_file_name
self._out_file_name: str = out_file_name
self._out_file_encoding: str = out_file_encoding
self._out_file_first_line: str = out_file_first_line
self._out_file_format: str = out_file_format
self._filter_file_name: str = filter_file_name
self._clean_filter: bool = clean_filter
@property
def src_channels_url(self) -> str:
return self._src_channels_url
@property
def injection_file_name(self) -> str:
return self._injection_file_name
@property
def out_file_name(self) -> str:
return self._out_file_name
@property
def out_file_encoding(self) -> str:
return self._out_file_encoding
@property
def out_file_first_line(self) -> str:
return self._out_file_first_line
@property
def out_file_format(self) -> str:
return self._out_file_format
@property
def filter_file_name(self) -> str:
return self._filter_file_name
@property
def clean_filter(self) -> bool:
return self._clean_filter
|
sys_word = {}
for x in range(0,325):
sys_word[x] = 0
file = open("UAD-0015.txt", "r+")
words = file.read().split()
file.close()
for word in words:
sys_word[int(word)] += 1
for x in range(0,325):
sys_word[x] = sys_word[x]/int(325)
file_ = open("a_1.txt", "w")
for x in range(0,325):
if x is 324:
file_.write(str(sys_word[x]) + "\n")
else:
file_.write(str(sys_word[x]) + ",")
file_.close()
print(sys_word)
|
#Soumya Pal
#Assignment 2 part 4
info = {
"name": "Shomo Pal",
"favorite_color": "Blue",
"favorite_number": 10,
"favorite_movies": ["Inception","The Shashank Redemption","One Piece (Anime not movie)"],
"favorite_songs" : [{'artist': 'Metallica', 'title': 'Nothing Else Matters'},
{'artist': 'Nirvana', 'title': 'Come as you are'}]
}
print(info["name"])
print(info["favorite_color"])
print(info["favorite_number"])
print("Movies:")
for movie_title in info["favorite_movies"]:
print("\t"+ movie_title)
print("Songs:")
for song_info in info["favorite_songs"]:
print(f"\t{song_info['artist']}: {song_info['title']}") |
print('='*18,'lojinha do zé','='*18)
P = float(input('qualo valor da compra R$'))
print('='*49)
print('[1] para pagar a vista/cheque')
print('[2] para pagar a vista no cartão')
print('[3] para pagar em ate 2x no cartão')
print('[4] para pagar parcelado em 3X ou mais no cartão')
e = int(input('digite sua escolha'))
print('='*49)
if e == 1:
d = (P*10)/100
p = P - d
print('pagamento realizado a vista no cheque no valor de R${:.2f} com 10% de desconto'.format(p))
elif e == 2:
d = (P * 5) / 100
p = P - d
print('pagamento realizado a vista no credito no valor de R${:.2f} com 5% de desconto'.format(p))
elif e == 3:
pa = P/2
print('pagamento realizado no credito parcelado em 2x de {:.2f} sem juros do valor total de R${:.2f}'.format(pa,P))
elif e == 4:
n = int(input('em quantas vezes quer parcelar >'))
f = (P*20)/100
pa = (P + f)/n
print('pagamento realizado no credito parcelado em {:.2f}x de R${:.2f} com juros de 20% do valor total de R${:.2f}'.format(n, pa, (P + f))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.