content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
#!/usr/bin/env python3
n = int(input())
i = 1
while i < n + 1:
if i % 3 == 0 and i % 5 != 0:
print("fizz")
elif i % 5 == 0 and i % 3 != 0:
print("buzz")
elif i % 5 == 0 and i % 3 == 0:
print("fizz-buzz")
else:
print(i)
i = i + 1
|
n = int(input())
i = 1
while i < n + 1:
if i % 3 == 0 and i % 5 != 0:
print('fizz')
elif i % 5 == 0 and i % 3 != 0:
print('buzz')
elif i % 5 == 0 and i % 3 == 0:
print('fizz-buzz')
else:
print(i)
i = i + 1
|
def _printf(fh, fmt, *args):
"""Implementation of perl $fh->printf method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
print(_format(fmt, *args), end='', file=fh)
return True
except Exception as _e:
OS_ERROR = str(_e)
if TRACEBACK:
if isinstance(fmt, str):
fmt = fmt.replace("\n", '\\n')
_cluck(f"printf({fmt},...) failed: {OS_ERROR}",skip=2)
if AUTODIE:
raise
return False
|
def _printf(fh, fmt, *args):
"""Implementation of perl $fh->printf method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
print(_format(fmt, *args), end='', file=fh)
return True
except Exception as _e:
os_error = str(_e)
if TRACEBACK:
if isinstance(fmt, str):
fmt = fmt.replace('\n', '\\n')
_cluck(f'printf({fmt},...) failed: {OS_ERROR}', skip=2)
if AUTODIE:
raise
return False
|
region = 'us-west-2'
vpc = dict(
source='./vpc'
)
inst = dict(
source='./inst',
vpc_id='${module.vpc.vpc_id}'
)
config = dict(
provider=dict(
aws=dict(region=region)
),
module=dict(
vpc=vpc,
inst=inst
)
)
|
region = 'us-west-2'
vpc = dict(source='./vpc')
inst = dict(source='./inst', vpc_id='${module.vpc.vpc_id}')
config = dict(provider=dict(aws=dict(region=region)), module=dict(vpc=vpc, inst=inst))
|
{
"targets": [
{
"target_name": "userid",
"sources": [ '<!@(ls -1 src/*.cc)' ],
"include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"],
"dependencies": ["<!(node -p \"require('node-addon-api').gyp\")"],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"CLANG_CXX_LIBRARY": "libc++",
"MACOSX_DEPLOYMENT_TARGET": "10.7",
},
"msvs_settings": {
"VCCLCompilerTool": { "ExceptionHandling": 1 },
},
"variables" : {
"generate_coverage": "<!(echo $GENERATE_COVERAGE)",
},
"conditions": [
['OS=="mac"', {
"cflags+": ["-fvisibility=hidden"],
"xcode_settings": {
"GCC_SYMBOLS_PRIVATE_EXTERN": "YES", # -fvisibility=hidden
},
}],
['generate_coverage=="yes"', {
"cflags+": ["--coverage"],
"cflags_cc+": ["--coverage"],
"link_settings": {
"libraries+": ["-lgcov"],
},
}],
],
},
],
}
|
{'targets': [{'target_name': 'userid', 'sources': ['<!@(ls -1 src/*.cc)'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7'}, 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'variables': {'generate_coverage': '<!(echo $GENERATE_COVERAGE)'}, 'conditions': [['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES'}}], ['generate_coverage=="yes"', {'cflags+': ['--coverage'], 'cflags_cc+': ['--coverage'], 'link_settings': {'libraries+': ['-lgcov']}}]]}]}
|
"""
Single linked list based on two pointer approach.
"""
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class slist:
"""
singly linked list class
"""
def __init__(self):
self._first = None
self._last = None
def _build_a_node(self, i: int, append:bool=True):
n = Node(val=i)
# Handle empty list case
if self._first is None and self._last is None:
self._first = n
self._last = n
else:
if append:
self._last.next = n
self._last = n
else:
n.next = self._first
self._first = n
def _find(self, x: int):
nodes = [self._first, None]
while nodes[0] != None:
if nodes[0].val == x:
return nodes
nodes[1] = nodes[0]
nodes[0] = nodes[0].next
return nodes
def append(self, i:int):
self._build_a_node(i)
def build_slist_from_list(self, a:list):
for i in a:
self.append(i)
def find(self, x:int):
nodes = self._find(x)
if nodes[0]:
return True
else:
return False
def delete(self, x:int):
nodes = self._find(x)
# in case of node found
if(nodes[0]):
currentnode = nodes[0]
previousnode = nodes[1]
# list has only one element and that element is x
if currentnode == self._first and currentnode == self._last and previousnode == None:
self._first = None
self._last = None
# x at first position and being removed
elif currentnode == self._first:
self._first = currentnode.next
# x at last position
elif currentnode == self._last:
previousnode.next = None
self._last = previousnode
# x is in between
else:
previousnode.next = currentnode.next
def reverse(self):
c = self._first
self._last = self._first
p = None
while c != None:
n = c.next
c.next = p
p = c
c = n
self._first = p
def has_a_cycle(self):
"""
find linked list has a cycle or not
:return:
"""
if self._first == None or self._first.next == None:
return False
ptr1 = self._first
ptr2 = self._first.next
while ptr1 != ptr2:
if ptr2 == None or ptr2.next == None:
return False
ptr1 = ptr1.next
ptr2 = ptr2.next.next
return True
def find_mid_point(self):
ptr1 = self._first
ptr2 = self._first
while(ptr2.next != None):
ptr1 = ptr1.next
ptr2 = ptr2.next.next
return ptr1.val
def __str__(self):
s = ""
n = self._first
# in case slist is empty
if n == None:
s = s + "Null"
# for other cases
while n != None:
s = s + str(n.val)
if n.next is not None:
s = s + "->"
else:
s = s + '->Null'
n = n.next
return s
def __len__(self):
l = 0
n = self._first
if not n:
return l
else:
while n is not None:
l +=1
n = n.next
return l
if __name__ == '__main__':
a = [1, 2, 3, 4, 5, 12, 6, 7, 8, 10, 10]
s = slist()
s.build_slist_from_list(a)
print(s.has_a_cycle())
|
"""
Single linked list based on two pointer approach.
"""
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Slist:
"""
singly linked list class
"""
def __init__(self):
self._first = None
self._last = None
def _build_a_node(self, i: int, append: bool=True):
n = node(val=i)
if self._first is None and self._last is None:
self._first = n
self._last = n
elif append:
self._last.next = n
self._last = n
else:
n.next = self._first
self._first = n
def _find(self, x: int):
nodes = [self._first, None]
while nodes[0] != None:
if nodes[0].val == x:
return nodes
nodes[1] = nodes[0]
nodes[0] = nodes[0].next
return nodes
def append(self, i: int):
self._build_a_node(i)
def build_slist_from_list(self, a: list):
for i in a:
self.append(i)
def find(self, x: int):
nodes = self._find(x)
if nodes[0]:
return True
else:
return False
def delete(self, x: int):
nodes = self._find(x)
if nodes[0]:
currentnode = nodes[0]
previousnode = nodes[1]
if currentnode == self._first and currentnode == self._last and (previousnode == None):
self._first = None
self._last = None
elif currentnode == self._first:
self._first = currentnode.next
elif currentnode == self._last:
previousnode.next = None
self._last = previousnode
else:
previousnode.next = currentnode.next
def reverse(self):
c = self._first
self._last = self._first
p = None
while c != None:
n = c.next
c.next = p
p = c
c = n
self._first = p
def has_a_cycle(self):
"""
find linked list has a cycle or not
:return:
"""
if self._first == None or self._first.next == None:
return False
ptr1 = self._first
ptr2 = self._first.next
while ptr1 != ptr2:
if ptr2 == None or ptr2.next == None:
return False
ptr1 = ptr1.next
ptr2 = ptr2.next.next
return True
def find_mid_point(self):
ptr1 = self._first
ptr2 = self._first
while ptr2.next != None:
ptr1 = ptr1.next
ptr2 = ptr2.next.next
return ptr1.val
def __str__(self):
s = ''
n = self._first
if n == None:
s = s + 'Null'
while n != None:
s = s + str(n.val)
if n.next is not None:
s = s + '->'
else:
s = s + '->Null'
n = n.next
return s
def __len__(self):
l = 0
n = self._first
if not n:
return l
else:
while n is not None:
l += 1
n = n.next
return l
if __name__ == '__main__':
a = [1, 2, 3, 4, 5, 12, 6, 7, 8, 10, 10]
s = slist()
s.build_slist_from_list(a)
print(s.has_a_cycle())
|
algorithm_defaults = {
'ERM': {
'train_loader': 'standard',
'uniform_over_groups': False,
'eval_loader': 'standard',
'randaugment_n': 2, # When running ERM + data augmentation
},
'groupDRO': {
'train_loader': 'standard',
'uniform_over_groups': True,
'distinct_groups': True,
'eval_loader': 'standard',
'group_dro_step_size': 0.01,
},
'deepCORAL': {
'train_loader': 'group',
'uniform_over_groups': True,
'distinct_groups': True,
'eval_loader': 'standard',
'coral_penalty_weight': 1.,
'randaugment_n': 2,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled & unlabeled examples
},
'IRM': {
'train_loader': 'group',
'uniform_over_groups': True,
'distinct_groups': True,
'eval_loader': 'standard',
'irm_lambda': 100.,
'irm_penalty_anneal_iters': 500,
},
'DANN': {
'train_loader': 'group',
'uniform_over_groups': True,
'distinct_groups': True,
'eval_loader': 'standard',
'randaugment_n': 2,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled & unlabeled examples
},
'AFN': {
'train_loader': 'standard',
'uniform_over_groups': False,
'eval_loader': 'standard',
'use_hafn': False,
'afn_penalty_weight': 0.01,
'safn_delta_r': 1.0,
'hafn_r': 1.0,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled & unlabeled examples
'randaugment_n': 2,
},
'FixMatch': {
'train_loader': 'standard',
'uniform_over_groups': False,
'eval_loader': 'standard',
'self_training_lambda': 1,
'self_training_threshold': 0.7,
'scheduler': 'FixMatchLR',
'randaugment_n': 2,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled examples
},
'PseudoLabel': {
'train_loader': 'standard',
'uniform_over_groups': False,
'eval_loader': 'standard',
'self_training_lambda': 1,
'self_training_threshold': 0.7,
'pseudolabel_T2': 0.4,
'scheduler': 'FixMatchLR',
'randaugment_n': 2,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled & unlabeled examples
},
'NoisyStudent': {
'train_loader': 'standard',
'uniform_over_groups': False,
'eval_loader': 'standard',
'noisystudent_add_dropout': True,
'noisystudent_dropout_rate': 0.5,
'scheduler': 'FixMatchLR',
'randaugment_n': 2,
'additional_train_transform': 'randaugment', # Apply strong augmentation to labeled & unlabeled examples
}
}
|
algorithm_defaults = {'ERM': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'randaugment_n': 2}, 'groupDRO': {'train_loader': 'standard', 'uniform_over_groups': True, 'distinct_groups': True, 'eval_loader': 'standard', 'group_dro_step_size': 0.01}, 'deepCORAL': {'train_loader': 'group', 'uniform_over_groups': True, 'distinct_groups': True, 'eval_loader': 'standard', 'coral_penalty_weight': 1.0, 'randaugment_n': 2, 'additional_train_transform': 'randaugment'}, 'IRM': {'train_loader': 'group', 'uniform_over_groups': True, 'distinct_groups': True, 'eval_loader': 'standard', 'irm_lambda': 100.0, 'irm_penalty_anneal_iters': 500}, 'DANN': {'train_loader': 'group', 'uniform_over_groups': True, 'distinct_groups': True, 'eval_loader': 'standard', 'randaugment_n': 2, 'additional_train_transform': 'randaugment'}, 'AFN': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'use_hafn': False, 'afn_penalty_weight': 0.01, 'safn_delta_r': 1.0, 'hafn_r': 1.0, 'additional_train_transform': 'randaugment', 'randaugment_n': 2}, 'FixMatch': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'self_training_lambda': 1, 'self_training_threshold': 0.7, 'scheduler': 'FixMatchLR', 'randaugment_n': 2, 'additional_train_transform': 'randaugment'}, 'PseudoLabel': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'self_training_lambda': 1, 'self_training_threshold': 0.7, 'pseudolabel_T2': 0.4, 'scheduler': 'FixMatchLR', 'randaugment_n': 2, 'additional_train_transform': 'randaugment'}, 'NoisyStudent': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'noisystudent_add_dropout': True, 'noisystudent_dropout_rate': 0.5, 'scheduler': 'FixMatchLR', 'randaugment_n': 2, 'additional_train_transform': 'randaugment'}}
|
"""django-anchors"""
__version__ = '0.1.dev0'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = '[email protected]'
__url__ = 'https://github.com/Fantomas42/django-anchors'
|
"""django-anchors"""
__version__ = '0.1.dev0'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = '[email protected]'
__url__ = 'https://github.com/Fantomas42/django-anchors'
|
def isinteger(s):
return s.isdigit() or s[0] == '-' and s[1:].isdigit()
def isfloat(x):
s = x.partition(".")
if s[1]=='.':
if s[0]=='' or s[0]=='-':
if s[2]=='' or s[2][0]=='-':
return False
else:
return isinteger(s[2])
elif isinteger(s[0]):
if s[2]!='' and s[2][0]=='-':
return False
return s[2]=='' or isinteger(s[2])
else:
return False
else:
return False
print(isfloat(".112"))
print(isfloat("-.112"))
print(isfloat("3.14"))
print(isfloat("-3.14"))
print(isfloat("-3.14"))
print(isfloat("5.0"))
print(isfloat("-777.0"))
print(isfloat("-777."))
print(isfloat("."))
print(isfloat(".."))
print(isfloat("-21.-1"))
print(isfloat("-.-1"))
|
def isinteger(s):
return s.isdigit() or (s[0] == '-' and s[1:].isdigit())
def isfloat(x):
s = x.partition('.')
if s[1] == '.':
if s[0] == '' or s[0] == '-':
if s[2] == '' or s[2][0] == '-':
return False
else:
return isinteger(s[2])
elif isinteger(s[0]):
if s[2] != '' and s[2][0] == '-':
return False
return s[2] == '' or isinteger(s[2])
else:
return False
else:
return False
print(isfloat('.112'))
print(isfloat('-.112'))
print(isfloat('3.14'))
print(isfloat('-3.14'))
print(isfloat('-3.14'))
print(isfloat('5.0'))
print(isfloat('-777.0'))
print(isfloat('-777.'))
print(isfloat('.'))
print(isfloat('..'))
print(isfloat('-21.-1'))
print(isfloat('-.-1'))
|
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
elif not root.right and not root.left:
return 0
elif not root.right:
return max(self.diameterOfBinaryTree(root.left),
1 + self.height(root.left))
elif not root.left:
return max(self.diameterOfBinaryTree(root.right),
1 + self.height(root.right))
else:
return max(self.diameterOfBinaryTree(root.right),
self.diameterOfBinaryTree(root.left),
self.height(root.left) + self.height(root.right) + 2)
def height(self, root):
if not root:
return 0
if not root.right and not root.left:
return 0
return 1 + max(self.height(root.left), self.height(root.right))
class Solution:
def diameterOfBinaryTree(self, root):
self.ans = 0
def depth(node):
if not node:
return 0
r = depth(node.right)
l = depth(node.left)
self.ans = max(self.ans, r+l)
return 1 + max(r, l)
depth(root)
return self.ans
|
class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
if not root:
return 0
elif not root.right and (not root.left):
return 0
elif not root.right:
return max(self.diameterOfBinaryTree(root.left), 1 + self.height(root.left))
elif not root.left:
return max(self.diameterOfBinaryTree(root.right), 1 + self.height(root.right))
else:
return max(self.diameterOfBinaryTree(root.right), self.diameterOfBinaryTree(root.left), self.height(root.left) + self.height(root.right) + 2)
def height(self, root):
if not root:
return 0
if not root.right and (not root.left):
return 0
return 1 + max(self.height(root.left), self.height(root.right))
class Solution:
def diameter_of_binary_tree(self, root):
self.ans = 0
def depth(node):
if not node:
return 0
r = depth(node.right)
l = depth(node.left)
self.ans = max(self.ans, r + l)
return 1 + max(r, l)
depth(root)
return self.ans
|
# Copyright (C) 2019 FireEye, Inc. All Rights Reserved.
"""
english letter probabilities
table from http://en.algoritmy.net/article/40379/Letter-frequency-English
"""
english_letter_probs_percent = [
['a', 8.167],
['b', 1.492],
['c', 2.782],
['d', 4.253],
['e', 12.702],
['f', 2.228],
['g', 2.015],
['h', 6.094],
['i', 6.966],
['j', 0.153],
['k', 0.772],
['l', 4.025],
['m', 2.406],
['n', 6.749],
['o', 7.507],
['p', 1.929],
['q', 0.095],
['r', 5.987],
['s', 6.327],
['t', 9.056],
['u', 2.758],
['v', 0.978],
['w', 2.360],
['x', 0.150],
['y', 1.974],
['z', 0.074]]
english_letter_probs = {lt: (per * 0.01) for lt, per in english_letter_probs_percent}
"""
Scrabble Scores
table from https://en.wikipedia.org/wiki/Scrabble_letter_distributions
"""
scrabble_dict = {"a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4,
"g": 2, "h": 4, "i": 1, "j": 8, "k": 5, "l": 1,
"m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1,
"s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8,
"y": 4, "z": 10}
|
"""
english letter probabilities
table from http://en.algoritmy.net/article/40379/Letter-frequency-English
"""
english_letter_probs_percent = [['a', 8.167], ['b', 1.492], ['c', 2.782], ['d', 4.253], ['e', 12.702], ['f', 2.228], ['g', 2.015], ['h', 6.094], ['i', 6.966], ['j', 0.153], ['k', 0.772], ['l', 4.025], ['m', 2.406], ['n', 6.749], ['o', 7.507], ['p', 1.929], ['q', 0.095], ['r', 5.987], ['s', 6.327], ['t', 9.056], ['u', 2.758], ['v', 0.978], ['w', 2.36], ['x', 0.15], ['y', 1.974], ['z', 0.074]]
english_letter_probs = {lt: per * 0.01 for (lt, per) in english_letter_probs_percent}
'\nScrabble Scores\ntable from https://en.wikipedia.org/wiki/Scrabble_letter_distributions\n'
scrabble_dict = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
|
arima = {
'order':[(2,1,0),(0,1,2),(1,1,1)],
'seasonal_order':[(0,0,0,0),(0,1,1,12)],
'trend':['n','c','t','ct']
}
elasticnet = {
'alpha':[i/10 for i in range(1,101)],
'l1_ratio':[0,0.25,0.5,0.75,1],
'normalizer':['scale','minmax',None]
}
gbt = {
'max_depth':[2,3],
'n_estimators':[100,500]
}
hwes = {
'trend':[None,'add','mul'],
'seasonal':[None,'add','mul'],
'damped_trend':[True,False]
}
knn = {
'n_neighbors':range(2,20),
'weights':['uniform','distance']
}
lightgbm = {
'max_depth':[i for i in range(5)] + [-1]
}
mlp = {
'activation':['relu','tanh'],
'hidden_layer_sizes':[(25,),(25,25,)],
'solver':['lbfgs','adam'],
'normalizer':['scale','minmax',None],
'random_state':[20]
}
mlr = {
'normalizer':['scale','minmax',None]
}
prophet = {
'n_changepoints':range(5)
}
rf = {
'max_depth':[5,10,None],
'n_estimators':[100,500,1000]
}
silverkite = {
'changepoints':range(5)
}
svr={
'kernel':['linear'],
'C':[.5,1,2,3],
'epsilon':[0.01,0.1,0.5]
}
xgboost = {
'max_depth':[2,3,4,5,6]
}
|
arima = {'order': [(2, 1, 0), (0, 1, 2), (1, 1, 1)], 'seasonal_order': [(0, 0, 0, 0), (0, 1, 1, 12)], 'trend': ['n', 'c', 't', 'ct']}
elasticnet = {'alpha': [i / 10 for i in range(1, 101)], 'l1_ratio': [0, 0.25, 0.5, 0.75, 1], 'normalizer': ['scale', 'minmax', None]}
gbt = {'max_depth': [2, 3], 'n_estimators': [100, 500]}
hwes = {'trend': [None, 'add', 'mul'], 'seasonal': [None, 'add', 'mul'], 'damped_trend': [True, False]}
knn = {'n_neighbors': range(2, 20), 'weights': ['uniform', 'distance']}
lightgbm = {'max_depth': [i for i in range(5)] + [-1]}
mlp = {'activation': ['relu', 'tanh'], 'hidden_layer_sizes': [(25,), (25, 25)], 'solver': ['lbfgs', 'adam'], 'normalizer': ['scale', 'minmax', None], 'random_state': [20]}
mlr = {'normalizer': ['scale', 'minmax', None]}
prophet = {'n_changepoints': range(5)}
rf = {'max_depth': [5, 10, None], 'n_estimators': [100, 500, 1000]}
silverkite = {'changepoints': range(5)}
svr = {'kernel': ['linear'], 'C': [0.5, 1, 2, 3], 'epsilon': [0.01, 0.1, 0.5]}
xgboost = {'max_depth': [2, 3, 4, 5, 6]}
|
"""Incoming data loaders
This file contains loader classes that allow reading iteratively through
vehicle entry data for various different data formats
Classes:
Vehicle
Entry
"""
class Vehicle():
"""Representation of a single vehicle."""
def __init__(self, entry, pce):
# vehicle properties
self.id = entry.id
self.type = entry.type
# set pce multiplier based on type
if self.type in ["passenger", "DEFAULT_VEHTYPE", "veh_passenger"]:
self.multiplier = pce["car"]
elif self.type in ["motorcycle", "veh_motorcycle"]:
self.multiplier = pce["moto"]
elif self.type in ["truck", "veh_truck"]:
self.multiplier = pce["truck"]
elif self.type in ["bus", "veh_bus"]:
self.multiplier = pce["bus"]
elif self.type in ["taxi", "veh_taxi"]:
self.multiplier = pce["taxi"]
else:
self.multiplier = pce["other"]
self.last_entry = None
self.new_entry = entry
def update(self):
"""Shift new entries to last and prepare for new"""
if self.new_entry != None:
self.last_entry = self.new_entry
self.new_entry = None
def distance_moved(self):
"""Calculate the distance the vehicle traveled within the same edge"""
return self.new_entry.pos - self.last_entry.pos
def approx_distance_moved(self, time_diff):
"""Approximate the distance the vehicle traveled between edges"""
return self.new_entry.speed * time_diff
def __repr__(self):
return ('{}({})'.format(self.__class__.__name__, self.id))
class Entry():
"""Representation of a single timestep sensor entry of a vehicle."""
def __init__(self, entry, time):
# vehicle properties
self.id = entry['id']
self.type = entry['type']
self.time = time
# extract edge and lane ids
self.edge_id = entry['lane'].rpartition('_')[0]
self.lane_id = entry['lane'].rpartition('_')[1]
# store position in edge
self.pos = float(entry['pos'])
self.speed = float(entry['speed'])
# store location/speed data
# self.x = float(entry['x'])
# self.y = float(entry['y'])
def __repr__(self):
return ('{}({})'.format(self.__class__.__name__, self.id))
|
"""Incoming data loaders
This file contains loader classes that allow reading iteratively through
vehicle entry data for various different data formats
Classes:
Vehicle
Entry
"""
class Vehicle:
"""Representation of a single vehicle."""
def __init__(self, entry, pce):
self.id = entry.id
self.type = entry.type
if self.type in ['passenger', 'DEFAULT_VEHTYPE', 'veh_passenger']:
self.multiplier = pce['car']
elif self.type in ['motorcycle', 'veh_motorcycle']:
self.multiplier = pce['moto']
elif self.type in ['truck', 'veh_truck']:
self.multiplier = pce['truck']
elif self.type in ['bus', 'veh_bus']:
self.multiplier = pce['bus']
elif self.type in ['taxi', 'veh_taxi']:
self.multiplier = pce['taxi']
else:
self.multiplier = pce['other']
self.last_entry = None
self.new_entry = entry
def update(self):
"""Shift new entries to last and prepare for new"""
if self.new_entry != None:
self.last_entry = self.new_entry
self.new_entry = None
def distance_moved(self):
"""Calculate the distance the vehicle traveled within the same edge"""
return self.new_entry.pos - self.last_entry.pos
def approx_distance_moved(self, time_diff):
"""Approximate the distance the vehicle traveled between edges"""
return self.new_entry.speed * time_diff
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.id)
class Entry:
"""Representation of a single timestep sensor entry of a vehicle."""
def __init__(self, entry, time):
self.id = entry['id']
self.type = entry['type']
self.time = time
self.edge_id = entry['lane'].rpartition('_')[0]
self.lane_id = entry['lane'].rpartition('_')[1]
self.pos = float(entry['pos'])
self.speed = float(entry['speed'])
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.id)
|
# This is a pytest config file
# https://docs.pytest.org/en/2.7.3/plugins.html
# It allows us to tell nbval (the py.text plugin we use to run
# notebooks and check their output is unchanged) to skip comparing
# notebook outputs for particular mimetypes.
def pytest_collectstart(collector):
if (
collector.fspath
and collector.fspath.ext == ".ipynb"
and hasattr(collector, "skip_compare")
):
# Skip plotly comparison, because something to do with
# responsive plot sizing makes output different in test
# environment
collector.skip_compare += ("application/vnd.plotly.v1+json",)
|
def pytest_collectstart(collector):
if collector.fspath and collector.fspath.ext == '.ipynb' and hasattr(collector, 'skip_compare'):
collector.skip_compare += ('application/vnd.plotly.v1+json',)
|
# model
model = Model()
i1 = Input("op1", "TENSOR_FLOAT32", "{2, 2, 2, 2}")
i3 = Output("op3", "TENSOR_FLOAT32", "{2, 2, 2, 2}")
model = model.Operation("RSQRT", i1).To(i3)
# Example 1. Input in operand 0,
input0 = {i1: # input 0
[1.0, 36.0, 2.0, 90, 4.0, 16.0, 25.0, 100.0,
23.0, 19.0, 40.0, 256.0, 4.0, 43.0, 8.0, 36.0]}
output0 = {i3: # output 0
[1.0, 0.166667, 0.70710678118, 0.105409, 0.5, 0.25, 0.2, 0.1,
0.208514, 0.229416, 0.158114, 0.0625, 0.5, 0.152499, 0.35355339059, 0.166667]}
# Instantiate an example
Example((input0, output0))
|
model = model()
i1 = input('op1', 'TENSOR_FLOAT32', '{2, 2, 2, 2}')
i3 = output('op3', 'TENSOR_FLOAT32', '{2, 2, 2, 2}')
model = model.Operation('RSQRT', i1).To(i3)
input0 = {i1: [1.0, 36.0, 2.0, 90, 4.0, 16.0, 25.0, 100.0, 23.0, 19.0, 40.0, 256.0, 4.0, 43.0, 8.0, 36.0]}
output0 = {i3: [1.0, 0.166667, 0.70710678118, 0.105409, 0.5, 0.25, 0.2, 0.1, 0.208514, 0.229416, 0.158114, 0.0625, 0.5, 0.152499, 0.35355339059, 0.166667]}
example((input0, output0))
|
#It's a simple calculator for doing Addition, Subtraction, Multiplication, Division and Percentage.
first_number = int(input("Enter your first number: "))
operators = input("Enter what you wanna do +,-,*,/,%: ")
second_number = int(input("Enter your second Number: "))
if operators == "+" :
first_number += second_number
print(f"Your Addition result is: {first_number}")
elif operators == "-" :
first_number -= second_number
print(f"Your Subtraction result is: {first_number}")
elif operators == "*" :
first_number *= second_number
print(f"Your Multiplication result is: {first_number}")
elif operators == "/" :
first_number /= second_number
print(f"Your Division result is: {first_number}")
elif operators == "%" :
first_number %= second_number
print(f"Your Modulus result is: {first_number}")
else :
print("You have chosen a wrong operator")
|
first_number = int(input('Enter your first number: '))
operators = input('Enter what you wanna do +,-,*,/,%: ')
second_number = int(input('Enter your second Number: '))
if operators == '+':
first_number += second_number
print(f'Your Addition result is: {first_number}')
elif operators == '-':
first_number -= second_number
print(f'Your Subtraction result is: {first_number}')
elif operators == '*':
first_number *= second_number
print(f'Your Multiplication result is: {first_number}')
elif operators == '/':
first_number /= second_number
print(f'Your Division result is: {first_number}')
elif operators == '%':
first_number %= second_number
print(f'Your Modulus result is: {first_number}')
else:
print('You have chosen a wrong operator')
|
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache='localhost',
instrument='Fluco',
experiment='Exp',
datasinks=['conssink', 'filesink', 'daemonsink',],
)
modules = ['nicos.commands.standard', 'nicos_ess.commands.epics']
devices = dict(
Fluco=device('nicos.devices.instrument.Instrument',
description='instrument object',
instrument='Fluco',
responsible='S. Body <[email protected]>',
),
Sample=device('nicos.devices.sample.Sample',
description='The currently used sample',
),
Exp=device('nicos.devices.experiment.Experiment',
description='experiment object',
dataroot='/opt/nicos-data',
sendmail=True,
serviceexp='p0',
sample='Sample',
),
filesink=device('nicos.devices.datasinks.AsciiScanfileSink',
),
conssink=device('nicos.devices.datasinks.ConsoleScanSink',
),
daemonsink=device('nicos.devices.datasinks.DaemonSink',
),
Space=device('nicos.devices.generic.FreeSpace',
description='The amount of free space for storing data',
path=None,
minfree=5,
),
)
|
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(cache='localhost', instrument='Fluco', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink'])
modules = ['nicos.commands.standard', 'nicos_ess.commands.epics']
devices = dict(Fluco=device('nicos.devices.instrument.Instrument', description='instrument object', instrument='Fluco', responsible='S. Body <[email protected]>'), Sample=device('nicos.devices.sample.Sample', description='The currently used sample'), Exp=device('nicos.devices.experiment.Experiment', description='experiment object', dataroot='/opt/nicos-data', sendmail=True, serviceexp='p0', sample='Sample'), filesink=device('nicos.devices.datasinks.AsciiScanfileSink'), conssink=device('nicos.devices.datasinks.ConsoleScanSink'), daemonsink=device('nicos.devices.datasinks.DaemonSink'), Space=device('nicos.devices.generic.FreeSpace', description='The amount of free space for storing data', path=None, minfree=5))
|
i=2
while i < 10:
j=1
while j < 10:
print(i,"*",j,"=",i*j)
j += 1
i += 1
|
i = 2
while i < 10:
j = 1
while j < 10:
print(i, '*', j, '=', i * j)
j += 1
i += 1
|
# Program that asks the user to input any positive integer and
# outputs the successive value of the following calculation.
# It should at each step calculate the next value by taking the current value
# if the it is even, divide it by two, if it is odd, multiply
# it by three and add one
# the program ends if the current value is one.
# first number and then check if it has a positive value
n = int(input("please enter a number: " ))
while n != 1:
# eliminating 0 and negative numbers
if n <= 0:
print("Please enter a positive number.")
break
# for even numbers:
elif n % 2== 0:
n=int(n/2)
print(n)
# for other integers (odd numbers)
else:
n=int(n*3+1)
print(n)
|
n = int(input('please enter a number: '))
while n != 1:
if n <= 0:
print('Please enter a positive number.')
break
elif n % 2 == 0:
n = int(n / 2)
print(n)
else:
n = int(n * 3 + 1)
print(n)
|
df =[['4', '1', '2', '7', '2', '5', '1'], ['9', '9', '8', '0', '2', '0', '8', '5', '0', '1', '3']]
str=''
dcf = ''.join(df)
print(dcf)
print()
|
df = [['4', '1', '2', '7', '2', '5', '1'], ['9', '9', '8', '0', '2', '0', '8', '5', '0', '1', '3']]
str = ''
dcf = ''.join(df)
print(dcf)
print()
|
parameters = {
"results": [
{
"type": "max",
"identifier":
{
"symbol": "S22",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
},
"referenceValue": 62.3, # YT
"tolerance": 0.05
},
{
"type": "disp_at_zero_y",
"step": "Step-1",
"identifier": [
{ # x
"symbol": "U2",
"nset": "Y+",
"position": "Node 3"
},
{ # y
"symbol": "S22",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
}
],
"zeroTol": 0.00623, # Defines how close to zero the y value needs to be
"referenceValue": 0.00889, # u_f = 2*GYT/YT
"tolerance": 1e-5
},
{
"type": "max",
"identifier":
{
"symbol": "SDV_CDM_d2",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
},
"referenceValue": 1.0,
"tolerance": 0.0
},
{
"type": "max",
"identifier":
{
"symbol": "SDV_CDM_d1T",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
},
"referenceValue": 0.0,
"tolerance": 0.0
},
{
"type": "max",
"identifier":
{
"symbol": "SDV_CDM_d1C",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
},
"referenceValue": 0.0,
"tolerance": 0.0
},
{
"type": "continuous",
"identifier":
{
"symbol": "S22",
"elset": "ALL_ELEMS",
"position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)"
},
"referenceValue": 0.0,
"tolerance": 0.1
}
]
}
|
parameters = {'results': [{'type': 'max', 'identifier': {'symbol': 'S22', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 62.3, 'tolerance': 0.05}, {'type': 'disp_at_zero_y', 'step': 'Step-1', 'identifier': [{'symbol': 'U2', 'nset': 'Y+', 'position': 'Node 3'}, {'symbol': 'S22', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}], 'zeroTol': 0.00623, 'referenceValue': 0.00889, 'tolerance': 1e-05}, {'type': 'max', 'identifier': {'symbol': 'SDV_CDM_d2', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 1.0, 'tolerance': 0.0}, {'type': 'max', 'identifier': {'symbol': 'SDV_CDM_d1T', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 0.0, 'tolerance': 0.0}, {'type': 'max', 'identifier': {'symbol': 'SDV_CDM_d1C', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 0.0, 'tolerance': 0.0}, {'type': 'continuous', 'identifier': {'symbol': 'S22', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 0.0, 'tolerance': 0.1}]}
|
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
def check(t, a, dp):
n=len(t)
for k in range(1, n):
if dp[a+0][a+k-1] and dp[a+k][a+n-1]:
return 1
return 0
n=len(s)
dp=[[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n-i):
t=s[j:j+i+1]
if t in wordDict:
dp[j][j+i]=1
else:
dp[j][j+i]=check(t, j, dp)
return dp[0][n-1]==1
|
class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
def check(t, a, dp):
n = len(t)
for k in range(1, n):
if dp[a + 0][a + k - 1] and dp[a + k][a + n - 1]:
return 1
return 0
n = len(s)
dp = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n - i):
t = s[j:j + i + 1]
if t in wordDict:
dp[j][j + i] = 1
else:
dp[j][j + i] = check(t, j, dp)
return dp[0][n - 1] == 1
|
expected_output = {
"clock_state": {
"system_status": {
"associations_address": "10.16.2.2",
"associations_local_mode": "client",
"clock_offset": 27.027,
"clock_refid": "127.127.1.1",
"clock_state": "synchronized",
"clock_stratum": 3,
"root_delay": 5.61,
}
},
"peer": {
"10.16.2.2": {
"local_mode": {
"client": {
"delay": 5.61,
"jitter": 3.342,
"mode": "synchronized",
"offset": 27.027,
"poll": 64,
"reach": 7,
"receive_time": 25,
"refid": "127.127.1.1",
"remote": "10.16.2.2",
"stratum": 3,
"configured": True,
"local_mode": "client",
}
}
},
"10.36.3.3": {
"local_mode": {
"client": {
"delay": 0.0,
"jitter": 15937.0,
"mode": "unsynchronized",
"offset": 0.0,
"poll": 512,
"reach": 0,
"receive_time": "-",
"refid": ".STEP.",
"remote": "10.36.3.3",
"stratum": 16,
"configured": True,
"local_mode": "client",
}
}
},
},
}
|
expected_output = {'clock_state': {'system_status': {'associations_address': '10.16.2.2', 'associations_local_mode': 'client', 'clock_offset': 27.027, 'clock_refid': '127.127.1.1', 'clock_state': 'synchronized', 'clock_stratum': 3, 'root_delay': 5.61}}, 'peer': {'10.16.2.2': {'local_mode': {'client': {'delay': 5.61, 'jitter': 3.342, 'mode': 'synchronized', 'offset': 27.027, 'poll': 64, 'reach': 7, 'receive_time': 25, 'refid': '127.127.1.1', 'remote': '10.16.2.2', 'stratum': 3, 'configured': True, 'local_mode': 'client'}}}, '10.36.3.3': {'local_mode': {'client': {'delay': 0.0, 'jitter': 15937.0, 'mode': 'unsynchronized', 'offset': 0.0, 'poll': 512, 'reach': 0, 'receive_time': '-', 'refid': '.STEP.', 'remote': '10.36.3.3', 'stratum': 16, 'configured': True, 'local_mode': 'client'}}}}}
|
#!/usr/python3.5
#-*- coding: utf-8 -*-
for row in range(10):
for j in range(row):
print (" ",end=" ")
for i in range(10-row):
print (i,end=" ")
print ()
|
for row in range(10):
for j in range(row):
print(' ', end=' ')
for i in range(10 - row):
print(i, end=' ')
print()
|
# SUM
def twoSumI(nums, target):
result = {}
for k, v in enumerate(nums):
sub = target - v
if sub in result:
return [result[sub], k]
result[v] = k
def twoSum(nums, target):
l, r = 0, len(nums) - 1
result = []
while l < r:
total = nums[l] + nums[r]
if total > target or (r < len(nums) - 1 and nums[r] == nums[r + 1]):
r -= 1
elif total < target or (l > 0 and nums[l - 1] == nums[l]):
l += 1
else:
result.append([nums[l], nums[r]])
l += 1
r -= 1
return result
def kSum(nums, target, k):
result = []
if k == 2:
return twoSum(nums, target)
for i in range(len(nums)):
if i == 0 or nums[i - 1] != nums[i]:
for sub in kSum(nums[i + 1:], target - nums[i], k - 1):
result.append([nums[i]] + sub)
return result
def threeSum(nums, target):
return kSum(nums, 0, 3)
def fourSum(nums, target):
return kSum(nums, 0, 4)
def pair(k, arr):
ret = dict()
count = 0
for i, val in enumerate(arr):
total = val + k
if total in ret:
print("{} - {}".format(val, total))
count += 1
ret[val] = i
return count
## String
def is_p(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def longest_palindrome(s):
if not s:
return
ret = ''
for i in range(len(s)):
old = expand(s, i, i)
even = expand(s, i, i + 1)
if len(old) > len(even):
tmp = old
else:
tmp = even
if len(ret) < len(tmp):
ret = tmp
return ret
def expand(s, i, j):
while i >= 0 and j <= len(s) - 1 and s[i] == s[j]:
i -= 1
j += 1
return s[i + 1: j]
def bubble_sort(nums):
# We set swapped to True so the loop looks runs at least once
swapped = True
while swapped:
swapped = False
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
# Swap the elements
nums[i], nums[i + 1] = nums[i + 1], nums[i]
# Set the flag to True so we'll loop again
swapped = True
def selection_sort(arr):
s = len(arr)
for i in range(s):
lowest_idx = i
for j in range(i + 1, s):
if arr[j] < arr[i]:
lowest_idx = j
arr[i], arr[lowest_idx] = arr[lowest_idx], arr[i]
def insertion_sort(nums):
# Start on the second element as we assume the first element is sorted
for i in range(1, len(nums)):
item_to_insert = nums[i]
# And keep a reference of the index of the previous element
j = i - 1
# Move all items of the sorted segment forward if they are larger than
# the item to insert
while j >= 0 and nums[j] > item_to_insert:
nums[j + 1] = nums[j]
j -= 1
# Insert the item
nums[j + 1] = item_to_insert
def quick_sort(arr, l, r):
if l < r:
lo, ro = l, r
l1 = partition(arr, lo, ro)
quick_sort(arr, l, l1)
quick_sort(arr, l1 + 1, r)
def partition(arr, lo, ro):
l, r = lo, ro
if l >= r:
return
pivot = arr[(l+r)//2]
while l <= r:
while arr[l] < pivot and l <= r:
l += 1
while arr[r] > pivot and r >= l:
r -= 1
if l >= r:
break
arr[l], arr[r] = arr[r], arr[l]
l += 1
r -= 1
return l
## Example
# two sum
# nums, target = [3, 2, 4], 6
# print(twoSum(nums, target))
#
# # three sum
# nums = [-2,0,1,1,2]
# nums.sort()
# print(kSum(nums, 0, 3))
# Palindronearr
# print(longest_palindrome('bacabd'))
# ## PAIR
# arr = [1, 5, 3, 4, 2]
# k = 2
# arr.sort(reverse=True)
# print(pair(2, arr))
## Sort
arr = [22, 5, 1, 18, 99, 0]
# quick_sort(arr, 0, len(arr) - 1)
selection_sort(arr)
print(arr)
# print(insertion_sort(arr))
def bubble_soft(arr):
s = len(arr)
for i in range(s):
for j in range(i + 1, s):
if arr[j] < arr[i]:
arr[i], arr[j] = arr[j], arr[i]
def selection_sort(arr):
s = len(arr)
for i in range(s):
min_idx = i
for j in range(i + 1, s):
if arr[j] < arr[i]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
def insertion_sort(arr):
s = len(arr)
for i in range(1, s):
insert_num = arr[i]
j = i - 1
while j >= 0 and arr[j] > insert_num:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = insert_num
def quick_sort(arr, l, r):
if l >= r:
return
def partition(lo, ro):
pivot = arr[(lo + ro)//2]
while lo <= ro:
while arr[lo] < pivot and lo <= ro:
lo += 1
while arr[ro] > pivot and ro >= lo:
ro -= 1
if lo <= ro:
arr[lo], arr[ro] = arr[ro], arr[lo]
ro -= 1
lo += 1
return lo - 1
mid = partition(l, r)
quick_sort(arr, l, mid)
quick_sort(arr, mid + 1, r)
#
# arr = [1, 3, 3, 2, 5, 0]
# quick_sort(arr, 0, len(arr) - 1)
#
# print(arr)
def isolated_area(arr):
total = 0
for i in range(len(arr)):
for j in range(len(arr[0])):
if arr[i][j] == 1:
dfs(arr, (i, j))
total += 1
return total
def dfs(arr, p):
stack = [p]
while not stack:
i, j = stack.pop()
arr[i][j] = 2
if arr[i - 1] == 0:
stack.insert(0, (i, j))
def int_para(val):
num_arr = []
while val > 0:
mod = val%10
num_arr.insert(0, mod)
val = val//10
def is_p():
l, r = 0, len(num_arr) - 1
while l <= r:
if num_arr[l] != num_arr[r]:
return False
l += 1
r -= 1
return True
return is_p()
# def expand(arr, i, j):
# while arr[i] == arr[j]:
# print(int_para(124521))
# [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
def word_search(board, word):
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if dfs(board, visited, (i, j), word, 1):
return True
return False
def dfs(board, visited, p, word, idx):
s1 = len(board) - 1
s2 = len(board[0]) - 1
i, j = p
# visited.add((i, j))
if idx >= len(word):
return True
if i + 1 <= s1 and (i+1, j) not in visited and board[i+1][j] == word[idx]:
if dfs(board, visited, (i+1, j), word, idx + 1):
return True
if i - 1 >= 0 and (i-1, j) not in visited and board[i-1][j] == word[idx]:
if dfs(board, visited, (i-1, j), word, idx + 1):
return True
if j + 1 <= s2 and (i, j + 1) not in visited and board[i][j + 1] == word[idx]:
if dfs(board, visited, (i, j + 1), word, idx + 1):
return True
if j - 1 >= 0 and (i, j - 1) not in visited and board[i][j - 1] == word[idx]:
if dfs(board, visited, (i, j - 1), word, idx + 1):
return True
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if self.dfs(board, visited, (i, j), word, 1):
return True
return False
def dfs(self, board, visited, p, word, idx):
s1 = len(board) - 1
s2 = len(board[0]) - 1
i, j = p
# visited.add((i, j))
tmp = board[i][j]
board[i][j] = '#'
if idx >= len(word):
return True
if i + 1 <= s1 and (i + 1, j) not in visited and board[i + 1][j] == word[idx]:
if self.dfs(board, visited, (i + 1, j), word, idx + 1):
return True
if i - 1 >= 0 and (i - 1, j) not in visited and board[i - 1][j] == word[idx]:
if self.dfs(board, visited, (i - 1, j), word, idx + 1):
return True
if j + 1 <= s2 and (i, j + 1) not in visited and board[i][j + 1] == word[idx]:
if self.dfs(board, visited, (i, j + 1), word, idx + 1):
return True
if j - 1 >= 0 and (i, j - 1) not in visited and board[i][j - 1] == word[idx]:
if self.dfs(board, visited, (i, j - 1), word, idx + 1):
return True
board[i][j] = tmp
# board = [["C","A","A"],
# ["A","A","A"],
# ["B","C","D"]]
board = [["A","B","C","E"],
["S","F","E","S"],
["A","D","E","E"]]
word = "ABCESEEEFS"
# sol = Solution()
# print(sol.exist(board, word))
class Solution:
def setZeroes(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
visited = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0 and (i, j) not in visited:
visited.add((i, j))
self.draw(matrix, visited, i, j)
def draw(self, matrix, visited, i, j):
s1 = len(matrix) - 1
s2 = len(matrix[0]) - 1
while s1 >= 0:
if matrix[s1][j] != 0:
visited.add((s1, j))
matrix[s1][j] = 0
s1 -= 1
while s2 >= 0:
if matrix[i][s2] != 0:
visited.add((i, s2))
matrix[i][s2] = 0
s2 -= 1
# matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
#
# sol = Solution()
# print(sol.setZeroes(matrix))
# print(matrix)
class Solution:
def num_decodings(self, s) -> int:
total = 0
self.ds(s, total)
return total
def ds(self, s, total):
sz = len(s)
i = 0
while i < sz:
if int(s[i]) <= 2:
total += 1
if i + 1 >= sz:
break
self.ds(s[i + 1:], total)
if i + 1 < sz and int(s[i + 1]) <= 6:
total += 1
if i + 2 >= sz:
break
self.ds(s[i + 2:], total)
else:
total += 1
if i + 1 >= sz:
break
self.ds(s[i + 1:], total)
s = "226"
sol = Solution()
print(sol.num_decodings(s))
|
def two_sum_i(nums, target):
result = {}
for (k, v) in enumerate(nums):
sub = target - v
if sub in result:
return [result[sub], k]
result[v] = k
def two_sum(nums, target):
(l, r) = (0, len(nums) - 1)
result = []
while l < r:
total = nums[l] + nums[r]
if total > target or (r < len(nums) - 1 and nums[r] == nums[r + 1]):
r -= 1
elif total < target or (l > 0 and nums[l - 1] == nums[l]):
l += 1
else:
result.append([nums[l], nums[r]])
l += 1
r -= 1
return result
def k_sum(nums, target, k):
result = []
if k == 2:
return two_sum(nums, target)
for i in range(len(nums)):
if i == 0 or nums[i - 1] != nums[i]:
for sub in k_sum(nums[i + 1:], target - nums[i], k - 1):
result.append([nums[i]] + sub)
return result
def three_sum(nums, target):
return k_sum(nums, 0, 3)
def four_sum(nums, target):
return k_sum(nums, 0, 4)
def pair(k, arr):
ret = dict()
count = 0
for (i, val) in enumerate(arr):
total = val + k
if total in ret:
print('{} - {}'.format(val, total))
count += 1
ret[val] = i
return count
def is_p(s):
(i, j) = (0, len(s) - 1)
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def longest_palindrome(s):
if not s:
return
ret = ''
for i in range(len(s)):
old = expand(s, i, i)
even = expand(s, i, i + 1)
if len(old) > len(even):
tmp = old
else:
tmp = even
if len(ret) < len(tmp):
ret = tmp
return ret
def expand(s, i, j):
while i >= 0 and j <= len(s) - 1 and (s[i] == s[j]):
i -= 1
j += 1
return s[i + 1:j]
def bubble_sort(nums):
swapped = True
while swapped:
swapped = False
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
(nums[i], nums[i + 1]) = (nums[i + 1], nums[i])
swapped = True
def selection_sort(arr):
s = len(arr)
for i in range(s):
lowest_idx = i
for j in range(i + 1, s):
if arr[j] < arr[i]:
lowest_idx = j
(arr[i], arr[lowest_idx]) = (arr[lowest_idx], arr[i])
def insertion_sort(nums):
for i in range(1, len(nums)):
item_to_insert = nums[i]
j = i - 1
while j >= 0 and nums[j] > item_to_insert:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = item_to_insert
def quick_sort(arr, l, r):
if l < r:
(lo, ro) = (l, r)
l1 = partition(arr, lo, ro)
quick_sort(arr, l, l1)
quick_sort(arr, l1 + 1, r)
def partition(arr, lo, ro):
(l, r) = (lo, ro)
if l >= r:
return
pivot = arr[(l + r) // 2]
while l <= r:
while arr[l] < pivot and l <= r:
l += 1
while arr[r] > pivot and r >= l:
r -= 1
if l >= r:
break
(arr[l], arr[r]) = (arr[r], arr[l])
l += 1
r -= 1
return l
arr = [22, 5, 1, 18, 99, 0]
selection_sort(arr)
print(arr)
def bubble_soft(arr):
s = len(arr)
for i in range(s):
for j in range(i + 1, s):
if arr[j] < arr[i]:
(arr[i], arr[j]) = (arr[j], arr[i])
def selection_sort(arr):
s = len(arr)
for i in range(s):
min_idx = i
for j in range(i + 1, s):
if arr[j] < arr[i]:
min_idx = j
(arr[i], arr[min_idx]) = (arr[min_idx], arr[i])
def insertion_sort(arr):
s = len(arr)
for i in range(1, s):
insert_num = arr[i]
j = i - 1
while j >= 0 and arr[j] > insert_num:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = insert_num
def quick_sort(arr, l, r):
if l >= r:
return
def partition(lo, ro):
pivot = arr[(lo + ro) // 2]
while lo <= ro:
while arr[lo] < pivot and lo <= ro:
lo += 1
while arr[ro] > pivot and ro >= lo:
ro -= 1
if lo <= ro:
(arr[lo], arr[ro]) = (arr[ro], arr[lo])
ro -= 1
lo += 1
return lo - 1
mid = partition(l, r)
quick_sort(arr, l, mid)
quick_sort(arr, mid + 1, r)
def isolated_area(arr):
total = 0
for i in range(len(arr)):
for j in range(len(arr[0])):
if arr[i][j] == 1:
dfs(arr, (i, j))
total += 1
return total
def dfs(arr, p):
stack = [p]
while not stack:
(i, j) = stack.pop()
arr[i][j] = 2
if arr[i - 1] == 0:
stack.insert(0, (i, j))
def int_para(val):
num_arr = []
while val > 0:
mod = val % 10
num_arr.insert(0, mod)
val = val // 10
def is_p():
(l, r) = (0, len(num_arr) - 1)
while l <= r:
if num_arr[l] != num_arr[r]:
return False
l += 1
r -= 1
return True
return is_p()
def word_search(board, word):
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if dfs(board, visited, (i, j), word, 1):
return True
return False
def dfs(board, visited, p, word, idx):
s1 = len(board) - 1
s2 = len(board[0]) - 1
(i, j) = p
if idx >= len(word):
return True
if i + 1 <= s1 and (i + 1, j) not in visited and (board[i + 1][j] == word[idx]):
if dfs(board, visited, (i + 1, j), word, idx + 1):
return True
if i - 1 >= 0 and (i - 1, j) not in visited and (board[i - 1][j] == word[idx]):
if dfs(board, visited, (i - 1, j), word, idx + 1):
return True
if j + 1 <= s2 and (i, j + 1) not in visited and (board[i][j + 1] == word[idx]):
if dfs(board, visited, (i, j + 1), word, idx + 1):
return True
if j - 1 >= 0 and (i, j - 1) not in visited and (board[i][j - 1] == word[idx]):
if dfs(board, visited, (i, j - 1), word, idx + 1):
return True
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
visited = set()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if self.dfs(board, visited, (i, j), word, 1):
return True
return False
def dfs(self, board, visited, p, word, idx):
s1 = len(board) - 1
s2 = len(board[0]) - 1
(i, j) = p
tmp = board[i][j]
board[i][j] = '#'
if idx >= len(word):
return True
if i + 1 <= s1 and (i + 1, j) not in visited and (board[i + 1][j] == word[idx]):
if self.dfs(board, visited, (i + 1, j), word, idx + 1):
return True
if i - 1 >= 0 and (i - 1, j) not in visited and (board[i - 1][j] == word[idx]):
if self.dfs(board, visited, (i - 1, j), word, idx + 1):
return True
if j + 1 <= s2 and (i, j + 1) not in visited and (board[i][j + 1] == word[idx]):
if self.dfs(board, visited, (i, j + 1), word, idx + 1):
return True
if j - 1 >= 0 and (i, j - 1) not in visited and (board[i][j - 1] == word[idx]):
if self.dfs(board, visited, (i, j - 1), word, idx + 1):
return True
board[i][j] = tmp
board = [['A', 'B', 'C', 'E'], ['S', 'F', 'E', 'S'], ['A', 'D', 'E', 'E']]
word = 'ABCESEEEFS'
class Solution:
def set_zeroes(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
visited = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0 and (i, j) not in visited:
visited.add((i, j))
self.draw(matrix, visited, i, j)
def draw(self, matrix, visited, i, j):
s1 = len(matrix) - 1
s2 = len(matrix[0]) - 1
while s1 >= 0:
if matrix[s1][j] != 0:
visited.add((s1, j))
matrix[s1][j] = 0
s1 -= 1
while s2 >= 0:
if matrix[i][s2] != 0:
visited.add((i, s2))
matrix[i][s2] = 0
s2 -= 1
class Solution:
def num_decodings(self, s) -> int:
total = 0
self.ds(s, total)
return total
def ds(self, s, total):
sz = len(s)
i = 0
while i < sz:
if int(s[i]) <= 2:
total += 1
if i + 1 >= sz:
break
self.ds(s[i + 1:], total)
if i + 1 < sz and int(s[i + 1]) <= 6:
total += 1
if i + 2 >= sz:
break
self.ds(s[i + 2:], total)
else:
total += 1
if i + 1 >= sz:
break
self.ds(s[i + 1:], total)
s = '226'
sol = solution()
print(sol.num_decodings(s))
|
# -*- coding: utf-8 -*-
"""
Created on 24 Dec 2019 20:40:06
@author: jiahuei
"""
def get_dict(fp):
data = {}
with open(fp, 'r') as f:
for ll in f.readlines():
_ = ll.split(',')
data[_[0]] = _[1].rstrip()
return data
def dump(data, keys, out_path):
out_str = ''
for k in keys:
out_str += '{},{}\r\n'.format(k, data[k])
with open(out_path, 'w') as f:
f.write(out_str)
SPLITS = ['train', 'valid', 'test']
for split in SPLITS:
print('Checking {} ... '.format(split), end='')
a = get_dict('/master/datasets/mscoco/captions_py2/mscoco_{}_v25595_s15.txt'.format(split))
b = get_dict('/master/datasets/mscoco/captions/mscoco_{}_v25595_s15.txt'.format(split))
a_keys = sorted(a.keys())
b_keys = sorted(b.keys())
a_values = sorted(a.values())
b_values = sorted(b.values())
if a_keys == b_keys and a_values == b_values:
print('OK')
else:
print('DIFFERENT')
del a, b
# dump(a, a_keys, '/master/datasets/insta/py2.txt')
# dump(b, a_keys, '/master/datasets/insta/py3.txt')
|
"""
Created on 24 Dec 2019 20:40:06
@author: jiahuei
"""
def get_dict(fp):
data = {}
with open(fp, 'r') as f:
for ll in f.readlines():
_ = ll.split(',')
data[_[0]] = _[1].rstrip()
return data
def dump(data, keys, out_path):
out_str = ''
for k in keys:
out_str += '{},{}\r\n'.format(k, data[k])
with open(out_path, 'w') as f:
f.write(out_str)
splits = ['train', 'valid', 'test']
for split in SPLITS:
print('Checking {} ... '.format(split), end='')
a = get_dict('/master/datasets/mscoco/captions_py2/mscoco_{}_v25595_s15.txt'.format(split))
b = get_dict('/master/datasets/mscoco/captions/mscoco_{}_v25595_s15.txt'.format(split))
a_keys = sorted(a.keys())
b_keys = sorted(b.keys())
a_values = sorted(a.values())
b_values = sorted(b.values())
if a_keys == b_keys and a_values == b_values:
print('OK')
else:
print('DIFFERENT')
del a, b
|
__author__ = 'Aaron Yang'
__email__ = '[email protected]'
__date__ = '1/10/2021 10:53 PM'
class Solution:
def smallestStringWithSwaps(self, s: str, pairs) -> str:
chars = list(s)
pairs.sort(key=lambda item: (item[0], item[1]))
for pair in pairs:
a, b = pair[0], pair[1]
chars[a], chars[b] = chars[b], chars[a]
return ''.join(chars)
Solution().smallestStringWithSwaps("dcab", [[0, 3], [1, 2], [0, 2]])
|
__author__ = 'Aaron Yang'
__email__ = '[email protected]'
__date__ = '1/10/2021 10:53 PM'
class Solution:
def smallest_string_with_swaps(self, s: str, pairs) -> str:
chars = list(s)
pairs.sort(key=lambda item: (item[0], item[1]))
for pair in pairs:
(a, b) = (pair[0], pair[1])
(chars[a], chars[b]) = (chars[b], chars[a])
return ''.join(chars)
solution().smallestStringWithSwaps('dcab', [[0, 3], [1, 2], [0, 2]])
|
"""Exceptions for Ambee."""
class AmbeeError(Exception):
"""Generic Ambee exception."""
class AmbeeConnectionError(AmbeeError):
"""Ambee connection exception."""
class AmbeeAuthenticationError(AmbeeConnectionError):
"""Ambee authentication exception."""
class AmbeeConnectionTimeoutError(AmbeeConnectionError):
"""Ambee connection Timeout exception."""
|
"""Exceptions for Ambee."""
class Ambeeerror(Exception):
"""Generic Ambee exception."""
class Ambeeconnectionerror(AmbeeError):
"""Ambee connection exception."""
class Ambeeauthenticationerror(AmbeeConnectionError):
"""Ambee authentication exception."""
class Ambeeconnectiontimeouterror(AmbeeConnectionError):
"""Ambee connection Timeout exception."""
|
# test bignum unary operations
i = 1 << 65
print(bool(i))
print(+i)
print(-i)
print(~i)
|
i = 1 << 65
print(bool(i))
print(+i)
print(-i)
print(~i)
|
def zeroes(n, cnt):
if n == 0:
return cnt
elif n % 10 == 0:
return zeroes(n//10, cnt+1)
else:
return zeroes(n//10, cnt)
n = int(input())
print(zeroes(n, 0))
|
def zeroes(n, cnt):
if n == 0:
return cnt
elif n % 10 == 0:
return zeroes(n // 10, cnt + 1)
else:
return zeroes(n // 10, cnt)
n = int(input())
print(zeroes(n, 0))
|
req = {
"userId": "admin",
"metadata": {
"@context": [
"https://w3id.org/ro/crate/1.0/context",
{
"@vocab": "https://schema.org/",
"osfcategory": "https://www.research-data-services.org/jsonld/osfcategory",
"zenodocategory": "https://www.research-data-services.org/jsonld/zenodocategory",
},
],
"@graph": [
{
"@id": "ro-crate-metadata.json",
"@type": "CreativeWork",
"about": {"@id": "./"},
"identifier": "ro-crate-metadata.json",
"conformsTo": {"@id": "https://w3id.org/ro/crate/1.0"},
"license": {"@id": "https://creativecommons.org/licenses/by-sa/3.0"},
"description": "Made with Describo: https://uts-eresearch.github.io/describo/",
},
{
"@type": "Dataset",
"datePublished": "2020-09-29T22:00:00.000Z",
"name": ["testtitle"],
"description": ["Beispieltest. Ganz viel\n\nasd mit umbruch"],
"creator": [
{"@id": "#edf6055e-9985-4dfe-9759-8f1aa640d396"},
{"@id": "#ac356e5f-fb71-400e-904e-a473c4fc890d"},
],
"zenodocategory": "publication/thesis",
"osfcategory": "analysis",
"@id": "./",
},
{
"@type": "Person",
"@reverse": {"creator": [{"@id": "./"}]},
"name": "Peter Heiss",
"familyName": "Heiss",
"givenName": "Peter",
"affiliation": [{"@id": "#4bafacfd-e123-44dc-90b9-63f974f85694"}],
"@id": "#edf6055e-9985-4dfe-9759-8f1aa640d396",
},
{
"@type": "Organization",
"name": "WWU",
"@reverse": {
"affiliation": [{"@id": "#edf6055e-9985-4dfe-9759-8f1aa640d396"}]
},
"@id": "#4bafacfd-e123-44dc-90b9-63f974f85694",
},
{
"@type": "Person",
"name": "Jens Stegmann",
"familyName": "Stegmann",
"givenName": "Jens",
"email": "",
"@reverse": {"creator": [{"@id": "./"}]},
"@id": "#ac356e5f-fb71-400e-904e-a473c4fc890d",
},
],
},
}
result = {
"data": {
"type": "nodes",
"attributes": {
"description": "Beispieltest. Ganz viel asd mit umbruch",
"category": "analysis",
"title": "testtitle",
},
}
}
|
req = {'userId': 'admin', 'metadata': {'@context': ['https://w3id.org/ro/crate/1.0/context', {'@vocab': 'https://schema.org/', 'osfcategory': 'https://www.research-data-services.org/jsonld/osfcategory', 'zenodocategory': 'https://www.research-data-services.org/jsonld/zenodocategory'}], '@graph': [{'@id': 'ro-crate-metadata.json', '@type': 'CreativeWork', 'about': {'@id': './'}, 'identifier': 'ro-crate-metadata.json', 'conformsTo': {'@id': 'https://w3id.org/ro/crate/1.0'}, 'license': {'@id': 'https://creativecommons.org/licenses/by-sa/3.0'}, 'description': 'Made with Describo: https://uts-eresearch.github.io/describo/'}, {'@type': 'Dataset', 'datePublished': '2020-09-29T22:00:00.000Z', 'name': ['testtitle'], 'description': ['Beispieltest. Ganz viel\n\nasd mit umbruch'], 'creator': [{'@id': '#edf6055e-9985-4dfe-9759-8f1aa640d396'}, {'@id': '#ac356e5f-fb71-400e-904e-a473c4fc890d'}], 'zenodocategory': 'publication/thesis', 'osfcategory': 'analysis', '@id': './'}, {'@type': 'Person', '@reverse': {'creator': [{'@id': './'}]}, 'name': 'Peter Heiss', 'familyName': 'Heiss', 'givenName': 'Peter', 'affiliation': [{'@id': '#4bafacfd-e123-44dc-90b9-63f974f85694'}], '@id': '#edf6055e-9985-4dfe-9759-8f1aa640d396'}, {'@type': 'Organization', 'name': 'WWU', '@reverse': {'affiliation': [{'@id': '#edf6055e-9985-4dfe-9759-8f1aa640d396'}]}, '@id': '#4bafacfd-e123-44dc-90b9-63f974f85694'}, {'@type': 'Person', 'name': 'Jens Stegmann', 'familyName': 'Stegmann', 'givenName': 'Jens', 'email': '', '@reverse': {'creator': [{'@id': './'}]}, '@id': '#ac356e5f-fb71-400e-904e-a473c4fc890d'}]}}
result = {'data': {'type': 'nodes', 'attributes': {'description': 'Beispieltest. Ganz viel asd mit umbruch', 'category': 'analysis', 'title': 'testtitle'}}}
|
class GoogleException(Exception):
def __init__(self, code, message, response):
self.status_code = code
self.error_type = message
self.message = message
self.response = response
self.get_error_type()
def get_error_type(self):
json_response = self.response.json()
if 'error' in json_response and 'errors' in json_response['error']:
self.error_type = json_response['error']['errors'][0]['reason']
|
class Googleexception(Exception):
def __init__(self, code, message, response):
self.status_code = code
self.error_type = message
self.message = message
self.response = response
self.get_error_type()
def get_error_type(self):
json_response = self.response.json()
if 'error' in json_response and 'errors' in json_response['error']:
self.error_type = json_response['error']['errors'][0]['reason']
|
command = input().lower()
in_progress = True
car_stopped = True
while in_progress:
if command == 'help':
print("start - to start the car")
print("stop - to stop the car")
print("quit - to ext")
elif command == 'start':
if car_stopped:
print("You started the car")
car_stopped = False
else:
print("The car has already been started")
elif command == 'stop':
if not car_stopped:
print("You stopped the car")
car_stopped = True
else:
print("The car is already stopped")
elif command == 'quit':
print("Exiting the program now")
in_progress = False
break
else:
print("That was not a valid command, try again. Enter 'help' for a list of valid commands")
command = input().lower()
|
command = input().lower()
in_progress = True
car_stopped = True
while in_progress:
if command == 'help':
print('start - to start the car')
print('stop - to stop the car')
print('quit - to ext')
elif command == 'start':
if car_stopped:
print('You started the car')
car_stopped = False
else:
print('The car has already been started')
elif command == 'stop':
if not car_stopped:
print('You stopped the car')
car_stopped = True
else:
print('The car is already stopped')
elif command == 'quit':
print('Exiting the program now')
in_progress = False
break
else:
print("That was not a valid command, try again. Enter 'help' for a list of valid commands")
command = input().lower()
|
def create_xml_doc(text):
JS("""
try //Internet Explorer
{
var xmlDoc=new ActiveXObject("Microsoft['XMLDOM']");
xmlDoc['async']="false";
xmlDoc['loadXML'](@{{text}});
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
var parser=new DOMParser();
xmlDoc=parser['parseFromString'](@{{text}},"text/xml");
}
catch(e)
{
return null;
}
}
return xmlDoc;
""")
|
def create_xml_doc(text):
js('\ntry //Internet Explorer\n {\n var xmlDoc=new ActiveXObject("Microsoft[\'XMLDOM\']");\n xmlDoc[\'async\']="false";\n xmlDoc[\'loadXML\'](@{{text}});\n }\ncatch(e)\n {\n try //Firefox, Mozilla, Opera, etc.\n {\n var parser=new DOMParser();\n xmlDoc=parser[\'parseFromString\'](@{{text}},"text/xml");\n }\n catch(e)\n {\n return null;\n }\n }\n return xmlDoc;\n ')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014, Chris Hoffman <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: win_service
short_description: Manage and query Windows services
description:
- Manage and query Windows services.
- For non-Windows targets, use the M(ansible.builtin.service) module instead.
options:
dependencies:
description:
- A list of service dependencies to set for this particular service.
- This should be a list of service names and not the display name of the
service.
- This works by C(dependency_action) to either add/remove or set the
services in this list.
type: list
elements: str
dependency_action:
description:
- Used in conjunction with C(dependency) to either add the dependencies to
the existing service dependencies.
- Remove the dependencies to the existing dependencies.
- Set the dependencies to only the values in the list replacing the
existing dependencies.
type: str
choices: [ add, remove, set ]
default: set
desktop_interact:
description:
- Whether to allow the service user to interact with the desktop.
- This can only be set to C(yes) when using the C(LocalSystem) username.
- This can only be set to C(yes) when the I(service_type) is
C(win32_own_process) or C(win32_share_process).
type: bool
default: no
description:
description:
- The description to set for the service.
type: str
display_name:
description:
- The display name to set for the service.
type: str
error_control:
description:
- The severity of the error and action token if the service fails to start.
- A new service defaults to C(normal).
- C(critical) will log the error and restart the system with the last-known
good configuration. If the startup fails on reboot then the system will
fail to operate.
- C(ignore) ignores the error.
- C(normal) logs the error in the event log but continues.
- C(severe) is like C(critical) but a failure on the last-known good
configuration reboot startup will be ignored.
choices:
- critical
- ignore
- normal
- severe
type: str
failure_actions:
description:
- A list of failure actions the service controller should take on each
failure of a service.
- The service manager will run the actions from first to last defined until
the service starts. If I(failure_reset_period_sec) has been exceeded then
the failure actions will restart from the beginning.
- If all actions have been performed the the service manager will repeat
the last service defined.
- The existing actions will be replaced with the list defined in the task
if there is a mismatch with any of them.
- Set to an empty list to delete all failure actions on a service
otherwise an omitted or null value preserves the existing actions on the
service.
type: list
elements: dict
suboptions:
delay_ms:
description:
- The time to wait, in milliseconds, before performing the specified action.
default: 0
type: raw
aliases:
- delay
type:
description:
- The action to be performed.
- C(none) will perform no action, when used this should only be set as
the last action.
- C(reboot) will reboot the host, when used this should only be set as
the last action as the reboot will reset the action list back to the
beginning.
- C(restart) will restart the service.
- C(run_command) will run the command specified by I(failure_command).
required: yes
type: str
choices:
- none
- reboot
- restart
- run_command
failure_actions_on_non_crash_failure:
description:
- Controls whether failure actions will be performed on non crash failures
or not.
type: bool
failure_command:
description:
- The command to run for a C(run_command) failure action.
- Set to an empty string to remove the command.
type: str
failure_reboot_msg:
description:
- The message to be broadcast to users logged on the host for a C(reboot)
failure action.
- Set to an empty string to remove the message.
type: str
failure_reset_period_sec:
description:
- The time in seconds after which the failure action list begings from the
start if there are no failures.
- To set this value, I(failure_actions) must have at least 1 action
present.
- Specify C('0xFFFFFFFF') to set an infinite reset period.
type: raw
aliases:
- failure_reset_period
force_dependent_services:
description:
- If C(yes), stopping or restarting a service with dependent services will
force the dependent services to stop or restart also.
- If C(no), stopping or restarting a service with dependent services may
fail.
type: bool
default: no
load_order_group:
description:
- The name of the load ordering group of which this service is a member.
- Specify an empty string to remove the existing load order group of a
service.
type: str
name:
description:
- Name of the service.
- If only the name parameter is specified, the module will report
on whether the service exists or not without making any changes.
required: yes
type: str
path:
description:
- The path to the executable to set for the service.
type: str
password:
description:
- The password to set the service to start as.
- This and the C(username) argument should be supplied together when using a local or domain account.
- If omitted then the password will continue to use the existing value password set.
- If specifying C(LocalSystem), C(NetworkService), C(LocalService), the C(NT SERVICE), or a gMSA this field can be
omitted as those accounts have no password.
type: str
pre_shutdown_timeout_ms:
description:
- The time in which the service manager waits after sending a preshutdown
notification to the service until it proceeds to continue with the other
shutdown actions.
aliases:
- pre_shutdown_timeout
type: raw
required_privileges:
description:
- A list of privileges the service must have when starting up.
- When set the service will only have the privileges specified on its
access token.
- The I(username) of the service must already have the privileges assigned.
- The existing privileges will be replace with the list defined in the task
if there is a mismatch with any of them.
- Set to an empty list to remove all required privileges, otherwise an
omitted or null value will keep the existing privileges.
- See L(privilege text constants,https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants)
for a list of privilege constants that can be used.
type: list
elements: str
service_type:
description:
- The type of service.
- The default type of a new service is C(win32_own_process).
- I(desktop_interact) can only be set if the service type is
C(win32_own_process) or C(win32_share_process).
choices:
- user_own_process
- user_share_process
- win32_own_process
- win32_share_process
type: str
sid_info:
description:
- Used to define the behaviour of the service's access token groups.
- C(none) will not add any groups to the token.
- C(restricted) will add the C(NT SERVICE\<service name>) SID to the access
token's groups and restricted groups.
- C(unrestricted) will add the C(NT SERVICE\<service name>) SID to the
access token's groups.
choices:
- none
- restricted
- unrestricted
type: str
start_mode:
description:
- Set the startup type for the service.
- A newly created service will default to C(auto).
type: str
choices: [ auto, delayed, disabled, manual ]
state:
description:
- The desired state of the service.
- C(started)/C(stopped)/C(absent)/C(paused) are idempotent actions that will not run
commands unless necessary.
- C(restarted) will always bounce the service.
- Only services that support the paused state can be paused, you can
check the return value C(can_pause_and_continue).
- You can only pause a service that is already started.
- A newly created service will default to C(stopped).
type: str
choices: [ absent, paused, started, stopped, restarted ]
update_password:
description:
- When set to C(always) and I(password) is set, the module will always report a change and set the password.
- Set to C(on_create) to only set the password if the module needs to create the service.
- If I(username) was specified and the service changed to that username then I(password) will also be changed if
specified.
- The current default is C(on_create) but this behaviour may change in the future, it is best to be explicit here.
choices:
- always
- on_create
type: str
username:
description:
- The username to set the service to start as.
- Can also be set to C(LocalSystem) or C(SYSTEM) to use the SYSTEM account.
- A newly created service will default to C(LocalSystem).
- If using a custom user account, it must have the C(SeServiceLogonRight)
granted to be able to start up. You can use the M(ansible.windows.win_user_right) module
to grant this user right for you.
- Set to C(NT SERVICE\service name) to run as the NT SERVICE account for that service.
- This can also be a gMSA in the form C(DOMAIN\gMSA$).
type: str
notes:
- This module historically returning information about the service in its return values. These should be avoided in
favour of the M(ansible.windows.win_service_info) module.
- Most of the options in this module are non-driver services that you can view in SCManager. While you can edit driver
services, not all functionality may be available.
- The user running the module must have the following access rights on the service to be able to use it with this
module - C(SERVICE_CHANGE_CONFIG), C(SERVICE_ENUMERATE_DEPENDENTS), C(SERVICE_QUERY_CONFIG), C(SERVICE_QUERY_STATUS).
- Changing the state or removing the service will also require futher rights depending on what needs to be done.
seealso:
- module: ansible.builtin.service
- module: community.windows.win_nssm
- module: ansible.windows.win_service_info
- module: ansible.windows.win_user_right
author:
- Chris Hoffman (@chrishoffman)
'''
EXAMPLES = r'''
- name: Restart a service
ansible.windows.win_service:
name: spooler
state: restarted
- name: Set service startup mode to auto and ensure it is started
ansible.windows.win_service:
name: spooler
start_mode: auto
state: started
- name: Pause a service
ansible.windows.win_service:
name: Netlogon
state: paused
- name: Ensure that WinRM is started when the system has settled
ansible.windows.win_service:
name: WinRM
start_mode: delayed
# A new service will also default to the following values:
# - username: LocalSystem
# - state: stopped
# - start_mode: auto
- name: Create a new service
ansible.windows.win_service:
name: service name
path: C:\temp\test.exe
- name: Create a new service with extra details
ansible.windows.win_service:
name: service name
path: C:\temp\test.exe
display_name: Service Name
description: A test service description
- name: Remove a service
ansible.windows.win_service:
name: service name
state: absent
# This is required to be set for non-service accounts that need to run as a service
- name: Grant domain account the SeServiceLogonRight user right
ansible.windows.win_user_right:
name: SeServiceLogonRight
users:
- DOMAIN\User
action: add
- name: Set the log on user to a domain account
ansible.windows.win_service:
name: service name
state: restarted
username: DOMAIN\User
password: Password
- name: Set the log on user to a local account
ansible.windows.win_service:
name: service name
state: restarted
username: .\Administrator
password: Password
- name: Set the log on user to Local System
ansible.windows.win_service:
name: service name
state: restarted
username: SYSTEM
- name: Set the log on user to Local System and allow it to interact with the desktop
ansible.windows.win_service:
name: service name
state: restarted
username: SYSTEM
desktop_interact: yes
- name: Set the log on user to Network Service
ansible.windows.win_service:
name: service name
state: restarted
username: NT AUTHORITY\NetworkService
- name: Set the log on user to Local Service
ansible.windows.win_service:
name: service name
state: restarted
username: NT AUTHORITY\LocalService
- name: Set the log on user as the services' virtual account
ansible.windows.win_service:
name: service name
username: NT SERVICE\service name
- name: Set the log on user as a gMSA
ansible.windows.win_service:
name: service name
username: DOMAIN\gMSA$ # The end $ is important and should be set for all gMSA
- name: Set dependencies to ones only in the list
ansible.windows.win_service:
name: service name
dependencies: [ service1, service2 ]
- name: Add dependencies to existing dependencies
ansible.windows.win_service:
name: service name
dependencies: [ service1, service2 ]
dependency_action: add
- name: Remove dependencies from existing dependencies
ansible.windows.win_service:
name: service name
dependencies:
- service1
- service2
dependency_action: remove
- name: Set required privileges for a service
ansible.windows.win_service:
name: service name
username: NT SERVICE\LocalService
required_privileges:
- SeBackupPrivilege
- SeRestorePrivilege
- name: Remove all required privileges for a service
ansible.windows.win_service:
name: service name
username: NT SERVICE\LocalService
required_privileges: []
- name: Set failure actions for a service with no reset period
ansible.windows.win_service:
name: service name
failure_actions:
- type: restart
- type: run_command
delay_ms: 1000
- type: restart
delay_ms: 5000
- type: reboot
failure_command: C:\Windows\System32\cmd.exe /c mkdir C:\temp
failure_reboot_msg: Restarting host because service name has failed
failure_reset_period_sec: '0xFFFFFFFF'
- name: Set only 1 failure action without a repeat of the last action
ansible.windows.win_service:
name: service name
failure_actions:
- type: restart
delay_ms: 5000
- type: none
- name: Remove failure action information
ansible.windows.win_service:
name: service name
failure_actions: []
failure_command: '' # removes the existing command
failure_reboot_msg: '' # removes the existing reboot msg
'''
RETURN = r'''
exists:
description: Whether the service exists or not.
returned: success
type: bool
sample: true
name:
description: The service name or id of the service.
returned: success and service exists
type: str
sample: CoreMessagingRegistrar
display_name:
description: The display name of the installed service.
returned: success and service exists
type: str
sample: CoreMessaging
state:
description: The current running status of the service.
returned: success and service exists
type: str
sample: stopped
start_mode:
description: The startup type of the service.
returned: success and service exists
type: str
sample: manual
path:
description: The path to the service executable.
returned: success and service exists
type: str
sample: C:\Windows\system32\svchost.exe -k LocalServiceNoNetwork
can_pause_and_continue:
description: Whether the service can be paused and unpaused.
returned: success and service exists
type: bool
sample: true
description:
description: The description of the service.
returned: success and service exists
type: str
sample: Manages communication between system components.
username:
description: The username that runs the service.
returned: success and service exists
type: str
sample: LocalSystem
desktop_interact:
description: Whether the current user is allowed to interact with the desktop.
returned: success and service exists
type: bool
sample: false
dependencies:
description: A list of services that is depended by this service.
returned: success and service exists
type: list
sample: false
depended_by:
description: A list of services that depend on this service.
returned: success and service exists
type: list
sample: false
'''
|
documentation = "\n---\nmodule: win_service\nshort_description: Manage and query Windows services\ndescription:\n- Manage and query Windows services.\n- For non-Windows targets, use the M(ansible.builtin.service) module instead.\noptions:\n dependencies:\n description:\n - A list of service dependencies to set for this particular service.\n - This should be a list of service names and not the display name of the\n service.\n - This works by C(dependency_action) to either add/remove or set the\n services in this list.\n type: list\n elements: str\n dependency_action:\n description:\n - Used in conjunction with C(dependency) to either add the dependencies to\n the existing service dependencies.\n - Remove the dependencies to the existing dependencies.\n - Set the dependencies to only the values in the list replacing the\n existing dependencies.\n type: str\n choices: [ add, remove, set ]\n default: set\n desktop_interact:\n description:\n - Whether to allow the service user to interact with the desktop.\n - This can only be set to C(yes) when using the C(LocalSystem) username.\n - This can only be set to C(yes) when the I(service_type) is\n C(win32_own_process) or C(win32_share_process).\n type: bool\n default: no\n description:\n description:\n - The description to set for the service.\n type: str\n display_name:\n description:\n - The display name to set for the service.\n type: str\n error_control:\n description:\n - The severity of the error and action token if the service fails to start.\n - A new service defaults to C(normal).\n - C(critical) will log the error and restart the system with the last-known\n good configuration. If the startup fails on reboot then the system will\n fail to operate.\n - C(ignore) ignores the error.\n - C(normal) logs the error in the event log but continues.\n - C(severe) is like C(critical) but a failure on the last-known good\n configuration reboot startup will be ignored.\n choices:\n - critical\n - ignore\n - normal\n - severe\n type: str\n failure_actions:\n description:\n - A list of failure actions the service controller should take on each\n failure of a service.\n - The service manager will run the actions from first to last defined until\n the service starts. If I(failure_reset_period_sec) has been exceeded then\n the failure actions will restart from the beginning.\n - If all actions have been performed the the service manager will repeat\n the last service defined.\n - The existing actions will be replaced with the list defined in the task\n if there is a mismatch with any of them.\n - Set to an empty list to delete all failure actions on a service\n otherwise an omitted or null value preserves the existing actions on the\n service.\n type: list\n elements: dict\n suboptions:\n delay_ms:\n description:\n - The time to wait, in milliseconds, before performing the specified action.\n default: 0\n type: raw\n aliases:\n - delay\n type:\n description:\n - The action to be performed.\n - C(none) will perform no action, when used this should only be set as\n the last action.\n - C(reboot) will reboot the host, when used this should only be set as\n the last action as the reboot will reset the action list back to the\n beginning.\n - C(restart) will restart the service.\n - C(run_command) will run the command specified by I(failure_command).\n required: yes\n type: str\n choices:\n - none\n - reboot\n - restart\n - run_command\n failure_actions_on_non_crash_failure:\n description:\n - Controls whether failure actions will be performed on non crash failures\n or not.\n type: bool\n failure_command:\n description:\n - The command to run for a C(run_command) failure action.\n - Set to an empty string to remove the command.\n type: str\n failure_reboot_msg:\n description:\n - The message to be broadcast to users logged on the host for a C(reboot)\n failure action.\n - Set to an empty string to remove the message.\n type: str\n failure_reset_period_sec:\n description:\n - The time in seconds after which the failure action list begings from the\n start if there are no failures.\n - To set this value, I(failure_actions) must have at least 1 action\n present.\n - Specify C('0xFFFFFFFF') to set an infinite reset period.\n type: raw\n aliases:\n - failure_reset_period\n force_dependent_services:\n description:\n - If C(yes), stopping or restarting a service with dependent services will\n force the dependent services to stop or restart also.\n - If C(no), stopping or restarting a service with dependent services may\n fail.\n type: bool\n default: no\n load_order_group:\n description:\n - The name of the load ordering group of which this service is a member.\n - Specify an empty string to remove the existing load order group of a\n service.\n type: str\n name:\n description:\n - Name of the service.\n - If only the name parameter is specified, the module will report\n on whether the service exists or not without making any changes.\n required: yes\n type: str\n path:\n description:\n - The path to the executable to set for the service.\n type: str\n password:\n description:\n - The password to set the service to start as.\n - This and the C(username) argument should be supplied together when using a local or domain account.\n - If omitted then the password will continue to use the existing value password set.\n - If specifying C(LocalSystem), C(NetworkService), C(LocalService), the C(NT SERVICE), or a gMSA this field can be\n omitted as those accounts have no password.\n type: str\n pre_shutdown_timeout_ms:\n description:\n - The time in which the service manager waits after sending a preshutdown\n notification to the service until it proceeds to continue with the other\n shutdown actions.\n aliases:\n - pre_shutdown_timeout\n type: raw\n required_privileges:\n description:\n - A list of privileges the service must have when starting up.\n - When set the service will only have the privileges specified on its\n access token.\n - The I(username) of the service must already have the privileges assigned.\n - The existing privileges will be replace with the list defined in the task\n if there is a mismatch with any of them.\n - Set to an empty list to remove all required privileges, otherwise an\n omitted or null value will keep the existing privileges.\n - See L(privilege text constants,https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants)\n for a list of privilege constants that can be used.\n type: list\n elements: str\n service_type:\n description:\n - The type of service.\n - The default type of a new service is C(win32_own_process).\n - I(desktop_interact) can only be set if the service type is\n C(win32_own_process) or C(win32_share_process).\n choices:\n - user_own_process\n - user_share_process\n - win32_own_process\n - win32_share_process\n type: str\n sid_info:\n description:\n - Used to define the behaviour of the service's access token groups.\n - C(none) will not add any groups to the token.\n - C(restricted) will add the C(NT SERVICE\\<service name>) SID to the access\n token's groups and restricted groups.\n - C(unrestricted) will add the C(NT SERVICE\\<service name>) SID to the\n access token's groups.\n choices:\n - none\n - restricted\n - unrestricted\n type: str\n start_mode:\n description:\n - Set the startup type for the service.\n - A newly created service will default to C(auto).\n type: str\n choices: [ auto, delayed, disabled, manual ]\n state:\n description:\n - The desired state of the service.\n - C(started)/C(stopped)/C(absent)/C(paused) are idempotent actions that will not run\n commands unless necessary.\n - C(restarted) will always bounce the service.\n - Only services that support the paused state can be paused, you can\n check the return value C(can_pause_and_continue).\n - You can only pause a service that is already started.\n - A newly created service will default to C(stopped).\n type: str\n choices: [ absent, paused, started, stopped, restarted ]\n update_password:\n description:\n - When set to C(always) and I(password) is set, the module will always report a change and set the password.\n - Set to C(on_create) to only set the password if the module needs to create the service.\n - If I(username) was specified and the service changed to that username then I(password) will also be changed if\n specified.\n - The current default is C(on_create) but this behaviour may change in the future, it is best to be explicit here.\n choices:\n - always\n - on_create\n type: str\n username:\n description:\n - The username to set the service to start as.\n - Can also be set to C(LocalSystem) or C(SYSTEM) to use the SYSTEM account.\n - A newly created service will default to C(LocalSystem).\n - If using a custom user account, it must have the C(SeServiceLogonRight)\n granted to be able to start up. You can use the M(ansible.windows.win_user_right) module\n to grant this user right for you.\n - Set to C(NT SERVICE\\service name) to run as the NT SERVICE account for that service.\n - This can also be a gMSA in the form C(DOMAIN\\gMSA$).\n type: str\nnotes:\n- This module historically returning information about the service in its return values. These should be avoided in\n favour of the M(ansible.windows.win_service_info) module.\n- Most of the options in this module are non-driver services that you can view in SCManager. While you can edit driver\n services, not all functionality may be available.\n- The user running the module must have the following access rights on the service to be able to use it with this\n module - C(SERVICE_CHANGE_CONFIG), C(SERVICE_ENUMERATE_DEPENDENTS), C(SERVICE_QUERY_CONFIG), C(SERVICE_QUERY_STATUS).\n- Changing the state or removing the service will also require futher rights depending on what needs to be done.\nseealso:\n- module: ansible.builtin.service\n- module: community.windows.win_nssm\n- module: ansible.windows.win_service_info\n- module: ansible.windows.win_user_right\nauthor:\n- Chris Hoffman (@chrishoffman)\n"
examples = "\n- name: Restart a service\n ansible.windows.win_service:\n name: spooler\n state: restarted\n\n- name: Set service startup mode to auto and ensure it is started\n ansible.windows.win_service:\n name: spooler\n start_mode: auto\n state: started\n\n- name: Pause a service\n ansible.windows.win_service:\n name: Netlogon\n state: paused\n\n- name: Ensure that WinRM is started when the system has settled\n ansible.windows.win_service:\n name: WinRM\n start_mode: delayed\n\n# A new service will also default to the following values:\n# - username: LocalSystem\n# - state: stopped\n# - start_mode: auto\n- name: Create a new service\n ansible.windows.win_service:\n name: service name\n path: C:\\temp\\test.exe\n\n- name: Create a new service with extra details\n ansible.windows.win_service:\n name: service name\n path: C:\\temp\\test.exe\n display_name: Service Name\n description: A test service description\n\n- name: Remove a service\n ansible.windows.win_service:\n name: service name\n state: absent\n\n# This is required to be set for non-service accounts that need to run as a service\n- name: Grant domain account the SeServiceLogonRight user right\n ansible.windows.win_user_right:\n name: SeServiceLogonRight\n users:\n - DOMAIN\\User\n action: add\n\n- name: Set the log on user to a domain account\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: DOMAIN\\User\n password: Password\n\n- name: Set the log on user to a local account\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: .\\Administrator\n password: Password\n\n- name: Set the log on user to Local System\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: SYSTEM\n\n- name: Set the log on user to Local System and allow it to interact with the desktop\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: SYSTEM\n desktop_interact: yes\n\n- name: Set the log on user to Network Service\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: NT AUTHORITY\\NetworkService\n\n- name: Set the log on user to Local Service\n ansible.windows.win_service:\n name: service name\n state: restarted\n username: NT AUTHORITY\\LocalService\n\n- name: Set the log on user as the services' virtual account\n ansible.windows.win_service:\n name: service name\n username: NT SERVICE\\service name\n\n- name: Set the log on user as a gMSA\n ansible.windows.win_service:\n name: service name\n username: DOMAIN\\gMSA$ # The end $ is important and should be set for all gMSA\n\n- name: Set dependencies to ones only in the list\n ansible.windows.win_service:\n name: service name\n dependencies: [ service1, service2 ]\n\n- name: Add dependencies to existing dependencies\n ansible.windows.win_service:\n name: service name\n dependencies: [ service1, service2 ]\n dependency_action: add\n\n- name: Remove dependencies from existing dependencies\n ansible.windows.win_service:\n name: service name\n dependencies:\n - service1\n - service2\n dependency_action: remove\n\n- name: Set required privileges for a service\n ansible.windows.win_service:\n name: service name\n username: NT SERVICE\\LocalService\n required_privileges:\n - SeBackupPrivilege\n - SeRestorePrivilege\n\n- name: Remove all required privileges for a service\n ansible.windows.win_service:\n name: service name\n username: NT SERVICE\\LocalService\n required_privileges: []\n\n- name: Set failure actions for a service with no reset period\n ansible.windows.win_service:\n name: service name\n failure_actions:\n - type: restart\n - type: run_command\n delay_ms: 1000\n - type: restart\n delay_ms: 5000\n - type: reboot\n failure_command: C:\\Windows\\System32\\cmd.exe /c mkdir C:\\temp\n failure_reboot_msg: Restarting host because service name has failed\n failure_reset_period_sec: '0xFFFFFFFF'\n\n- name: Set only 1 failure action without a repeat of the last action\n ansible.windows.win_service:\n name: service name\n failure_actions:\n - type: restart\n delay_ms: 5000\n - type: none\n\n- name: Remove failure action information\n ansible.windows.win_service:\n name: service name\n failure_actions: []\n failure_command: '' # removes the existing command\n failure_reboot_msg: '' # removes the existing reboot msg\n"
return = '\nexists:\n description: Whether the service exists or not.\n returned: success\n type: bool\n sample: true\nname:\n description: The service name or id of the service.\n returned: success and service exists\n type: str\n sample: CoreMessagingRegistrar\ndisplay_name:\n description: The display name of the installed service.\n returned: success and service exists\n type: str\n sample: CoreMessaging\nstate:\n description: The current running status of the service.\n returned: success and service exists\n type: str\n sample: stopped\nstart_mode:\n description: The startup type of the service.\n returned: success and service exists\n type: str\n sample: manual\npath:\n description: The path to the service executable.\n returned: success and service exists\n type: str\n sample: C:\\Windows\\system32\\svchost.exe -k LocalServiceNoNetwork\ncan_pause_and_continue:\n description: Whether the service can be paused and unpaused.\n returned: success and service exists\n type: bool\n sample: true\ndescription:\n description: The description of the service.\n returned: success and service exists\n type: str\n sample: Manages communication between system components.\nusername:\n description: The username that runs the service.\n returned: success and service exists\n type: str\n sample: LocalSystem\ndesktop_interact:\n description: Whether the current user is allowed to interact with the desktop.\n returned: success and service exists\n type: bool\n sample: false\ndependencies:\n description: A list of services that is depended by this service.\n returned: success and service exists\n type: list\n sample: false\ndepended_by:\n description: A list of services that depend on this service.\n returned: success and service exists\n type: list\n sample: false\n'
|
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
# write your code here
if not candidates or len(candidates) == 0:
return [[]]
candidates.sort()
self.results = []
self.target = target
visited = [False for _ in range(len(candidates))]
self._find_combination_sum(candidates, [], visited, 0)
return self.results
def _find_combination_sum(self, candidates, current_combination, visited, start):
if sum(current_combination) == self.target:
current_combination.sort()
self.results.append(current_combination[:])
return
for i in range(start, len(candidates)):
if sum(current_combination) + candidates[i] > self.target:
break
if i > 0 and candidates[i - 1] == candidates[i] and not visited[i - 1]:
continue
current_combination.append(candidates[i])
visited[i] = True
self._find_combination_sum(candidates, current_combination, visited, i)
current_combination.pop()
visited[i] = False
|
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combination_sum(self, candidates, target):
if not candidates or len(candidates) == 0:
return [[]]
candidates.sort()
self.results = []
self.target = target
visited = [False for _ in range(len(candidates))]
self._find_combination_sum(candidates, [], visited, 0)
return self.results
def _find_combination_sum(self, candidates, current_combination, visited, start):
if sum(current_combination) == self.target:
current_combination.sort()
self.results.append(current_combination[:])
return
for i in range(start, len(candidates)):
if sum(current_combination) + candidates[i] > self.target:
break
if i > 0 and candidates[i - 1] == candidates[i] and (not visited[i - 1]):
continue
current_combination.append(candidates[i])
visited[i] = True
self._find_combination_sum(candidates, current_combination, visited, i)
current_combination.pop()
visited[i] = False
|
# test exception matching against a tuple
try:
fail
except (Exception,):
print('except 1')
try:
fail
except (Exception, Exception):
print('except 2')
try:
fail
except (TypeError, NameError):
print('except 3')
try:
fail
except (TypeError, ValueError, Exception):
print('except 4')
|
try:
fail
except (Exception,):
print('except 1')
try:
fail
except (Exception, Exception):
print('except 2')
try:
fail
except (TypeError, NameError):
print('except 3')
try:
fail
except (TypeError, ValueError, Exception):
print('except 4')
|
def printMaximum(num):
d = {}
for i in range(10):
d[i] = 0
for i in str(num):
d[int(i)] += 1
res = 0
m = 1
for i in list(d.keys()):
while d[i] > 0:
res = res + i*m
d[i] -= 1
m *= 10
return res
# Driver code
num = 38293367
print(printMaximum(num))
|
def print_maximum(num):
d = {}
for i in range(10):
d[i] = 0
for i in str(num):
d[int(i)] += 1
res = 0
m = 1
for i in list(d.keys()):
while d[i] > 0:
res = res + i * m
d[i] -= 1
m *= 10
return res
num = 38293367
print(print_maximum(num))
|
NUMERIC = "numeric"
CATEGORICAL = "categorical"
TEST_MODEL = "test"
SINGLE_MODEL = "single"
MODEL_SEARCH = "search"
SHUTDOWN = "shutdown"
DEFAULT_PORT = 8042
DEFAULT_MAX_JOBS = 4
ERROR = "error"
QUEUED = "queued"
STARTED = "started"
IN_PROGRESS = "in-progress"
FINISHED = "finished"
# This can be any x where np.exp(x) + 1 == np.exp(x) Going up to 512
# isn't strictly necessary, but hey, why not?
LARGE_EXP = 512
EPSILON = 1e-4
# Parameters that can appear in the layers of models
MATRIX_PARAMS = [
'weights'
]
VEC_PARAMS = [
'mean',
'variance',
'offset',
'scale',
'stdev'
]
# Model search parameters
VALIDATION_FRAC = 0.15
MAX_VALIDATION_ROWS = 4096
LEARN_INCREMENT = 8
MAX_QUEUE = LEARN_INCREMENT * 4
N_CANDIDATES = MAX_QUEUE * 64
|
numeric = 'numeric'
categorical = 'categorical'
test_model = 'test'
single_model = 'single'
model_search = 'search'
shutdown = 'shutdown'
default_port = 8042
default_max_jobs = 4
error = 'error'
queued = 'queued'
started = 'started'
in_progress = 'in-progress'
finished = 'finished'
large_exp = 512
epsilon = 0.0001
matrix_params = ['weights']
vec_params = ['mean', 'variance', 'offset', 'scale', 'stdev']
validation_frac = 0.15
max_validation_rows = 4096
learn_increment = 8
max_queue = LEARN_INCREMENT * 4
n_candidates = MAX_QUEUE * 64
|
class TopTen:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if self.num <= 10:
val = self.num
self.num += 1
return val
else:
raise StopIteration
values = TopTen()
print(next(values))
for i in values:
print(i)
|
class Topten:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if self.num <= 10:
val = self.num
self.num += 1
return val
else:
raise StopIteration
values = top_ten()
print(next(values))
for i in values:
print(i)
|
class cached_property:
def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
def __get__(self, obj, cls):
if obj is None:
return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
|
class Cached_Property:
def __init__(self, func):
self.__doc__ = getattr(func, '__doc__')
self.func = func
def __get__(self, obj, cls):
if obj is None:
return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
|
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
def tf_pack_ext(pb):
assert (pb.attr["N"].i == len(pb.input))
return {
'axis': pb.attr["axis"].i,
'N': pb.attr["N"].i,
'infer': None
}
|
def tf_pack_ext(pb):
assert pb.attr['N'].i == len(pb.input)
return {'axis': pb.attr['axis'].i, 'N': pb.attr['N'].i, 'infer': None}
|
class ZoomAdminAccount(object):
""" Model to hold Zoom Admin Account info """
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
|
class Zoomadminaccount(object):
""" Model to hold Zoom Admin Account info """
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
|
#!/usr/bin/python3
ls = [l.strip().split(" ") for l in open("inputs/08.in", "r").readlines()]
def run(sw):
acc,p,ps = 0,0,[]
while p < len(ls):
if p in ps: return acc if sw == -1 else -1
ps.append(p)
acc += int(ls[p][1]) if ls[p][0] == "acc" else 0
p += int(ls[p][1]) if (ls[p][0]=="jmp" and sw!=p) or (ls[p][0]=="nop" and sw==p) else 1
return acc
def brute():
for i,l in enumerate(ls):
if l[0] == "acc": continue
ans = run(i)
if ans != -1: return ans
print("Part 1:", run(-1))
print("Part 2:", brute())
|
ls = [l.strip().split(' ') for l in open('inputs/08.in', 'r').readlines()]
def run(sw):
(acc, p, ps) = (0, 0, [])
while p < len(ls):
if p in ps:
return acc if sw == -1 else -1
ps.append(p)
acc += int(ls[p][1]) if ls[p][0] == 'acc' else 0
p += int(ls[p][1]) if ls[p][0] == 'jmp' and sw != p or (ls[p][0] == 'nop' and sw == p) else 1
return acc
def brute():
for (i, l) in enumerate(ls):
if l[0] == 'acc':
continue
ans = run(i)
if ans != -1:
return ans
print('Part 1:', run(-1))
print('Part 2:', brute())
|
counter = 0
def merge(array, left, right):
i = j = k = 0
global counter
while i < len(left) and j < len(right):
if left[i] <= right[j]:
array[k] = left[i]
k += 1
i += 1
else:
array[k] = right[j]
counter += len(left) - i
k += 1
j += 1
if len(left) > i:
array[k:] = left[i:]
elif len(right) > j:
array[k:] = right[j:]
def mergesort(array):
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
mergesort(left)
mergesort(right)
merge(array, left, right)
return array
fin = open("inversions.in")
fout = open("inversions.out", "w")
n = int(fin.readline())
array = list(map(int, fin.readline().split()))
mergesort(array)
print(counter, file=fout)
fin.close()
fout.close()
|
counter = 0
def merge(array, left, right):
i = j = k = 0
global counter
while i < len(left) and j < len(right):
if left[i] <= right[j]:
array[k] = left[i]
k += 1
i += 1
else:
array[k] = right[j]
counter += len(left) - i
k += 1
j += 1
if len(left) > i:
array[k:] = left[i:]
elif len(right) > j:
array[k:] = right[j:]
def mergesort(array):
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
mergesort(left)
mergesort(right)
merge(array, left, right)
return array
fin = open('inversions.in')
fout = open('inversions.out', 'w')
n = int(fin.readline())
array = list(map(int, fin.readline().split()))
mergesort(array)
print(counter, file=fout)
fin.close()
fout.close()
|
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains C++ code needed to export one dimensional static arrays.
"""
namespace = "pyplusplus::convenience"
file_name = "__convenience.pypp.hpp"
code = \
"""// Copyright 2004-2008 Roman Yakovenko.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __convenience_pyplusplus_hpp__
#define __convenience_pyplusplus_hpp__
#include "boost/python.hpp"
namespace pyplusplus{ namespace convenience{
//TODO: Replace index_type with Boost.Python defined ssize_t type.
// This should be done by checking Python and Boost.Python version.
typedef int index_type;
inline void
raise_error( PyObject *exception, const char *message ){
PyErr_SetString(exception, message);
boost::python::throw_error_already_set();
}
inline index_type sequence_len(boost::python::object const& obj){
if( !PySequence_Check( obj.ptr() ) ){
raise_error( PyExc_TypeError, "Sequence expected" );
}
index_type result = PyObject_Length( obj.ptr() );
if( PyErr_Occurred() ){
boost::python::throw_error_already_set();
}
return result;
}
inline void
ensure_sequence( boost::python::object seq, index_type expected_length=-1 ){
index_type length = sequence_len( seq );
if( expected_length != -1 && length != expected_length ){
std::stringstream err;
err << "Expected sequence length is " << expected_length << ". "
<< "Actual sequence length is " << length << ".";
raise_error( PyExc_ValueError, err.str().c_str() );
}
}
template< class ExpectedType >
void ensure_uniform_sequence( boost::python::object seq, index_type expected_length=-1 ){
ensure_sequence( seq, expected_length );
index_type length = sequence_len( seq );
for( index_type index = 0; index < length; ++index ){
boost::python::object item = seq[index];
boost::python::extract<ExpectedType> type_checker( item );
if( !type_checker.check() ){
std::string expected_type_name( boost::python::type_id<ExpectedType>().name() );
std::string item_type_name("different");
PyObject* item_impl = item.ptr();
if( item_impl && item_impl->ob_type && item_impl->ob_type->tp_name ){
item_type_name = std::string( item_impl->ob_type->tp_name );
}
std::stringstream err;
err << "Sequence should contain only items with type \\"" << expected_type_name << "\\". "
<< "Item at position " << index << " has \\"" << item_type_name << "\\" type.";
raise_error( PyExc_ValueError, err.str().c_str() );
}
}
}
template< class Iterator, class Inserter >
void copy_container( Iterator begin, Iterator end, Inserter inserter ){
for( Iterator index = begin; index != end; ++index )
inserter( *index );
}
template< class Inserter >
void copy_sequence( boost::python::object const& seq, Inserter inserter ){
index_type length = sequence_len( seq );
for( index_type index = 0; index < length; ++index ){
inserter = seq[index];
}
}
template< class Inserter, class TItemType >
void copy_sequence( boost::python::object const& seq, Inserter inserter, boost::type< TItemType > ){
index_type length = sequence_len( seq );
for( index_type index = 0; index < length; ++index ){
boost::python::object item = seq[index];
inserter = boost::python::extract< TItemType >( item );
}
}
struct list_inserter{
list_inserter( boost::python::list& py_list )
: m_py_list( py_list )
{}
template< class T >
void operator()( T const & value ){
m_py_list.append( value );
}
private:
boost::python::list& m_py_list;
};
template < class T >
struct array_inserter_t{
array_inserter_t( T* array, index_type size )
: m_array( array )
, m_curr_pos( 0 )
, m_size( size )
{}
void insert( const T& item ){
if( m_size <= m_curr_pos ){
std::stringstream err;
err << "Index out of range. Array size is" << m_size << ", "
<< "current position is" << m_curr_pos << ".";
raise_error( PyExc_ValueError, err.str().c_str() );
}
m_array[ m_curr_pos ] = item;
m_curr_pos += 1;
}
array_inserter_t<T>&
operator=( boost::python::object const & item ){
insert( boost::python::extract< T >( item ) );
return *this;
}
private:
T* m_array;
index_type m_curr_pos;
const index_type m_size;
};
template< class T>
array_inserter_t<T> array_inserter( T* array, index_type size ){
return array_inserter_t<T>( array, size );
}
inline boost::python::object
get_out_argument( boost::python::object result, const char* arg_name ){
if( !PySequence_Check( result.ptr() ) ){
return result;
}
boost::python::object cls = boost::python::getattr( result, "__class__" );
boost::python::object cls_name = boost::python::getattr( cls, "__name__" );
std::string name = boost::python::extract< std::string >( cls_name );
if( "named_tuple" == name ){
return boost::python::getattr( result, arg_name );
}
else{
return result;
}
}
inline boost::python::object
get_out_argument( boost::python::object result, index_type index ){
if( !PySequence_Check( result.ptr() ) ){
return result;
}
boost::python::object cls = boost::python::getattr( result, "__class__" );
boost::python::object cls_name = boost::python::getattr( cls, "__name__" );
std::string name = boost::python::extract< std::string >( cls_name );
if( "named_tuple" == name ){
return result[ index ];
}
else{
return result;
}
}
} /*pyplusplus*/ } /*convenience*/
namespace pyplus_conv = pyplusplus::convenience;
#endif//__convenience_pyplusplus_hpp__
"""
|
"""
This file contains C++ code needed to export one dimensional static arrays.
"""
namespace = 'pyplusplus::convenience'
file_name = '__convenience.pypp.hpp'
code = '// Copyright 2004-2008 Roman Yakovenko.\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef __convenience_pyplusplus_hpp__\n#define __convenience_pyplusplus_hpp__\n\n#include "boost/python.hpp"\n\nnamespace pyplusplus{ namespace convenience{\n\n//TODO: Replace index_type with Boost.Python defined ssize_t type.\n// This should be done by checking Python and Boost.Python version.\ntypedef int index_type;\n\ninline void\nraise_error( PyObject *exception, const char *message ){\n PyErr_SetString(exception, message);\n boost::python::throw_error_already_set();\n}\n\ninline index_type sequence_len(boost::python::object const& obj){\n if( !PySequence_Check( obj.ptr() ) ){\n raise_error( PyExc_TypeError, "Sequence expected" );\n }\n\n index_type result = PyObject_Length( obj.ptr() );\n if( PyErr_Occurred() ){\n boost::python::throw_error_already_set();\n }\n return result;\n}\n\ninline void\nensure_sequence( boost::python::object seq, index_type expected_length=-1 ){\n index_type length = sequence_len( seq );\n if( expected_length != -1 && length != expected_length ){\n std::stringstream err;\n err << "Expected sequence length is " << expected_length << ". "\n << "Actual sequence length is " << length << ".";\n raise_error( PyExc_ValueError, err.str().c_str() );\n }\n}\n\ntemplate< class ExpectedType >\nvoid ensure_uniform_sequence( boost::python::object seq, index_type expected_length=-1 ){\n ensure_sequence( seq, expected_length );\n\n index_type length = sequence_len( seq );\n for( index_type index = 0; index < length; ++index ){\n boost::python::object item = seq[index];\n\n boost::python::extract<ExpectedType> type_checker( item );\n if( !type_checker.check() ){\n std::string expected_type_name( boost::python::type_id<ExpectedType>().name() );\n\n std::string item_type_name("different");\n PyObject* item_impl = item.ptr();\n if( item_impl && item_impl->ob_type && item_impl->ob_type->tp_name ){\n item_type_name = std::string( item_impl->ob_type->tp_name );\n }\n\n std::stringstream err;\n err << "Sequence should contain only items with type \\"" << expected_type_name << "\\". "\n << "Item at position " << index << " has \\"" << item_type_name << "\\" type.";\n raise_error( PyExc_ValueError, err.str().c_str() );\n }\n }\n}\n\ntemplate< class Iterator, class Inserter >\nvoid copy_container( Iterator begin, Iterator end, Inserter inserter ){\n for( Iterator index = begin; index != end; ++index )\n inserter( *index );\n}\n\ntemplate< class Inserter >\nvoid copy_sequence( boost::python::object const& seq, Inserter inserter ){\n index_type length = sequence_len( seq );\n for( index_type index = 0; index < length; ++index ){\n inserter = seq[index];\n }\n}\n\ntemplate< class Inserter, class TItemType >\nvoid copy_sequence( boost::python::object const& seq, Inserter inserter, boost::type< TItemType > ){\n index_type length = sequence_len( seq );\n for( index_type index = 0; index < length; ++index ){\n boost::python::object item = seq[index];\n inserter = boost::python::extract< TItemType >( item );\n }\n}\n\nstruct list_inserter{\n list_inserter( boost::python::list& py_list )\n : m_py_list( py_list )\n {}\n \n template< class T >\n void operator()( T const & value ){\n m_py_list.append( value );\n }\nprivate:\n boost::python::list& m_py_list;\n};\n\ntemplate < class T >\nstruct array_inserter_t{\n array_inserter_t( T* array, index_type size )\n : m_array( array )\n , m_curr_pos( 0 )\n , m_size( size )\n {}\n\n void insert( const T& item ){\n if( m_size <= m_curr_pos ){\n std::stringstream err;\n err << "Index out of range. Array size is" << m_size << ", "\n << "current position is" << m_curr_pos << ".";\n raise_error( PyExc_ValueError, err.str().c_str() );\n }\n m_array[ m_curr_pos ] = item;\n m_curr_pos += 1;\n }\n\n array_inserter_t<T>& \n operator=( boost::python::object const & item ){\n insert( boost::python::extract< T >( item ) );\n return *this;\n }\n \nprivate:\n T* m_array;\n index_type m_curr_pos;\n const index_type m_size;\n};\n\ntemplate< class T>\narray_inserter_t<T> array_inserter( T* array, index_type size ){\n return array_inserter_t<T>( array, size );\n}\n\ninline boost::python::object \nget_out_argument( boost::python::object result, const char* arg_name ){\n if( !PySequence_Check( result.ptr() ) ){\n return result;\n } \n boost::python::object cls = boost::python::getattr( result, "__class__" );\n boost::python::object cls_name = boost::python::getattr( cls, "__name__" );\n std::string name = boost::python::extract< std::string >( cls_name );\n if( "named_tuple" == name ){\n return boost::python::getattr( result, arg_name ); \n }\n else{\n return result;\n }\n \n}\n\ninline boost::python::object \nget_out_argument( boost::python::object result, index_type index ){\n if( !PySequence_Check( result.ptr() ) ){\n return result;\n } \n boost::python::object cls = boost::python::getattr( result, "__class__" );\n boost::python::object cls_name = boost::python::getattr( cls, "__name__" );\n std::string name = boost::python::extract< std::string >( cls_name );\n if( "named_tuple" == name ){\n return result[ index ]; \n }\n else{\n return result;\n }\n}\n\n} /*pyplusplus*/ } /*convenience*/\n\nnamespace pyplus_conv = pyplusplus::convenience;\n\n#endif//__convenience_pyplusplus_hpp__\n\n'
|
"""
This module contains the error messages issued by the Cerberus Validator.
The test suite uses this module as well.
"""
ERROR_SCHEMA_MISSING = "validation schema missing"
ERROR_SCHEMA_FORMAT = "'%s' is not a schema, must be a dict"
ERROR_DOCUMENT_MISSING = "document is missing"
ERROR_DOCUMENT_FORMAT = "'%s' is not a document, must be a dict"
ERROR_UNKNOWN_RULE = "unknown rule '%s' for field '%s'"
ERROR_DEFINITION_FORMAT = "schema definition for field '%s' must be a dict"
ERROR_UNKNOWN_FIELD = "unknown field"
ERROR_REQUIRED_FIELD = "required field"
ERROR_UNKNOWN_TYPE = "unrecognized data-type '%s'"
ERROR_BAD_TYPE = "must be of %s type"
ERROR_MIN_LENGTH = "min length is %d"
ERROR_MAX_LENGTH = "max length is %d"
ERROR_UNALLOWED_VALUES = "unallowed values %s"
ERROR_UNALLOWED_VALUE = "unallowed value %s"
ERROR_ITEMS_LIST = "length of list should be %d"
ERROR_READONLY_FIELD = "field is read-only"
ERROR_MAX_VALUE = "max value is %d"
ERROR_MIN_VALUE = "min value is %d"
ERROR_EMPTY_NOT_ALLOWED = "empty values not allowed"
ERROR_NOT_NULLABLE = "null value not allowed"
ERROR_REGEX = "value does not match regex '%s'"
ERROR_DEPENDENCIES_FIELD = "field '%s' is required"
|
"""
This module contains the error messages issued by the Cerberus Validator.
The test suite uses this module as well.
"""
error_schema_missing = 'validation schema missing'
error_schema_format = "'%s' is not a schema, must be a dict"
error_document_missing = 'document is missing'
error_document_format = "'%s' is not a document, must be a dict"
error_unknown_rule = "unknown rule '%s' for field '%s'"
error_definition_format = "schema definition for field '%s' must be a dict"
error_unknown_field = 'unknown field'
error_required_field = 'required field'
error_unknown_type = "unrecognized data-type '%s'"
error_bad_type = 'must be of %s type'
error_min_length = 'min length is %d'
error_max_length = 'max length is %d'
error_unallowed_values = 'unallowed values %s'
error_unallowed_value = 'unallowed value %s'
error_items_list = 'length of list should be %d'
error_readonly_field = 'field is read-only'
error_max_value = 'max value is %d'
error_min_value = 'min value is %d'
error_empty_not_allowed = 'empty values not allowed'
error_not_nullable = 'null value not allowed'
error_regex = "value does not match regex '%s'"
error_dependencies_field = "field '%s' is required"
|
class ExtDefines(object):
EDEFINE1 = 'ED1'
EDEFINE2 = 'ED2'
EDEFINE3 = 'ED3'
EDEFINES = (
(EDEFINE1, 'EDefine 1'),
(EDEFINE2, 'EDefine 2'),
(EDEFINE3, 'EDefine 3'),
)
class EmptyDefines(object):
"""
This should not show up when a module is dumped!
"""
pass
|
class Extdefines(object):
edefine1 = 'ED1'
edefine2 = 'ED2'
edefine3 = 'ED3'
edefines = ((EDEFINE1, 'EDefine 1'), (EDEFINE2, 'EDefine 2'), (EDEFINE3, 'EDefine 3'))
class Emptydefines(object):
"""
This should not show up when a module is dumped!
"""
pass
|
# n = n
# time = O(logn)
# space = O(1)
# done time = 5m
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n + 1
while left < right:
mid = left + right >> 1
comp = isBadVersion(mid)
if comp:
right = mid
else:
left = mid + 1
return right
|
class Solution:
def first_bad_version(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n + 1
while left < right:
mid = left + right >> 1
comp = is_bad_version(mid)
if comp:
right = mid
else:
left = mid + 1
return right
|
def fib(n: int) -> int:
if n < 2: # base case
return n
return fib(n - 2) + fib(n - 1)
if __name__ == "__main__":
print(fib(2))
print(fib(10))
|
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 2) + fib(n - 1)
if __name__ == '__main__':
print(fib(2))
print(fib(10))
|
#!/usr/bin/env python3
class ApiDefaults:
url_verify = "/api/verify_api_key"
url_refresh = "/api/import/refresh"
url_add = "/api/import/add"
|
class Apidefaults:
url_verify = '/api/verify_api_key'
url_refresh = '/api/import/refresh'
url_add = '/api/import/add'
|
"""
entradas
nbilletes50-->int-->n1
nbilletes20-->int-->n2
nbilletes10-->int-->n3
nbilletes5-->int-->n4
nbilletes2-->int-->n5
nbilletes1-->int-->n6
nbilletes500-->int-->n7
nbilletes100-->int-->n8
salidas
total_dinero-->str-->td
"""
n1=(int(input("digite la cantidad de billetes de $50000 ")))
n2=(int(input("digite la cantidad de billetes de $20000 ")))
n3=(int(input("digite la cantidad de billetes de $10000 ")))
n4=(int(input("digite la cantidad de billetes de $5000 ")))
n5=(int(input("digite la cantidad de billetes de $2000 ")))
n6=(int(input("digite la cantidad de billetes de $1000 ")))
n7=(int(input("digite la cantidad de billetes de $500 ")))
n8=(int(input("digite la cantidad de billetes de $100 ")))
td=(n1*50000)+(n2*20000)+(n3*10000)+(n4*5000)+(n5*2000)+(n6*1000)+(n7*500)+(n8*100)
print("el total de dinero es $" + str (td))
|
"""
entradas
nbilletes50-->int-->n1
nbilletes20-->int-->n2
nbilletes10-->int-->n3
nbilletes5-->int-->n4
nbilletes2-->int-->n5
nbilletes1-->int-->n6
nbilletes500-->int-->n7
nbilletes100-->int-->n8
salidas
total_dinero-->str-->td
"""
n1 = int(input('digite la cantidad de billetes de $50000 '))
n2 = int(input('digite la cantidad de billetes de $20000 '))
n3 = int(input('digite la cantidad de billetes de $10000 '))
n4 = int(input('digite la cantidad de billetes de $5000 '))
n5 = int(input('digite la cantidad de billetes de $2000 '))
n6 = int(input('digite la cantidad de billetes de $1000 '))
n7 = int(input('digite la cantidad de billetes de $500 '))
n8 = int(input('digite la cantidad de billetes de $100 '))
td = n1 * 50000 + n2 * 20000 + n3 * 10000 + n4 * 5000 + n5 * 2000 + n6 * 1000 + n7 * 500 + n8 * 100
print('el total de dinero es $' + str(td))
|
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
sum = 0
for w in range(len(grid)):
for h in range(len(grid[0])):
if grid[w][h] == 1: add_length = 4
else: continue
if w != 0 and grid[w - 1][h] == 1: add_length -= 2
if h != 0 and grid[w][h - 1] == 1: add_length -= 2
sum += add_length
return sum
class Solution2:
def islandPerimeter(self, grid: List[List[int]]) -> int:
total = 0
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
cur = 4
for dx, dy in direct:
new_x = i + dx
new_y = j + dy
if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]):
if grid[new_x][new_y] == 1:
cur -= 1
total += cur
return total
|
class Solution(object):
def island_perimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
sum = 0
for w in range(len(grid)):
for h in range(len(grid[0])):
if grid[w][h] == 1:
add_length = 4
else:
continue
if w != 0 and grid[w - 1][h] == 1:
add_length -= 2
if h != 0 and grid[w][h - 1] == 1:
add_length -= 2
sum += add_length
return sum
class Solution2:
def island_perimeter(self, grid: List[List[int]]) -> int:
total = 0
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
cur = 4
for (dx, dy) in direct:
new_x = i + dx
new_y = j + dy
if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]):
if grid[new_x][new_y] == 1:
cur -= 1
total += cur
return total
|
"""Exceptions raised by this package."""
class MetaloaderError(Exception):
"""Base exception for all errors within this package."""
class MetaloaderNotImplemented(MetaloaderError):
"""Something is yet not implemented in the library."""
|
"""Exceptions raised by this package."""
class Metaloadererror(Exception):
"""Base exception for all errors within this package."""
class Metaloadernotimplemented(MetaloaderError):
"""Something is yet not implemented in the library."""
|
words = "sort the inner content in descending order"
result = []
for w in words.split():
if len(w)>3:
result.append(w[0]+''.join(sorted(w[1:-1], reverse=True))+w[-1])
else:
result.append(w)
|
words = 'sort the inner content in descending order'
result = []
for w in words.split():
if len(w) > 3:
result.append(w[0] + ''.join(sorted(w[1:-1], reverse=True)) + w[-1])
else:
result.append(w)
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.total = 0
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
def dfs(node, type):
if node is None:
return
if node.left is None and node.right is None and type == 1:
self.total += node.val
dfs(node.left, 1)
dfs(node.right, 2)
dfs(root.left, 1)
dfs(root.right, 2)
return self.total
t1 = TreeNode(2)
t1.left = TreeNode(3)
slu = Solution()
print(slu.sumOfLeftLeaves(t1))
|
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.total = 0
def sum_of_left_leaves(self, root: TreeNode) -> int:
if not root:
return 0
def dfs(node, type):
if node is None:
return
if node.left is None and node.right is None and (type == 1):
self.total += node.val
dfs(node.left, 1)
dfs(node.right, 2)
dfs(root.left, 1)
dfs(root.right, 2)
return self.total
t1 = tree_node(2)
t1.left = tree_node(3)
slu = solution()
print(slu.sumOfLeftLeaves(t1))
|
language_map = {
'ko': 'ko_KR',
'ja': 'ja_JP',
'zh': 'zh_CN'
}
|
language_map = {'ko': 'ko_KR', 'ja': 'ja_JP', 'zh': 'zh_CN'}
|
# Time: O(n)
# Space: O(1)
# Given an array nums of integers, you can perform operations on the array.
#
# In each operation, you pick any nums[i] and delete it to earn nums[i] points.
# After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
#
# You start with 0 points.
# Return the maximum number of points you can earn by applying such operations.
#
# Example 1:
# Input: nums = [3, 4, 2]
# Output: 6
# Explanation:
# Delete 4 to earn 4 points, consequently 3 is also deleted.
# Then, delete 2 to earn 2 points. 6 total points are earned.
#
# Example 2:
# Input: nums = [2, 2, 3, 3, 3, 4]
# Output: 9
# Explanation:
# Delete 3 to earn 3 points, deleting both 2's and the 4.
# Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
# 9 total points are earned.
#
# Note:
# - The length of nums is at most 20000.
# - Each element nums[i] is an integer in the range [1, 10000].
class Solution(object):
def deleteAndEarn(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
vals = [0] * 10001
for num in nums:
vals[num] += num
val_i, val_i_1 = vals[0], 0
for i in xrange(1, len(vals)):
val_i_1, val_i_2 = val_i, val_i_1
val_i = max(vals[i] + val_i_2, val_i_1)
return val_i
|
class Solution(object):
def delete_and_earn(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
vals = [0] * 10001
for num in nums:
vals[num] += num
(val_i, val_i_1) = (vals[0], 0)
for i in xrange(1, len(vals)):
(val_i_1, val_i_2) = (val_i, val_i_1)
val_i = max(vals[i] + val_i_2, val_i_1)
return val_i
|
global numbering
numbering = [0,1,2,3]
num = 0
filterbegin = '''res(); for (i=0, o=0; i<115; i++){'''
o = ['MSI', 'APPV', 'Citrix MSI', 'Normal','Express','Super Express (BOPO)', 'Simple', 'Medium', 'Complex', 'May', 'June', 'July', 'August']
filterending = '''if (val1 == eq1){ if (val2 == eq2){ if (val3 == eq3){ if (val4 == eq4){ if (val5 == eq5){ if (val6 == eq6){ if (val7 == eq7){ if (val8 == eq8){ op() }}}}}}}}}'''
l = [0, 1, 2]
m = [3, 4, 5]
n = [6, 7, 8]
p = [9, 10, 11, 12]
filtnum = 0
filtername = f'''\nfunction quadfilter{filtnum}()'''
with open("quadfilterfile.txt", 'a') as f:
f.write('''
function op(){
z = o + 1.1
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = snum[i]
z = o + 1.2
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = tnum[i]
z = o + 1.3
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = pname[i]
z = o + 1.4
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = bau[i]
z = o + 1.5
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = ptype[i]
z = o + 1.6
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = rtype[i]
z = o + 1.7
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = bopo[i]
z = o + 1.8
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = comp[i]
z = o + 1.9
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = sdate[i]
z = o + 1.16
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = edate[i]
z = o + 1.17
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = month[i]
z = o + 1.27
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = ssla[i]
z = o + 1.26
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = slame[i]
z = o + 1.21
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = slam[i]
z = o + 1.15
document.getElementById(z).style.display = ""
document.getElementById(z).innerHTML = remark[i]
o++; document.getElementById("mainsum").innerHTML = "Found "+o+" Results For Your Search"
}
''')
for a1 in range(0, 3):
a2 = o[a1]
if a1 in l:
a1a = "ptype[i]"
elif a1 in m:
a1a = "rtype[i]"
elif a1 in n:
a1a = "comp[i]"
elif a1 in p:
a1a = "month[i]"
for b1 in range(0, 3):
b2 = o[b1]
if b1 != a1:
if b1 in l:
b1b = "ptype[i]"
elif b1 in m:
b1b = "rtype[i]"
elif b1 in n:
b1b = "comp[i]"
elif b1 in p:
b1b = "month[i]"
for c1 in range(3, 6):
c2 = o[c1]
if c1 != a1:
if c1 != b1:
if c1 in l:
c1c = "ptype[i]"
elif c1 in m:
c1c = "rtype[i]"
elif c1 in n:
c1c = "comp[i]"
elif c1 in p:
c1c = "month[i]"
for d1 in range(3, 6):
d2 = o[d1]
if d1 != a1:
if d1 != b1:
if d1 != c1:
if d1 in l:
d1d = "ptype[i]"
elif d1 in m:
d1d = "rtype[i]"
elif d1 in n:
d1d = "comp[i]"
elif d1 in p:
d1d = "month[i]"
for e1 in range(6, 9):
e2 = o[e1]
if e1 != a1:
if e1 != b1:
if e1 != c1:
if e1 != d1:
if e1 in l:
e1e = "ptype[i]"
elif e1 in m:
e1e = "rtype[i]"
elif e1 in n:
e1e = "comp[i]"
elif e1 in p:
e1e = "month[i]"
for f1 in range(6, 9):
f2 = o[f1]
if f1 != a1:
if f1 != b1:
if f1 != c1:
if f1 != d1:
if f1 != e1:
if f1 in l:
f1f = "ptype[i]"
elif f1 in m:
f1f = "rtype[i]"
elif f1 in n:
f1f = "comp[i]"
elif f1 in p:
f1f = "month[i]"
for g1 in range(9, 13):
g2 = o[g1]
if g1 != a1:
if g1 != b1:
if g1 != c1:
if g1 != d1:
if g1 != e1:
if g1 != f1:
if g1 in l:
g1g = "ptype[i]"
elif g1 in m:
g1g = "rtype[i]"
elif g1 in n:
g1g = "comp[i]"
elif g1 in p:
g1g = "month[i]"
for x in range(9, 13):
if x != a1:
if x != b1:
if x != c1:
if x != d1:
if x != e1:
if x != f1:
if x != g1:
if x in l:
x1 = "ptype[i]"
elif x in m:
x1 = "rtype[i]"
elif x in n:
x1 = "comp[i]"
elif x in p:
x1 = "month[i]"
filtnum = filtnum + 1
with open("quadfilterfile.txt", 'a') as f:
f.write(f'''function quadfilter{filtnum}()'''+"{"+f'''{filterbegin}
val1 = "{a2}"; eq1 = "{a1a}"; val2 = "{b2}"; eq2 = "{b1b}"; val3 = "{c2}"; eq3 = "{c1c}"; val4 = "{d2}"; eq4 = "{d1d}"; val5 = "{e2}"; eq5 = "{e1e}"; val6 = "{f2}"; eq6 = "{f1f}"; val7 = "{g2}"; eq7 = "{g1g}"; val8 = "{o[x]}"; eq8 = "{x1}"
{filterending}\n''')
m1 = ['a1', 'a2', 'a3', 'a4','a5','a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13']
filtnum = 0
for z1 in range(0, 3):
for z2 in range(0, 3):
if z2 != z1:
for z3 in range(3, 6):
if z2 != z1:
if z3 != z2:
for z4 in range(3, 6):
if z2 != z1:
if z3 != z2:
if z4 != z3:
for z5 in range(6, 9):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
for z6 in range(6, 9):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
for z7 in range(9, 13):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
if z7 != z6:
for z8 in range(9, 13):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
if z7 != z6:
if z8 != z7:
filtnum = filtnum + 1
with open("b13wala.txt", 'a') as f:
f.write(f'''if (document.getElementById("{m1[z1]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z2]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z3]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z4]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z5]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z6]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z7]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z8]}").style.backgroundColor == "rgb(66, 153, 225)"'''+"{\n"+f'''triplefilter{filtnum}\n'''+"}")
|
global numbering
numbering = [0, 1, 2, 3]
num = 0
filterbegin = 'res(); for (i=0, o=0; i<115; i++){'
o = ['MSI', 'APPV', 'Citrix MSI', 'Normal', 'Express', 'Super Express (BOPO)', 'Simple', 'Medium', 'Complex', 'May', 'June', 'July', 'August']
filterending = 'if (val1 == eq1){ if (val2 == eq2){ if (val3 == eq3){ if (val4 == eq4){ if (val5 == eq5){ if (val6 == eq6){ if (val7 == eq7){ if (val8 == eq8){ op() }}}}}}}}}'
l = [0, 1, 2]
m = [3, 4, 5]
n = [6, 7, 8]
p = [9, 10, 11, 12]
filtnum = 0
filtername = f'\nfunction quadfilter{filtnum}()'
with open('quadfilterfile.txt', 'a') as f:
f.write(' \n function op(){\n \n z = o + 1.1\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = snum[i]\n \n z = o + 1.2\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = tnum[i]\n z = o + 1.3\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = pname[i]\n z = o + 1.4\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = bau[i]\n z = o + 1.5\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = ptype[i]\n z = o + 1.6\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = rtype[i]\n \n z = o + 1.7\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = bopo[i]\n z = o + 1.8\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = comp[i]\n z = o + 1.9\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = sdate[i]\n z = o + 1.16\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = edate[i]\n z = o + 1.17\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = month[i]\n \n z = o + 1.27\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = ssla[i]\n z = o + 1.26\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = slame[i]\n z = o + 1.21\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = slam[i]\n z = o + 1.15\n document.getElementById(z).style.display = ""\n document.getElementById(z).innerHTML = remark[i]\n o++; document.getElementById("mainsum").innerHTML = "Found "+o+" Results For Your Search"\n }\n ')
for a1 in range(0, 3):
a2 = o[a1]
if a1 in l:
a1a = 'ptype[i]'
elif a1 in m:
a1a = 'rtype[i]'
elif a1 in n:
a1a = 'comp[i]'
elif a1 in p:
a1a = 'month[i]'
for b1 in range(0, 3):
b2 = o[b1]
if b1 != a1:
if b1 in l:
b1b = 'ptype[i]'
elif b1 in m:
b1b = 'rtype[i]'
elif b1 in n:
b1b = 'comp[i]'
elif b1 in p:
b1b = 'month[i]'
for c1 in range(3, 6):
c2 = o[c1]
if c1 != a1:
if c1 != b1:
if c1 in l:
c1c = 'ptype[i]'
elif c1 in m:
c1c = 'rtype[i]'
elif c1 in n:
c1c = 'comp[i]'
elif c1 in p:
c1c = 'month[i]'
for d1 in range(3, 6):
d2 = o[d1]
if d1 != a1:
if d1 != b1:
if d1 != c1:
if d1 in l:
d1d = 'ptype[i]'
elif d1 in m:
d1d = 'rtype[i]'
elif d1 in n:
d1d = 'comp[i]'
elif d1 in p:
d1d = 'month[i]'
for e1 in range(6, 9):
e2 = o[e1]
if e1 != a1:
if e1 != b1:
if e1 != c1:
if e1 != d1:
if e1 in l:
e1e = 'ptype[i]'
elif e1 in m:
e1e = 'rtype[i]'
elif e1 in n:
e1e = 'comp[i]'
elif e1 in p:
e1e = 'month[i]'
for f1 in range(6, 9):
f2 = o[f1]
if f1 != a1:
if f1 != b1:
if f1 != c1:
if f1 != d1:
if f1 != e1:
if f1 in l:
f1f = 'ptype[i]'
elif f1 in m:
f1f = 'rtype[i]'
elif f1 in n:
f1f = 'comp[i]'
elif f1 in p:
f1f = 'month[i]'
for g1 in range(9, 13):
g2 = o[g1]
if g1 != a1:
if g1 != b1:
if g1 != c1:
if g1 != d1:
if g1 != e1:
if g1 != f1:
if g1 in l:
g1g = 'ptype[i]'
elif g1 in m:
g1g = 'rtype[i]'
elif g1 in n:
g1g = 'comp[i]'
elif g1 in p:
g1g = 'month[i]'
for x in range(9, 13):
if x != a1:
if x != b1:
if x != c1:
if x != d1:
if x != e1:
if x != f1:
if x != g1:
if x in l:
x1 = 'ptype[i]'
elif x in m:
x1 = 'rtype[i]'
elif x in n:
x1 = 'comp[i]'
elif x in p:
x1 = 'month[i]'
filtnum = filtnum + 1
with open('quadfilterfile.txt', 'a') as f:
f.write(f'function quadfilter{filtnum}()' + '{' + f'{filterbegin}\nval1 = "{a2}"; eq1 = "{a1a}"; val2 = "{b2}"; eq2 = "{b1b}"; val3 = "{c2}"; eq3 = "{c1c}"; val4 = "{d2}"; eq4 = "{d1d}"; val5 = "{e2}"; eq5 = "{e1e}"; val6 = "{f2}"; eq6 = "{f1f}"; val7 = "{g2}"; eq7 = "{g1g}"; val8 = "{o[x]}"; eq8 = "{x1}"\n{filterending}\n')
m1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13']
filtnum = 0
for z1 in range(0, 3):
for z2 in range(0, 3):
if z2 != z1:
for z3 in range(3, 6):
if z2 != z1:
if z3 != z2:
for z4 in range(3, 6):
if z2 != z1:
if z3 != z2:
if z4 != z3:
for z5 in range(6, 9):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
for z6 in range(6, 9):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
for z7 in range(9, 13):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
if z7 != z6:
for z8 in range(9, 13):
if z2 != z1:
if z3 != z2:
if z4 != z3:
if z5 != z4:
if z6 != z5:
if z7 != z6:
if z8 != z7:
filtnum = filtnum + 1
with open('b13wala.txt', 'a') as f:
f.write(f'if (document.getElementById("{m1[z1]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z2]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z3]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z4]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z5]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z6]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z7]}").style.backgroundColor == "rgb(66, 153, 225)" && if (document.getElementById("{m1[z8]}").style.backgroundColor == "rgb(66, 153, 225)"' + '{\n' + f'triplefilter{filtnum}\n' + '}')
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countUnivalSubtrees(self, root: TreeNode) -> int:
self.count = 0
self.is_uni(root)
return self.count
# Check whether subtree is uni-value
def is_uni(self, node):
if not node:
return True
# Node has no children
if node.left is None and node.right is None:
self.count += 1
return True
# Check if all chidren are univalue subtrees
is_uni = True
if node.left:
is_uni = self.is_uni(node.left) and is_uni and node.val == node.left.val
if node.right:
is_uni = self.is_uni(node.right) and is_uni and node.val == node.right.val
# If all children are univalue subtrees, increment count
if is_uni:
self.count += 1
return is_uni
|
class Solution:
def count_unival_subtrees(self, root: TreeNode) -> int:
self.count = 0
self.is_uni(root)
return self.count
def is_uni(self, node):
if not node:
return True
if node.left is None and node.right is None:
self.count += 1
return True
is_uni = True
if node.left:
is_uni = self.is_uni(node.left) and is_uni and (node.val == node.left.val)
if node.right:
is_uni = self.is_uni(node.right) and is_uni and (node.val == node.right.val)
if is_uni:
self.count += 1
return is_uni
|
#!/usr/bin/env python3
# Label key for repair state
# (IN_SERVICE, OUT_OF_POOL, READY_FOR_REPAIR, IN_REPAIR, AFTER_REPAIR)
REPAIR_STATE = "REPAIR_STATE"
# Annotation key for the last update time of the repair state
REPAIR_STATE_LAST_UPDATE_TIME = "REPAIR_STATE_LAST_UPDATE_TIME"
# Annotation key for the last email time for jobs on node in repair
REPAIR_STATE_LAST_EMAIL_TIME = "REPAIR_STATE_LAST_EMAIL_TIME"
# Annotation key for unhealthy rules
REPAIR_UNHEALTHY_RULES = "REPAIR_UNHEALTHY_RULES"
# Annotation key for whether the node is in repair cycle.
# An unschedulable node that is not in repair cycle can be manually repaired
# by administrator without repair cycle interruption.
REPAIR_CYCLE = "REPAIR_CYCLE"
# Annotation key for repair message - what phase the node is undergoing
REPAIR_MESSAGE = "REPAIR_MESSAGE"
|
repair_state = 'REPAIR_STATE'
repair_state_last_update_time = 'REPAIR_STATE_LAST_UPDATE_TIME'
repair_state_last_email_time = 'REPAIR_STATE_LAST_EMAIL_TIME'
repair_unhealthy_rules = 'REPAIR_UNHEALTHY_RULES'
repair_cycle = 'REPAIR_CYCLE'
repair_message = 'REPAIR_MESSAGE'
|
######################################################################################################################
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance #
# with the License. A copy of the License is located at #
# #
# http://aws.amazon.com/asl/ #
# #
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES #
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #
# and limitations under the License. #
######################################################################################################################
BOOLEAN_FALSE_VALUES = [
"false",
"no",
"disabled",
"off",
"0"
]
BOOLEAN_TRUE_VALUES = [
"true",
"yes",
"enabled",
"on",
"1"
]
# name of environment variable that holds the name of the configuration table
ENV_CONFIG_TABLE = "CONFIG_TABLE"
ENV_CONFIG_BUCKET = "CONFIG_BUCKET"
TASKS_OBJECTS = "TaskConfigurationObjects"
# names of attributes in configuration
# name of the action
CONFIG_ACTION_NAME = "Action"
# debug parameter
CONFIG_DEBUG = "Debug"
# notifications for started/ended tasks
CONFIG_TASK_NOTIFICATIONS = "TaskNotifications"
# list of cross account roles
CONFIG_ACCOUNTS = "Accounts"
# name of alternative cross account role
CONFIG_TASK_CROSS_ACCOUNT_ROLE_NAME = "CrossAccountRole"
# description
CONFIG_DESCRIPTION = "Description"
# Switch to enable/disable task
CONFIG_ENABLED = "Enabled"
# tag filter for tags of source resource of an event
CONFIG_EVENT_SOURCE_TAG_FILTER = "SourceEventTagFilter"
# cron expression interval for time/date based tasks
CONFIG_INTERVAL = "Interval"
# internal task
CONFIG_INTERNAL = "Internal"
# name of the task
CONFIG_TASK_NAME = "Name"
# parameters of a task
CONFIG_PARAMETERS = "Parameters"
# switch to indicate if resource in the account of the scheduler should be processed
CONFIG_THIS_ACCOUNT = "ThisAccount"
# timezone for time/date scheduled task
CONFIG_TIMEZONE = "Timezone"
# tag filter to select resources processed by the task
CONFIG_TAG_FILTER = "TagFilter"
# regions where to select/process resources
CONFIG_REGIONS = "Regions"
# dryrun switch, passed to the tasks action
CONFIG_DRYRUN = "Dryrun"
# events that trigger the task
CONFIG_EVENTS = "Events"
# event scopes
CONFIG_EVENT_SCOPES = "EventScopes"
# stack id if created from cloudformation stack
CONFIG_STACK_ID = "StackId"
# action timeout
CONFIG_TASK_TIMEOUT = "TaskTimeout"
# action select memory
CONFIG_TASK_SELECT_SIZE = "SelectSize"
# action select memory
CONFIG_TASK_EXECUTE_SIZE = "ExecuteSize"
# action completion memory
CONFIG_TASK_COMPLETION_SIZE = "CompletionSize"
# action completion memory when running in ECS
CONFIG_ECS_COMPLETION_MEMORY = "CompletionEcsMemoryValue"
# action select memory when running in ECS
CONFIG_ECS_SELECT_MEMORY = "SelectEcsMemoryValueValue"
# action select memory when running in ECS
CONFIG_ECS_EXECUTE_MEMORY = "ExecuteEcsMemoryValue"
# Task metrics
CONFIG_TASK_METRICS = "TaskMetrics"
|
boolean_false_values = ['false', 'no', 'disabled', 'off', '0']
boolean_true_values = ['true', 'yes', 'enabled', 'on', '1']
env_config_table = 'CONFIG_TABLE'
env_config_bucket = 'CONFIG_BUCKET'
tasks_objects = 'TaskConfigurationObjects'
config_action_name = 'Action'
config_debug = 'Debug'
config_task_notifications = 'TaskNotifications'
config_accounts = 'Accounts'
config_task_cross_account_role_name = 'CrossAccountRole'
config_description = 'Description'
config_enabled = 'Enabled'
config_event_source_tag_filter = 'SourceEventTagFilter'
config_interval = 'Interval'
config_internal = 'Internal'
config_task_name = 'Name'
config_parameters = 'Parameters'
config_this_account = 'ThisAccount'
config_timezone = 'Timezone'
config_tag_filter = 'TagFilter'
config_regions = 'Regions'
config_dryrun = 'Dryrun'
config_events = 'Events'
config_event_scopes = 'EventScopes'
config_stack_id = 'StackId'
config_task_timeout = 'TaskTimeout'
config_task_select_size = 'SelectSize'
config_task_execute_size = 'ExecuteSize'
config_task_completion_size = 'CompletionSize'
config_ecs_completion_memory = 'CompletionEcsMemoryValue'
config_ecs_select_memory = 'SelectEcsMemoryValueValue'
config_ecs_execute_memory = 'ExecuteEcsMemoryValue'
config_task_metrics = 'TaskMetrics'
|
{
"targets": [
{
"target_name": "ecdh",
"include_dirs": ["<!(node -e \"require('nan')\")"],
"cflags": ["-Wall", "-O2"],
"sources": ["ecdh.cc"],
"conditions": [
["OS=='win'", {
"conditions": [
[
"target_arch=='x64'", {
"variables": {
"openssl_root%": "C:/OpenSSL-Win64"
},
}, {
"variables": {
"openssl_root%": "C:/OpenSSL-Win32"
}
}
]
],
"libraries": [
"-l<(openssl_root)/lib/libeay32.lib",
],
"include_dirs": [
"<(openssl_root)/include",
],
}, {
"conditions": [
[
"target_arch=='ia32'", {
"variables": {
"openssl_config_path": "<(nodedir)/deps/openssl/config/piii"
}
}
],
[
"target_arch=='x64'", {
"variables": {
"openssl_config_path": "<(nodedir)/deps/openssl/config/k8"
},
}
],
[
"target_arch=='arm'", {
"variables": {
"openssl_config_path": "<(nodedir)/deps/openssl/config/arm"
}
}
],
[
"target_arch=='arm64'", {
"variables": {
"openssl_config_path": "<(nodedir)/deps/openssl/config/aarch64"
}
}
],
],
"include_dirs": [
"<(nodedir)/deps/openssl/openssl/include",
"<(openssl_config_path)"
]
}
]]
}
]
}
|
{'targets': [{'target_name': 'ecdh', 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'cflags': ['-Wall', '-O2'], 'sources': ['ecdh.cc'], 'conditions': [["OS=='win'", {'conditions': [["target_arch=='x64'", {'variables': {'openssl_root%': 'C:/OpenSSL-Win64'}}, {'variables': {'openssl_root%': 'C:/OpenSSL-Win32'}}]], 'libraries': ['-l<(openssl_root)/lib/libeay32.lib'], 'include_dirs': ['<(openssl_root)/include']}, {'conditions': [["target_arch=='ia32'", {'variables': {'openssl_config_path': '<(nodedir)/deps/openssl/config/piii'}}], ["target_arch=='x64'", {'variables': {'openssl_config_path': '<(nodedir)/deps/openssl/config/k8'}}], ["target_arch=='arm'", {'variables': {'openssl_config_path': '<(nodedir)/deps/openssl/config/arm'}}], ["target_arch=='arm64'", {'variables': {'openssl_config_path': '<(nodedir)/deps/openssl/config/aarch64'}}]], 'include_dirs': ['<(nodedir)/deps/openssl/openssl/include', '<(openssl_config_path)']}]]}]}
|
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
|
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
|
"""
Discover & provide the log group name
"""
class LogGroupProvider(object):
"""
Resolve the name of log group given the name of the resource
"""
@staticmethod
def for_lambda_function(function_name):
"""
Returns the CloudWatch Log Group Name created by default for the AWS Lambda function with given name
Parameters
----------
function_name : str
Name of the Lambda function
Returns
-------
str
Default Log Group name used by this function
"""
return "/aws/lambda/{}".format(function_name)
|
"""
Discover & provide the log group name
"""
class Loggroupprovider(object):
"""
Resolve the name of log group given the name of the resource
"""
@staticmethod
def for_lambda_function(function_name):
"""
Returns the CloudWatch Log Group Name created by default for the AWS Lambda function with given name
Parameters
----------
function_name : str
Name of the Lambda function
Returns
-------
str
Default Log Group name used by this function
"""
return '/aws/lambda/{}'.format(function_name)
|
'''
This module contains some exception classes
'''
class SecondryStructureError(Exception):
'''
Raised when the Secondry structure is not correct
'''
def __init__(self, residue, value):
messgae = '''
ERROR: Secondary Structure Input is not parsed correctly.
Please make sure the value after the C alpha shift is
one of the following
- alpha : a, alpha, h, helix
- beta : b, beta, sheet, strand
- coil : c, coil, r, (assumed to be 50%% alpha and 50%% beta)
- A number between 0 and 1. 1 = 100%% alpha helix, 0. = 100%% beta sheet
The Value given for residue %s is %s ''' % (residue, value)
Exception.__init__(self, messgae)
class ShiftMatrixStatesOrder(Exception):
'''
Raised when the order of the states in the chemical shift file is
incorrect
'''
def __init__(self, file_):
messgae = '''
ERROR: The order of the states in the file containing the
chemical shifts is different. Please correct this.
This is File: %s''' % (file_)
Exception.__init__(self, messgae)
|
"""
This module contains some exception classes
"""
class Secondrystructureerror(Exception):
"""
Raised when the Secondry structure is not correct
"""
def __init__(self, residue, value):
messgae = '\n ERROR: Secondary Structure Input is not parsed correctly.\n Please make sure the value after the C alpha shift is\n one of the following\n\n - alpha : a, alpha, h, helix\n - beta : b, beta, sheet, strand\n - coil : c, coil, r, (assumed to be 50%% alpha and 50%% beta)\n - A number between 0 and 1. 1 = 100%% alpha helix, 0. = 100%% beta sheet\n\n The Value given for residue %s is %s ' % (residue, value)
Exception.__init__(self, messgae)
class Shiftmatrixstatesorder(Exception):
"""
Raised when the order of the states in the chemical shift file is
incorrect
"""
def __init__(self, file_):
messgae = '\n ERROR: The order of the states in the file containing the\n chemical shifts is different. Please correct this.\n This is File: %s' % file_
Exception.__init__(self, messgae)
|
class get_method_name_decorator:
def __init__(self, fn):
self.fn = fn
def __set_name__(self, owner, name):
owner.method_names.add(self.fn)
setattr(owner, name, self.fn)
|
class Get_Method_Name_Decorator:
def __init__(self, fn):
self.fn = fn
def __set_name__(self, owner, name):
owner.method_names.add(self.fn)
setattr(owner, name, self.fn)
|
# https://www.devdungeon.com/content/colorize-terminal-output-python
# https://www.geeksforgeeks.org/print-colors-python-terminal/
class CONST:
class print_color:
class control:
'''
Full name: Perfect_color_text
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class fore:
'''
Full name: Perfect_fore_color
'''
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class background:
'''
Full name: Perfect_background_color
'''
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
class cv_color:
line = (0,255,0)
circle = (255,255,0)
if __name__ == "__main__":
print (CONST.print_color.fore.yellow + 'Hello world. ' + CONST.print_color.fore.red + 'Hey!')
|
class Const:
class Print_Color:
class Control:
"""
Full name: Perfect_color_text
"""
reset = '\x1b[0m'
bold = '\x1b[01m'
disable = '\x1b[02m'
underline = '\x1b[04m'
reverse = '\x1b[07m'
strikethrough = '\x1b[09m'
invisible = '\x1b[08m'
class Fore:
"""
Full name: Perfect_fore_color
"""
black = '\x1b[30m'
red = '\x1b[31m'
green = '\x1b[32m'
orange = '\x1b[33m'
blue = '\x1b[34m'
purple = '\x1b[35m'
cyan = '\x1b[36m'
lightgrey = '\x1b[37m'
darkgrey = '\x1b[90m'
lightred = '\x1b[91m'
lightgreen = '\x1b[92m'
yellow = '\x1b[93m'
lightblue = '\x1b[94m'
pink = '\x1b[95m'
lightcyan = '\x1b[96m'
class Background:
"""
Full name: Perfect_background_color
"""
black = '\x1b[40m'
red = '\x1b[41m'
green = '\x1b[42m'
orange = '\x1b[43m'
blue = '\x1b[44m'
purple = '\x1b[45m'
cyan = '\x1b[46m'
lightgrey = '\x1b[47m'
class Cv_Color:
line = (0, 255, 0)
circle = (255, 255, 0)
if __name__ == '__main__':
print(CONST.print_color.fore.yellow + 'Hello world. ' + CONST.print_color.fore.red + 'Hey!')
|
found = False
while not found:
num = float(input())
if 1 <= num <= 100:
print(f"The number {num} is between 1 and 100")
found = True
|
found = False
while not found:
num = float(input())
if 1 <= num <= 100:
print(f'The number {num} is between 1 and 100')
found = True
|
# MathHelper.py - Some helpful math utilities.
# Created by Josh Kennedy on 18 May 2014
#
# Pop a Dots
# Copyright 2014 Chad Jensen and Josh Kennedy
# Copyright 2015-2016 Sirkles LLC
def lerp(value1, value2, amount):
return value1 + ((value2 - value1) * amount)
def isPowerOfTwo(value):
return (value > 0) and ((value & (value - 1)) == 0)
def toDegrees(radians):
return radians * 57.295779513082320876798154814105
def toRadians(degrees):
return degrees * 0.017453292519943295769236907684886
def clamp(value, low, high):
if value < low:
return low
else:
if value > high:
return high
else:
return value
def nextPowerOfTwo(value):
return_value = 1
while return_value < value:
return_value <<= 1
return return_value
|
def lerp(value1, value2, amount):
return value1 + (value2 - value1) * amount
def is_power_of_two(value):
return value > 0 and value & value - 1 == 0
def to_degrees(radians):
return radians * 57.29577951308232
def to_radians(degrees):
return degrees * 0.017453292519943295
def clamp(value, low, high):
if value < low:
return low
elif value > high:
return high
else:
return value
def next_power_of_two(value):
return_value = 1
while return_value < value:
return_value <<= 1
return return_value
|
## Function
def insertShiftArray(arr, num):
"""
This function takes in two parameters: a list, and an integer. insertShiftArray will place the integer at the middle index of the list provided.
"""
answerArr = []
middle = 0
# No math methods, if/else to determine odd or even to find middle index
if len(arr) % 2 == 0:
middle = len(arr) / 2
else:
middle = len(arr) / 2 + 0.5
# Loop through originally arr length + 1 more iteration for our addition.
for i in range(len(arr) + 1):
if i < middle:
# append first half
answerArr.append(arr[i])
elif i == middle:
# append parameter2 num to middle of our have list
answerArr.append(num)
answerArr.append(arr[i])
elif i > middle and i < len(arr):
# append second half
answerArr.append(arr[i])
return answerArr
|
def insert_shift_array(arr, num):
"""
This function takes in two parameters: a list, and an integer. insertShiftArray will place the integer at the middle index of the list provided.
"""
answer_arr = []
middle = 0
if len(arr) % 2 == 0:
middle = len(arr) / 2
else:
middle = len(arr) / 2 + 0.5
for i in range(len(arr) + 1):
if i < middle:
answerArr.append(arr[i])
elif i == middle:
answerArr.append(num)
answerArr.append(arr[i])
elif i > middle and i < len(arr):
answerArr.append(arr[i])
return answerArr
|
# Adds testing.TestEnvironment provider if "env" attr is specified
# https://bazel.build/rules/lib/testing#TestEnvironment
def phase_test_environment(ctx, p):
test_env = ctx.attr.env
if test_env:
return struct(
external_providers = {
"TestingEnvironment": testing.TestEnvironment(test_env),
},
)
return struct()
|
def phase_test_environment(ctx, p):
test_env = ctx.attr.env
if test_env:
return struct(external_providers={'TestingEnvironment': testing.TestEnvironment(test_env)})
return struct()
|
# coding: utf-8
"""
.. _available-parsers:
Available Parsers
=================
This package contains a collection of parsers which you can use in conjonction
with builders to convert tables from one format to another.
You can pick a builder in the :ref:`Available Builders <available-builders>`.
"""
|
"""
.. _available-parsers:
Available Parsers
=================
This package contains a collection of parsers which you can use in conjonction
with builders to convert tables from one format to another.
You can pick a builder in the :ref:`Available Builders <available-builders>`.
"""
|
def keyquery():
return( set([]) )
def getval(prob):
return( prob.file )
|
def keyquery():
return set([])
def getval(prob):
return prob.file
|
#!/usr/bin/env python3
print('1a')
print('1b')
print('2a\n')
print('2b\n')
print('3a\r\n')
print('3b\r\n')
print('4a\r')
print('4b\r')
print('5a\n\r')
print('5b\n\r')
|
print('1a')
print('1b')
print('2a\n')
print('2b\n')
print('3a\r\n')
print('3b\r\n')
print('4a\r')
print('4b\r')
print('5a\n\r')
print('5b\n\r')
|
# You are given a string and your task is to swap cases.
# In other words, convert all lowercase letters to uppercase letters and vice versa.
def swap_case(s):
return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
def swap_case(s):
return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
# uncompyle6 version 3.7.2
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: extract__one_file_exe__pyinstaller\_test_file.py
__author__ = 'ipetrash'
def say():
print('Hello World!')
if __name__ == '__main__':
say()
|
__author__ = 'ipetrash'
def say():
print('Hello World!')
if __name__ == '__main__':
say()
|
input = """
d(1).
d(2).
d(3).
d(4) :- #min{V : d(V)} = 1.
"""
output = """
d(1).
d(2).
d(3).
d(4) :- #min{V : d(V)} = 1.
"""
|
input = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #min{V : d(V)} = 1.\n\n'
output = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #min{V : d(V)} = 1.\n\n'
|
"""
Count the number of inversions in a sequence of orderable items.
Description:
Informally, when we say inversion we mean inversion from the (ascending)
sorted order.
For a more formal definition, let's call the list of items L. We call
inversion a pair of indices i, j with i < j and L[i] > L[j], where L[i] is
the ith item of the list and L[j] the jth one.
In a given list of size N there could be up to O(N**2) inversions. To do the
counting efficiently (i.e. in O(N*log(N)) time) we use a divide and conquer
approach. More specifically, we piggyback on the mergesort algorithm.
Author:
Christos Nitsas
(nitsas)
(chrisnitsas)
Language:
Python 3(.4)
Date:
October, 2014
"""
__all__ = ['count_inversions', 'count', 'mergesort_and_count']
def count_inversions(sequence):
"""
Count the number of inversions in the sequence and return an integer.
sequence -- a sequence of items that can be compared using <=
we assume the sequence is sliceable
We count inversions from the ascending order.
This will piggyback on the mergesort divide and conquer algorithm.
"""
_, num_inversions = mergesort_and_count(sequence)
return num_inversions
count = count_inversions
def mergesort_and_count(sequence):
"""
Sort the sequence into a list (call this "merged"), count the number "N"
of inversions, and return a tuple with "merged" and "N".
"""
if len(sequence) <= 1:
return (list(sequence), 0)
left = sequence[:len(sequence)//2]
right = sequence[len(sequence)//2:]
return merge_and_count_inversions(mergesort_and_count(left),
mergesort_and_count(right))
def merge_and_count_inversions(left_tuple, right_tuple):
"""
Count the number of split inversions while merging the given results of
the left and right subproblems and return a tuple containing the
resulting merged sorted list and the total number of inversions.
left_tuple -- a tuple containing the sorted sublist and the count of
inversions from the left subproblem
right_tuple -- a tuple containing the sorted sublist and the count of
inversions from the right subproblem
We call split inversions the pairs of items where the larger item is in
the left subsequence and the smaller item is in the right.
The total number of inversions "count_total" is:
count_total = count_left + count_right + count_split,
where "count_left", "count_right" are the number of inversions in the
left and right subsequence respectively and "count_split" is the number
of split inversions.
"""
left, count_left = left_tuple
right, count_right = right_tuple
merged, count_split = list(), 0
# Careful!
# If we use list slicing in the following loop we might end up with
# worse than O(L*log(L)) complexity. We will use indices instead.
index_l, index_r = 0, 0
while len(left) - index_l > 0 and len(right) - index_r > 0:
if left[index_l] <= right[index_r]:
merged.append(left[index_l])
index_l += 1
# no inversions discovered here
else:
# the item right[index_r] is smaller than every item in
# left[index_l:]
merged.append(right[index_r])
index_r += 1
# all the items of left[index_l:] formed inversions with the
# item we just appended to "merged"
count_split += len(left) - index_l
if len(left) - index_l > 0:
merged.extend(left[index_l:])
# no more inversions
elif len(right) - index_r > 0:
merged.extend(right[index_r:])
# no more inversions
count_total = count_left + count_right + count_split
return (merged, count_total)
|
"""
Count the number of inversions in a sequence of orderable items.
Description:
Informally, when we say inversion we mean inversion from the (ascending)
sorted order.
For a more formal definition, let's call the list of items L. We call
inversion a pair of indices i, j with i < j and L[i] > L[j], where L[i] is
the ith item of the list and L[j] the jth one.
In a given list of size N there could be up to O(N**2) inversions. To do the
counting efficiently (i.e. in O(N*log(N)) time) we use a divide and conquer
approach. More specifically, we piggyback on the mergesort algorithm.
Author:
Christos Nitsas
(nitsas)
(chrisnitsas)
Language:
Python 3(.4)
Date:
October, 2014
"""
__all__ = ['count_inversions', 'count', 'mergesort_and_count']
def count_inversions(sequence):
"""
Count the number of inversions in the sequence and return an integer.
sequence -- a sequence of items that can be compared using <=
we assume the sequence is sliceable
We count inversions from the ascending order.
This will piggyback on the mergesort divide and conquer algorithm.
"""
(_, num_inversions) = mergesort_and_count(sequence)
return num_inversions
count = count_inversions
def mergesort_and_count(sequence):
"""
Sort the sequence into a list (call this "merged"), count the number "N"
of inversions, and return a tuple with "merged" and "N".
"""
if len(sequence) <= 1:
return (list(sequence), 0)
left = sequence[:len(sequence) // 2]
right = sequence[len(sequence) // 2:]
return merge_and_count_inversions(mergesort_and_count(left), mergesort_and_count(right))
def merge_and_count_inversions(left_tuple, right_tuple):
"""
Count the number of split inversions while merging the given results of
the left and right subproblems and return a tuple containing the
resulting merged sorted list and the total number of inversions.
left_tuple -- a tuple containing the sorted sublist and the count of
inversions from the left subproblem
right_tuple -- a tuple containing the sorted sublist and the count of
inversions from the right subproblem
We call split inversions the pairs of items where the larger item is in
the left subsequence and the smaller item is in the right.
The total number of inversions "count_total" is:
count_total = count_left + count_right + count_split,
where "count_left", "count_right" are the number of inversions in the
left and right subsequence respectively and "count_split" is the number
of split inversions.
"""
(left, count_left) = left_tuple
(right, count_right) = right_tuple
(merged, count_split) = (list(), 0)
(index_l, index_r) = (0, 0)
while len(left) - index_l > 0 and len(right) - index_r > 0:
if left[index_l] <= right[index_r]:
merged.append(left[index_l])
index_l += 1
else:
merged.append(right[index_r])
index_r += 1
count_split += len(left) - index_l
if len(left) - index_l > 0:
merged.extend(left[index_l:])
elif len(right) - index_r > 0:
merged.extend(right[index_r:])
count_total = count_left + count_right + count_split
return (merged, count_total)
|
# Law of large number
# How to get first line input
n, m, k = map(int, input().split())
data = list(map(int, input().split()))
solution = 0
count_use_max_value = 0
data.sort(reverse=True)
for i in range(0, m):
if count_use_max_value >= k:
solution += data[1]
count_use_max_value = 0
else:
solution += data[0]
count_use_max_value += 1
print(solution)
|
(n, m, k) = map(int, input().split())
data = list(map(int, input().split()))
solution = 0
count_use_max_value = 0
data.sort(reverse=True)
for i in range(0, m):
if count_use_max_value >= k:
solution += data[1]
count_use_max_value = 0
else:
solution += data[0]
count_use_max_value += 1
print(solution)
|
# FIXME need to fix TWO_RIG_AX_TO_MOVE here; empirically-derived, like we did with safe trajectories
# define rig_ax to be moved to achieve either min or max given that we are at designated rough home position
TWO_RIG_AX_TO_MOVE = {
# rough_home ax1 min max ax2 min max
'+x': [('pitch', -10, +10), ('roll', -10, +10)],
'-x': [('pitch', +160, +172), ('roll', -10, +10)],
'+y': [('pitch', +70, +90), ('yaw', -80, -100)],
'-y': [('pitch', -90, -110), ('roll', -10, +10)],
'+z': [('pitch', -90, -110), ('roll', -10, +10)],
'-z': [('pitch', +70, +90), ('yaw', -10, +10)],
}
# map axis letter to ESP axis (stage) number
ESP_AX = {'roll': 1, 'pitch': 2, 'yaw': 3}
# move sequence for safe trajectories -- minimal moves for rough home to rough home transitions
ORIG_SAFE_TRAJ_MOVES = [
# rough_home ax1 pos1, ax2 pos2, etc.
('+x', [(2, 0)]),
('-z', [(2, 80)]),
('+y', [(3, -90)]),
('-x', [(2, 170)]),
('-y', [(2, -100), (3, -90)]),
('+z', [(3, 0)]),
]
NEXT_SAFE_TRAJ_MOVES = [
# rough_home ax1 pos1, ax2 pos2, etc.
('+y', [(3, -90)]),
('-x', [(2, 170)]),
('-y', [(2, -100), (3, -90)]),
('+z', [(3, 0)]),
]
SAFE_TRAJ_MOVES = [
# rough_home ax1 pos1, ax2 pos2, etc.
('+z', [(3, 0)]),
]
# time to allow stage to settle (e.g. after a move, wait a short bit before querying actual position)
ESP_SETTLE = 3 # seconds
|
two_rig_ax_to_move = {'+x': [('pitch', -10, +10), ('roll', -10, +10)], '-x': [('pitch', +160, +172), ('roll', -10, +10)], '+y': [('pitch', +70, +90), ('yaw', -80, -100)], '-y': [('pitch', -90, -110), ('roll', -10, +10)], '+z': [('pitch', -90, -110), ('roll', -10, +10)], '-z': [('pitch', +70, +90), ('yaw', -10, +10)]}
esp_ax = {'roll': 1, 'pitch': 2, 'yaw': 3}
orig_safe_traj_moves = [('+x', [(2, 0)]), ('-z', [(2, 80)]), ('+y', [(3, -90)]), ('-x', [(2, 170)]), ('-y', [(2, -100), (3, -90)]), ('+z', [(3, 0)])]
next_safe_traj_moves = [('+y', [(3, -90)]), ('-x', [(2, 170)]), ('-y', [(2, -100), (3, -90)]), ('+z', [(3, 0)])]
safe_traj_moves = [('+z', [(3, 0)])]
esp_settle = 3
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
else:
curList = [ root ]
while True:
nextList = []
expanded = False
for curRoot in curList:
curRootLeft = curRoot.left
curRootRight = curRoot.right
curRoot.left = None
curRoot.right = None
nextList.append( curRoot )
if curRootLeft != None:
nextList.append( curRootLeft )
expanded = True
if curRootRight != None:
nextList.append( curRootRight )
expanded = True
if expanded:
curList = nextList
else:
break
outList = [ x.val for x in curList ]
return outList
|
class Solution:
def preorder_traversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
else:
cur_list = [root]
while True:
next_list = []
expanded = False
for cur_root in curList:
cur_root_left = curRoot.left
cur_root_right = curRoot.right
curRoot.left = None
curRoot.right = None
nextList.append(curRoot)
if curRootLeft != None:
nextList.append(curRootLeft)
expanded = True
if curRootRight != None:
nextList.append(curRootRight)
expanded = True
if expanded:
cur_list = nextList
else:
break
out_list = [x.val for x in curList]
return outList
|
def lambda_handler(event, context):
n = int(event['number'])
n = n * -1 if n < 0 else n
subject = event.get('__TRIGGERFLOW_SUBJECT', None)
return {'number': n, '__TRIGGERFLOW_SUBJECT': subject}
|
def lambda_handler(event, context):
n = int(event['number'])
n = n * -1 if n < 0 else n
subject = event.get('__TRIGGERFLOW_SUBJECT', None)
return {'number': n, '__TRIGGERFLOW_SUBJECT': subject}
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class UpdateLinuxPasswordReqParams(object):
"""Implementation of the 'UpdateLinuxPasswordReqParams' model.
Specifies the user input parameters.
Attributes:
linux_current_password (string): Specifies the current password.
linux_password (string): Specifies the new linux password.
linux_username (string): Specifies the linux username for which the
password will be updated.
verify_password (bool): True if request is only to verify if current
password matches with set password.
"""
# Create a mapping from Model property names to API property names
_names = {
"linux_password":'linuxPassword',
"linux_username":'linuxUsername',
"linux_current_password":'linuxCurrentPassword',
"verify_password":'verifyPassword'
}
def __init__(self,
linux_password=None,
linux_username=None,
linux_current_password=None,
verify_password=None):
"""Constructor for the UpdateLinuxPasswordReqParams class"""
# Initialize members of the class
self.linux_current_password = linux_current_password
self.linux_password = linux_password
self.linux_username = linux_username
self.verify_password = verify_password
@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
linux_password = dictionary.get('linuxPassword')
linux_username = dictionary.get('linuxUsername')
linux_current_password = dictionary.get('linuxCurrentPassword')
verify_password = dictionary.get('verifyPassword')
# Return an object of this model
return cls(linux_password,
linux_username,
linux_current_password,
verify_password)
|
class Updatelinuxpasswordreqparams(object):
"""Implementation of the 'UpdateLinuxPasswordReqParams' model.
Specifies the user input parameters.
Attributes:
linux_current_password (string): Specifies the current password.
linux_password (string): Specifies the new linux password.
linux_username (string): Specifies the linux username for which the
password will be updated.
verify_password (bool): True if request is only to verify if current
password matches with set password.
"""
_names = {'linux_password': 'linuxPassword', 'linux_username': 'linuxUsername', 'linux_current_password': 'linuxCurrentPassword', 'verify_password': 'verifyPassword'}
def __init__(self, linux_password=None, linux_username=None, linux_current_password=None, verify_password=None):
"""Constructor for the UpdateLinuxPasswordReqParams class"""
self.linux_current_password = linux_current_password
self.linux_password = linux_password
self.linux_username = linux_username
self.verify_password = verify_password
@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
linux_password = dictionary.get('linuxPassword')
linux_username = dictionary.get('linuxUsername')
linux_current_password = dictionary.get('linuxCurrentPassword')
verify_password = dictionary.get('verifyPassword')
return cls(linux_password, linux_username, linux_current_password, verify_password)
|
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:shell.bzl", "shell")
def _addlicense_impl(ctx):
out_file = ctx.actions.declare_file(ctx.label.name + ".bash")
exclude_patterns_str = ""
if ctx.attr.exclude_patterns:
exclude_patterns = ["-not -path %s" % shell.quote(pattern) for pattern in ctx.attr.exclude_patterns]
exclude_patterns_str = " ".join(exclude_patterns)
substitutions = {
"@@ADDLICENSE_SHORT_PATH@@": shell.quote(ctx.executable._addlicense.short_path),
"@@MODE@@": shell.quote(ctx.attr.mode),
"@@EXCLUDE_PATTERNS@@": exclude_patterns_str,
}
ctx.actions.expand_template(
template = ctx.file._runner,
output = out_file,
substitutions = substitutions,
is_executable = True,
)
runfiles = ctx.runfiles(files = [ctx.executable._addlicense])
return [DefaultInfo(
runfiles = runfiles,
executable = out_file,
)]
addlicense = rule(
implementation = _addlicense_impl,
attrs = {
"mode": attr.string(
values = [
"format",
"check",
],
default = "format",
),
"exclude_patterns": attr.string_list(
allow_empty = True,
doc = "A list of glob patterns passed to the find command. E.g. './vendor/*' to exclude the Go vendor directory",
default = [
".*.git/*",
".*.project/*",
".*idea/*",
],
),
"_addlicense": attr.label(
default = Label("@com_github_google_addlicense//:addlicense"),
executable = True,
cfg = "host",
),
"_runner": attr.label(
default = Label("//bazel/rules_addlicense:runner.bash.template"),
allow_single_file = True,
),
},
executable = True,
)
|
load('@bazel_skylib//lib:paths.bzl', 'paths')
load('@bazel_skylib//lib:shell.bzl', 'shell')
def _addlicense_impl(ctx):
out_file = ctx.actions.declare_file(ctx.label.name + '.bash')
exclude_patterns_str = ''
if ctx.attr.exclude_patterns:
exclude_patterns = ['-not -path %s' % shell.quote(pattern) for pattern in ctx.attr.exclude_patterns]
exclude_patterns_str = ' '.join(exclude_patterns)
substitutions = {'@@ADDLICENSE_SHORT_PATH@@': shell.quote(ctx.executable._addlicense.short_path), '@@MODE@@': shell.quote(ctx.attr.mode), '@@EXCLUDE_PATTERNS@@': exclude_patterns_str}
ctx.actions.expand_template(template=ctx.file._runner, output=out_file, substitutions=substitutions, is_executable=True)
runfiles = ctx.runfiles(files=[ctx.executable._addlicense])
return [default_info(runfiles=runfiles, executable=out_file)]
addlicense = rule(implementation=_addlicense_impl, attrs={'mode': attr.string(values=['format', 'check'], default='format'), 'exclude_patterns': attr.string_list(allow_empty=True, doc="A list of glob patterns passed to the find command. E.g. './vendor/*' to exclude the Go vendor directory", default=['.*.git/*', '.*.project/*', '.*idea/*']), '_addlicense': attr.label(default=label('@com_github_google_addlicense//:addlicense'), executable=True, cfg='host'), '_runner': attr.label(default=label('//bazel/rules_addlicense:runner.bash.template'), allow_single_file=True)}, executable=True)
|
class Solution:
def findComplement(self, num: int) -> int:
res =i = 0
while num:
if not num & 1:
res |= 1 << i
num = num >> 1
i += 1
return res
class Solution:
def findComplement(self, num: int) -> int:
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num
class Solution:
def findComplement(self, num: int) -> int:
copy = num;
i = 0;
while copy != 0 :
copy >>= 1;
num ^= (1<<i);
i += 1;
return num;
class Solution:
def findComplement(self, num: int) -> int:
mask = 1
while( mask < num):
mask = (mask << 1) | 1
return ~num & mask
class Solution:
def findComplement(self, num: int) -> int:
n = 0;
while (n < num):
n = (n << 1) | 1;
return n - num;
|
class Solution:
def find_complement(self, num: int) -> int:
res = i = 0
while num:
if not num & 1:
res |= 1 << i
num = num >> 1
i += 1
return res
class Solution:
def find_complement(self, num: int) -> int:
i = 1
while i <= num:
i = i << 1
return i - 1 ^ num
class Solution:
def find_complement(self, num: int) -> int:
copy = num
i = 0
while copy != 0:
copy >>= 1
num ^= 1 << i
i += 1
return num
class Solution:
def find_complement(self, num: int) -> int:
mask = 1
while mask < num:
mask = mask << 1 | 1
return ~num & mask
class Solution:
def find_complement(self, num: int) -> int:
n = 0
while n < num:
n = n << 1 | 1
return n - num
|
class C:
def foo(self):
pass
class D:
def bar(self):
pass
class E:
def baz(self):
pass
def f():
return 0
def g():
return
x = (C(), D(), E())
a, b, c = x
x[0].bar() # NO bar
x[1].baz() # NO baz
x[2].foo() # baz
a.bar() # NO bar
b.baz() # NO baz
c.foo() # NO foo
|
class C:
def foo(self):
pass
class D:
def bar(self):
pass
class E:
def baz(self):
pass
def f():
return 0
def g():
return
x = (c(), d(), e())
(a, b, c) = x
x[0].bar()
x[1].baz()
x[2].foo()
a.bar()
b.baz()
c.foo()
|
# 2019-01-15
# csv file reading
f = open('score.csv', 'r')
lines = f.readlines()
f.close()
for line in lines:
total = 0
count = 0
scores = line[:-1].split(',')
# print(scores)
for score in scores:
total += int(score)
count += 1
print("Total = %3d, Avg = %.2f" % (total, total / count))
|
f = open('score.csv', 'r')
lines = f.readlines()
f.close()
for line in lines:
total = 0
count = 0
scores = line[:-1].split(',')
for score in scores:
total += int(score)
count += 1
print('Total = %3d, Avg = %.2f' % (total, total / count))
|
#
# PySNMP MIB module INTEL-RSVP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTEL-RSVP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:43:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
mib2ext, = mibBuilder.importSymbols("INTEL-GEN-MIB", "mib2ext")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibIdentifier, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, IpAddress, Integer32, Bits, ObjectIdentity, Gauge32, Counter64, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "NotificationType", "TimeTicks", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "IpAddress", "Integer32", "Bits", "ObjectIdentity", "Gauge32", "Counter64", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
rsvp = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6, 33))
conf = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6, 33, 1))
confIfTable = MibTable((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1), )
if mibBuilder.loadTexts: confIfTable.setStatus('mandatory')
confIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1), ).setIndexNames((0, "INTEL-RSVP-MIB", "confIfIndex"))
if mibBuilder.loadTexts: confIfEntry.setStatus('mandatory')
confIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: confIfIndex.setStatus('mandatory')
confIfCreateObj = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confIfCreateObj.setStatus('mandatory')
confIfDeleteObj = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("delete", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confIfDeleteObj.setStatus('mandatory')
confIfUdpEncap = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confIfUdpEncap.setStatus('mandatory')
confIfRsvpTotalBw = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confIfRsvpTotalBw.setStatus('mandatory')
confIfMaxBwPerFlow = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confIfMaxBwPerFlow.setStatus('mandatory')
confRsvpEnabled = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confRsvpEnabled.setStatus('mandatory')
confRefreshTimer = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confRefreshTimer.setStatus('mandatory')
confCleanupFactor = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: confCleanupFactor.setStatus('mandatory')
mibBuilder.exportSymbols("INTEL-RSVP-MIB", rsvp=rsvp, confIfTable=confIfTable, conf=conf, confIfIndex=confIfIndex, confIfDeleteObj=confIfDeleteObj, confIfRsvpTotalBw=confIfRsvpTotalBw, confCleanupFactor=confCleanupFactor, confIfUdpEncap=confIfUdpEncap, confIfMaxBwPerFlow=confIfMaxBwPerFlow, confIfEntry=confIfEntry, confRefreshTimer=confRefreshTimer, confRsvpEnabled=confRsvpEnabled, confIfCreateObj=confIfCreateObj)
|
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint')
(mib2ext,) = mibBuilder.importSymbols('INTEL-GEN-MIB', 'mib2ext')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(mib_identifier, notification_type, time_ticks, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, unsigned32, ip_address, integer32, bits, object_identity, gauge32, counter64, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'NotificationType', 'TimeTicks', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Unsigned32', 'IpAddress', 'Integer32', 'Bits', 'ObjectIdentity', 'Gauge32', 'Counter64', 'iso')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
rsvp = mib_identifier((1, 3, 6, 1, 4, 1, 343, 6, 33))
conf = mib_identifier((1, 3, 6, 1, 4, 1, 343, 6, 33, 1))
conf_if_table = mib_table((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1))
if mibBuilder.loadTexts:
confIfTable.setStatus('mandatory')
conf_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1)).setIndexNames((0, 'INTEL-RSVP-MIB', 'confIfIndex'))
if mibBuilder.loadTexts:
confIfEntry.setStatus('mandatory')
conf_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
confIfIndex.setStatus('mandatory')
conf_if_create_obj = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(5, 5)).setFixedLength(5)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confIfCreateObj.setStatus('mandatory')
conf_if_delete_obj = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1))).clone(namedValues=named_values(('delete', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confIfDeleteObj.setStatus('mandatory')
conf_if_udp_encap = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confIfUdpEncap.setStatus('mandatory')
conf_if_rsvp_total_bw = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 5), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confIfRsvpTotalBw.setStatus('mandatory')
conf_if_max_bw_per_flow = mib_table_column((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 6), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confIfMaxBwPerFlow.setStatus('mandatory')
conf_rsvp_enabled = mib_scalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confRsvpEnabled.setStatus('mandatory')
conf_refresh_timer = mib_scalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 3), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confRefreshTimer.setStatus('mandatory')
conf_cleanup_factor = mib_scalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 4), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
confCleanupFactor.setStatus('mandatory')
mibBuilder.exportSymbols('INTEL-RSVP-MIB', rsvp=rsvp, confIfTable=confIfTable, conf=conf, confIfIndex=confIfIndex, confIfDeleteObj=confIfDeleteObj, confIfRsvpTotalBw=confIfRsvpTotalBw, confCleanupFactor=confCleanupFactor, confIfUdpEncap=confIfUdpEncap, confIfMaxBwPerFlow=confIfMaxBwPerFlow, confIfEntry=confIfEntry, confRefreshTimer=confRefreshTimer, confRsvpEnabled=confRsvpEnabled, confIfCreateObj=confIfCreateObj)
|
"""
For each character in the `S` (if it is not a number), it has 2 possibilities, upper or lower.
So starting from an empty string
We explore all the possibilities for the character at index i is upper or lower.
The time complexity is `O(2^N)`.
The space took `O(2^N), too. And the recursion level has N level.
"""
class Solution(object):
def letterCasePermutation(self, S):
def dfs(path, i):
if i>=len(S):
opt.append(path)
return
if S[i] not in num_char:
dfs(path+S[i].upper(), i+1)
dfs(path+S[i].lower(), i+1)
else:
dfs(path+S[i], i+1)
num_char = set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
opt = []
dfs('', 0)
return opt
|
"""
For each character in the `S` (if it is not a number), it has 2 possibilities, upper or lower.
So starting from an empty string
We explore all the possibilities for the character at index i is upper or lower.
The time complexity is `O(2^N)`.
The space took `O(2^N), too. And the recursion level has N level.
"""
class Solution(object):
def letter_case_permutation(self, S):
def dfs(path, i):
if i >= len(S):
opt.append(path)
return
if S[i] not in num_char:
dfs(path + S[i].upper(), i + 1)
dfs(path + S[i].lower(), i + 1)
else:
dfs(path + S[i], i + 1)
num_char = set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
opt = []
dfs('', 0)
return opt
|
def create_mapping(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
mapping = {
'image': {
"mappings": {
"doc": {
"properties": {
"license_version": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"view_count": {
"type": "long"
},
"provider": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"source": {
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
},
"type": "text"
},
"license": {
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
},
"type": "text"
},
"url": {
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"type": "text"
},
"tags": {
"properties": {
"accuracy": {
"type": "float"
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "english"
}
}
},
"foreign_landing_url": {
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
},
"type": "text"
},
"id": {
"type": "long"
},
"identifier": {
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"type": "text"
},
"title": {
"type": "text",
"similarity": "boolean",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "english"
},
"creator": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"created_on": {
"type": "date"
},
"description": {
"fields": {
"keyword": {
"type": "keyword"
}
},
"type": "text",
"analyzer": "english"
},
"height": {
"type": "integer"
},
"width": {
"type": "integer"
},
"extension": {
"fields": {
"keyword": {
"ignore_above": 8,
"type": "keyword"
}
},
"type": "text"
},
}
}
}
}
}
return mapping[table_name]
|
def create_mapping(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
mapping = {'image': {'mappings': {'doc': {'properties': {'license_version': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}}, 'view_count': {'type': 'long'}, 'provider': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}}, 'source': {'fields': {'keyword': {'ignore_above': 256, 'type': 'keyword'}}, 'type': 'text'}, 'license': {'fields': {'keyword': {'ignore_above': 256, 'type': 'keyword'}}, 'type': 'text'}, 'url': {'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}, 'type': 'text'}, 'tags': {'properties': {'accuracy': {'type': 'float'}, 'name': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}, 'analyzer': 'english'}}}, 'foreign_landing_url': {'fields': {'keyword': {'ignore_above': 256, 'type': 'keyword'}}, 'type': 'text'}, 'id': {'type': 'long'}, 'identifier': {'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}, 'type': 'text'}, 'title': {'type': 'text', 'similarity': 'boolean', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}, 'analyzer': 'english'}, 'creator': {'type': 'text', 'fields': {'keyword': {'type': 'keyword', 'ignore_above': 256}}}, 'created_on': {'type': 'date'}, 'description': {'fields': {'keyword': {'type': 'keyword'}}, 'type': 'text', 'analyzer': 'english'}, 'height': {'type': 'integer'}, 'width': {'type': 'integer'}, 'extension': {'fields': {'keyword': {'ignore_above': 8, 'type': 'keyword'}}, 'type': 'text'}}}}}}
return mapping[table_name]
|
"""
Clear separation of the near universal extensions API from the default
implementations.
"""
|
"""
Clear separation of the near universal extensions API from the default
implementations.
"""
|
# Algorithms > Bit Manipulation > Counter game
# Louise and Richard play a game, find the winner of the game.
#
# https://www.hackerrank.com/challenges/counter-game/problem
#
pow2 = [1 << i for i in range(63, -1, -1)]
def counterGame(n):
player = 0
while n != 1:
# print( ["Louise", "Richard"][player],n)
for i in pow2:
if n == i:
n = n // 2
if n != 1:
player = 1 - player
break
elif n & i == i:
n = n - i
if n != 1:
player = 1 - player
break
return ["Louise", "Richard"][player]
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
result = counterGame(n)
print(result)
|
pow2 = [1 << i for i in range(63, -1, -1)]
def counter_game(n):
player = 0
while n != 1:
for i in pow2:
if n == i:
n = n // 2
if n != 1:
player = 1 - player
break
elif n & i == i:
n = n - i
if n != 1:
player = 1 - player
break
return ['Louise', 'Richard'][player]
if __name__ == '__main__':
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
result = counter_game(n)
print(result)
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
def sub_report():
print("Hey, I'm a function inside my subscript.")
|
def sub_report():
print("Hey, I'm a function inside my subscript.")
|
# -*- coding: utf-8 -*-
TOTAL_SESSION_NUM = 2
REST_DURATION = 5 * 60
BLOCK_DURATION = 2 * 60
MINIMUM_PULSE_CYCLE = 0.5
MAXIMUM_PULSE_CYCLE = 1.2
PPG_SAMPLE_RATE = 200
PPG_FIR_FILTER_TAP_NUM = 200
PPG_FILTER_CUTOFF = [0.5, 5.0]
PPG_SYSTOLIC_PEAK_DETECTION_THRESHOLD_COEFFICIENT = 0.5
BIOPAC_HEADER_LINES = 11
BIOPAC_MSEC_PER_SAMPLE_LINE_NUM = 2
BIOPAC_ECG_CHANNEL = 1
BIOPAC_SKIN_CONDUCTANCE_CHANNEL = 3
ECG_R_PEAK_DETECTION_THRESHOLD = 2.0
ECG_MF_HRV_CUTOFF = [0.07, 0.15]
ECG_HF_HRV_CUTOFF = [0.15, 0.5]
TRAINING_DATA_RATIO = 0.75
|
total_session_num = 2
rest_duration = 5 * 60
block_duration = 2 * 60
minimum_pulse_cycle = 0.5
maximum_pulse_cycle = 1.2
ppg_sample_rate = 200
ppg_fir_filter_tap_num = 200
ppg_filter_cutoff = [0.5, 5.0]
ppg_systolic_peak_detection_threshold_coefficient = 0.5
biopac_header_lines = 11
biopac_msec_per_sample_line_num = 2
biopac_ecg_channel = 1
biopac_skin_conductance_channel = 3
ecg_r_peak_detection_threshold = 2.0
ecg_mf_hrv_cutoff = [0.07, 0.15]
ecg_hf_hrv_cutoff = [0.15, 0.5]
training_data_ratio = 0.75
|
# Link to the problem: https://www.codechef.com/problems/STACKS
def binary_search(arr, x):
l = 0
r = len(arr)
while l < r:
mid = (r + l) // 2
if x < arr[mid]:
r = mid
else:
l = mid + 1
return l
def main():
T = int(input())
while T:
T -= 1
_ = int(input())
given_stack = list(map(int, input().split()))
top_stacks = []
for i in given_stack:
to_push = binary_search(top_stacks, i)
if to_push == len(top_stacks):
top_stacks.append(i)
else:
top_stacks[to_push] = i
print(len(top_stacks), end=" ")
print(" ".join([str(i) for i in top_stacks]))
if __name__ == "__main__":
main()
|
def binary_search(arr, x):
l = 0
r = len(arr)
while l < r:
mid = (r + l) // 2
if x < arr[mid]:
r = mid
else:
l = mid + 1
return l
def main():
t = int(input())
while T:
t -= 1
_ = int(input())
given_stack = list(map(int, input().split()))
top_stacks = []
for i in given_stack:
to_push = binary_search(top_stacks, i)
if to_push == len(top_stacks):
top_stacks.append(i)
else:
top_stacks[to_push] = i
print(len(top_stacks), end=' ')
print(' '.join([str(i) for i in top_stacks]))
if __name__ == '__main__':
main()
|
class CorruptedStateSpaceModelStructureException(Exception):
pass
class CorruptedStochasticModelStructureException(Exception):
pass
|
class Corruptedstatespacemodelstructureexception(Exception):
pass
class Corruptedstochasticmodelstructureexception(Exception):
pass
|
API_ACCESS = 'YOUR_API_ACCESS'
API_SECRET = 'YOUR_API_SECRET'
BTC_UNIT = 0.001
BTC_AMOUNT = BTC_UNIT
CNY_UNIT = 0.01
CNY_STEP = CNY_UNIT
DIFFERENCE_STEP = 2.0
MIN_SURPLUS = 0.5
NO_GOOD_SLEEP = 15
MAX_TRIAL = 3
MAX_OPEN_ORDERS = 3
TOO_MANY_OPEN_SLEEP = 10
DEBUG_MODE = True
REMOVE_THRESHOLD = 20.0
REMOVE_UNREALISTIC = True
CANCEL_ALL_ON_STARTUP = True
GET_INFO_BEFORE_SLEEP = True
|
api_access = 'YOUR_API_ACCESS'
api_secret = 'YOUR_API_SECRET'
btc_unit = 0.001
btc_amount = BTC_UNIT
cny_unit = 0.01
cny_step = CNY_UNIT
difference_step = 2.0
min_surplus = 0.5
no_good_sleep = 15
max_trial = 3
max_open_orders = 3
too_many_open_sleep = 10
debug_mode = True
remove_threshold = 20.0
remove_unrealistic = True
cancel_all_on_startup = True
get_info_before_sleep = True
|
'''
Description: python solution of AddTwoNumbers (https://leetcode-cn.com/problems/add-two-numbers/)
Author: Kotori Y
Date: 2021-04-20 16:49:38
LastEditors: Kotori Y
LastEditTime: 2021-04-20 16:51:04
FilePath: \LeetCode-Code\codes\LinkedList\AddTwoNumbers\AddTwoNumbers.py
AuthorMail: [email protected]
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head, tail = [None, None]
carry = 0
while (l1 or l2):
n1 = l1.val if l1 else 0
n2 = l2.val if l2 else 0
sum_ = n1 + n2 + carry
carry = sum_ // 10
if not head:
head = tail = ListNode(sum_ % 10)
else:
tail.next = ListNode(sum_ % 10)
tail = tail.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if (carry > 0):
tail.next = ListNode(carry)
return head
|
"""
Description: python solution of AddTwoNumbers (https://leetcode-cn.com/problems/add-two-numbers/)
Author: Kotori Y
Date: 2021-04-20 16:49:38
LastEditors: Kotori Y
LastEditTime: 2021-04-20 16:51:04
FilePath: \\LeetCode-Code\\codes\\LinkedList\\AddTwoNumbers\\AddTwoNumbers.py
AuthorMail: [email protected]
"""
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
(head, tail) = [None, None]
carry = 0
while l1 or l2:
n1 = l1.val if l1 else 0
n2 = l2.val if l2 else 0
sum_ = n1 + n2 + carry
carry = sum_ // 10
if not head:
head = tail = list_node(sum_ % 10)
else:
tail.next = list_node(sum_ % 10)
tail = tail.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry > 0:
tail.next = list_node(carry)
return head
|
"""
DFS Steps:
- create and empty stack and and list of explored elements
- take the starting element and push it into the stack and add it to the visited list
- check if it has any children that are unvisited.
- if it has unvisited kids, pick one and add it to the top of the stack and the visited list
- recursively check them kids till there are no more kids or all kids are visited.
- when you get to a leaf or node with all visited kids, pop it off the top of the stack
- pick the previous node and check it's kids for unvisited ones
- rinse and repeat till you find the destination node you were looking for
"""
graph = {'A': ['B', 'C', 'E'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B', 'D'],
'F': ['C'],
'G': ['C']}
def dfs_recursive(graph, start, visited=[]):
# put the starting element into our stack
visited += [start]
# for all the neighbors of our current node, perform dfs
for neighbor in graph[start]:
if neighbor not in visited:
# current neigbor becomes new start
visited = dfs_recursive(graph, neighbor, visited)
return visited
def depth_first_search(graph, start):
"""
Without recursion
"""
visited = []
stack = [start]
while stack:
# get the element at the top of the stack
node = stack.pop()
if node not in visited:
# add it to the list of visited nodes
visited.append(node)
# get its neighbors
neighbors = graph[node]
# for all it's unvisited neighbors, add them to the stack
# each of them will be visited later
for neighbor in neighbors:
if neighbor not in visited:
stack.append(neighbor)
return visited
print(dfs_recursive(graph, 'A')) # ['A', 'B', 'D', 'E', 'C', 'F', 'G']
print(depth_first_search(graph, 'A')) # ['A', 'E', 'D', 'B', 'C', 'G', 'F']
|
"""
DFS Steps:
- create and empty stack and and list of explored elements
- take the starting element and push it into the stack and add it to the visited list
- check if it has any children that are unvisited.
- if it has unvisited kids, pick one and add it to the top of the stack and the visited list
- recursively check them kids till there are no more kids or all kids are visited.
- when you get to a leaf or node with all visited kids, pop it off the top of the stack
- pick the previous node and check it's kids for unvisited ones
- rinse and repeat till you find the destination node you were looking for
"""
graph = {'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C']}
def dfs_recursive(graph, start, visited=[]):
visited += [start]
for neighbor in graph[start]:
if neighbor not in visited:
visited = dfs_recursive(graph, neighbor, visited)
return visited
def depth_first_search(graph, start):
"""
Without recursion
"""
visited = []
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
neighbors = graph[node]
for neighbor in neighbors:
if neighbor not in visited:
stack.append(neighbor)
return visited
print(dfs_recursive(graph, 'A'))
print(depth_first_search(graph, 'A'))
|
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) < 3: return max(nums)
n = len(nums)
ans1 = self.robHouse(nums[:n-1])
ans2 = self.robHouse(nums[1:])
return max(ans1, ans2)
def robHouse(self, nums):
prev, curr = 0, 0
for num in nums:
v = max(curr, prev + num)
prev = curr
curr = v
return curr
|
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) < 3:
return max(nums)
n = len(nums)
ans1 = self.robHouse(nums[:n - 1])
ans2 = self.robHouse(nums[1:])
return max(ans1, ans2)
def rob_house(self, nums):
(prev, curr) = (0, 0)
for num in nums:
v = max(curr, prev + num)
prev = curr
curr = v
return curr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.