content stringlengths 7 1.05M |
|---|
def clear_screen():
Xs = [
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
3, 3, 3, 3, 3,
4, 4, 4, 4, 4
];
Ys = [
0, 1, 2, 3, 4,
0, 1, 2, 3, 4,
0, 1, 2, 3, 4,
0, 1, 2, 3, 4,
0, 1, 2, 3, 4
];
i = 0
while i < 25:
led.unplot(Xs[i], Ys[i])
i = i + 1
def on_forever():
if input.temperature() < 40:
clear_screen()
Xs = [ 0, 1, 2, 3, 4 ]
Ys = [ 3, 4, 3, 2, 1 ]
indice = 0
while indice < 5:
led.plot(Xs[indice], Ys[indice])
indice = indice + 1
elif input.temperature() > 40:
clear_screen()
Xs = [ 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4 ]
Ys = [ 0, 0, 0, 1, 1, 1, 2, 2, 2, 4, 4, 4 ]
indice = 0
while indice < 12:
led.plot(Xs[indice], Ys[indice])
indice = indice + 1
basic.forever(on_forever)
|
_MESH_ID_COUNTER = 0
def _get_mesh_id():
global _MESH_ID_COUNTER
_MESH_ID_COUNTER += 1
return _MESH_ID_COUNTER
class Mesh(object):
def __init__(self):
self.id = _get_mesh_id()
self.timestamp = 0
def has_submeshes(self):
return False
def submeshes(self):
return []
|
def draw_chessboard(n, s, upper_left = 'black'):
black_white = int(n/2) * (s * '1' + s * '0')
white_black = int(n/2) * (s * '0' + s * '1')
if upper_left == 'black':
first = black_white
second = white_black
else:
first = white_black
second = black_white
for n_row in range(int(n/2)):
for s_row in range(s):
print(first)
for s_row in range(s):
print(second)
# draw example
draw_chessboard(6, 3, upper_left = 'white') |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if not root.left and not root.right:
return True
if root.left and root.left.val >= root.val:
return False
if root.right and root.val >= root.right.val:
return False
if not self.isValidBST(root.left):
return False
if not self.isValidBST(root.right):
return False
return True
|
"""This problem was asked by Google.
An XOR linked list is a more memory efficient doubly linked list. Instead of each
node holding next and prev fields, it holds a field named both, which is an XOR of
the next node and the previous node. Implement an XOR linked list;
it has an add(element) which adds the element to the end, and a get(index) which
returns the node at index.
If using a language that has no pointers (such as Python), you can assume you have
access to get_pointer and dereference_pointer functions that converts between
nodes and memory addresses."""
# Creating a class for the main linked list
class XorLinked(object):
def __init__(self):
self.length = 0
self.head = None
def add(self, element):
if self.length == 0:
nod = Node(element,0)
self.head = element
def get_pointer(node):
return 15
def dereference_pointer(pointer):
return Node(12,2)
# class of structure of node.
class Node(object):
def __init__(self, value, xor):
self.value = value
self.xor_pointer = xor
|
def create_model_definition(clazz):
return ModelDefinition(clazz.swagger_types, clazz.attribute_map, clazz)
class ModelDefinition(object):
def __init__(self, swagger_types, attribute_map, model_clazz):
self.swagger_types = swagger_types
self.attribute_map = attribute_map
self.model_clazz = model_clazz
def create_model(self, **kwargs):
return self.model_clazz(**kwargs)
|
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n==0:return 0
nums=[0,1]
for i in range(2,n+1):
if i%2==0:
nums.append(nums[i//2])
else:
nums.append(nums[i//2]+nums[(i//2)+1])
return max(nums)
|
class TB3Importer:
def __init__(self,import_path):
self.path = import_path
def import_bank(self):
assert(False) |
# terrascript/resource/azurerm.py
__all__ = []
|
price = float(input("Please enter your total price = "))
member = input("Are you a member, please enter y or n = ")
if price >= 100:
price -= 50
elif price >= 50:
price -= 30
elif price >= 30:
price -= 10
else:
price = price
if member == "y":
price *= 0.8
print("Your final price=%.2f" % price)
|
"""
The `~certbot_dns_aliyun.dns_aliyun` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the Aliyun API.
Credentials
-----------
# Aliyun API credentials used by Certbot
certbot_dns_aliyun:dns_aliyun_api_key = xxxxxx
certbot_dns_aliyun:dns_aliyun_secret_key = xxxxxxx
"""
|
"""
Copyright (c) 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# global parameters
num_test_classes = 100
num_train_classes = 1000
subdir_name = 'msasl'
frames_type = 'global_crops'
root_dir = 'data'
mixup_images_file = 'imagenet_train_list.txt'
mixup_images_root = 'imagenet/train'
data_root_dir = '{}/{}'.format(root_dir, subdir_name)
work_dir = None
load_from = None
resume_from = None
# model settings
model_partial_init = False
model = dict(
type='ASLNet3D',
backbone=dict(
type='MobileNetV3_S3D',
num_input_layers=3,
mode='large',
pretrained=None,
pretrained2d=False,
width_mult=1.0,
pool1_stride_t=1,
# block ids: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
temporal_strides=(1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1),
temporal_kernels=(5, 3, 3, 3, 3, 5, 5, 3, 3, 5, 3, 3, 3, 3, 3),
use_st_att= (0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0),
use_temporal_avg_pool=True,
input_bn=False,
out_conv=True,
out_attention=False,
weight_norm='none',
dropout_cfg=dict(
p=0.1,
mu=0.1,
sigma=0.03,
dist='gaussian'
),
),
spatial_temporal_module=dict(
type='AggregatorSpatialTemporalModule',
modules=[
dict(type='AverageSpatialTemporalModule',
temporal_size=4,
spatial_size=7),
],
),
cls_head=dict(
type='ClsHead',
with_avg_pool=False,
temporal_size=1,
spatial_size=1,
dropout_ratio=None,
in_channels=960,
num_classes=num_train_classes,
embedding=True,
embd_size=256,
num_centers=1,
st_scale=10.0,
reg_weight=1.0,
reg_threshold=0.1,
angle_std=None,
class_counts=None,
main_loss_cfg=dict(
type='AMSoftmaxLoss',
scale_cfg=dict(
type='PolyScheduler',
start_scale=30.0,
end_scale=5.0,
power=1.2,
num_epochs=41.276,
),
pr_product=True,
margin_type='cos',
margin=0.35,
gamma=0.0,
t=1.0,
conf_penalty_weight=0.085,
filter_type='positives',
top_k=None,
),
extra_losses_cfg=dict(
loss_lpush=dict(
type='LocalPushLoss',
margin=0.1,
weight=1.0,
smart_margin=True,
),
),
),
masked_num=None,
grad_reg_weight=None,
bn_eval=False,
)
train_cfg = None
test_cfg = None
# dataset settings
train_dataset_type = 'StreamDataset'
test_dataset_type = 'StreamDataset'
images_dir = '{}/{}'.format(data_root_dir, frames_type)
img_norm_cfg = dict(
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
std=[0.229 * 255, 0.224 * 255, 0.225 * 255],
to_rgb=True)
data = dict(
videos_per_gpu=14,
workers_per_gpu=3,
num_test_classes=num_test_classes,
train=dict(
type=train_dataset_type,
ann_file='{}/train{}.txt'.format(data_root_dir, num_train_classes),
img_prefix=images_dir,
img_norm_cfg=img_norm_cfg,
out_length=16,
out_fps=15,
num_segments=1,
temporal_jitter=True,
modality='RGB',
image_tmpl='img_{:05d}.jpg',
img_scale=256,
input_size=(224, 224),
min_intersection=0.6,
div_255=False,
flip_ratio=0.5,
rotate_delta=10.0,
resize_keep_ratio=True,
random_crop=True,
scale_limits=[1.0, 0.875],
extra_augm=dict(
brightness_range=(65, 190),
contrast_range=(0.6, 1.4),
saturation_range=(0.7, 1.3),
hue_delta=18,
noise_sigma=None),
dropout_prob=0.1,
dropout_scale=0.2,
mixup_alpha=0.2,
mixup_images_file='{}/{}'.format(root_dir, mixup_images_file),
mixup_images_root='{}/{}'.format(root_dir, mixup_images_root),
test_mode=False),
val=dict(
type=test_dataset_type,
ann_file='{}/val{}.txt'.format(data_root_dir, num_test_classes),
img_prefix=images_dir,
img_norm_cfg=img_norm_cfg,
out_length=16,
out_fps=15,
num_segments=1,
temporal_jitter=False,
modality='RGB',
image_tmpl='img_{:05d}.jpg',
img_scale=256,
input_size=(224, 224),
div_255=False,
flip_ratio=None,
rotate_delta=None,
resize_keep_ratio=True,
random_crop=False,
test_mode=True),
test=dict(
type=test_dataset_type,
ann_file='{}/test{}.txt'.format(data_root_dir, num_test_classes),
img_prefix=images_dir,
img_norm_cfg=img_norm_cfg,
out_length=16,
out_fps=15,
num_segments=1,
temporal_jitter=False,
modality='RGB',
image_tmpl='img_{:05d}.jpg',
img_scale=256,
input_size=(224, 224),
div_255=False,
flip_ratio=None,
rotate_delta=None,
resize_keep_ratio=True,
random_crop=False,
test_mode=True)
)
# optimizer
optimizer = dict(type='SGD', lr=1e-2, momentum=0.9, weight_decay=1e-4)
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
cudnn_benchmark = True
# learning policy
lr_config = dict(
warmup='linear',
warmup_iters=5,
warmup_ratio=1e-2,
policy='step',
step=[25, 50],
)
checkpoint_config = dict(interval=1)
workflow = [('train', 1)]
# yapf:disable
log_config = dict(
interval=10,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
# runtime settings
total_epochs = 80
eval_epoch = 1
dist_params = dict(backend='nccl')
log_level = 'INFO'
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def maxSumTwoNoOverlap(self, A, L, M):
"""
:type A: List[int]
:type L: int
:type M: int
:rtype: int
"""
for i in range(1, len(A)):
A[i] += A[i-1]
result, L_max, M_max = A[L+M-1], A[L-1], A[M-1]
for i in range(L+M, len(A)):
L_max = max(L_max, A[i-M] - A[i-L-M])
M_max = max(M_max, A[i-L] - A[i-L-M])
result = max(result,
L_max + A[i] - A[i-M],
M_max + A[i] - A[i-L])
return result
|
app = ix.application
# Propose to save the project if it's modified
reponse, filename = ix.check_need_save()
if reponse.is_yes():
app.save_project(filename)
if not reponse.is_cancelled():
recent_location = app.get_current_project_filename()
if (recent_location == "" and app.get_recent_files("project").get_count() > 0):
recent_location = app.get_recent_files("project")[0]
extensions = app.get_project_extension_name()
str_ext = "{"
for i in range(extensions.get_count()):
str_ext += extensions[i]
if (i+1) < extensions.get_count():
str_ext += ","
str_ext += "}"
filename = ix.api.GuiWidget.open_file(app, recent_location, "Open Project File...", "Known Files\t*." + str_ext)
if filename != "":
clarisse_win = app.get_event_window()
old_cursor = clarisse_win.get_mouse_cursor()
clarisse_win.set_mouse_cursor(ix.api.Gui.MOUSE_CURSOR_WAIT)
app.disable()
app.load_project(filename)
app.enable()
clarisse_win.set_mouse_cursor(old_cursor)
|
"""
Given two integers a and b, return the sum of the two integers without using the operators + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
"""
# V0
# https://leetcode.com/problems/sum-of-two-integers/discuss/1214257/Python-1-line%3A-91-faster
class Souluton:
def getSum(self, a, b):
tmp = math.exp(a) * math.exp(b)
r = int(math.log(tmp))
return r
# V0'
# https://blog.csdn.net/fuxuemingzhu/article/details/79379939
#########
# XOR op:
#########
# https://stackoverflow.com/questions/14526584/what-does-the-xor-operator-do
# XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.
# -> XOR : RETURN 1 if only one "1", return 0 else
# -> XOR extra : Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ. It is symbolized by the prefix operator J and by the infix operators XOR, EOR, EXOR, ⊻, ⩒, ⩛, ⊕, ↮, and ≢. Wikipedia
# a | b | a ^ b
# --|---|------
# 0 | 0 | 0
# 0 | 1 | 1
# 1 | 0 | 1
# 1 | 1 | 0
# This operation is performed between every two corresponding bits of a number.
# Example: 7 ^ 10
# In binary: 0111 ^ 1010
# 0111
# ^ 1010
# ======
# 1101 = 13
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 2**31-1 #0x7FFFFFFF
# 32 bits interger min
MIN = 2**31 #0x80000000
# mask to get last 32 bits
mask = 2**32-1 #0xFFFFFFFF
while b != 0:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
# if a is negative, get a's 32 bits complement positive first
# then get 32-bit positive's Python complement negative
return a if a <= MAX else ~(a ^ mask)
# V0'
# https://blog.csdn.net/fuxuemingzhu/article/details/79379939
class Solution():
def getSum(self, a, b):
MAX = 2**31-1 #0x7fffffff
MIN = 2**31 #0x80000000
mask = 2**32-1 #0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & mask, ((a & b) << 1)
return a if a <= MAX else ~(a ^ mask)
# V1
# http://bookshadow.com/weblog/2016/06/30/leetcode-sum-of-two-integers/
# https://blog.csdn.net/fuxuemingzhu/article/details/79379939
# https://blog.csdn.net/coder_orz/article/details/52034541
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX_INT = 0x7FFFFFFF
MASK = 0x100000000
r, c, p = 0, 0, 1
while a | b | c:
if (a ^ b ^ c) & 1: r = (r | p) % MASK
p <<= 1
c = (a & b | b & c | a & c) & 1
a = (a >> 1) % MASK
b = (b >> 1) % MASK
return r if r <= MAX_INT else ~((r & MAX_INT) ^ MAX_INT)
# V1'
# https://www.jiuzhang.com/solution/371-sum-of-two-integers/#tag-highlight-lang-python
class Solution():
def getSum(self, a, b):
MAX = 0x7fffffff
MIN = 0x80000000
mask = 0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & mask, ((a & b) << 1)
return a if a <= MAX else ~(a ^ mask)
# V2
# Time: O(1)
# Space: O(1)
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
bit_length = 32
neg_bit, mask = (1 << bit_length) >> 1, ~(~0 << bit_length)
a = (a | ~mask) if (a & neg_bit) else (a & mask)
b = (b | ~mask) if (b & neg_bit) else (b & mask)
while b:
carry = a & b
a ^= b
a = (a | ~mask) if (a & neg_bit) else (a & mask)
b = carry << 1
b = (b | ~mask) if (b & neg_bit) else (b & mask)
return a
def getSum2(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 0x7FFFFFFF
# 32 bits interger min
MIN = 0x80000000
# mask to get last 32 bits
mask = 0xFFFFFFFF
while b:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
# if a is negative, get a's 32 bits complement positive first
# then get 32-bit positive's Python complement negative
return a if a <= MAX else ~(a ^ mask)
def minus(self, a, b):
b = self.getSum(~b, 1)
return self.getSum(a, b)
def multiply(self, a, b):
isNeg = (a > 0) ^ (b > 0)
x = a if a > 0 else self.getSum(~a, 1)
y = b if b > 0 else self.getSum(~b, 1)
ans = 0
while y & 0x01:
ans = self.getSum(ans, x)
y >>= 1
x <<= 1
return self.getSum(~ans, 1) if isNeg else ans
def divide(self, a, b):
isNeg = (a > 0) ^ (b > 0)
x = a if a > 0 else self.getSum(~a, 1)
y = b if b > 0 else self.getSum(~b, 1)
ans = 0
for i in range(31, -1, -1):
if (x >> i) >= y:
x = self.minus(x, y << i)
ans = self.getSum(ans, 1 << i)
return self.getSum(~ans, 1) if isNeg else ans
|
# Time: O(logn)
# Space: O(1)
class ArrayReader(object):
def compareSub(self, l, r, x, y):
pass
def length(self):
pass
class Solution(object):
def getIndex(self, reader):
"""
:type reader: ArrayReader
:rtype: integer
"""
left, right = 0, reader.length()-1
while left < right:
mid = left + (right-left)//2
if reader.compareSub(left, mid, mid if (right-left+1)%2 else mid+1, right) >= 0:
right = mid
else:
left = mid+1
return left
|
def letter_queue(commands):
queue = []
for command in commands:
if command == 'POP':
if len(queue) > 0:
queue.pop(0)
else:
queue.append(command.split(' ')[1])
return ''.join(queue)
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert letter_queue(("PUSH A", "POP", "POP", "PUSH Z", "PUSH D", "PUSH O", "POP", "PUSH T")) == "DOT", "dot example"
assert letter_queue(("POP", "POP")) == "", "Pop, Pop, empty"
assert letter_queue(("PUSH H", "PUSH I")) == "HI", "Hi!"
assert letter_queue(()) == "", "Nothing"
print("All done? Earn rewards by using the 'Check' button!")
|
class Graph:
def __init__(self, graph_dict={}):
self.graph_dictionary = graph_dict
def vertices(self):
return list(self.graph_dictionary.keys())
def generateEdges(self):
edges = []
for vertex in self.graph_dictionary:
#print("vertex = ")
for neighbour in self.graph_dictionary[vertex]:
if {neighbour, vertex} not in edges:
edges.append({vertex, neighbour})
return edges
def edges(self):
return self.generateEdges()
def addVertex(self, vertex):
if vertex not in self.graph_dictionary:
self.graph_dictionary[vertex] = []
def addEdge(self, edge):
edge = set(edge)
vertex1, vertex2 = tuple(edge)
if vertex1 in self.graph_dictionary:
self.graph_dictionary[vertex1].append(vertex2)
else:
self.graph_dictionary[vertex1] = [vertex2]
def checkForPath(self, source, destination, path=[]):
graph = self.graph_dictionary
path = path+[source]
if source == destination:
return path
if source not in graph:
return None
for vertex in graph[source]:
if vertex not in path:
extendedPath = self.checkForPath(vertex, destination, path)
if extendedPath:
return extendedPath
return None
if __name__ == "__main__":
g = {
"a": ["c"],
"b": ["c", "e"],
"c": ["a", "b", "d", "e"],
"d": ["c"],
"e": ["c", "b"],
"f": []
}
graph = Graph(g)
print("vertices : ", graph.vertices())
print()
print("edges : ", graph.edges())
print()
pathResult = graph.checkForPath("a", "b")
if pathResult == None:
print("No path")
else:
print("path is : ", pathResult)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Work out the first ten digits of the sum of the
following one-hundred 50-digit numbers.
"""
n = """37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690"""
def add(values, last_carry=0):
carry = 0
for d in range(len(values[0]) -1, -1, -1):
i = int(values[0][d])
for j in values[1:]:
i += int(j[d])
if i + last_carry >= 10:
carry += 1
i %= 10
last_carry = carry
carry = 0
return last_carry
def last_ten(n):
digits = []
for d in n.split():
digits.append([])
for i in range(0, len(d), 10):
digits[-1].append(d[i:i+10])
digits = [[d[i] for d in digits] for i in range(len(digits[0]))]
carry = 0
for x in digits[1::-1]:
carry = add(x, carry)
result = carry
for i in digits[0]:
result += int(i)
return str(result)[:10]
def easy(n):
return str(sum(int(d) for d in n.split()))[:10]
def main():
print(easy(n))
print(last_ten(n))
if __name__ == '__main__':
main() |
def nMatchedChar(str1,str2):
temp1=str1.lower()
temp2=str2.lower()
count=0
for ch1 in temp1:
for ch2 in temp2:
if ch1==ch2:
count+=1
return count
print(nMatchedChar("Hello","hello")) |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: Yichu Zhou - flyaway1217@gmail.com
# Blog: zhouyichu.com
#
# Python release: 3.8.0
#
# Date: 2020-07-24 16:12:52
# Last modified: 2021-04-08 09:30:32
"""
Logger configurations.
"""
PACKAGE_NAME = 'directprobe'
LOG_FILE = PACKAGE_NAME + '.log'
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s-%(filename)s-%(levelname)s: %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.FileHandler',
'filename': LOG_FILE,
},
'console': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.StreamHandler',
# 'stream': 'ext://sys.stdout',
},
},
'loggers': {
PACKAGE_NAME: {
'level': 'DEBUG',
'handlers': ['console', 'file']
},
'__main__': {
'level': 'DEBUG',
'handlers': ['console', 'file']
},
},
}
def set_log_path(path):
LOGGING_CONFIG['handlers']['file']['filename'] = path
|
BOARD_SIZE = 3 # for a standard h4 board use '3'
SHOW_HINTS = True # displays possible moves (doesn't include captures)
FRAME_RATE = 30
FONT = 'Cambria'
FONT_SIZE = 40
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
HEX_SIZE = 40
TEXT_COLOR = (255, 255, 255)
BACKGROUND_COLOR = (60, 71, 77)
BOARD_COLOR = (64, 128, 172) # blue
HINT_COLOR = (200, 0, 0)
TIMED_MODE = 0 # 1 for per-move, 2 for per-game, 3 for per-player. 0 counts elapsed time up. Anything else disables the timer display.
TIME_LIMIT = 300 * FRAME_RATE # number of frames
# BOARD_COLOR = (210, 65, 65) # red
# HINT_COLOR = (0, 200, 0)
# BOARD_COLOR = (70, 160, 85) # green
# HINT_COLOR = (0, 0, 200)
|
"""
Palindrome Integer
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
Input: 121
Output: True
Input: -121
Output: False
Output explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: 10
Output: false
Output oxplanation: Reads 01 from right to left. Therefore it is not a palindrome.
=========================================
Juste reverse the number and compare it with the original.
Time Complexity: O(N) , N = number of digits
Space Complexity: O(1)
If you care about integer overflow (in Python you shouldn't care about this), then reverse only a half of the number
and compare it with the other half. Also this solution is faster than the previous one because iterates only a half of the number.
Time Complexity: O(N)
Space Complexity: O(1)
"""
##############
# Solution 1 #
##############
def palindrome_integer_1(x):
if x < 0:
return False
rev = 0
temp = x
while temp > 0:
rev = (rev * 10) + (temp % 10)
temp //= 10
return rev == x
##############
# Solution 2 #
##############
def palindrome_integer_2(x):
# check if negative or ends with zero
if (x < 0) or (x > 0 and x % 10 == 0):
return False
rev = 0
# if the reversed number is bigger from the original
# that means the reversed number has same number of digits or more (1 or 2 more)
while x > rev:
rev = (rev * 10) + (x % 10)
x //= 10
# first comparison is for even number of digits and the second for odd number of digits
return (rev == x) or (rev // 10 == x)
###########
# Testing #
###########
# Test 1
# Correct result => True
x = 121
print(palindrome_integer_1(x))
print(palindrome_integer_2(x))
# Test 2
# Correct result => False
x = -121
print(palindrome_integer_1(x))
print(palindrome_integer_2(x))
# Test 2
# Correct result => False
x = 10
print(palindrome_integer_1(x))
print(palindrome_integer_2(x))
|
def is_self_dividing(x):
s = str(x)
for d in s:
if d == '0' or x % int(d) != 0:
return False
return True
class Solution:
def selfDividingNumbers(self, left, right):
ans = []
for x in range(left, right+1):
if is_self_dividing(x):
ans.append(x)
return ans
|
expected_output = {
'total': 4,
'interfaces': {
'ethernet1/1': {
'area': 0,
'network': '10.254.32.221/30',
'cost': 410,
'state': 'down',
'full_neighbors': 0,
'configured_neighbors': 0
},
'ethernet5/1': {
'area': 0,
'network': '10.254.32.3/31',
'cost': 21,
'state': 'ptpt',
'full_neighbors': 1,
'configured_neighbors': 1
},
'ethernet7/1': {
'area': 0,
'network': '10.254.32.109/31',
'cost': 20,
'state': 'ptpt',
'full_neighbors': 1,
'configured_neighbors': 1
},
'loopback1': {
'area': 0,
'network': '23.33.33.22/32',
'cost': 1,
'state': 'DR',
'full_neighbors': 0,
'configured_neighbors': 0
}
}
}
|
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Determines if a string is an integer or not. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : January 28, 2019 #
# #
############################################################################################
def obtain_user_input(input_mess: str) -> str:
user_data, valid = '', False
while not valid:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise ValueError(f'Oops! data needed')
valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
def determine_type(main_test: str) -> None:
try:
result_int = int(main_test)
if result_int:
print(f'String is an integer')
except ValueError:
print(f'String is not an ingeer')
if __name__ == "__main__":
test_int = obtain_user_input(input_mess='Enter a string: ')
determine_type(main_test=test_int)
|
# Define the class, inherit from the base
class ASTReward(object):
"""Function to calculate the rewards for timesteps when optimizing AST solver policies.
"""
def __init__(self):
pass
def give_reward(self, action, **kwargs):
"""Returns the reward for a given time step.
Parameters
----------
action : array_like
Action taken by the AST solver.
kwargs :
Accepts relevant info for computing the reward.
Returns
-------
reward : float
Reward based on the previous action.
"""
raise NotImplementedError
|
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
:mod:`tests` -- Integration / Functional Tests for Nova
===================================
.. automodule:: tests
:platform: Unix
:synopsis: Tests for Nova.
.. moduleauthor:: Nirmal Ranganathan <nirmal.ranganathan@rackspace.com>
.. moduleauthor:: Tim Simpson <tim.simpson@rackspace.com>
"""
|
l = 10 # Global variable
def fun1(n):
global l # permit for make operation on global variable
#l = 5 # Local variable
l = l + 50 #We cant make operation on global variable
print(l)
print(n, "I have printed")
fun1("This is me")
print(l)
|
# -*- encoding: utf-8 -*-
'''
@Filename : simulate_settings.py
@Datetime : 2020/09/24 10:21:18
@Author : Joe-Bu
@version : 1.0
'''
NORMAL_ITEMS = ['watertemp', 'pH', 'DO', 'conductivity', 'turbidity']
NORMAL_INDEX = ['codmn', 'nh3n', 'tp', 'tn']
model_params = dict(
savedir = '../../model',
modes = 'predict', # train/predict
index = 'codmn', # TP/TN/NH3N/CODMn
indexs = ['codmn','nh3n','tp','tn'], # TP+TN+NH3N+CODMn
model = 'XGB', # RF/GBRT/XGB
models = ['RF','GBRT','XGB'] # RF+GBRT+XGB
) |
# ds_config.py
#
# DocuSign configuration settings
DS_CONFIG = {
"ds_client_id": "{INTEGRATION_KEY_AUTH_CODE}", # The app's DocuSign integration key
"ds_client_secret": "{SECRET_KEY}", # The app's DocuSign integration key's secret
"signer_email": "{SIGNER_EMAIL}",
"signer_name": "{SIGNER_NAME}",
"app_url": "http://localhost:5000", # The url of the application. Eg http://localhost:5000
# NOTE: You must add a Redirect URI of appUrl/ds/callback to your Integration Key.
# Example: http://localhost:5000/ds/callback
"authorization_server": "https://account-d.docusign.com",
"allow_silent_authentication": True, # a user can be silently authenticated if they have an
# active login session on another tab of the same browser
"target_account_id": None, # Set if you want a specific DocuSign AccountId,
# If None, the user's default account will be used.
"demo_doc_path": "demo_documents",
"doc_salary_docx": "World_Wide_Corp_salary.docx",
"doc_docx": "World_Wide_Corp_Battle_Plan_Trafalgar.docx",
"doc_pdf": "World_Wide_Corp_lorem.pdf",
# Payment gateway information is optional
"gateway_account_id": "{DS_PAYMENT_GATEWAY_ID}",
"gateway_name": "stripe",
"gateway_display_name": "Stripe",
"github_example_url": "https://github.com/docusign/code-examples-python/tree/master/app/",
"documentation": "", # Use an empty string to indicate no documentation path.
"quickstart": "{QUICKSTART_VALUE}"
}
DS_JWT = {
"ds_client_id": "{INTEGRATION_KEY_JWT}",
"ds_impersonated_user_id": "{IMPERSONATED_USER_ID}", # The id of the user.
"private_key_file": "./private.key", # Create a new file in your repo source folder named private.key then copy and paste your RSA private key there and save it.
"authorization_server": "account-d.docusign.com"
}
|
# table.py
def print_table(objects, colnames):
'''
Make a nicely formatted table showing attributes from a list of objects
'''
# Emit table headers
for colname in colnames:
print('{:>10s}'.format(colname), end=' ')
print()
for obj in objects:
# Emit a row of table data
for colname in colnames:
print('{:>10s}'.format(str(getattr(obj, colname))), end=' ')
print()
def print_table(objects, colnames, formatter):
'''
Make a nicely formatted table showing attributes from a list of objects
'''
formatter.headings(colnames)
for obj in objects:
rowdata = [str(getattr(obj, colname)) for colname in colnames ]
formatter.row(rowdata)
class TableFormatter(object):
# Serves a design spec for making tables (use inheritance to customize)
def headings(self, headers):
raise NotImplementedError
def row(self, rowdata):
raise NotImplementedError
class TextTableFormatter(TableFormatter):
def headings(self, headers):
for header in headers:
print('{:>10s}'.format(header), end=' ')
print()
def row(self, rowdata):
for item in rowdata:
print('{:>10s}'.format(item), end=' ')
print()
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(rowdata))
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end='')
for h in headers:
print('<th>{}</th>'.format(h), end='')
print('</tr>')
def row(self, rowdata):
print('<tr>', end='')
for d in rowdata:
print('<td>{}</td>'.format(d), end='')
print('</tr>')
|
'''
@Author: qinzhonghe96@163.com
@Date: 2020-03-01 14:31:44
@LastEditors: qinzhonghe96@163.com
@LastEditTime: 2020-03-01 17:34:18
@Description:
'''
|
class Treasure(object):
def __init__(self, value):
self.value = value
class Coins(Treasure):
def __init__(self):
super().__init__(2)
class Pouch(Treasure):
def __init__(self):
super().__init__(6)
class GoldJewelry(Treasure):
def __init__(self):
super().__init__(10)
class Gemstone(Treasure):
def __init__(self):
super().__init__(14)
class SmallTreasureChest(Treasure):
def __init__(self):
super().__init__(20)
|
'''Given two integers A and B, A modulo B is the remainder when dividing A by B.
For example, the numbers 7, 14, 27 and 38 become 1, 2, 0 and 2, modulo 3.
Write a program that accepts 10 numbers as input and outputs the number of distinct numbers in the input,
if the numbers are considered modulo 42.
The input will contain 10 non-negative integers, each smaller than 1000, one per line.
Output the number of distinct values when considered modulo 42 on a single line. '''
mod_result = []
for i in range(10):
a = int(input())
mod_result.append(a%42)
mod_result = set(mod_result)
print(len(mod_result)) |
# AUTOMATICALLY GENERATED BY GENGUPPY
about="(iguppy.gsl.Text\nRecordingInter\np1\n(dp2\nS'tag_configs'\np3\n(dp4\nI0\n((S'spacing1'\np5\nI11\ntp6\n(S'font'\np7\n(S'times'\np8\nI24\nS'bold'\ntttp9\nsI1\n(g6\n(S'tabs'\np10\n(F23.5\nS'center'\np11\nF57\nS'left'\np12\nttp13\n(g7\n(g8\nI12\nS'bold'\ntp14\ntp15\ntp16\nsI2\n(g6\ng15\ntp17\nsI3\n(g6\n(g7\n(g8\nI12\ntp18\ntp19\ntp20\nsI4\n((g5\nI6\ntp21\ng13\ntp22\nsI5\n(g21\n(g7\n(g8\nI10\nS'italic'\ntttp23\nsI6\n(g21\n(g7\n(g8\nI10\ntttp24\nsI7\n(g21\ng19\ntp25\nsI8\n(g19\ntp26\nssS'_gsl_tk_geometry'\np27\nS'400x200'\np28\nsS'_gsl_title'\np29\nS'About Heapy Profile Browser'\np30\nsS'appends'\np31\n(lp32\nI0\naS'Heapy Profile Browser \\n'\np33\naI1\naS'\\t'\naI2\naS'Version'\np34\naI1\naS'\\t'\naI3\naS'0.1\\n'\np35\naI4\naS'\\t'\naI2\naS'Author'\np36\naI4\naS'\\t'\naI3\naS'Sverker Nilsson\\n'\np37\naI4\naS'\\t'\naI2\naS'Email'\np38\naI4\naS'\\t'\naI3\naS'sn@sncs.se\\n'\np39\naI4\naS'\\t'\naI2\naS'License'\np40\naI4\naS'\\t'\naI3\naS'MIT \\n'\np41\naI5\naS'Copyright (c) 2005--2008'\np42\naI6\naS' S. Nilsson Computer System AB Linkoping, Sweden '\np43\naI7\naS'\\n'\nasb."
help='(iguppy.gsl.Text\nRecordingInter\np1\n(dp2\nS\'tag_configs\'\np3\n(dp4\nI0\n((S\'spacing1\'\np5\nI10\ntp6\n(S\'font\'\np7\n(S\'times\'\np8\nI20\nS\'bold\'\ntttp9\nsI1\n(g6\n(g7\n(g8\nI12\nttp10\ntp11\nsI2\n((g5\nI6\ntp12\ng10\ntp13\nsI3\n((g5\nI9\ntp14\n(g7\n(g8\nI16\nS\'bold\'\ntttp15\nsI4\n(g10\ntp16\nsI5\n((S\'lmargin2\'\np17\nI36\ntp18\ng12\n(S\'tabs\'\np19\n(F97.5\nS\'center\'\np20\nF169\nS\'left\'\np21\nttp22\n(S\'lmargin1\'\np23\nI36\ntp24\n(g7\n(g8\nI12\nS\'bold\'\ntp25\ntp26\ntp27\nsI6\n(g18\ng12\ng24\ng26\ntp28\nsI7\n(g18\ng12\ng24\ng10\ntp29\nsI8\n(g22\ntp30\nsI9\n(g12\ng22\ntp31\nsI10\n(g18\ng24\ng10\ntp32\nsI11\n(g18\ng12\n(g19\n(F96\ng20\nF166\ng21\nttp33\ng24\ng26\ntp34\nsI12\n(g12\ng33\ntp35\nsI13\n(g18\ng12\n(g19\n(F71.5\ng20\nF117\ng21\nttp36\ng24\ng26\ntp37\nsI14\n(g36\ntp38\nsI15\n(g12\ng36\ntp39\nsI16\n(g18\ng24\n(g7\n(g8\nI10\nttp40\ntp41\nsI17\n(g18\n(g5\nI8\ntp42\ng24\ng26\ntp43\nsI18\n((g17\nI72\ntp44\n(g23\nI72\ntp45\ng10\ntp46\nsI19\n(g44\ng12\n(g19\n(F125.5\ng20\nF189\ng21\nttp47\ng45\ng26\ntp48\nsI20\n(g44\ng12\ng45\ng26\ntp49\nsI21\n(g44\ng12\ng45\ng10\ntp50\nsI22\n(g47\ntp51\nsI23\n(g12\ng47\ntp52\nsI24\n(g44\ng45\ng26\ntp53\nsI25\n(g44\ng12\n(g19\n(F116.5\ng20\nF171\ng21\nttp54\ng45\ng26\ntp55\nsI26\n(g54\ntp56\nsI27\n(g18\ng12\n(g19\n(F54.5\ng20\nF83\ng21\nttp57\ng24\ng26\ntp58\nsI28\n(g12\ng57\ntp59\nsI29\n(g14\ng10\ntp60\nsI30\n(g44\ng12\n(g19\n(F115.5\ng20\nF169\ng21\nttp61\ng45\ng26\ntp62\nsI31\n(g61\ntp63\nsI32\n(g12\ng61\ntp64\nsI33\n(g44\ng45\ng40\ntp65\nsI34\n(g44\ng12\n(g19\n(F111.5\ng20\nF161\ng21\nttp66\ng45\ng26\ntp67\nsI35\n(g66\ntp68\nsI36\n(g12\ng66\ntp69\nsI37\n(g18\ng42\ng24\ng10\ntp70\nssS\'_gsl_title\'\np71\nS\'Help for Heapy Profile Browser\'\np72\nsS\'appends\'\np73\n(lp74\nI0\naS\'Menus\\n\'\np75\naI1\naS\'Click on the dotted line at the top of a menu to "tear it off": a separate window containing the menu is created. \\n\'\np76\naI3\naS\'File Menu\\n\'\np77\naI5\naS\'\\t\'\naI6\naS\'New Profile Browser\'\np78\naI5\naS\'\\t\'\naI7\naS\'Create a new browser window with the same\\n\'\np79\naI8\naS\'\\t\\t\'\np80\naI7\naS\'file as the one opened in the current window. \\n\'\np81\naI9\naS\'\\t\'\naI6\naS\'Open Profile\'\np82\naI9\naS\'\\t\'\naI7\naS\'Open a profile data file in the current window.\\n\'\np83\naI9\naS\'\\t\'\naI6\naS\'Close Window\'\np84\naI9\naS\'\\t\'\naI7\naS\'Close the current window (exits from Tk if it\\n\'\np85\naI8\nag80\naI7\naS\'was the last browser window). \\n\'\np86\naI9\naS\'\\t\'\naI6\naS\'Clear Cache\'\np87\naI9\naS\'\\t\'\naI7\naS\'Clear the sample cache, releasing its memory.\\n\'\np88\naI8\nag80\naI7\naS\'The cache will be automatically filled again\\n\'\np89\naI8\nag80\naI7\naS\'when needed. \\n\'\np90\naI8\nag80\naI10\naS\'This command is a kind of temporary /\'\np91\naI7\naS\'\\n\'\naI8\nag80\naI10\naS\'experimental feature. I think the cache handling\'\np92\naI7\naS\'\\n\'\naI8\nag80\naI10\naS\'should be made automatic and less memory\'\np93\naI7\naS\'\\n\'\naI8\nag80\naI10\naS\'consuming. \'\np94\naI7\naS\'\\n\'\naI3\naS\'Pane Menu\\n\'\np95\naI11\naS\'\\t\'\naI6\naS\'Show Control Panel\'\np96\naI11\naS\'\\t\'\naI7\naS\'Show the control panel pane.\\n\'\np97\naI12\naS\'\\t\'\naI6\naS\'Show Graph\'\np98\naI12\naS\'\\t\'\naI7\naS\'Show the graph pane.\\n\'\np99\naI12\naS\'\\t\'\naI6\naS\'Show Table\'\np100\naI12\naS\'\\t\'\naI7\naS\'Show the table pane. \\n\'\np101\naI3\naS\'Graph Menu\\n\'\np102\naI13\naS\'\\t\'\naI6\naS\'Bars / Lines\'\np103\naI13\naS\'\\t\'\naI7\naS\'Choose whether the graph should be displayed using bars\\n\'\np104\naI14\nag80\naI7\naS\'or lines. \\n\'\np105\naI14\nag80\naI10\naS\'When using bars, the sample value (size or count) for\'\np106\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'different kinds of objects will be stacked on top of each\'\np107\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'other so the total height represents the total value of a\'\np108\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'sample. When using lines, each line represents the value\'\np109\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'for a single kind of object. The 10 largest values are\'\np110\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'shown in each sample point. Each kind has a particular\'\np111\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'color, choosen arbitrary but it is always the same color\'\np112\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'for the same kind. The remaing kinds, if any, are shown in\'\np113\naI7\naS\'\\n\'\naI14\nag80\naI10\naS\'black. \'\np114\naI7\naS\'\\n\'\naI15\naS\'\\t\'\naI6\naS\'Size / Count\'\np115\naI15\naS\'\\t\'\naI7\naS\'Choose whether the graph should display the size of\\n\'\np116\naI14\nag80\naI7\naS\'objects of a particular kind or the number of objects of\\n\'\np117\naI14\nag80\naI7\naS\'that kind. \\n\'\np118\naI14\nag80\naI16\naS\'(Note that this affects only the graph, the table will still\'\np119\naI7\naS\'\\n\'\naI14\nag80\naI16\naS\'choose size or kind as it were choosen in the table menu.)\'\np120\naI7\naS\'\\n\'\naI14\nag80\naI7\naS\'\\n\'\naI3\naS\'Table Menu\\n\'\np121\naI17\naS\'Header submenu\\n\'\np122\naI18\naS\'This menu has a choice of header for each column of the table. The data of each column is determined by the header of that column, as well as the headers of previous columns. So if you change the first column header (A/B), the data in that column will change as well as the data under the next header (Size/Count) and the ones that follow. \\n\'\np123\naI19\naS\'\\t\'\naI20\naS\'A / B\'\np124\naI19\naS\'\\t\'\naI21\naS\'Use the sample at the A or B marker in the graph.\\n\'\np125\naI22\nag80\naI18\naS\'The kinds of objects shown in the table under this\'\np126\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'column are taken from the 10 largest sample values\'\np127\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'at that point, in the same order as they are shown in\'\np128\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'the graph. The ordering in the graph depends on\'\np129\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'the choice of count or size in the graph menu.\'\np130\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'However, the table may show count or size\'\np131\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'independent from the choice in the graph. \'\np132\naI21\naS\'\\n\'\naI23\naS\'\\t\'\naI20\nag115\naI23\naS\'\\t\'\naI21\naS\'Show the size or count of the kinds of objects in\\n\'\np133\naI22\nag80\naI21\naS\'each row, taken from those choosen in the A / B\\n\'\np134\naI22\nag80\naI21\naS\'column. \\n\'\np135\naI23\naS\'\\t\'\naI20\naS\'%A:Tot / %B:Tot\'\np136\naI23\naS\'\\t\'\naI21\naS\'Show percentage of the Size / Count column,\\n\'\np137\naI22\nag80\naI21\naS\'relative to the total (size or count) at either the A or\\n\'\np138\naI22\nag80\naI21\naS\'B sample point. \\n\'\np139\naI23\naS\'\\t\'\naI20\naS\'Cumul /\'\np140\naI23\naS\'\\t\'\naI21\naS\'Show either a cumulative sum of the Size / Count\\n\'\np141\naI22\naS\'\\t\'\naI20\naS\'\'\naI24\naS\'A-B / B-A\'\np142\naI22\naS\'\\t\'\naI21\naS\'column, or the difference A-B or B-A. \\n\'\np143\naI22\nag80\naI18\naS\'The cumulative sum is taken by summing from the\'\np144\naI21\naS\'\\n\'\naI22\nag80\naI18\naS\'first table row down to the last row. \'\np145\naI21\naS\'\\n\'\naI23\naS\'\\t\'\naI20\nag136\naI23\naS\'\\t\'\naI21\naS\'Show percentage of the previous field, relative to\\n\'\np146\naI22\nag80\naI21\naS\'either the A or B total. \\n\'\np147\naI23\naS\'\\t\'\naI20\naS\'Kind\'\np148\naI23\naS\'\\t\'\naI21\naS\'Shows the kind of objects. This is currently the only\\n\'\np149\naI22\nag80\naI21\naS\'alternative for this column. The kind shown\\n\'\np150\naI22\nag80\naI21\naS\'corresponds to the color shown in the A / B\\n\'\np151\naI22\nag80\naI21\naS\'column. A special kind is <Other> which\\n\'\np152\naI22\nag80\naI21\naS\'summarizes the remaining data if there were more\\n\'\np153\naI22\nag80\naI21\naS\'than 10 different kinds in the sample. \\n\'\np154\naI17\naS\'Scrollbar submenu\\n\'\np155\naI25\naS\'\\t\'\naI20\naS\'Auto / On / Off\'\np156\naI25\naS\'\\t\'\naI21\naS\'Choose a scrollbar mode. The usual setting is Auto\\n\'\np157\naI26\nag80\naI21\naS\'which shows the scrollbar only when needed. \\n\'\np158\naI3\naS\'Window Menu\\n\'\np159\naI10\naS\'This menu lists the names of all open windows. Selecting one brings it to the top, deiconifying it if necessary. \\n\'\np160\naI3\naS\'Help Menu\\n\'\np161\naI27\naS\'\\t\'\naI6\naS\'About\'\np162\naI27\naS\'\\t\'\naI7\naS\'Version, author, email, copyright.\\n\'\np163\naI28\naS\'\\t\'\naI6\naS\'Help\'\np164\naI28\naS\'\\t\'\naI7\naS\'Open this help window. \\n\'\np165\naI0\naS\'Panes\\n\'\np166\naI1\naS\'There are 3 panes in the main window shown by default. At the top is the Control Panel, at the bottom left the Graph and at the bottom right the Table. \\n\'\np167\naI3\naS\'Control Panel Pane\\n\'\np168\naI29\naS\'This contains controls for the graph and the markers. It also has a quick-exit button and a collect button.\\n\'\np169\naI17\naS\'X / Y axis control\\n\'\np170\naI18\naS\'The two frames in the Control Panel having an X or Y button in the top left corner control each axis of the graph. The X, horizontal, axis shows the sample point. The Y axis shows either the size or count, as choosen in the Graph menu. \\n\'\np171\naI30\naS\'\\t\'\naI20\naS\'X / Y Button\'\np172\naI30\naS\'\\t\'\naI21\naS\'Brings up a menu, currently containing some buttons\\n\'\np173\naI31\nag80\naI21\naS\'that can also be accessed directly in the panel. \\n\'\np174\naI32\naS\'\\t\'\naI20\naS\'Grid button\'\np175\naI32\naS\'\\t\'\naI21\naS\'Select if the graph should show grid lines.\\n\'\np176\naI32\naS\'\\t\'\naI20\naS\'Range buttons\'\np177\naI32\naS\'\\t\'\naI21\naS\'Change the range that is shown in the displayed\\n\'\np178\naI31\naS\'\\t\'\naI20\naS\'\'\naI24\naS\'- / +\'\np179\naI31\naS\'\\t\'\naI21\naS\'portion of the graph. For each time + or - is pressed the\\n\'\np180\naI31\nag80\naI21\naS\'range will be stepped up or down in the sequence (1, 2,\\n\'\np181\naI31\nag80\naI21\naS\'5) and multiples thereoff. \\n\'\np182\naI32\naS\'\\t\'\naI20\naS\'Range field\'\np183\naI32\naS\'\\t\'\naI21\naS\'The current range is shown here, and a new range can\\n\'\np184\naI31\nag80\naI21\naS\'be entered by writing to this field and pressing Enter.\\n\'\np185\naI31\nag80\naI21\naS\'The format is an integer that may be followed by a\\n\'\np186\naI31\nag80\naI21\naS\'multiplier, K, M, G, or T, meaning that the value is\\n\'\np187\naI31\nag80\naI21\naS\'multipled by 1000, 1E6, 1E9, or 1E12 respectively.\\n\'\np188\naI31\nag80\naI21\naS\'The maximum range is 1T. \\n\'\np189\naI17\naS\'A / B sample control\\n\'\np190\naI18\naS\'Each of the frames showing A or B in the top left corner controls one of the sample markers. The current position is shown in the bottom left corner.\'\np191\naI33\naS\'(This is currently not an entry field - TODO - but the marker may be moved long distances by directly dragging it in the Graph frame.) \'\np192\naI18\naS\'\\n\'\naI34\naS\'\\t\'\naI20\naS\'- / + \'\np193\naI34\naS\'\\t\'\naI21\naS\'Step the marker one step to the left (-) or to the right (+).\\n\'\np194\naI35\nag80\naI18\naS\'The table will be updated to show new data if it was set\'\np195\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'to show such data that were dependent on the marker\'\np196\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'moved. \'\np197\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'The graph will show the new marker position. If the\'\np198\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'marker was outside of the displayed portion of the\'\np199\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'graph, the graph will scroll so the marker becomes\'\np200\naI21\naS\'\\n\'\naI35\nag80\naI18\naS\'visible. \'\np201\naI21\naS\'\\n\'\naI36\naS\'\\t\'\naI20\naS\'Track button\'\np202\naI36\naS\'\\t\'\naI21\naS\'Press to set the marker to the last sample in the file and\\n\'\np203\naI35\nag80\naI21\naS\'stay at the end as new samples are added. (New\\n\'\np204\naI35\nag80\naI21\naS\'samples are periodically read from the end of the file\\n\'\np205\naI35\nag80\naI21\naS\'when auto-collect is selected via the Collect button.) \\n\'\np206\naI35\nag80\naI18\naS\'Tracking is turned off when the marker is manually\'\np207\naI21\naS\'\\n\'\naI35\nag80\naI18\nag197\naI21\naS\'\\n\'\naI17\naS\'Exit button\\n\'\np208\naI18\naS\'Exits the program, a shortcut for the Exit command in the File menu.\\n\'\np209\naI17\naS\'Collect button\\n\'\np210\naI18\naS\'When selected, the browser will collect new samples from the current file, and will continue to do this periodically.\\n\'\np211\naI33\naS\'Currently it will check the file for new data once a second. \'\np212\naI18\naS\'\\n\'\naI3\naS\'Graph Pane\\n\'\np213\naI10\naS\'This pane shows the currently visible portion of the sample file. It can be scrolled via an horizontal scrollbar. The two markers are shown as buttons labeled A and B above the graph and with lines extending down in the graph. Markers can be moved by the mouse. \\n\'\np214\naI7\naS\'How to move the markers is hopefully quite self evident when tried out but I wrote up some details about it anyway.\\n\'\np215\naI17\naS\'Marker movement details\\n\'\np216\naI37\naS"Holding down the mouse button and moving the mouse moves the underlying marker. Klicking the mouse button over a marker without moving the mouse, selects the marker. While it is selected any movement of the mouse within the graph will move the marker with it. Klicking again anywhere in the graph will deselect the marker. If the marker can be moved, the cursor will be an arrow indicating the direction it can be moved, left or right or both. If the marker can not be moved in any direction, the cursor will show a circle or disc. The marker can not move outside the available samples. Moving the mouse outside of the graph also restricts the movement of the mouse, even if the mouse button is pressed. This is intentional so that the marker can be moved longer distances than the mouse can move. Moving the mouse to the right of the graph, the marker can only be moved to the right - moving back the mouse will not move the marker back until the mouse enters the graph area again. Similarly for the left side. Above or below the graph, the mouse will not move the marker at all but will show a circle to indicate that the mouse may be \'recirculated\' to move back into the graph. \\n"\np217\naI3\naS\'Table Pane\\n\'\np218\naI10\naS\'This pane shows a table based on the configuration set in the Table menu. The sample number and time stamp show in the header. \\n\'\np219\nasb.'
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"get_splits": "00_data.ipynb",
"TitledStrEx": "00_data.ipynb",
"PreprocCategorize": "00_data.ipynb",
"PreprocCategoryBlock": "00_data.ipynb",
"TextGetter": "00_data.ipynb",
"KeyGetter": "00_data.ipynb",
"TransTensorText": "00_data.ipynb",
"find_first": "00_data.ipynb",
"split_by_sep": "00_data.ipynb",
"TokTransform": "00_data.ipynb",
"TokBatchTransform": "00_data.ipynb",
"PadBatchTransform": "00_data.ipynb",
"untuple": "00_data.ipynb",
"to_tuple": "00_data.ipynb",
"LMBatchTfm": "00_data.ipynb",
"Undict": "00_data.ipynb",
"UndictS2S": "00_data.ipynb",
"TransformersTextBlock": "00_data.ipynb",
"TransformersLMBlock": "00_data.ipynb",
"tokenize": "00_data.ipynb",
"group_texts": "00_data.ipynb",
"MultiChoiceTransform": "00_data.ipynb",
"MultiChoiceBlock": "00_data.ipynb",
"PadTokBatchTransform": "00_data.ipynb",
"TokenClassificationBlock": "00_data.ipynb",
"default_splitter": "01_learner.ipynb",
"to_device": "01_learner.ipynb",
"TransCallback": "01_learner.ipynb",
"GeneratePreds": "01_learner.ipynb",
"TransLearner": "01_learner.ipynb",
"MetricCallback": "02_metrics.ipynb",
"RougeScore": "02_metrics.ipynb",
"Seqeval": "02_metrics.ipynb"}
modules = ["data.py",
"learner.py",
"metrics.py"]
doc_url = "https://aikindergarten.github.io/fasthugs/"
git_url = "https://github.com/aikindergarten/fasthugs/tree/master/"
def custom_doc_links(name): return None
|
class JsIdentifier:
def __init__(self, data: object):
self.name = data.name
self.type = 'any'
def set_type(self, new_type: str) -> None:
self.type = new_type
def to_dict(self) -> dict:
return {
'name': self.name,
'type': self.type
}
|
def start_processes(pool_of_workers):
for worker in pool_of_workers:
worker.start()
print ("--- Workers started") |
"""
A small set of functions for doing math operations
"""
#Write a function named add that adds two values
def add(a,b):
"""
IF YOU PUT TEXT HERE THIS WILL SHOW UP WHEN YOU RUN HELP
"""
return a + b
def mult(a,b):
"""
Function that multiplies two arguments
"""
return a * b
def divide(a,b):
"""
Function that divides two arguments
"""
return a/b
def subtract(a,b):
"""
Function that subtracts the second element from the first
"""
return a - b
def mod(a,b):
"""
Function that return the modulus of two numbers (a%b)
Takes arguments mod(a,b)
"""
i = 1
if float(a/b) - int(a/b) != 0.0:
while True:
if b*i < a:
i +=1
else:
return a - b * (i-1)
break
elif b > a:
return a
else:
return 0
|
def description_from_url_walmart(link):
description = ''
try:
remove_initial = link.replace("https://www.walmart.com/ip/","")
for i in remove_initial:
if(i!="/"):
description += i
else:
break
description = description.replace('-',' ')
except:
description = ''
return description
|
actually = list(map(int, input().split()))
da, ma, ya = actually
expected = list(map(int, input().split()))
de, me, ye = expected
fine = 0
if ya > ye:
fine = 10000
elif ya == ye:
if ma > me:
fine = (ma - me) * 500
elif ma == me and da > de:
fine = (da - de) * 15
print(fine)
|
def is_char_mapped(str_a, str_b):
if len(str_a) != len(str_b):
return False
char_map = dict()
for char_a, char_b in zip(str_a, str_b):
if char_a not in char_map:
char_map[char_a] = char_b
elif char_map[char_a] != char_b:
return False
return True
# Tests
assert is_char_mapped("abc", "bcd")
assert not is_char_mapped("foo", "bar")
|
# isFoldable.py
# determine flat foldability of maps
# Author: Sam Vinitsky
# Date: 3/5/16
# class to store an N by N map
class Map:
m = 1
n = 1
cp = [[]]
def __init__(self, cp):
self.cp = cp
self.m = len(cp) + 1
self.n = len(cp[0]) + 1 # m x n map is specified by (m-1)x(n-1) creases
# determine if this linear ordering satisfies the butterfly condition for this map
def satisfiesButterflyCondition(self, linearOrdering):
return True
# determine if this linear ordering satisfies the partial ordering induces by the checkerboard pattern + cp
def satisfiesPartialOrdering(self, linearOrdering):
return True
# map is an N by N array, linear ordering is stored as a list
# determine if map can be folded into linearOrdering
def isLinearOrderingValid(self, linearOrdering):
if self.satisfiesButterflyCondition(linearOrdering):
if self.satisfiesPartialOrdering(linearOrdering):
return True
return False
# an ordering of the faces (0,0) through (m-1,n-1)
class LinearOrdering:
m = 1
n = 1
linearOrdering = [(0,0)]
def __init__(self, m, n, lo):
self.m = m
self.n = n
self.linearOrdering = lo
def main():
cp = [[]]
myMap = Map(cp)
myLinearOrdering = LinearOrdering(1, 1, [(0,0)])
print(myMap.isLinearOrderingValid(myLinearOrdering))
if __name__ == "__main__":
main() |
n = int(input())
collection = set()
for _ in range(n):
username = input()
collection.add(username)
[print(x) for x in collection]
|
#!/usr/bin/env python3
# Q learning learning rate
alpha = 1.0
# Q learning discount rate
gamma = 0.4
# Epsilon initial
epsilon_initial = 0.9
# Epsilon final
epsilon_final = 0.0
# Annealing timesteps
annealing_timesteps = 1000
# threshold
threshold = 16.0
|
def test_home(client):
rv = client.post("/test", json={"a": 12})
assert rv.is_json
assert rv.json["a"] == 12
def test_home_bad(client):
rv = client.post("/test", json={"a": "str"})
assert rv.is_json
assert rv.status_code == 400
|
ary=[3,7,1,6,1,1,1,1,1,1,5,1,1,1,99,1,1,88,1,1,1,1,1,2]
one_is_count=0
count=0
for i in range(0,len(ary)):
if ary[i]==1:
one_is_count+=1
if one_is_count%3==0:
count+=1
if ary[i]==99:
break
print(count) |
watchdog_config = """
# SDSLabs Watchdog configuration START
session optional pam_exec.so seteuid log=/opt/watchdog/logs/ssh.logs /opt/watchdog/bin/watchdog ssh
# SDSLabs Watchdog configuration END
"""
inside_watchdog_config_section = False
def process_line(line):
global inside_watchdog_config_section
if inside_watchdog_config_section and line == "# SDSLabs Watchdog configuration END\n":
inside_watchdog_config_section = False
return ''
if inside_watchdog_config_section:
return ''
if line == "# SDSLabs Watchdog configuration START\n":
inside_watchdog_config_section = True
return ''
return line
def main():
iput = open("/etc/pam.d/sshd")
oput = open("watchdog_tmp_ssh", "w")
lines = iput.readlines()
for l in lines:
oputline = process_line(l)
oput.write(oputline)
oput.write(watchdog_config)
iput.close()
oput.close()
main() |
#Faça um programa que leia um número inteiro e imprima a tabuada de multiplicação deste número. Suponha que o número lido da entrada é maior que zero.
cont = 1
numero = int(input())
while cont<=9:
print(numero, "X", cont, "=", numero * cont)
cont = cont+1 |
#!/usr/local/bin/python
# Code Fights Create Array Problem
def createArray(size):
return [1] * size
def main():
tests = [
[4, [1, 1, 1, 1]],
[2, [1, 1]],
[1, [1]],
[5, [1, 1, 1, 1, 1]]
]
for t in tests:
res = createArray(t[0])
ans = t[1]
if ans == res:
print("PASSED: createArray({}) returned {}"
.format(t[0], res))
else:
print("FAILED: createArray({}) returned {}, answer: {}"
.format(t[0], res, ans))
if __name__ == '__main__':
main()
|
def to_roman(base, base_1, base_5, base_10):
d = {}
for i in range(1, 10):
if 0 <= i <= 3:
d[i * base] = base_1 * i
elif i == 4:
d[i * base] = base_1 + base_5
elif 5 <= i <= 8:
d[i * base] = base_5 + (i - 5) * base_1
elif i == 9:
d[i * base] = base_1 + base_10
return d
roman_numerals = to_roman(1, 'I', 'V', 'X')
roman_numerals.update(to_roman(10, 'X', 'L', 'C'))
roman_numerals.update(to_roman(100, 'C', 'D', 'M'))
roman_numerals.update({i: 'M' * (i // 1000) for i in range(1000, 10000, 1000)})
print(roman_numerals)
def numeral(number):
r = []
for n, v in enumerate(reversed(list(str(number)))):
roman_numerals.get(int(v) * pow(10, n), '')
r.append(roman_numerals.get(int(v) * pow(10, n), ''))
return ''.join(reversed(r))
'''Another good solution:
roman_numbers = (
( 'M', 1000 ), ( 'CM', 900 ),
( 'D', 500 ), ( 'CD', 400 ),
( 'C', 100 ), ( 'XC', 90 ),
( 'L', 50 ), ( 'XL', 40 ),
( 'X', 10 ), ( 'IX', 9 ),
( 'V', 5 ), ( 'IV', 4 ),
( 'I', 1 )
)
def numeral(arabic):
if arabic < 1:
raise ValueError("Romans did not count below 1")
if arabic > 3000:
raise ValueError("Romans did not count beyond 3000")
roman = ""
for roman_number, value in roman_numbers:
while arabic >= value:
roman += roman_number
arabic -= value
return roman
'''
|
# LC Contest 170
# Time: O(n^2), n=len(s)
# Space: O(n^2)
class Solution:
def minInsertions(self, s: str) -> int:
memo = {}
return self.util(s, memo)
def util(self, s, memo):
if s in memo:
return memo[s]
start = 0
end = len(s)-1
if len(s)==1 or len(s)==0:
return 0
if len(s)==2 and s[0]!=s[1]:
return 1
if s[start]==s[end]:
memo[s] = self.util(s[1:-1], memo)
else:
memo[s] = 1+min(self.util(s[1:], memo), self.util(s[:-1], memo))
return memo[s]
|
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017-2018 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
class Server(object):
@staticmethod
def name(elem_s):
return elem_s.get('name', None)
@staticmethod
def address(elem_s):
return elem_s.get('addr', None)
@staticmethod
def components(elem_s):
return elem_s.get('components', [])
@staticmethod
def services(elem_s):
return elem_s.get('services', [])
@staticmethod
def num_components(elem_s):
return len(elem_s.get('components', []))
@staticmethod
def num_services(elem_s):
return len(elem_s.get('services', []))
@staticmethod
def interfaces(elem_s):
return elem_s.get('interfaces', dict())
@staticmethod
def routes(elem_s):
return elem_s.get('routes', dict())
@staticmethod
def num_routes(elem_s):
return len(elem_s.get('routes', []))
|
## @file
# This file is used to define common items of class object
#
# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
## SkuInfoClass
#
# This class defined SkuInfo item used in Module/Platform/Package files
#
# @param object: Inherited from object class
# @param SkuIdName: Input value for SkuIdName, default is ''
# @param SkuId: Input value for SkuId, default is ''
# @param VariableName: Input value for VariableName, default is ''
# @param VariableGuid: Input value for VariableGuid, default is ''
# @param VariableOffset: Input value for VariableOffset, default is ''
# @param HiiDefaultValue: Input value for HiiDefaultValue, default is ''
# @param VpdOffset: Input value for VpdOffset, default is ''
# @param DefaultValue: Input value for DefaultValue, default is ''
#
# @var SkuIdName: To store value for SkuIdName
# @var SkuId: To store value for SkuId
# @var VariableName: To store value for VariableName
# @var VariableGuid: To store value for VariableGuid
# @var VariableOffset: To store value for VariableOffset
# @var HiiDefaultValue: To store value for HiiDefaultValue
# @var VpdOffset: To store value for VpdOffset
# @var DefaultValue: To store value for DefaultValue
#
class SkuInfoClass(object):
def __init__(self, SkuIdName = '', SkuId = '', VariableName = '', VariableGuid = '', VariableOffset = '',
HiiDefaultValue = '', VpdOffset = '', DefaultValue = '', VariableGuidValue = '', VariableAttribute = '', DefaultStore = None):
self.SkuIdName = SkuIdName
self.SkuId = SkuId
#
# Used by Hii
#
if DefaultStore is None:
DefaultStore = {}
self.VariableName = VariableName
self.VariableGuid = VariableGuid
self.VariableGuidValue = VariableGuidValue
self.VariableOffset = VariableOffset
self.HiiDefaultValue = HiiDefaultValue
self.VariableAttribute = VariableAttribute
self.DefaultStoreDict = DefaultStore
#
# Used by Vpd
#
self.VpdOffset = VpdOffset
#
# Used by Default
#
self.DefaultValue = DefaultValue
## Convert the class to a string
#
# Convert each member of the class to string
# Organize to a single line format string
#
# @retval Rtn Formatted String
#
def __str__(self):
Rtn = 'SkuId = ' + str(self.SkuId) + "," + \
'SkuIdName = ' + str(self.SkuIdName) + "," + \
'VariableName = ' + str(self.VariableName) + "," + \
'VariableGuid = ' + str(self.VariableGuid) + "," + \
'VariableOffset = ' + str(self.VariableOffset) + "," + \
'HiiDefaultValue = ' + str(self.HiiDefaultValue) + "," + \
'VpdOffset = ' + str(self.VpdOffset) + "," + \
'DefaultValue = ' + str(self.DefaultValue) + ","
return Rtn
def __deepcopy__(self,memo):
new_sku = SkuInfoClass()
new_sku.SkuIdName = self.SkuIdName
new_sku.SkuId = self.SkuId
new_sku.VariableName = self.VariableName
new_sku.VariableGuid = self.VariableGuid
new_sku.VariableGuidValue = self.VariableGuidValue
new_sku.VariableOffset = self.VariableOffset
new_sku.HiiDefaultValue = self.HiiDefaultValue
new_sku.VariableAttribute = self.VariableAttribute
new_sku.DefaultStoreDict = {key:value for key,value in self.DefaultStoreDict.items()}
new_sku.VpdOffset = self.VpdOffset
new_sku.DefaultValue = self.DefaultValue
return new_sku
|
def all_hillslopes(landuse, soils):
return list(landuse.domlc_d.keys())
def _identify_outcrop_mukeys(soils):
outcrop_mukeys = []
_soils = soils.subs_summary
for top in _soils:
desc = _soils[top]['desc'].lower()
if 'melody-rock outcrop' in desc or 'ellispeak-rock outcrop' in desc:
mukey = str(_soils[top]['mukey'])
outcrop_mukeys.append(mukey)
return outcrop_mukeys
def bare_or_sodgrass_or_bunchgrass_selector(landuse, soils):
domlc_d = landuse.domlc_d
topaz_ids = []
for top in domlc_d:
if domlc_d[top] in ['100', '101', '103']:
topaz_ids.append(top)
return topaz_ids
def not_shrub_and_not_outcrop_selector(landuse, soils):
domlc_d = landuse.domlc_d
domsoil_d = soils.domsoil_d
outcrop_mukeys = _identify_outcrop_mukeys(soils)
topaz_ids = []
for top in domsoil_d:
if str(domsoil_d[top]) not in outcrop_mukeys and domlc_d[top] != '104':
topaz_ids.append(top)
return topaz_ids
def shrub_and_not_outcrop_selector(landuse, soils):
domlc_d = landuse.domlc_d
domsoil_d = soils.domsoil_d
outcrop_mukeys = _identify_outcrop_mukeys(soils)
topaz_ids = []
for top in domsoil_d:
if str(domsoil_d[top]) not in outcrop_mukeys and domlc_d[top] == '104':
topaz_ids.append(top)
return topaz_ids
def not_shrub_selector(landuse, soils):
domlc_d = landuse.domlc_d
topaz_ids = []
for top in domlc_d:
if str(domlc_d[top]) != '104':
topaz_ids.append(top)
return topaz_ids
def shrub_selector(landuse, soils):
domlc_d = landuse.domlc_d
topaz_ids = []
for top in domlc_d:
if domlc_d[top] == '104':
topaz_ids.append(top)
return topaz_ids
def outcrop_selector(landuse, soils):
domsoil_d = soils.domsoil_d
outcrop_mukeys = _identify_outcrop_mukeys(soils)
topaz_ids = []
for top in domsoil_d:
if domsoil_d[top] in outcrop_mukeys:
topaz_ids.append(top)
return topaz_ids
def not_outcrop_selector(landuse, soils):
domsoil_d = soils.domsoil_d
outcrop_mukeys = _identify_outcrop_mukeys(soils)
topaz_ids = []
for top in domsoil_d:
if domsoil_d[top] not in outcrop_mukeys:
topaz_ids.append(top)
return topaz_ids
|
def is_private(pattern):
"""
Check availability of pattern.
"""
if pattern:
return pattern.startswith('_')
|
#!/usr/bin/python3
# * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved.
# *
# * SPDX-License-Identifier: LGPL-2.1-only
validate_ospf_status = 'run show protocols ospf neighbor'
validate_vpn_tunnel_status = 'run show vpn ipsec sa'
validate_vpn_ipsec_status = 'run show vpn ipsec status'
R1_pingcheck = ['R2R1interfaceIP', 'R2R3interfaceIP', 'R3R2interfaceIP']
R2_pingcheck = ['R1R2interfaceIP', 'R3R2interfaceIP']
R3_pingcheck = ['R2R3interfaceIP', 'R1R2interfaceIP', 'R2R1interfaceIP']
R1_interface_config = [
'interfaces dataplane R1H1interface address INTERFACE1IP/24',
'interfaces dataplane R1R2interface address INTERFACE2IP/24',
]
R1_interface_tunnel_config = [
'interfaces tunnel tun0 local-ip R1tunnelinterfaceLocal',
'interfaces tunnel tun0 remote-ip R1tunnelinterfaceRemote',
'interfaces tunnel tun0 encapsulation gre',
]
R1_protocol_config = ['protocols ospf area 0 network NW/24',]
R1_ipsec_vpn_config = [
'security vpn ike make-before-break',
'security vpn ipsec esp-group vm1-esp proposal 1 encryption aes128gcm128',
'security vpn ipsec esp-group vm1-esp proposal 1 hash null',
'security vpn ipsec ike-group vm1-ike ike-version 2',
'security vpn ipsec ike-group vm1-ike proposal 1 dh-group 19',
'security vpn ipsec ike-group vm1-ike proposal 1 encryption aes128gcm128',
'security vpn ipsec ike-group vm1-ike proposal 1 hash sha2_512',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP authenticat mode pre-shared-secret',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP authenticat pre-shared-secret test123',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP default-esp-group vm1-esp',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP ike-group vm1-ike ',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP local-address R1ipsecvpnlocalIP',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP tunnel 0',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP tunnel 0 local prefix R1ipsecvpnPeerLocalPrefix/24',
'security vpn ipsec site-to-site peer R1ipsecvpnpeerIP tunnel 0 remote prefix R1ipsecvpnPeerRemotePrefix/24',
]
R2_interface_config = [
'interfaces dataplane R2R1interface address INTERFACE1IP/24',
'interfaces dataplane R2R3interface address INTERFACE2IP/24',
]
R2_protocol_config = [
'protocols ospf area 0 network NW/24',
'protocols ospf area 0 network NW/24',
]
R3_interface_config = [
'interfaces dataplane R3R2interface address INTERFACE1IP/24',
'interfaces dataplane R3H2interface address INTERFACE2IP/24',
]
R3_interface_tunnel_config = [
'interfaces tunnel tun0 local-ip R3tunnelinterfaceLocal',
'interfaces tunnel tun0 remote-ip R3tunnelinterfaceRemote',
'interfaces tunnel tun0 encapsulation gre',
]
R3_protocol_config = ['protocols ospf area 0 network NW/24',]
R3_ipsec_vpn_config = [
'security vpn ike make-before-break',
'security vpn ipsec esp-group vm3-esp proposal 1 encryption aes128gcm128',
'security vpn ipsec esp-group vm3-esp proposal 1 hash null',
'security vpn ipsec ike-group vm2-ike ike-version 2',
'security vpn ipsec ike-group vm2-ike proposal 1 dh-group 19',
'security vpn ipsec ike-group vm2-ike proposal 1 encryption aes128gcm128',
'security vpn ipsec ike-group vm2-ike proposal 1 hash sha2_512',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP authenticat mode pre-shared-secret',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP authenticat pre-shared-secret test123',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP default-esp-group vm3-esp',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP ike-group vm2-ike ',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP local-address R3ipsecvpnlocalIP',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP tunnel 0',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP tunnel 0 remote prefix R3ipsecvpnPeerRemotePrefix/24',
'security vpn ipsec site-to-site peer R3ipsecvpnpeerIP tunnel 0 local prefix R3ipsecvpnPeerLocalPrefix/24',
]
|
class DeploymentConfig(object):
"""
"""
# This is very dynamic right now
# This gives me enough getters and setters for now
# TODO: have a schema of sorts.
def __init(self, **kwargs):
self.__dict__.update(kwargs)
|
def isMonotonic(array):
if not array or len(array) == 1:
return True
return monotonic(False, array) or monotonic(True, array)
def monotonic(increasing, array):
if increasing:
# check for increasing monotonic
for i in range(1, len(array)):
if array[i - 1] > array[i]:
return False
else:
# check for decreasing monotonic
for i in range(1, len(array)):
if array[i - 1] < array[i]:
return False
return True
|
# Possible values for Boolean truth checking
TRUTH = ('true', 't', 'yes', 'y', '1')
# Parent HPO-Term IDs of modifier terms
MODIFIER_IDS = {5, 12823, 40279, 31797, 32223, 32443}
|
'''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
'''
# 2018-6-17
# Generate Parenthese
# https://blog.csdn.net/zl87758539/article/details/51643837
# DFS
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.res = []
self.generateParenthesisIter('',n, n)
return self.res
def generateParenthesisIter(self, mstr, r, l,i="f"):
print(mstr,r,l,i)
if r ==0 and l==0:
self.res.append(mstr)
if l>0:
self.generateParenthesisIter(mstr+'(',r,l-1,i="s")
if r>0 and r>l:
self.generateParenthesisIter(mstr+')',r-1,l,i="t")
print(mstr,r,l,i)
# test
n = 3
test = Solution()
res = test.generateParenthesis(n)
print(res) |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])
|
# Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
# No final mostre a matriz com a formatação correta.
matriz = [[], [], []]
for c in range(0, 3):
for x in range(0, 3):
matriz[c].append(int(input(f'Valor [ {c}, {x} ]: ')))
print('-' * 30)
for c in range(0, 3):
for x in range(0, 3):
print(f'[ {matriz[c][x]} ]', end='')
print()
|
class Solution:
def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
n = len(nums)
answer = [0 for _ in range(n)]
# N.B. Nobody says maximumBit > 0
if maximumBit <= 0:
return answer
# From now on, we are assured maximumBit is a positive integer
xor_int = nums[0]
for i in range(1,n):
xor_int ^= nums[i]
# Decide k for each i below
for i in range(n):
xor_bitstr = bin(xor_int)[2:]
n_bits = len(xor_bitstr)
if n_bits >= maximumBit:
#sub_xor_bitstr = xor_bitstr[-maximumBit:]
sub_xor_int = xor_int & int("1"*maximumBit, 2)
k = ~sub_xor_int & int("1"*(len(bin(sub_xor_int))-2), 2)
else:
k_bitstr = "1"*(maximumBit - n_bits) + xor_bitstr.replace("0", "2").replace("1", "0").replace("2", "1")
k = int(k_bitstr, 2)
answer[i] = k
discarded = nums.pop()
xor_int ^= discarded
return answer
def test(nums, maximumBit, expected):
sol = getMaximumXor(nums, maximumBit)
if sol == expected:
print("Congratulations!")
else:
print(f"sol = {sol}")
print(f"expected = {expected}")
print()
if __name__ == "__main__":
test_id = 0
test_id += 1
print(f"testcase {test_id}")
nums = [0,1,1,3]
maximumBit = 2
expected = [0,3,2,3]
test(nums, maximumBit, expected)
test_id += 1
print(f"testcase {test_id}")
nums = [2,3,4,7]
maximumBit = 3
expected = [5,2,6,5]
test(nums, maximumBit, expected)
test_id += 1
print(f"testcase {test_id}")
nums = [0,1,2,2,5,7]
maximumBit = 3
expected = [4,3,6,4,6,7]
test(nums, maximumBit, expected)
|
# Time: O(n)
# Space: O(1)
class Solution:
# @param {integer[]} preorder
# @return {boolean}
def verifyPreorder(self, preorder):
low, i = float("-inf"), -1
for p in preorder:
if p < low:
return False
while i >= 0 and p > preorder[i]:
low = preorder[i]
i -= 1
i += 1
preorder[i] = p
return True
class Solution2:
# @param {integer[]} preorder
# @return {boolean}
def verifyPreorder(self, preorder):
low = float("-inf")
path = []
for p in preorder:
if p < low:
return False
while path and p > path[-1]:
low = path[-1]
path.pop()
path.append(p)
return True
|
# .gitignore should include reference to config.py
# SAVE THIS FILE AS CONFIG.PY
consumer_key = "YOUR_CONSUMER_KEY"
consumer_secret = "YOUR_CONSUMER_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"
|
# Copyright 2018 the rules_bison authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
load("@rules_m4//m4:m4.bzl", "M4_TOOLCHAIN_TYPE", "m4_toolchain")
BISON_TOOLCHAIN_TYPE = "@rules_bison//bison:toolchain_type"
BisonToolchainInfo = provider(fields = ["all_files", "bison_tool", "bison_env"])
def _template_vars(toolchain):
return platform_common.TemplateVariableInfo({
"BISON": toolchain.bison_tool.executable.path,
})
def _bison_toolchain_info(ctx):
m4 = m4_toolchain(ctx)
bison_runfiles = ctx.attr.bison_tool[DefaultInfo].default_runfiles.files
bison_env = dict(m4.m4_env)
if "M4" not in bison_env:
bison_env["M4"] = "{}.runfiles/{}/{}".format(
ctx.executable.bison_tool.path,
ctx.executable.bison_tool.owner.workspace_name,
m4.m4_tool.executable.short_path,
)
bison_env["BISON_PKGDATADIR"] = "{}.runfiles/{}/data".format(
ctx.executable.bison_tool.path,
ctx.executable.bison_tool.owner.workspace_name,
)
bison_env.update(ctx.attr.bison_env)
toolchain = BisonToolchainInfo(
all_files = depset(
direct = [ctx.executable.bison_tool],
transitive = [bison_runfiles, m4.all_files],
),
bison_tool = ctx.attr.bison_tool.files_to_run,
bison_env = bison_env,
)
return [
platform_common.ToolchainInfo(bison_toolchain = toolchain),
_template_vars(toolchain),
]
bison_toolchain_info = rule(
_bison_toolchain_info,
attrs = {
"bison_tool": attr.label(
mandatory = True,
executable = True,
cfg = "host",
),
"bison_env": attr.string_dict(),
},
provides = [
platform_common.ToolchainInfo,
platform_common.TemplateVariableInfo,
],
toolchains = [M4_TOOLCHAIN_TYPE],
)
def _bison_toolchain_alias(ctx):
toolchain = ctx.toolchains[BISON_TOOLCHAIN_TYPE].bison_toolchain
return [
DefaultInfo(files = toolchain.all_files),
_template_vars(toolchain),
]
bison_toolchain_alias = rule(
_bison_toolchain_alias,
toolchains = [BISON_TOOLCHAIN_TYPE],
provides = [
DefaultInfo,
platform_common.TemplateVariableInfo,
],
)
|
class TrieNode:
def __init__(self, char, parent=None):
self._char = char
self._word_at = {}
self._parent = parent
self._children = []
@property
def is_root(self):
return self._parent is None
@property
def is_leaf(self):
return len(self._children) == 0
@property
def char(self):
return self._char
@property
def children(self):
return self._children
@property
def parent(self):
return self._parent
@property
def word_at(self):
return self._word_at
class Trie:
def __init__(self):
self._root = TrieNode('#')
def is_empty(self):
return self._root is None
def empty(self):
self._root = TrieNode('#')
def depth(self, node):
d = 0
current_node = node
while current_node.parent is not None:
d += 1
current_node = current_node.parent
return d
def preorder(self, func):
self._preorder(self._root, func)
def _preorder(self, node, func):
func(node)
for child in node.children:
self._preorder(child, func)
def postorder(self, func: TrieNode) -> None:
self._postorder(self._root, func)
def _postorder(self, node, func):
for child in node.children:
self._postorder(child, func)
func(node)
def print_node(self, node: TrieNode) -> None:
print(node.char)
def print_trie(self):
func = self.print_node
self.preorder(func)
def add_word(self, string, file_path):
current_node = self._root
for char in string:
add_to_node = True
for child in current_node.children:
if child.char == char:
current_node = child
add_to_node = False
break
if add_to_node:
new_node = TrieNode(char, current_node)
current_node.children.append(new_node)
current_node = new_node
count_at_node = current_node.word_at.get(file_path, 0)
current_node.word_at[file_path] = count_at_node + 1
# trazi rec u trie stablu i vraca recnik koji sadrzi
# dokumente gde je rec nadjena i broj nadjenih reci u svakom dokumentu
def find_word(self, word):
string = word.lower()
current_node = self._root
for char in string:
char_found = False
for child in current_node.children:
if child.char.lower() == char:
current_node = child
char_found = True
break
if not char_found:
return {}
return current_node.word_at.copy()
|
# Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class OperationsToTest(object):
@staticmethod
def allOperations():
def add(x, y):
return x + y
def mult(x, y):
return x * y
def div(x, y):
return x / y
def sub(x, y):
return x - y
def eq(x, y):
return x == y
def ne(x, y):
return x != y
def gt(x, y):
return x > y
def lt(x, y):
return x < y
def power(x, y):
return x ** y
def xor(x, y):
return x ^ y
return [add, mult, div, sub, eq, ne, gt, lt, power, xor]
|
class ExceptionEventArgs(EventArgs):
""" Provides error exception data for media events. """
ErrorException=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the exception that details the cause of the failure.
Get: ErrorException(self: ExceptionEventArgs) -> Exception
"""
|
"""
@author: David Lei
@since: 26/08/2016
@modified:
"""
|
# Time: O(k), where k is the steps to be happy number
# Space: O(k)
# 202
# Write an algorithm to determine if a number is "happy".
#
# A happy number is a number defined by the following process:
# Starting with any positive integer, replace the number by the sum
# of the squares of its digits, and repeat the process until
# the number equals 1 (where it will stay), or it loops endlessly
# in a cycle which does not include 1. Those numbers for which
# this process ends in 1 are happy numbers.
#
# Example: 19 is a happy number
#
# 1^2 + 9^2 = 82
# 8^2 + 2^2 = 68
# 6^2 + 8^2 = 100
# 1^2 + 0^2 + 0^2 = 1
#
class Solution:
# @param {integer} n
# @return {boolean}
def isHappy(self, n): # USE THIS
lookup = set()
while n != 1 and n not in lookup:
lookup.add(n)
n = sum(int(c)**2 for c in str(n))
return n == 1
def isHappy2(self, n):
ht = set()
while n != 1 and n not in ht:
ht.add(n)
m = 0
while n:
n, p = divmod(n, 10)
m += p**2
n = m
return n == 1
print(Solution().isHappy(19)) # True |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author: liulonghui(liulonghui@gochinatv.com)
# Copyright 2017 GoChinaTV
class BaseConfig(object):
DEBUG = False
# 地址前缀
APPLICATION_ROOT = '/api/v1'
METRICS_LOG_FILE = './sensitive_work.flask.log'
# 词库路径
WORD_PATH = "/Users/vego/project/sensitiveword/keywords/keywords.txt"
# WORD_UPDATE_FREQUENCY = 30
REPLACE_CHAR = '*'
|
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-12-17 15:47:16
# @Last Modified by: 何睿
# @Last Modified time: 2018-12-17 15:47:16
class Solution:
def __init__(self):
self.res = []
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 0 or n == 0:
return 0
self.res = [[0 for _ in range(n)] for _ in range(m)]
return self.recursion(m, n)
def recursion(self, m, n):
# 递归结束条件,当到达最左边的时候或者到达最上层的时候,结束递归
if m == 1 or n == 1:
return 1
# 递归检查,检查当前位置是否已经遍历过,如果是则直接返回
if self.res[m-1][n-1] > 0:
return self.res[m-1][n-1]
# 获得走到此位置左边的走法
left = self.recursion(m, n-1)
# 获得此位置右边的走法
top = self.recursion(m-1, n)
# 记录当前位置的走法
self.res[m-1][n-1] = left+top
# 返回
return self.res[m-1][n-1]
if __name__ == "__main__":
so = Solution()
res = so.uniquePaths(7, 3)
print(res)
|
# mostrar na tela numeros pares que estão entre 1 e 50
for c in range(0, 51, 2):
print(c, end=' ')
print('FIM') |
#!/usr/bin/env python
def selection_sort(array: list):
for i in range(len(array) - 1):
min_value = min(array[i:])
min_index = array.index(min_value, i)
if min_index == i:
# already in-place
continue
else:
array[i], array[min_index] = array[min_index], array[i]
|
#
# PySNMP MIB module PDN-ENTITY-SENSOR-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-ENTITY-SENSOR-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:38:45 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")
SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion")
entPhySensorEntry, entPhySensorValue, EntitySensorValue = mibBuilder.importSymbols("ENTITY-SENSOR-MIB", "entPhySensorEntry", "entPhySensorValue", "EntitySensorValue")
pdn_common, = mibBuilder.importSymbols("PDN-HEADER-MIB", "pdn-common")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
ModuleIdentity, Counter32, NotificationType, iso, Counter64, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, IpAddress, ObjectIdentity, TimeTicks, MibIdentifier, Integer32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter32", "NotificationType", "iso", "Counter64", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "IpAddress", "ObjectIdentity", "TimeTicks", "MibIdentifier", "Integer32", "Unsigned32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
pdnEntitySensorExtMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45))
pdnEntitySensorExtMIB.setRevisions(('2003-06-06 00:00', '2003-04-24 00:00', '2003-04-16 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: pdnEntitySensorExtMIB.setRevisionsDescriptions(('Removed pdnEntPhySensorExtIndex. This object was originally added to be one of the objects each notification. However, this is redundent in that each notification object has the index as part of its instance. So the object is not needed.', 'Change the conformance/compliance section to be consistent with standard MIBs.', 'Initial release.',))
if mibBuilder.loadTexts: pdnEntitySensorExtMIB.setLastUpdated('200306060000Z')
if mibBuilder.loadTexts: pdnEntitySensorExtMIB.setOrganization('Paradyne Networks MIB Working Group Other information about group editing the MIB')
if mibBuilder.loadTexts: pdnEntitySensorExtMIB.setContactInfo('Paradyne Networks, Inc. 8545 126th Avenue North Largo, FL 33733 www.paradyne.com General Comments to: mibwg_team@paradyne.com Editors Jesus Pinto Clay Sikes')
if mibBuilder.loadTexts: pdnEntitySensorExtMIB.setDescription('This MIB module is a supplement to the ENTITY-SENSOR-MIB, RFC 3433.')
pdnEntitySensorExtNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 0))
pdnEntitySensorExtObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1))
pdnEntitySensorExtAFNs = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 2))
pdnEntitySensorExtConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3))
pdnEntPhySensorExtTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1), )
if mibBuilder.loadTexts: pdnEntPhySensorExtTable.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtTable.setDescription('This table extends the entPhySensorTable.')
pdnEntPhySensorExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1, 1), )
entPhySensorEntry.registerAugmentions(("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtEntry"))
pdnEntPhySensorExtEntry.setIndexNames(*entPhySensorEntry.getIndexNames())
if mibBuilder.loadTexts: pdnEntPhySensorExtEntry.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtEntry.setDescription('An extended entry in the entPhySensorTable.')
pdnEntPhySensorExtNotificationEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("thresholdExceeded", 0)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pdnEntPhySensorExtNotificationEnable.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtNotificationEnable.setDescription('Provides that ability to enable and disable notifications relative to objects in this table. When this bit is set, pdnEntPhySensorExtThesholdExceededSet and pdnEntPhySensorExtThesholdExceededCleared notifications should be generated. When this bit is reset, pdnEntPhySensorExtThesholdExceededSet, and pdnEntPhySensorExtThesholdExceededCleared notifications should be not be generated.')
pdnEntPhySensorExtUpperThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1, 1, 2), EntitySensorValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pdnEntPhySensorExtUpperThreshold.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtUpperThreshold.setDescription("This object sets the upper limit of a sensor's threshold. When the value of entPhySensorValue becomes greater than the value of this object, an 'Upper Threshold Exceeded' state is entered.")
pdnEntPhySensorExtLowerThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1, 1, 3), EntitySensorValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: pdnEntPhySensorExtLowerThreshold.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtLowerThreshold.setDescription("This object sets the lower limit of a sensor's threshold. When the value of entPhySensorValue becomes less than the value of this object, a 'Lower Threshold Exceeded' state is entered.")
pdnEntPhySensorExtThresholdState = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noThresholdsExceeded", 1), ("upperThresholdExceeded", 2), ("lowerThresholdExceeded", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdState.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdState.setDescription('This object returns the threshold state of the sensor.')
pdnEntPhySensorExtThresholdExceededSet = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 0, 1)).setObjects(("ENTITY-SENSOR-MIB", "entPhySensorValue"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtThresholdState"))
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdExceededSet.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdExceededSet.setDescription('This trap/notification signifies that a sensor value has exceeded its threshold limit. i.e. its entPhySensorValue is greater than its pdnEntPhySensorExtUpperThreshold or less than its pdnEntPhySensorExtLowerThreshold.')
pdnEntPhySensorExtThresholdExceededCleared = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 0, 100)).setObjects(("ENTITY-SENSOR-MIB", "entPhySensorValue"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtThresholdState"))
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdExceededCleared.setStatus('current')
if mibBuilder.loadTexts: pdnEntPhySensorExtThresholdExceededCleared.setDescription('This trap/notification signifies that a sensor value that had exceeded its threshold limit, is now operating with in its threshold limits. i.e. its entPhySensorValue is less than or equal to its pdnEntPhySensorExtUpperThreshold and greater than or equal to its pdnEntPhySensorExtLowerThreshold.')
pdnEntitySensorExtCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 1))
pdnEntitySensorExtGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2))
pdnEntitySensorExtMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 1, 1)).setObjects(("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntitySensorExtThresholdGroup"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntitySensorExtThresholdNtfyGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
pdnEntitySensorExtMIBCompliance = pdnEntitySensorExtMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: pdnEntitySensorExtMIBCompliance.setDescription('The compliance statement for pdnEntitySensorExt entities which implement the pdnEntitySensorExtMIB.')
pdnEntitySensorExtObjGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2, 1))
pdnEntitySensorExtAfnGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2, 2))
pdnEntitySensorExtNtfyGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2, 3))
pdnEntitySensorExtThresholdGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2, 1, 1)).setObjects(("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtNotificationEnable"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtUpperThreshold"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtLowerThreshold"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtThresholdState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
pdnEntitySensorExtThresholdGroup = pdnEntitySensorExtThresholdGroup.setStatus('current')
if mibBuilder.loadTexts: pdnEntitySensorExtThresholdGroup.setDescription('A collection of objects for setting and reporting thresholds.')
pdnEntitySensorExtThresholdNtfyGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 45, 3, 2, 3, 1)).setObjects(("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtThresholdExceededSet"), ("PDN-ENTITY-SENSOR-EXT-MIB", "pdnEntPhySensorExtThresholdExceededCleared"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
pdnEntitySensorExtThresholdNtfyGroup = pdnEntitySensorExtThresholdNtfyGroup.setStatus('current')
if mibBuilder.loadTexts: pdnEntitySensorExtThresholdNtfyGroup.setDescription('Notifications relative to thresholds going out of or in to specification.')
mibBuilder.exportSymbols("PDN-ENTITY-SENSOR-EXT-MIB", pdnEntitySensorExtObjects=pdnEntitySensorExtObjects, pdnEntitySensorExtConformance=pdnEntitySensorExtConformance, pdnEntitySensorExtGroups=pdnEntitySensorExtGroups, pdnEntitySensorExtNotifications=pdnEntitySensorExtNotifications, pdnEntitySensorExtObjGroups=pdnEntitySensorExtObjGroups, PYSNMP_MODULE_ID=pdnEntitySensorExtMIB, pdnEntitySensorExtMIB=pdnEntitySensorExtMIB, pdnEntPhySensorExtThresholdState=pdnEntPhySensorExtThresholdState, pdnEntPhySensorExtUpperThreshold=pdnEntPhySensorExtUpperThreshold, pdnEntitySensorExtThresholdNtfyGroup=pdnEntitySensorExtThresholdNtfyGroup, pdnEntPhySensorExtThresholdExceededCleared=pdnEntPhySensorExtThresholdExceededCleared, pdnEntitySensorExtNtfyGroups=pdnEntitySensorExtNtfyGroups, pdnEntitySensorExtAFNs=pdnEntitySensorExtAFNs, pdnEntPhySensorExtEntry=pdnEntPhySensorExtEntry, pdnEntPhySensorExtThresholdExceededSet=pdnEntPhySensorExtThresholdExceededSet, pdnEntitySensorExtAfnGroups=pdnEntitySensorExtAfnGroups, pdnEntitySensorExtThresholdGroup=pdnEntitySensorExtThresholdGroup, pdnEntPhySensorExtNotificationEnable=pdnEntPhySensorExtNotificationEnable, pdnEntPhySensorExtTable=pdnEntPhySensorExtTable, pdnEntitySensorExtMIBCompliance=pdnEntitySensorExtMIBCompliance, pdnEntPhySensorExtLowerThreshold=pdnEntPhySensorExtLowerThreshold, pdnEntitySensorExtCompliances=pdnEntitySensorExtCompliances)
|
def event( ip, table_name ):
return {
"Records": [
{
"eventID": "6d0d4899c7a77eaad208b2b0ff951846",
"eventName": "MODIFY",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "#VISITOR" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"Type": { "S": "visitor" },
"NumberSessions": { "N": "6" },
"SK": { "S": "#VISITOR" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"SequenceNumber": "40085300000000003642247411",
"SizeBytes": 91,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "f16dc2d0a70b839b910a1318f09c6925",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "VISIT#2020-12-16T17:23:30.877Z" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"App": {
"S": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) " + \
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 " + \
"Safari/605.1.15"
},
"OS": { "S": "10.15.6" },
"Device": { "S": "mac" },
"DateVisited": { "S": "2020-12-16T17:23:30.877Z" },
"DeviceType": { "S": "desktop" },
"Webkit": { "S": "605.1.15" },
"Type": { "S": "browser" },
"Version": { "S": "14.0.2" },
"SK": { "S": "VISIT#2020-12-16T17:23:30.877Z" },
"Height": { "N": "1366" },
"PK": { "S": f"VISITOR#{ ip }" },
"DateAdded": { "S": "2020-12-16T17:24:46.688Z" },
"Width": { "N": "1024" },
"Browser": { "S": "safari" }
},
"SequenceNumber": "40085400000000003642247443",
"SizeBytes": 401,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "00e86f87d57568e99f5f40cbb4d9dc6b",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "SESSION#2020-12-16T17:23:30.877Z" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"Type": { "S": "session" },
"GSI2SK": { "S": "#SESSION" },
"SK": { "S": "SESSION#2020-12-16T17:23:30.877Z" },
"TotalTime": { "N": "7.454" },
"GSI2PK": { "S": f"SESSION#{ ip }#2020-12-16T17:23:30.877Z" },
"PK": { "S": f"VISITOR#{ ip }" },
"AverageTime": { "N": "2.484666666666667" }
},
"SequenceNumber": "40085500000000003642247444",
"SizeBytes": 222,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "808a901c4ef33d8b0f97ba69cc61d500",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "VISIT#2020-12-16T17:23:30.877Z#/" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"User": { "N": "0" },
"Title": { "S": "Tyler Norlund" },
"GSI2PK": { "S": f"SESSION#{ ip }#2020-12-16T17:23:30.877Z" },
"Slug": { "S": "/" },
"PreviousSlug": { "NULL": True },
"Type": { "S": "visit" },
"GSI1PK": { "S": "PAGE#/" },
"GSI2SK": { "S": "VISIT#2020-12-16T17:23:30.877Z" },
"GSI1SK": { "S": "VISIT#2020-12-16T17:23:30.877Z" },
"SK": { "S": "VISIT#2020-12-16T17:23:30.877Z#/" },
"TimeOnPage": { "N": "2.2680000000000002" },
"NextTitle": { "S": "Website" },
"PK": { "S": f"VISITOR#{ ip }" },
"PreviousTitle": { "NULL": True },
"NextSlug": { "S": "/projects/web" }
},
"SequenceNumber": "40085600000000003642247445",
"SizeBytes": 368,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "9371f29ab879c6d339caf668c7480e62",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "VISIT#2020-12-16T17:23:33.145Z#/projects/web" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"User": { "N": "0" },
"Title": { "S": "Website" },
"GSI2PK": { "S": f"SESSION#{ ip }#2020-12-16T17:23:30.877Z" },
"Slug": { "S": "/projects/web" },
"PreviousSlug": { "S": "/" },
"Type": { "S": "visit" },
"GSI1PK": { "S": "PAGE#/projects/web" },
"GSI2SK": { "S": "VISIT#2020-12-16T17:23:33.145Z" },
"GSI1SK": { "S": "VISIT#2020-12-16T17:23:33.145Z" },
"SK": { "S": "VISIT#2020-12-16T17:23:33.145Z#/projects/web" },
"TimeOnPage": { "N": "3.5540000000000003" },
"NextTitle": { "S": "Website" },
"PK": { "S": f"VISITOR#{ ip }" },
"PreviousTitle": { "S": "Tyler Norlund" },
"NextSlug": { "S": "/projects/web" }
},
"SequenceNumber": "40085700000000003642247446",
"SizeBytes": 422,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "5df611a92e8d912aee4f7d5ae7914db5",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": {
"S": "VISIT#2020-12-16T17:23:38.331Z#/projects/web/analytics"
},
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"User": { "N": "0" },
"Title": { "S": "Analytics" },
"GSI2PK": { "S": f"SESSION#{ ip }#2020-12-16T17:23:30.877Z" },
"Slug": { "S": "/projects/web/analytics" },
"PreviousSlug": { "S": "/projects/web" },
"Type": { "S": "visit" },
"GSI1PK": { "S": "PAGE#/projects/web/analytics" },
"GSI2SK": { "S": "VISIT#2020-12-16T17:23:38.331Z" },
"GSI1SK": { "S": "VISIT#2020-12-16T17:23:38.331Z" },
"SK": {
"S": "VISIT#2020-12-16T17:23:38.331Z#/projects/web/analytics"
},
"TimeOnPage": { "NULL": True },
"NextTitle": { "NULL": True },
"PK": { "S": f"VISITOR#{ ip }" },
"PreviousTitle": { "S": "Website" },
"NextSlug": { "NULL": True }
},
"SequenceNumber": "40085800000000003642247447",
"SizeBytes": 443,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
},
{
"eventID": "acb0f8b453d27aa1b8185a3bd9e49040",
"eventName": "INSERT",
"eventVersion": "1.1",
"eventSource": "aws:dynamodb",
"awsRegion": "us-west-2",
"dynamodb": {
"ApproximateCreationDateTime": 1608053091,
"Keys": {
"SK": { "S": "VISIT#2020-12-16T17:23:36.699Z#/projects/web" },
"PK": { "S": f"VISITOR#{ ip }" }
},
"NewImage": {
"User": { "N": "0" },
"Title": { "S": "Website" },
"GSI2PK": { "S": f"SESSION#{ ip }#2020-12-16T17:23:30.877Z" },
"Slug": { "S": "/projects/web" },
"PreviousSlug": { "S": "/projects/web" },
"Type": { "S": "visit" },
"GSI1PK": { "S": "PAGE#/projects/web" },
"GSI2SK": { "S": "VISIT#2020-12-16T17:23:36.699Z" },
"GSI1SK": { "S": "VISIT#2020-12-16T17:23:36.699Z" },
"SK": { "S": "VISIT#2020-12-16T17:23:36.699Z#/projects/web" },
"TimeOnPage": { "N": "1.6320000000000001" },
"NextTitle": { "S": "Analytics" },
"PK": { "S": f"VISITOR#{ ip }" },
"PreviousTitle": { "S": "Website" },
"NextSlug": { "S": "/projects/web/analytics" }
},
"SequenceNumber": "40085900000000003642247448",
"SizeBytes": 440,
"StreamViewType": "NEW_IMAGE"
},
"eventSourceARN": "arn:aws:dynamodb:us-west-2:681647709217:table/" + \
f"{ table_name }/stream/2020-12-07T03:47:26.281"
}
]
}
|
class BibleProc:
def __init__(self):
pass
def consume(self,verses):
ret = ""
for i in verses:
out = ""
for v in i:
add = str(v[3])
if (v[0] == 'Proverbs'):
add = add.replace("\n\n","\n")
add += "\n"
out += add
ret += out+"\n\n\n"
return ret[:-3]
|
#globalVars.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2007 NVDA Contributors <http://www.nvda-project.org/>
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""global variables module
@var foregroundObject: holds the current foreground object
@type foregroundObject: L{NVDAObjects.NVDAObject}
@var focusObject: holds the current focus object
@type focusObject: L{NVDAObjects.NVDAObject}
@var mouseObject: holds the object that is at the position of the mouse pointer
@type mouseObject: L{NVDAObjects.NVDAObject}
@var mouseOldX: the last x coordinate of the mouse pointer before its current position
@type oldMouseX: int
@var mouseOldY: the last y coordinate of the mouse pointer before its current position
@type oldMouseY: int
@var navigatorObject: holds the current navigator object
@type navigatorObject: L{NVDAObjects.NVDAObject}
@var navigatorTracksFocus: if true, the navigator object will follow the focus as it changes
@type navigatorTracksFocus: boolean
"""
startTime=0
desktopObject=None
foregroundObject=None
focusObject=None
focusAncestors=[]
focusDifferenceLevel=None
mouseObject=None
mouseOldX=None
mouseOldY=None
navigatorObject=None
reviewPosition=None
reviewPositionObj=None
lastProgressValue=0
appArgs=None
appArgsExtra=None
settingsRing = None
speechDictionaryProcessing=True
exitCode=0
|
rupees=[3000, 600000, 324990909, 90990900, 30000, 5600000, 690909090, 31010101, 532010, 510, 4100]
l=len(rupees)
i=0
Crorepati=0
Lakhpati=0
Dilwale=0
while i<l:
if rupees[i]>=10000000:
Crorepati+=1
elif rupees[i]>100000:
Lakhpati+=1
else:
Dilwale+=1
i+=1
print(Crorepati,"croepati hai")
print(Lakhpati,"Lakhpati hai")
print(Dilwale,"Dilwale hai") |
DOMAIN = "ds_air"
CONF_GW = "gw"
DEFAULT_HOST = "192.168.1.103"
DEFAULT_PORT = 8008
DEFAULT_GW = "DTA117C611"
GW_LIST = ["DTA117C611", "DTA117B611"]
|
class UserModel(Tower):
@model_property
def inference(self):
def position_encoding(sentence_size, embedding_size):
"""
Position Encoding described in section 4.1 [1]
"""
encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
ls = sentence_size+1
le = embedding_size+1
for i in range(1, le):
for j in range(1, ls):
encoding[i-1, j-1] = (i - (le-1)/2) * (j - (ls-1)/2)
encoding = 1 + 4 * encoding / embedding_size / sentence_size
return np.transpose(encoding)
def memn2n(x, embeddings, weights, encoding, hops):
"""
Create model
"""
with tf.variable_scope("memn2n"):
# x has shape [batch_size, story_size, sentence_size, 2]
# unpack along last dimension to extract stories and questions
stories, questions = tf.unpack(x, axis=3)
self.summaries.append(tf.histogram_summary("stories_hist", stories))
self.summaries.append(tf.histogram_summary("questions_hist", questions))
# assume single sentence in question
questions = questions[:, 0, :]
self.summaries.append(tf.histogram_summary("question_hist", questions))
q_emb = tf.nn.embedding_lookup(embeddings['B'], questions, name='q_emb')
u_0 = tf.reduce_sum(q_emb * encoding, 1)
u = [u_0]
for _ in xrange(hops):
m_emb = tf.nn.embedding_lookup(embeddings['A'], stories, name='m_emb')
m = tf.reduce_sum(m_emb * encoding, 2) + weights['TA']
# hack to get around no reduce_dot
u_temp = tf.transpose(tf.expand_dims(u[-1], -1), [0, 2, 1])
dotted = tf.reduce_sum(m * u_temp, 2)
# Calculate probabilities
probs = tf.nn.softmax(dotted)
probs_temp = tf.transpose(tf.expand_dims(probs, -1), [0, 2, 1])
c_temp = tf.transpose(m, [0, 2, 1])
o_k = tf.reduce_sum(c_temp * probs_temp, 2)
u_k = tf.matmul(u[-1], weights['H']) + o_k
if self.is_training:
u_k = tf.nn.dropout(u_k, 0.75)
u.append(u_k)
o = tf.matmul(u_k, weights['W'])
if self.is_training:
o = tf.nn.dropout(o, 0.75)
return o
# configuration
sentence_size = self.input_shape[1]
story_size = self.input_shape[0]
embedding_size = 25
hops = 3
dict_size = 40
encoding = tf.constant(position_encoding(sentence_size, embedding_size), name="encoding")
x = tf.to_int32(tf.reshape(self.x, shape=[-1, story_size, sentence_size, 2]), name='x_int')
# model parameters
initializer = tf.random_normal_initializer(stddev=0.1)
embeddings = {
'A': tf.get_variable('A', [dict_size, embedding_size], initializer=initializer),
'B': tf.get_variable('B', [dict_size, embedding_size], initializer=initializer),
}
weights = {
'TA': tf.get_variable('TA', [story_size, embedding_size], initializer=initializer),
'H': tf.get_variable('H', [embedding_size, embedding_size], initializer=initializer),
'W': tf.get_variable('W', [embedding_size, dict_size], initializer=initializer),
}
self._nil_vars = [embeddings['A'].name, embeddings['B'].name]
self.summaries.append(tf.histogram_summary("A_hist", embeddings['A']))
self.summaries.append(tf.histogram_summary("B_hist", embeddings['B']))
self.summaries.append(tf.histogram_summary("TA_hist", weights['TA']))
self.summaries.append(tf.histogram_summary("H_hist", weights['H']))
self.summaries.append(tf.histogram_summary("W_hist", weights['W']))
self.summaries.append(tf.histogram_summary("X_hist", x))
# create model
model = memn2n(x, embeddings, weights, encoding, hops)
return model
@model_property
def loss(self):
# label has shape [batch_size, 1, story_size, sentence_size]
# assume single-word labels
y = tf.to_int64(self.y[:, 0, 0, 0], name='y_int')
self.summaries.append(tf.histogram_summary("Y_hist", y))
loss = digits.classification_loss(self.inference, y)
accuracy = digits.classification_accuracy(self.inference, y)
self.summaries.append(tf.scalar_summary(accuracy.op.name, accuracy))
return loss
def gradientUpdate(self, grads_and_vars):
def add_gradient_noise(t, stddev=1e-3, name=None):
t = tf.convert_to_tensor(t, name="t")
gn = tf.random_normal(tf.shape(t), stddev=stddev)
return tf.add(t, gn, name=name)
def zero_nil_slot(t, name=None):
t = tf.convert_to_tensor(t, name="t")
s = tf.shape(t)[1]
z = tf.zeros(tf.pack([1, s]))
return tf.concat(0, [z, tf.slice(t, [1, 0], [-1, -1])], name=name)
max_grad_norm=40.0
grads_and_vars = [(tf.clip_by_norm(g, max_grad_norm), v) for g,v in grads_and_vars]
grads_and_vars = [(add_gradient_noise(g), v) for g,v in grads_and_vars]
nil_grads_and_vars = []
for g, v in grads_and_vars:
if v.name in self._nil_vars:
print("grad zero nil slot")
g = zero_nil_slot(g)
g = tf.Print(g, [g], message="This is g: ", first_n=10, summarize=100)
nil_grads_and_vars.append((g, v))
else:
nil_grads_and_vars.append((g, v))
return nil_grads_and_vars
|
"Core exceptions raised by the LedisDB client"
class LedisError(Exception):
pass
class ServerError(LedisError):
pass
class ConnectionError(ServerError):
pass
class BusyLoadingError(ConnectionError):
pass
class TimeoutError(LedisError):
pass
class InvalidResponse(ServerError):
pass
class ResponseError(LedisError):
pass
class DataError(LedisError):
pass
class ExecAbortError(ResponseError):
pass
class TxNotBeginError(LedisError):
pass |
def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise ValueError("strands must be of equal length")
return sum([1 for (a,b) in zip(strand_a, strand_b) if a != b])
|
if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
students = sorted(students, key = lambda x: x[1])
#print(students)
#second_lowest_score = students[1][1]
second_lowest_score = sorted(list(set([x[1] for x in students])))[1]
desired_students = []
for stu in students:
if stu[1] == second_lowest_score:
desired_students.append(stu[0])
print("\n".join(sorted(desired_students)))
|
def main(j, args, params, tags, tasklet):
page = args.page
modifier = j.portal.tools.html.portalhtmlfactory.getPageModifierGridDataTables(page)
namespace = args.getTag('namespace')
category = args.getTag('category')
url = args.getTag('url')
fieldnames = args.getTag('fieldnames', '').split(',')
fieldids = args.getTag('fieldids', '').split(',')
if url:
page = modifier.addTableFromURL(url, fieldnames)
else:
page = modifier.addTableForModel(namespace, category, fieldnames, fieldids)
params.result = page
return params
def match(j, args, params, tags, tasklet):
return True
|
# Faça um Programa que converta metros para centímetros.
metros = float(input("Digite a quantidade de metros: "))
centimetros = metros * 100
print(metros, "metros é igual a ", centimetros, "centimetros")
|
def check_prime(number):
# Check individual integers for prime
if number == 1:
return False
if number == 2 or number == 3:
return True
if number % 2 == 0 or number % 3 == 0:
return False
# For numbers larger than equal to 5, check for prime
i = 5
while i*i <= number:
if number % i == 0 or number % (i+2) == 0:
return False
i += 6
return True
if __name__ == "__main__":
# Read integer input from stdin
T = int(input())
for _ in range(T):
# Read input integer from stdin
n = int(input())
# Check for prime
if check_prime(n) == True:
print("Prime")
else:
print("Not prime")
|
# Time: O(n)
# Space: O(1)
# 309
# Say you have an array for which the ith element is the price of
# a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete as
# many transactions as you like (ie, buy one and sell one share of the
# stock multiple times) with the following restrictions:
#
# You may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).
# After you sell your stock, you cannot buy stock on next day.
# (ie, cooldown 1 day)
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
# three states buy/sell/coolDown can be simplified as 2 states own/notOwn
class Solution(object):
# only relay on the balance of past two days
# holdpre, hold: balance if own stock in previous day and current day
# cashpre, cash: balance if not own stock in previous day and current day
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
holdpre = -prices[0]
hold = max(-prices[0], -prices[1])
cashpre = 0
cash = max(0, prices[1]-prices[0])
for p in prices[2:]:
holdpre, cashpre, hold, cash = hold, cash, max(hold, cashpre-p), max(cash, hold+p)
return max(cash, hold)
# or more clear with a rotating array
# notOwn[i]表示在第i天不持有股票所能获得的最大累计收益
# own[i]表示在第i天持有股票所能获得的最大累计收益
# also do space optimization
def maxProfit_rotatingArray(self, prices):
N = len(prices)
if N < 2:
return 0
own = [-prices[0], max(-prices[0], -prices[1]), 0]
notOwn = [0, max(0, prices[1]-prices[0]), 0]
for i in range(2, N):
notOwn[i%3] = max(notOwn[(i-1)%3], own[(i-1)%3] + prices[i])
own[i%3] = max(own[(i-1)%3], notOwn[(i-2)%3] - prices[i])
return notOwn[(N-1)%3]
# 3 states
def maxProfit_kamyu(self, prices):
if not prices:
return 0
buy, sell, coolDown = [0] * 2, [0] * 2, [0] * 2
buy[0] = -prices[0]
for i in xrange(1, len(prices)):
# Bought before or buy today.
buy[i % 2] = max(buy[(i - 1) % 2],
coolDown[(i - 1) % 2] - prices[i])
# Sell today.
sell[i % 2] = buy[(i - 1) % 2] + prices[i]
# Sold before yesterday or sold yesterday.
coolDown[i % 2] = max(coolDown[(i - 1) % 2], sell[(i - 1) % 2])
return max(coolDown[(len(prices) - 1) % 2],
sell[(len(prices) - 1) % 2])
print(Solution().maxProfit([1, 2, 3, 0, 2])) # 3 = [buy, sell, cooldown, buy, sell]
|
class Column:
def __init__(self, name='', type=None, equivalences=None):
self._name = name
if not type:
type = []
self._type = type
if not equivalences:
equivalences = []
self._equivalences = equivalences
self.primary = False
self.foreign = False
@property
def name(self):
return self._name
@property
def type(self):
return self._type
def add_type(self, type):
self.type.append(type)
@property
def equivalences(self):
return self._equivalences
def add_equivalence(self, equivalence):
self.equivalences.append(equivalence)
def is_equivalent(self, word):
if word in self.equivalences:
return True
else:
return False
def is_primary(self):
return self.primary
def set_as_primary(self):
self.primary = True
def is_foreign(self):
return self.foreign
def set_as_foreign(self, references):
self.foreign = references
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
arr = sorted ( arr )
diff = 10 ** 20
for i in range ( n - 1 ) :
if arr [ i + 1 ] - arr [ i ] < diff :
diff = arr [ i + 1 ] - arr [ i ]
return diff
#TOFILL
if __name__ == '__main__':
param = [
([3, 25, 44, 46, 54, 60, 81],3,),
([82, 68, -98, -66, -36, -42, 98, -38, 58, -6, -28, 70, -24, 18, 16, 10, 92, 44, 28, -96, -72, 24, 28, -80, -4, 38, 88, 76],22,),
([1, 1, 1],2,),
([87, 25, 80, 45, 44, 20, 48, 47, 51, 54, 68, 47, 89, 95, 15, 29, 5, 45, 2, 64, 53, 96, 94, 22, 23, 43, 61, 75, 74, 50],15,),
([-74, -48, -42, -26, -16, -12, 0, 4, 8, 18, 46, 46, 62, 70, 74, 88, 92, 96, 98],18,),
([0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0],36,),
([27, 42, 59, 80],2,),
([-96, -94, 10, -36, 18, -40],4,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1],12,),
([96],0,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class PodInfo_PodSpec_VolumeInfo_FC(object):
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model.
Fibre channel volumes
Attributes:
fs_type (string): TODO: Type description here.
lun (int): TODO: Type description here.
target_wwn_s (list of string): Array of Fibre Channel target's
World Wide Names
"""
# Create a mapping from Model property names to API property names
_names = {
"fs_type":'fsType',
"lun":'lun',
"target_wwn_s":'targetWWNs'
}
def __init__(self,
fs_type=None,
lun=None,
target_wwn_s=None):
"""Constructor for the PodInfo_PodSpec_VolumeInfo_FC class"""
# Initialize members of the class
self.fs_type = fs_type
self.lun = lun
self.target_wwn_s = target_wwn_s
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
fs_type = dictionary.get('fsType')
lun = dictionary.get('lun')
target_wwn_s = dictionary.get('targetWWNs')
# Return an object of this model
return cls(fs_type,
lun,
target_wwn_s)
|
################################################################################# SUJET DM3 ################################################################################
#GERBER Zoé 20183203
#TIJANI Lobna 20181449
#MARTIN Fanny 20181851
#LEMERCIER Camille 20180595
###Enoncé###:
"""
A partir d'une séquence nucléotidique, vous recherchez tous les orfs dans les 3 phases directes,ainsi que celles sur le brin reverse complémentaire.
Vous donnerez les coordonnées de tous les orfs trouvés ainsi que leur séquence, leur longueur et leur traduction.
Commence avec ATG, se termine par TAG ou TAA ou TGA et doit tenir compte de la séquence à partir du premier caractère, puis la deuxième, puis de troisième
"""
#Définition d'un ORF sur wikipédia:
"""
En génétique moléculaire, un cadre de lecture ouvert, ou phase ouverte de lecture (open reading frame ou ORF en anglais)
est une partie d'un cadre de lecture susceptible d'être traduit en protéine ou en peptide.
C'est une suite de codons comprenant le codon start et un codon stop
Un codon d'initiation AUG du cadre de lecture ouvert — codon qui n'est pas nécessairement le 1er de celui-ci — peut indiquer le début de la traduction.
Le site de terminaison de la transcription est situé après le cadre de lecture ouvert, au-delà du codon stop.
La notion de cadre de lecture ouvert est très utilisée pour la prédiction de gènes.
Chaque séquence d'ADN peut contenir trois cadres de lecture décalés d'un nucléotide les uns par rapport aux autres (+1 ou -1).
Sur l'ADN, il peut y avoir transcription en ARN de l'un ou l'autre des 2 brins, ce qui conduit à un total de 6 cadres de lecture.
"""
##############Début du programme##############
#On rentre tout d'abord une séquence nucleotidique(ADN);
seqADN = input("Entrez une séquence nucléotidique : ")
print("\n")
#On vérifie si la séquence donnée est valide :
seqADN = seqADN.upper()
def verif (adn):
i=0
erreur = 0
for i in adn :
if not (( i == 'A' ) or ( i == 'T' ) or ( i == 'C' ) or ( i == 'G' )):
erreur = erreur + 1
return (erreur)
erreur = verif(seqADN)
if (verif(seqADN) == 0):#il n'y a donc aucune erreur dans la sequence donnée.
print (seqADN, "est valide \n")
else:
print (seqADN , "n'est pas une sequence valide")
print ("il y a ", erreur , "erreur(s) dans cette séquence \n")
#Creation de la séquence de l'ADN complémentaire :
def seqADNc (adn):
i=0
seqADNcompl = ""
for i in adn :
if (i == "A"):
seqADNcompl = seqADNcompl + "T"
elif (i == "T" ):
seqADNcompl = seqADNcompl + "A"
elif (i == "C"):
seqADNcompl = seqADNcompl + "G"
else :
seqADNcompl = seqADNcompl + "C"
return (seqADNcompl)
#Séquence du brin complémentaire
seqADNcompl=seqADNc(seqADN)
if (verif(seqADN) == 0):#affiche seulement si la séquence d'ADN donnée est valide.
print ("la sequence d'ADN complémentaire à notre sequence de base est : ", seqADNcompl,"\n")
#Création de la séquence reverse complémentaire :
def reverseC(adn):
i=0
seqADNrc = ""
for i in adn :
if (i == "A"):
seqADNrc = "A" + seqADNrc
elif (i == "T" ):
seqADNrc = "T" + seqADNrc
elif (i == "C"):
seqADNrc = "C" + seqADNrc
else :
seqADNrc = "G" + seqADNrc
return (seqADNrc)
#séquence du brin reverse complémentaire:
seqADNrc = reverseC(seqADNcompl)
if (verif(seqADN) == 0):#affiche seulement si la séquence d'ADN donnée est valide.
print ("la sequence d'ADN reverse complémentaire est : ", seqADNrc,"\n")
#Transcription de la sequence d'ADN en ARNmessager;
"""changer les T en U"""
def transcription (adn):
i=0
seqARN = ""
for i in adn :
if (i == "A"):
seqARN = seqARN + "A"
elif (i == "T" ):
seqARN = seqARN + "U"
elif (i == "C"):
seqARN = seqARN + "C"
else :
seqARN = seqARN + "G"
return (seqARN)
#séquence ARN du brin direct:
seqARN = transcription(seqADN)
if (verif(seqADN) == 0):#affiche seulement si la séquence d'ADN donnée au debut est valide.
print ("la sequence d'ARN transcrite est : ", seqARN ,"\n")
#sequence ARN du brin reverse complémentaire:
SeqARNrc = transcription(seqADNrc)
if (verif(seqADN) == 0):#affiche seulement si la séquence d'ADN donnée au debut est valide.
print("la sequence ARN a partir du reverse complementaire:",SeqARNrc,"\n \n\n")
#Création du code génétique
#afin de permettre la traduction de l'ARNm
codeGene = { "UUU" : "F",
"UCU" : "S",
"UAU" : "Y",
"UGU" : "C",
"UUC" : "F",
"UCC" : "S",
"UAC" : "Y",
"UGC" : "C",
"UUA" : "L",
"UCA" : "S",
"UAA" : "stop",
"UGA": "stop",
"UUG": "L",
"UCG": "S",
"UAG": "stop",
"UGG": "W",
"CUU": "L",
"CCU": "P",
"CAU": "H",
"CGU": "R",
"CUC": "L",
"CCC": "P",
"CAC": "H",
"CGC": "R",
"CUA": "L",
"CCA": "P",
"CAA": "Q",
"CGA": "R",
"CUG": "L",
"CCG": "P",
"CAG": "Q",
"CGG": "R",
"AUU": "I",
"ACU": "T",
"AAU": "N",
"AGU": "S",
"AUC": "I",
"ACC": "T",
"AAC": "N",
"AGC": "S",
"AUA": "I",
"ACA": "T",
"AAA": "K",
"AGA": "R",
"AUG": "M",
"ACG": "T",
"AAG": "K",
"AGG": "R",
"GUU": "V",
"GCU": "A",
"GAU": "D",
"GGU": "G",
"GUC": "V",
"GCC": "A",
"GAC": "D",
"GGC": "G",
"GUA": "V",
"GCA": "A",
"GAA": "E",
"GGA": "G",
"GUG": "V",
"GCG": "A",
"GAG": "E",
"GGG": "G",
}
#######################################Traduction en proteine#################################################
taille=3
#création des fonctions qui permettent de commencer a traduire l'ARNm au premier codon start pour les trois différentes phases :
#Phase1#
def init1(arn):
i=0
seqARNtrad1=""
for i in range(0,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
seqARNtrad1= arn[i:]
break
return(seqARNtrad1)
#Phase 2#
def init2(arn):
i=0
seqARNtrad2=""
for i in range(1,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
seqARNtrad2= arn[i:]
break
return (seqARNtrad2)
#Phase 3#
def init3(arn):
i=0
seqARNtrad3=""
for i in range(2,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
seqARNtrad3= arn[i:]
break
return (seqARNtrad3)
#création fonctions fin ORF, dans la phase 1(a partir de la sequence qui commence par un ATG):
def FinSeq(arn):
i=0
SeqStop1=""
for i in range(0,len(arn),3):
codon=arn[i:i+3]
if ((codon=="UAG")or (codon=="UGA")or(codon=="UAA")):
SeqStop1=arn[:i]
break
elif ((codon!="UAG")or (codon!="UGA")or(codon!="UAA")):
SeqStop1=arn
return (SeqStop1)
#Création de la fonction qui permet la traduction des séquences qui commence par un AUG :
def tradC(arn):
i=0
prot = ""
for i in range(0,len(arn)-taille+1,3) :
codon = arn[i:i+taille]
prot = prot + codeGene[codon]
if ("stop" in prot):
break
return (prot)
#Création des 3 fonctions pour determiner les debuts des ORF:
"""permet de resortir la coordonnée du A du codon start"""
#Phase 1
def debutORF1(arn):
i=0
debut1=0
for i in range(0,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
debut1= i+1#car le i correspond a un chiffre en dessous de celui voulu.
break
elif(codon!="AUG"):
debut1=0
return (debut1)
#Phase 2
def debutORF2(arn):
i=0
debut2=0
for i in range(1,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
debut2= i+1#car le i correspond a un chiffre en dessous de celui voulu.
break
elif(codon!="AUG"):
debut2=0
return (debut2)
#Phase3
def debutORF3(arn):
i=0
debut3=0
for i in range(2,len(arn),3):
codon=arn[i:i+3]
if (codon=="AUG"):
debut3= i+1#car le i correspond a un chiffre en dessous de celui voulu.
break
elif(codon!="AUG"):
debut3=0
return (debut3)
####fin des fonctions.
###Les proteines sur l'ARNm
#appel des fonctions pour sequences a traduire
""" création des sequences qui commence par un AUG dans les trois phases du brin direct"""
seqARN1 = init1(seqARN)#phase1
seqARN2 = init2(seqARN)#phase2
seqARN3 = init3(seqARN)#phase3
""" création des séquences a traduire, qui commence a partir du codon start et qui finisse avant le codon stop dans les trois phases """
seqARNtrad1=FinSeq(seqARN1)#phase1
seqARNtrad2=FinSeq(seqARN2)#phase2
seqARNtrad3=FinSeq(seqARN3)#phase3
#appel des fonctions pour debut ORF
"""permet de ressortir les coordonnées du A du codon start """
debut1=0
debut1=debutORF1(seqARN)#phase1
debut2=0
debut2=debutORF2(seqARN)#phase2
debut3=0
debut3=debutORF3(seqARN)#phase3
#appel des fonctions pour fin ORF:
""" permet de recupérer les coordonnées du dernier nucleotides avant le codon stop trouvé dans les trois phases différentes
calcul de la taille de la sequence a traduire, on y ajoutera le nombre i, coordonnée du A afin de rajouter le debut de la séquence que nous avons precedement enlevé."""
fin1=0
fin1=len(seqARNtrad1)#phase1
fin2=0
fin2=len(seqARNtrad2)#phase2
fin3=0
fin3=len(seqARNtrad3)#phase3
### ARNm ###
if (verif(seqADN) == 0):#affiche seulement si la sequence d'ADN donnée est valide.
print("-->les proteines sur l'ARNm\n \n")
#Proteine1
prot1 = tradC(seqARNtrad1)
print("-Proteine en phase 1:\n")
if len(prot1)==0:
print("il n'y a pas de codon start dans la phase 1 du brin direct donc, pas de proteine dans cette phase.")
elif len(prot1)!=0:
print("sequence à traduire en phase 1 :",(seqARNtrad1))
print ("La protéine 1 traduite selon le 1er ORF est : " , prot1)
print ("La longueur de la proteine 1 est de ",len(prot1), "acide(s) aminé(s)")
if ((fin1+debut1-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut1,"ème nucléotide, et la fin au ",(fin1+debut1-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut1,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n")
#Proteine2
prot2 = tradC(seqARNtrad2)
print("-Proteine en phase 2:\n")
if len(prot2)==0:
print("il n'y a pas de codon start dans la phase 2 du brin direct donc, pas de proteine dans cette phase.")
elif len(prot2)!=0:
print("sequence à traduire en phase 2 :",(seqARNtrad2))
print ("La protéine 2 traduite selon le 2eme ORF est : " , prot2)
print ("La longueur de la proteine 2 est de ",len(prot2), "acide(s) aminé(s)")
if ((fin2+debut2-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut2,"ème nucléotide, et la fin au ",(fin2+debut2-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut2,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n")
#Proteine3
prot3 = tradC(seqARNtrad3)
print("-Proteine en phase 3:\n")
if len(prot3)==0:
print("il n'y a pas de codon start dans la phase 3 du brin direct donc, pas de proteine dans cette phase.")
elif len(prot3)!=0:
print("sequence à traduire en phase 3 :",(seqARNtrad3))
print ("La protéine 3 traduite selon le 3eme ORF est : " , prot3)
print ("La longueur de la proteine 3 est de ",len(prot3), "acide(s) aminé(s)")
if ((fin3+debut3-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut3,"ème nucléotide, et la fin au ",(fin3+debut3-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut3,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n\n\n")
##Les proteines sur l'ADN reverse complementaire##
#Transcription du reverse complementaire#
#Appel des fonctions pour creer la sequence a traduire
""" commencer a un AUG dans les trois différentes phases"""
seqARN1rc = init1(SeqARNrc)#phase1
seqARN2rc = init2(SeqARNrc)#phase2
seqARN3rc = init3(SeqARNrc)#phase3
""" finir avant le codon stop pour les trois phases également"""
seqARNtrad1rc=FinSeq(seqARN1rc)#phase1
seqARNtrad2rc=FinSeq(seqARN2rc)#phase2
seqARNtrad3rc=FinSeq(seqARN3rc)#phase3
#appel des fonctions pour debut ORF
debut1rc=0
debut1rc=debutORF1(SeqARNrc)#phase1
debut2rc=0
debut2rc=debutORF2(SeqARNrc)#phase2
debut3rc=0
debut3rc=debutORF3(SeqARNrc)#phase3
#appel des fonctions pour fin ORF:
fin1rc=0
fin1rc=len(seqARNtrad1rc)#phase1
fin2rc=0
fin2rc=len(seqARNtrad2rc)#phase2
fin3rc=0
fin3rc=len(seqARNtrad3rc)#phase3
## ARN reverse complémentaire ##
if (verif(seqADN) == 0):#si la sequence d'ADN donnée n'est pas valide, cela n'affichera rien.
print("-->les proteines sur l'ARNm du reverse complémentaire:\n \n")
#Proteine1
print("-Proteine en phase 1:\n")
prot1rc = tradC(seqARNtrad1rc)
if len(prot1rc)==0:
print("il n'y a pas de codon start dans la phase 1 du brin reverse complémentaire donc, pas de proteine dans cette phase.")
elif len(prot1rc)!=0:
print("sequence à traduire en phase 1 :",(seqARNtrad1rc))
print ("La protéine 1 traduite selon le 1er ORF est : " , prot1rc)
print ("La longueur de la proteine 1 est de ",len(prot1rc), "acide(s) aminé(s)")
if ((fin1rc+debut1rc-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut1rc,"ème nucléotide, et la fin au ",(fin1rc+debut1rc-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut1rc,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n")
#Proteine2
print("-Proteine en phase 2:\n")
prot2rc = tradC(seqARNtrad2rc)
if len(prot2rc)==0:
print("il n'y a pas de codon start dans la phase 2 du brin reverse complémentaire donc, pas de proteine dans cette phase.")
elif len(prot2rc)!=0:
print("sequence à traduire en phase 2 :",(seqARNtrad2rc))
print ("La protéine 2 traduite selon le 2eme ORF est : " , prot2rc)
print ("La longueur de la proteine 2 est de ",len(prot2rc), "acide(s) aminé(s)")
if ((fin2rc+debut2rc-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut2rc,"ème nucléotide, et la fin au ",(fin2rc+debut2rc-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut2rc,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n")
#Proteine3
print("-Proteine en phase 3:\n")
prot3rc = tradC(seqARNtrad3rc)
if len(prot3rc)==0:
print("il n'y a pas de codon start dans la phase 3 du brin reverse complémentaire donc, pas de proteine dans cette phase.")
elif len(prot3rc)!=0:
print("sequence à traduire en phase 3 :",(seqARNtrad3rc))
print ("La protéine 3 traduite selon le 3eme ORF est : " , prot3rc)
print ("La longueur de la proteine 3 est de ",len(prot3rc), "acide(s) aminé(s)")
if ((fin3rc+debut3rc-1)!=len(seqARN)):
print(" le debut de cet ORF est au ",debut3rc,"ème nucléotide, et la fin au ",(fin3rc+debut3rc-1), "ème nucléotide")
else:
print(" le debut de cet ORF est au ",debut3rc,"ème nucléotide, et la fin au ",len(seqADN), "ème nucléotide, (la fin de la sequence, il n'y a pas de codon stop)")
print("\n\n")
|
#!/usr/bin/env python3
with open("input.txt", "r") as f:
num = []
for elem in f.read().split(","):
num.append(int(elem))
for _ in range(0, 80):
new_num = []
for elem in num:
if elem == 0:
new_num.append(8)
new_num.append(6)
else:
new_num.append(elem - 1)
num = new_num
print(len(num))
|
class Other:
def __init__(self, name2):
self.name2 = name2
def get_name2(self):
return self.name2
@staticmethod
def decode(data):
f_name2 = data["name2"]
if not isinstance(f_name2, str):
raise Exception("not a string")
return Other(f_name2)
def encode(self):
data = dict()
if self.name2 is None:
raise Exception("name2: is a required field")
data["name2"] = self.name2
return data
def __repr__(self):
return "<Other name2:{!r}>".format(self.name2)
|
"""
Ejercicio 2
===========
"""
try:
n1 = float(input('Enter the first number: '))
n2 = float(input('Enter the second number: '))
op = str(input('Enter the operator (+,-,*,/): '))
if op == '+':
res = n1 + n2
elif op == '-':
res = n1 - n2
elif op == '*':
res = n1 * n2
elif op == '/':
res = n1 / n2
else:
print('Invalid operator selected')
print('The final result is {}'.format(res))
except ValueError:
print('Invalid numbers selected!') |
data = [
{
'id': 1,
'name': 'One cool plane',
'wings': 5,
},
{
'id': 2,
'name': 'One very cool plane',
'wings': 8,
},
{
'id': 3,
'name': 'Boring plane',
'wings': 2,
},
]
|
class Source:
'''
Source class to define source objects
'''
def __init__(self,id,name,description,url,category,language,country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.language = language
self.country = country
class Article:
'''
Class that instantiates objects of the news article objects of the news sources
'''
def __init__(self,id,name,author,title,description,url,urlToImage,publishedAt):
self.id = id
self.name = name
self.author = author
self.title = title
self.description = description
self.url = url
self.urlToImage = urlToImage
self.publishedAt = publishedAt
class Category:
'''
Class that instantiates objects of the news categories objects of the news sources
'''
def __init__(self,author,description,time,url,image,title):
self.author = author
self.description = description
self.time = time
self.url = url
self.image = image
self.title = title
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.