content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class LevelUpCooldownError(Exception):
pass
class MaxLevelError(Exception):
pass
| class Levelupcooldownerror(Exception):
pass
class Maxlevelerror(Exception):
pass |
#
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
RESULT_OK = 0
RESULT_ERROR = 1
PLUGIN_ERRORS = "plugin_errors"
ERRORS = "errors"
class Result(object):
def __init__(self):
self._result = {}
self._result["result_code"] = RESULT_OK # no error so far..
self._result["result"] = []
def add(self, obj_list):
self._result["result"].extend(obj_list)
def pluginError(self, pluginName, errorMsg):
self._result["result_code"] = RESULT_ERROR
pluginErrors = self._result.get(PLUGIN_ERRORS, {})
# get the list of error messages for plugin or a new list
# if it's the first error
pluginErrorMessages = pluginErrors.get(pluginName, [])
pluginErrorMessages.append(errorMsg)
# put the plugin error list to the error dict
# we could do that only for the first time,
# but this way we can save one 'if key in dict'
pluginErrors[pluginName] = pluginErrorMessages
self._result[PLUGIN_ERRORS] = pluginErrors
def error(self, errorMsg):
self._result["result_code"] = RESULT_ERROR
errors = self._result.get(ERRORS, [])
errors.append(errorMsg)
self._result[ERRORS] = errors
def to_dict(self):
return self._result
class FilterResult(Result):
def __init__(self):
super(FilterResult, self).__init__()
class WeightResult(Result):
def __init__(self):
super(WeightResult, self).__init__()
| result_ok = 0
result_error = 1
plugin_errors = 'plugin_errors'
errors = 'errors'
class Result(object):
def __init__(self):
self._result = {}
self._result['result_code'] = RESULT_OK
self._result['result'] = []
def add(self, obj_list):
self._result['result'].extend(obj_list)
def plugin_error(self, pluginName, errorMsg):
self._result['result_code'] = RESULT_ERROR
plugin_errors = self._result.get(PLUGIN_ERRORS, {})
plugin_error_messages = pluginErrors.get(pluginName, [])
pluginErrorMessages.append(errorMsg)
pluginErrors[pluginName] = pluginErrorMessages
self._result[PLUGIN_ERRORS] = pluginErrors
def error(self, errorMsg):
self._result['result_code'] = RESULT_ERROR
errors = self._result.get(ERRORS, [])
errors.append(errorMsg)
self._result[ERRORS] = errors
def to_dict(self):
return self._result
class Filterresult(Result):
def __init__(self):
super(FilterResult, self).__init__()
class Weightresult(Result):
def __init__(self):
super(WeightResult, self).__init__() |
mys1 = {1,2,3,4}
mys2 = {3,4,5,6}
mys1.difference_update(mys2)
print(mys1) # DU1
mys3 = {'a','b','c','d'}
mys4 = {'d','w','f','g'}
mys5 = {'v','w','x','z'}
mys3.difference_update(mys4)
print(mys3) # DU2
mys4.difference_update(mys5)
print(mys4) # DU3
| mys1 = {1, 2, 3, 4}
mys2 = {3, 4, 5, 6}
mys1.difference_update(mys2)
print(mys1)
mys3 = {'a', 'b', 'c', 'd'}
mys4 = {'d', 'w', 'f', 'g'}
mys5 = {'v', 'w', 'x', 'z'}
mys3.difference_update(mys4)
print(mys3)
mys4.difference_update(mys5)
print(mys4) |
NUMERICAL_TYPE = "num"
NUMERICAL_PREFIX = "n_"
CATEGORY_TYPE = "cat"
CATEGORY_PREFIX = "c_"
TIME_TYPE = "time"
TIME_PREFIX = "t_"
MULTI_CAT_TYPE = "multi-cat"
MULTI_CAT_PREFIX = "m_"
MULTI_CAT_DELIMITER = ","
MAIN_TABLE_NAME = "main"
MAIN_TABLE_TEST_NAME = "main_test"
TABLE_PREFIX = "table_"
LABEL = "label"
HASH_MAX = 200
AGG_FEAT_MAX = 4
RANDOM_SEED = 2019
N_RANDOM_COL = 7
SAMPLE_SIZE = 100000
HYPEROPT_TEST_SIZE = 0.5
BEST_ITER_THRESHOLD = 100
IMBALANCE_RATE = 0.001
MEMORY_LIMIT = 10000 # 10GB
N_EST = 500
N_STOP = 10
KFOLD = 5 | numerical_type = 'num'
numerical_prefix = 'n_'
category_type = 'cat'
category_prefix = 'c_'
time_type = 'time'
time_prefix = 't_'
multi_cat_type = 'multi-cat'
multi_cat_prefix = 'm_'
multi_cat_delimiter = ','
main_table_name = 'main'
main_table_test_name = 'main_test'
table_prefix = 'table_'
label = 'label'
hash_max = 200
agg_feat_max = 4
random_seed = 2019
n_random_col = 7
sample_size = 100000
hyperopt_test_size = 0.5
best_iter_threshold = 100
imbalance_rate = 0.001
memory_limit = 10000
n_est = 500
n_stop = 10
kfold = 5 |
# Operations allowed : Insertion, Addition, Deletion
def func(str1, str2, m, n):
dp = [[0 for x in range(n+1)] for x in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
return dp[m][n]
if __name__ == '__main__':
str1 = "hacktoberfest"
str2 = "hackerearth"
print(func(str1, str2, len(str1), len(str2)))
| def func(str1, str2, m, n):
dp = [[0 for x in range(n + 1)] for x in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])
return dp[m][n]
if __name__ == '__main__':
str1 = 'hacktoberfest'
str2 = 'hackerearth'
print(func(str1, str2, len(str1), len(str2))) |
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
def create_file_start_length_list(file_nevents_list, max_events_per_run = -1, max_events_total = -1, max_files_per_run = 1):
file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total)
return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run)
##__________________________________________________________________||
def _apply_max_events_total(file_nevents_list, max_events_total = -1):
if max_events_total < 0: return file_nevents_list
ret = [ ]
for file, nevents in file_nevents_list:
if max_events_total == 0: break
nevents = min(max_events_total, nevents)
ret.append((file, nevents))
max_events_total -= nevents
return ret
##__________________________________________________________________||
def _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run):
if not file_nevents_list:
return [ ]
total_nevents = sum([n for f, n, in file_nevents_list])
if total_nevents == 0:
return [ ]
if max_files_per_run == 0:
return [ ]
if max_events_per_run == 0:
return [ ]
if max_events_per_run < 0:
max_events_per_run = total_nevents
total_nfiles = len(set([f for f, n, in file_nevents_list]))
if max_files_per_run < 0:
max_files_per_run = total_nfiles
files = [ ]
nevents = [ ]
start = [ ]
length = [ ]
i = 0
for file_, nev in file_nevents_list:
if nev == 0:
continue
if i == len(files):
# create a new run
files.append([ ])
nevents.append(0)
start.append(0)
length.append(0)
files[i].append(file_)
nevents[i] += nev
if max_events_per_run >= nevents[i]:
length[i] = nevents[i]
else:
dlength = max_events_per_run - length[i]
length[i] = max_events_per_run
i += 1
files.append([file_])
nevents.append(nevents[i-1] - length[i-1])
start.append(dlength)
while max_events_per_run < nevents[i]:
length.append(max_events_per_run)
i += 1
files.append([file_])
nevents.append(nevents[i-1] - length[i-1])
start.append(start[i-1] + length[i-1])
length.append(nevents[i])
if max_events_per_run == nevents[i]:
i += 1 # to next run
continue
if max_files_per_run == len(files[i]):
i += 1 # to next run
# print files, nevents, start, length
ret = list(zip(files, start, length))
return ret
##__________________________________________________________________||
def _start_length_pairs_for_split_lists(ntotal, max_per_list):
# e.g., ntotal = 35, max_per_list = 10
if max_per_list < 0: return [(0, ntotal)]
nlists = ntotal//max_per_list
# https://stackoverflow.com/questions/1282945/python-integer-division-yields-float
# nlists = 3
ret = [(i*max_per_list, max_per_list) for i in range(nlists)]
# e.g., [(0, 10), (10, 10), (20, 10)]
remainder = ntotal % max_per_list
# e.g., 5
if remainder > 0:
last = (nlists*max_per_list, remainder)
# e.g, (30, 5)
ret.append(last)
# e.g., [(0, 10), (10, 10), (20, 10), (30, 5)]
return ret
##__________________________________________________________________||
def _minimum_positive_value(vals):
# returns -1 if all negative or empty
vals = [v for v in vals if v >= 0]
if not vals: return -1
return min(vals)
##__________________________________________________________________||
| def create_file_start_length_list(file_nevents_list, max_events_per_run=-1, max_events_total=-1, max_files_per_run=1):
file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total)
return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run)
def _apply_max_events_total(file_nevents_list, max_events_total=-1):
if max_events_total < 0:
return file_nevents_list
ret = []
for (file, nevents) in file_nevents_list:
if max_events_total == 0:
break
nevents = min(max_events_total, nevents)
ret.append((file, nevents))
max_events_total -= nevents
return ret
def _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run):
if not file_nevents_list:
return []
total_nevents = sum([n for (f, n) in file_nevents_list])
if total_nevents == 0:
return []
if max_files_per_run == 0:
return []
if max_events_per_run == 0:
return []
if max_events_per_run < 0:
max_events_per_run = total_nevents
total_nfiles = len(set([f for (f, n) in file_nevents_list]))
if max_files_per_run < 0:
max_files_per_run = total_nfiles
files = []
nevents = []
start = []
length = []
i = 0
for (file_, nev) in file_nevents_list:
if nev == 0:
continue
if i == len(files):
files.append([])
nevents.append(0)
start.append(0)
length.append(0)
files[i].append(file_)
nevents[i] += nev
if max_events_per_run >= nevents[i]:
length[i] = nevents[i]
else:
dlength = max_events_per_run - length[i]
length[i] = max_events_per_run
i += 1
files.append([file_])
nevents.append(nevents[i - 1] - length[i - 1])
start.append(dlength)
while max_events_per_run < nevents[i]:
length.append(max_events_per_run)
i += 1
files.append([file_])
nevents.append(nevents[i - 1] - length[i - 1])
start.append(start[i - 1] + length[i - 1])
length.append(nevents[i])
if max_events_per_run == nevents[i]:
i += 1
continue
if max_files_per_run == len(files[i]):
i += 1
ret = list(zip(files, start, length))
return ret
def _start_length_pairs_for_split_lists(ntotal, max_per_list):
if max_per_list < 0:
return [(0, ntotal)]
nlists = ntotal // max_per_list
ret = [(i * max_per_list, max_per_list) for i in range(nlists)]
remainder = ntotal % max_per_list
if remainder > 0:
last = (nlists * max_per_list, remainder)
ret.append(last)
return ret
def _minimum_positive_value(vals):
vals = [v for v in vals if v >= 0]
if not vals:
return -1
return min(vals) |
def buildFireTraps(start, end, step, x, y):
for i in range(start, end+1, step):
if x:
hero.buildXY("fire-trap", x, i)
else:
hero.buildXY("fire-trap", i, y)
buildFireTraps(40, 112, 24, False, 114)
buildFireTraps(110, 38, -18, 140, False)
buildFireTraps(132, 32, -20, False, 22)
buildFireTraps(28, 108, 16, 20, False)
hero.moveXY(40, 94)
| def build_fire_traps(start, end, step, x, y):
for i in range(start, end + 1, step):
if x:
hero.buildXY('fire-trap', x, i)
else:
hero.buildXY('fire-trap', i, y)
build_fire_traps(40, 112, 24, False, 114)
build_fire_traps(110, 38, -18, 140, False)
build_fire_traps(132, 32, -20, False, 22)
build_fire_traps(28, 108, 16, 20, False)
hero.moveXY(40, 94) |
"""exercism protein translation module."""
def proteins(strand):
"""
Translate RNA sequences into proteins.
:param strand string - The RNA to translate.
:return list - The protein the RNA translated into.
"""
# Some unit tests seem to be funky because of the order ...
# proteins = set()
proteins = []
stop_codons = ["UAA", "UAG", "UGA"]
protein_map = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan"
}
for index in range(0, len(strand), 3):
codon = strand[index:index + 3]
if codon in stop_codons:
break
# proteins.add(protein_map.get(codon))
protein = protein_map.get(codon)
if proteins.count(protein) == 0:
proteins.append(protein)
# proteins = list(proteins)
# proteins.sort()
return proteins
| """exercism protein translation module."""
def proteins(strand):
"""
Translate RNA sequences into proteins.
:param strand string - The RNA to translate.
:return list - The protein the RNA translated into.
"""
proteins = []
stop_codons = ['UAA', 'UAG', 'UGA']
protein_map = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UCG': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan'}
for index in range(0, len(strand), 3):
codon = strand[index:index + 3]
if codon in stop_codons:
break
protein = protein_map.get(codon)
if proteins.count(protein) == 0:
proteins.append(protein)
return proteins |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-10
Last_modify: 2016-01-10
******************************************
'''
'''
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases.
If you want a challenge, please do not see below and
ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely
(ie, no given input specs).
You are responsible to gather all the input requirements up front.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the
first non-whitespace character is found. Then, starting from this character,
takes an optional initial plus or minus sign followed by as many numerical
digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral
number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid
integral number, or if no such sequence exists because either str is empty or
it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
'''
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
mini, maxi = ord('0'), ord('9')
outi = 0
s = 1
start = 0
for i in range(len(str)):
if i == start:
if str[i] == ' ':
start += 1
continue
if str[i] == '+':
continue
if str[i] == '-':
s = -1
continue
num = ord(str[i])
if num >= mini and num <= maxi:
num = num - mini
outi = outi * 10 + num
else:
break
if outi >= 2 ** 31:
if s == 1:
outi = 2 ** 31 - 1
else:
outi = 2 ** 31
return s * outi
| """
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-10
Last_modify: 2016-01-10
******************************************
"""
'\nImplement atoi to convert a string to an integer.\n\nHint: Carefully consider all possible input cases.\nIf you want a challenge, please do not see below and\nask yourself what are the possible input cases.\n\nNotes: It is intended for this problem to be specified vaguely\n(ie, no given input specs).\nYou are responsible to gather all the input requirements up front.\n\nRequirements for atoi:\nThe function first discards as many whitespace characters as necessary until the\nfirst non-whitespace character is found. Then, starting from this character,\ntakes an optional initial plus or minus sign followed by as many numerical\ndigits as possible, and interprets them as a numerical value.\n\nThe string can contain additional characters after those that form the integral\nnumber, which are ignored and have no effect on the behavior of this function.\n\nIf the first sequence of non-whitespace characters in str is not a valid\nintegral number, or if no such sequence exists because either str is empty or\nit contains only whitespace characters, no conversion is performed.\n\nIf no valid conversion could be performed, a zero value is returned.\nIf the correct value is out of the range of representable values,\nINT_MAX (2147483647) or INT_MIN (-2147483648) is returned.\n'
class Solution(object):
def my_atoi(self, str):
"""
:type str: str
:rtype: int
"""
(mini, maxi) = (ord('0'), ord('9'))
outi = 0
s = 1
start = 0
for i in range(len(str)):
if i == start:
if str[i] == ' ':
start += 1
continue
if str[i] == '+':
continue
if str[i] == '-':
s = -1
continue
num = ord(str[i])
if num >= mini and num <= maxi:
num = num - mini
outi = outi * 10 + num
else:
break
if outi >= 2 ** 31:
if s == 1:
outi = 2 ** 31 - 1
else:
outi = 2 ** 31
return s * outi |
# TLV format:
# TAG | LENGTH | VALUE
# Header contains nested TLV triplets
TRACE_TAG_HEADER = 1
TRACE_TAG_EVENTS = 2
TRACE_TAG_FILES = 3
TRACE_TAG_METADATA = 4
HEADER_TAG_VERSION = 1
HEADER_TAG_FILES = 2
HEADER_TAG_METADATA = 3
| trace_tag_header = 1
trace_tag_events = 2
trace_tag_files = 3
trace_tag_metadata = 4
header_tag_version = 1
header_tag_files = 2
header_tag_metadata = 3 |
"""
capo_optimizer library, allows quick determination of
optimal guitar capo positioning.
"""
version = (0, 0, 1)
__version__ = '.'.join(map(str, version))
| """
capo_optimizer library, allows quick determination of
optimal guitar capo positioning.
"""
version = (0, 0, 1)
__version__ = '.'.join(map(str, version)) |
menu = """
What would your weight would be in other celestian bodies
Choose a celestial body
1-Sun
2-Mercury
3-Venus
4-Mars
5-Jupiter
6-Saturn
7-Uranus
8-Neptune
9-The Moon
10- Ganymede
"""
option = int(input(menu))
class celestial_body:
def gravity_calculation(name,acceleration):
mass = float(input("What is your mass?"))
weigth = mass * acceleration
print("Your weight on", celestial_body, "would be", weigth)
if option == 1:
sun = celestial_body
sun.gravity_calculation("The Sun",274)
elif option == 2:
mercury = celestial_body
mercury.gravity_calculation("Mercury",3.7)
elif option == 3:
venus = celestial_body
venus.gravity_calculation("Venus",8.87)
elif option == 4:
mars = celestial_body
mars.gravity_calculation("Mars",3.72)
elif option == 5:
jupiter = celestial_body
jupiter.gravity_calculation("Jupiter",24.79)
elif option == 6:
saturn = celestial_body
saturn.gravity_calculation("Saturn",10.44)
elif option == 7:
uranus = celestial_body
uranus.gravity_calculation("Uranus",8.87)
elif option == 8:
neptune = celestial_body
neptune.gravity_calculation("Neptune",11.15)
elif option == 9:
moon = celestial_body
moon.gravity_calculation("The moon",1.62)
elif option == 10:
ganymede = celestial_body
ganymede.gravity_calculation("Ganymede",1.42)
else:
print("That is not an option")
| menu = '\nWhat would your weight would be in other celestian bodies\nChoose a celestial body\n\n1-Sun\n2-Mercury\n3-Venus\n4-Mars\n5-Jupiter\n6-Saturn\n7-Uranus\n8-Neptune\n9-The Moon\n10- Ganymede\n'
option = int(input(menu))
class Celestial_Body:
def gravity_calculation(name, acceleration):
mass = float(input('What is your mass?'))
weigth = mass * acceleration
print('Your weight on', celestial_body, 'would be', weigth)
if option == 1:
sun = celestial_body
sun.gravity_calculation('The Sun', 274)
elif option == 2:
mercury = celestial_body
mercury.gravity_calculation('Mercury', 3.7)
elif option == 3:
venus = celestial_body
venus.gravity_calculation('Venus', 8.87)
elif option == 4:
mars = celestial_body
mars.gravity_calculation('Mars', 3.72)
elif option == 5:
jupiter = celestial_body
jupiter.gravity_calculation('Jupiter', 24.79)
elif option == 6:
saturn = celestial_body
saturn.gravity_calculation('Saturn', 10.44)
elif option == 7:
uranus = celestial_body
uranus.gravity_calculation('Uranus', 8.87)
elif option == 8:
neptune = celestial_body
neptune.gravity_calculation('Neptune', 11.15)
elif option == 9:
moon = celestial_body
moon.gravity_calculation('The moon', 1.62)
elif option == 10:
ganymede = celestial_body
ganymede.gravity_calculation('Ganymede', 1.42)
else:
print('That is not an option') |
'''
Classes to work with WebSphere Application Servers
Author: Christoph Stoettner
Mail: christoph.stoettner@stoeps.de
Documentation: http://scripting101.stoeps.de
Version: 5.0.1
Date: 09/19/2015
License: Apache 2.0
'''
class WasServers:
def __init__(self):
# Get a list of all servers in WAS cell (dmgr, nodeagents, AppServer,
# webserver)
self.AllServers = self.getAllServers()
self.WebServers = self.getWebServers()
self.AppServers = self.getAllServersWithoutWeb()
# self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers()
self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers()
def getAllServers(self):
# get a list of all servers
self.servers = AdminTask.listServers().splitlines()
return self.servers
def getAppServers(self):
# get a list of all application servers
# includes webserver, but no dmgr and nodeagents
self.servers = AdminTask.listServers(
'[-serverType APPLICATION_SERVER]').splitlines()
return self.servers
def getWebServers(self):
# get a list of all webservers
self.webservers = AdminTask.listServers(
'[-serverType WEB_SERVER]').splitlines()
return self.webservers
def getAllServersWithoutWeb(self):
# inclusive dmgr and nodeagents
self.AppServers = self.AllServers
for webserver in self.WebServers:
self.AppServers.remove(webserver)
return self.AppServers
def getAttrServers(self):
# get jvm, node, cell from single application server
srvNum = 0
jvm = []
cell = []
node = []
servername = []
for server in self.AppServers:
srvNum += 1
javavm = AdminConfig.list('JavaVirtualMachine', server)
jvm.append(javavm)
srv = server.split('/')
cell.append(srv[1])
node.append(srv[3])
servername.append(srv[5].split('|')[0])
self.jvm = jvm
cell = cell
node = node
servername = servername
# return ( serverNum, jvm, cell, node, serverName )
return (srvNum, self.jvm, cell, node, servername)
| """
Classes to work with WebSphere Application Servers
Author: Christoph Stoettner
Mail: christoph.stoettner@stoeps.de
Documentation: http://scripting101.stoeps.de
Version: 5.0.1
Date: 09/19/2015
License: Apache 2.0
"""
class Wasservers:
def __init__(self):
self.AllServers = self.getAllServers()
self.WebServers = self.getWebServers()
self.AppServers = self.getAllServersWithoutWeb()
(self.serverNum, self.jvm, self.cell, self.node, self.serverName) = self.getAttrServers()
def get_all_servers(self):
self.servers = AdminTask.listServers().splitlines()
return self.servers
def get_app_servers(self):
self.servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
return self.servers
def get_web_servers(self):
self.webservers = AdminTask.listServers('[-serverType WEB_SERVER]').splitlines()
return self.webservers
def get_all_servers_without_web(self):
self.AppServers = self.AllServers
for webserver in self.WebServers:
self.AppServers.remove(webserver)
return self.AppServers
def get_attr_servers(self):
srv_num = 0
jvm = []
cell = []
node = []
servername = []
for server in self.AppServers:
srv_num += 1
javavm = AdminConfig.list('JavaVirtualMachine', server)
jvm.append(javavm)
srv = server.split('/')
cell.append(srv[1])
node.append(srv[3])
servername.append(srv[5].split('|')[0])
self.jvm = jvm
cell = cell
node = node
servername = servername
return (srvNum, self.jvm, cell, node, servername) |
class Solution:
def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
ans = [""] * len(S)
for i in range(len(S)):
ans[i] = S[i]
for i in range(len(indexes)):
start = indexes[i]
src = sources[i]
change = 1
for j in range(len(src)):
if S[start + j] != src[j]:
change = 0
break
if change == 0:
continue
ans[start] = targets[i]
for j in range(1,len(src)):
ans[start + j] = ""
return "".join(ans)
| class Solution:
def find_replace_string(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
ans = [''] * len(S)
for i in range(len(S)):
ans[i] = S[i]
for i in range(len(indexes)):
start = indexes[i]
src = sources[i]
change = 1
for j in range(len(src)):
if S[start + j] != src[j]:
change = 0
break
if change == 0:
continue
ans[start] = targets[i]
for j in range(1, len(src)):
ans[start + j] = ''
return ''.join(ans) |
###############################################################################
# Singlecell plot arrays #
###############################################################################
tag = "singlecell"
| tag = 'singlecell' |
class PipelineNotDeployed(Exception):
def __init__(self, pipeline_id=None, message="Pipeline not deployed") -> None:
self.pipeline_id = pipeline_id
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.pipeline_id} -> {self.message}"
| class Pipelinenotdeployed(Exception):
def __init__(self, pipeline_id=None, message='Pipeline not deployed') -> None:
self.pipeline_id = pipeline_id
self.message = message
super().__init__(self.message)
def __str__(self):
return f'{self.pipeline_id} -> {self.message}' |
class TGConfigError(Exception):pass
def coerce_config(configuration, prefix, converters):
"""Convert configuration values to expected types."""
options = dict((key[len(prefix):], configuration[key])
for key in configuration if key.startswith(prefix))
for option, converter in converters.items():
if option in options:
options[option] = converter(options[option])
return options
| class Tgconfigerror(Exception):
pass
def coerce_config(configuration, prefix, converters):
"""Convert configuration values to expected types."""
options = dict(((key[len(prefix):], configuration[key]) for key in configuration if key.startswith(prefix)))
for (option, converter) in converters.items():
if option in options:
options[option] = converter(options[option])
return options |
class Solution:
def search(self, nums, target):
if not nums: return -1
x, y = 0, len(nums) - 1
while x <= y:
m = x + (y - x) // 2
if nums[m] > nums[0]:
x = m + 1
elif nums[m] < nums[0]:
y = m
else:
x = y if nums[x] > nums[y] else y + 1
break
print(x, y)
if target > nums[0]:
lo, hi = 0, x - 1
elif target < nums[0]:
lo, hi = x, len(nums) - 1
else:
return 0
print(lo, hi)
while lo <= hi:
m = lo + (hi - lo) // 2
if nums[m] == target:
return m
elif nums[m] > target:
hi = m - 1
else:
lo = m + 1
return -1
if __name__ == '__main__':
ret1 = Solution().search(nums=[4, 5, 6, 7, 0, 1, 2], target=2)
ret2 = Solution().search(nums=[1], target=1)
ret3 = Solution().search(nums=[1, 3], target=1)
ret4 = Solution().search(nums=[1, 3], target=3)
ret5 = Solution().search(nums=[3, 1], target=1)
print(ret1, ret2, ret3, ret4, ret5)
ret = Solution().search(nums=[1, 3, 5], target=5)
print(ret)
| class Solution:
def search(self, nums, target):
if not nums:
return -1
(x, y) = (0, len(nums) - 1)
while x <= y:
m = x + (y - x) // 2
if nums[m] > nums[0]:
x = m + 1
elif nums[m] < nums[0]:
y = m
else:
x = y if nums[x] > nums[y] else y + 1
break
print(x, y)
if target > nums[0]:
(lo, hi) = (0, x - 1)
elif target < nums[0]:
(lo, hi) = (x, len(nums) - 1)
else:
return 0
print(lo, hi)
while lo <= hi:
m = lo + (hi - lo) // 2
if nums[m] == target:
return m
elif nums[m] > target:
hi = m - 1
else:
lo = m + 1
return -1
if __name__ == '__main__':
ret1 = solution().search(nums=[4, 5, 6, 7, 0, 1, 2], target=2)
ret2 = solution().search(nums=[1], target=1)
ret3 = solution().search(nums=[1, 3], target=1)
ret4 = solution().search(nums=[1, 3], target=3)
ret5 = solution().search(nums=[3, 1], target=1)
print(ret1, ret2, ret3, ret4, ret5)
ret = solution().search(nums=[1, 3, 5], target=5)
print(ret) |
class Chapter:
id: float
title: str
text: str
| class Chapter:
id: float
title: str
text: str |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
p1 = head
for _ in range(k):
if p1:
p1 = p1.next
else:
return None
p2 = head
while p1:
p1 = p1.next
p2 = p2.next
return p2
| class Solution:
def get_kth_from_end(self, head: ListNode, k: int) -> ListNode:
p1 = head
for _ in range(k):
if p1:
p1 = p1.next
else:
return None
p2 = head
while p1:
p1 = p1.next
p2 = p2.next
return p2 |
with open('input.txt') as f:
lines = f.readlines()
ans = 0
for line in lines:
input, output = line.split(" | ")
for word in output.split():
length = len(word)
if length == 2 or length == 4 or length == 3 or length == 7:
ans += 1
print(ans)
| with open('input.txt') as f:
lines = f.readlines()
ans = 0
for line in lines:
(input, output) = line.split(' | ')
for word in output.split():
length = len(word)
if length == 2 or length == 4 or length == 3 or (length == 7):
ans += 1
print(ans) |
def fibonacci_iterative(num):
a = 0
b = 1
total = 0
for _ in range(2, num + 1):
total = a + b
a = b
b = total
return total
def fibonacci_recursive(num):
if num < 2:
return num
return fibonacci_recursive(num-1) + fibonacci_recursive(num-2)
print(fibonacci_iterative(10))
print(fibonacci_recursive(10))
| def fibonacci_iterative(num):
a = 0
b = 1
total = 0
for _ in range(2, num + 1):
total = a + b
a = b
b = total
return total
def fibonacci_recursive(num):
if num < 2:
return num
return fibonacci_recursive(num - 1) + fibonacci_recursive(num - 2)
print(fibonacci_iterative(10))
print(fibonacci_recursive(10)) |
data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
def makedict(**kwargs):
return kwargs
data = makedict(red=1, green=2, blue=3)
print(data)
def dodict(*args, **kwds):
d = {}
for k, v in args: d[k] = v
d.update(kwds)
return d
tada = dodict(yellow=2, green=4, *data.items())
print(tada)
| data = {'red': 1, 'green': 2, 'blue': 3}
def makedict(**kwargs):
return kwargs
data = makedict(red=1, green=2, blue=3)
print(data)
def dodict(*args, **kwds):
d = {}
for (k, v) in args:
d[k] = v
d.update(kwds)
return d
tada = dodict(*data.items(), yellow=2, green=4)
print(tada) |
"""69. Sqrt(x)"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#####Practice
###############
l = 0
r = x
while l <= r:
mid = l + (r - l)//2
if mid*mid <= x < (mid+1)*(mid+1):
return mid
elif mid*mid > x:
r = mid - 1
else:
l = mid + 1
### short way
r = x
while r*r > x:
r = (r + x/r)//2
return r
| """69. Sqrt(x)"""
class Solution(object):
def my_sqrt(self, x):
"""
:type x: int
:rtype: int
"""
l = 0
r = x
while l <= r:
mid = l + (r - l) // 2
if mid * mid <= x < (mid + 1) * (mid + 1):
return mid
elif mid * mid > x:
r = mid - 1
else:
l = mid + 1
r = x
while r * r > x:
r = (r + x / r) // 2
return r |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>)
{
'name': 'Singapore - Accounting',
'author': 'Tech Receptives',
'website': 'http://www.techreceptives.com',
'category': 'Localization',
'description': """
Singapore accounting chart and localization.
=======================================================
After installing this module, the Configuration wizard for accounting is launched.
* The Chart of Accounts consists of the list of all the general ledger accounts
required to maintain the transactions of Singapore.
* On that particular wizard, you will be asked to pass the name of the company,
the chart template to follow, the no. of digits to generate, the code for your
account and bank account, currency to create journals.
* The Chart of Taxes would display the different types/groups of taxes such as
Standard Rates, Zeroed, Exempted, MES and Out of Scope.
* The tax codes are specified considering the Tax Group and for easy accessibility of
submission of GST Tax Report.
""",
'depends': ['base', 'account'],
'data': [
'data/l10n_sg_chart_data.xml',
'data/account_tax_data.xml',
'data/account_chart_template_data.yml',
],
}
| {'name': 'Singapore - Accounting', 'author': 'Tech Receptives', 'website': 'http://www.techreceptives.com', 'category': 'Localization', 'description': '\nSingapore accounting chart and localization.\n=======================================================\n\nAfter installing this module, the Configuration wizard for accounting is launched.\n * The Chart of Accounts consists of the list of all the general ledger accounts\n required to maintain the transactions of Singapore.\n * On that particular wizard, you will be asked to pass the name of the company,\n the chart template to follow, the no. of digits to generate, the code for your\n account and bank account, currency to create journals.\n\n * The Chart of Taxes would display the different types/groups of taxes such as\n Standard Rates, Zeroed, Exempted, MES and Out of Scope.\n * The tax codes are specified considering the Tax Group and for easy accessibility of\n submission of GST Tax Report.\n\n ', 'depends': ['base', 'account'], 'data': ['data/l10n_sg_chart_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.yml']} |
# A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number
# of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
# For example, take 153 (3 digits):
# 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
# and 1634 (4 digits):
# 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
# The Challenge:
# Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10.
# Error checking for text strings or other invalid inputs is not required, only valid integers will be passed into the function.
#https://www.codewars.com/kata/narcissistic-numbers/train/python
def is_narcissistic(num):
if 0:
return False
n = num
exponente = len(str(num))
sum = 0
while n > 0:
sum += pow(int(n % 10), exponente)
n = int(n/10)
return sum == num
print (is_narcissistic(12))
print (is_narcissistic(153))
print (is_narcissistic(1634)) | def is_narcissistic(num):
if 0:
return False
n = num
exponente = len(str(num))
sum = 0
while n > 0:
sum += pow(int(n % 10), exponente)
n = int(n / 10)
return sum == num
print(is_narcissistic(12))
print(is_narcissistic(153))
print(is_narcissistic(1634)) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name) | class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name) |
class Solution:
"""
@param n: an integer
@param k: an integer
@return: how many problem can you accept
"""
def canAccept(self, n, k):
n = int(n / k)
start = 0
end = n
while start + 1 < end:
mid = start + int((end - start) / 2)
fact = ((1 + mid) * mid) / 2
if fact <= n:
start = mid
else:
end = mid
if ((1 + end) * end) / 2 <= n:
return end
return start | class Solution:
"""
@param n: an integer
@param k: an integer
@return: how many problem can you accept
"""
def can_accept(self, n, k):
n = int(n / k)
start = 0
end = n
while start + 1 < end:
mid = start + int((end - start) / 2)
fact = (1 + mid) * mid / 2
if fact <= n:
start = mid
else:
end = mid
if (1 + end) * end / 2 <= n:
return end
return start |
# Note that we can only test things here all implementations must support
valid_data = [
("acceptInsecureCerts", [
False, None,
]),
("browserName", [
None,
]),
("browserVersion", [
None,
]),
("platformName", [
None,
]),
("pageLoadStrategy", [
None,
"none",
"eager",
"normal",
]),
("proxy", [
None,
]),
("timeouts", [
None, {},
{"script": 0, "pageLoad": 2.0, "implicit": 2**53 - 1},
{"script": 50, "pageLoad": 25},
{"script": 500},
]),
("unhandledPromptBehavior", [
"dismiss",
"accept",
None,
]),
("test:extension", [
None, False, "abc", 123, [],
{"key": "value"},
]),
]
invalid_data = [
("acceptInsecureCerts", [
1, [], {}, "false",
]),
("browserName", [
1, [], {}, False,
]),
("browserVersion", [
1, [], {}, False,
]),
("platformName", [
1, [], {}, False,
]),
("pageLoadStrategy", [
1, [], {}, False,
"invalid",
"NONE",
"Eager",
"eagerblah",
"interactive",
" eager",
"eager "]),
("proxy", [
1, [], "{}",
{"proxyType": "SYSTEM"},
{"proxyType": "systemSomething"},
{"proxy type": "pac"},
{"proxy-Type": "system"},
{"proxy_type": "system"},
{"proxytype": "system"},
{"PROXYTYPE": "system"},
{"proxyType": None},
{"proxyType": 1},
{"proxyType": []},
{"proxyType": {"value": "system"}},
{" proxyType": "system"},
{"proxyType ": "system"},
{"proxyType ": " system"},
{"proxyType": "system "},
]),
("timeouts", [
1, [], "{}", False,
{"invalid": 10},
{"PAGELOAD": 10},
{"page load": 10},
{" pageLoad": 10},
{"pageLoad ": 10},
{"pageLoad": None},
{"pageLoad": False},
{"pageLoad": []},
{"pageLoad": "10"},
{"pageLoad": 2.5},
{"pageLoad": -1},
{"pageLoad": 2**53},
{"pageLoad": {"value": 10}},
{"pageLoad": 10, "invalid": 10},
]),
("unhandledPromptBehavior", [
1, [], {}, False,
"DISMISS",
"dismissABC",
"Accept",
" dismiss",
"dismiss ",
])
]
invalid_extensions = [
"firefox",
"firefox_binary",
"firefoxOptions",
"chromeOptions",
"automaticInspection",
"automaticProfiling",
"platform",
"version",
"browser",
"platformVersion",
"javascriptEnabled",
"nativeEvents",
"seleniumProtocol",
"profile",
"trustAllSSLCertificates",
"initialBrowserUrl",
"requireWindowFocus",
"logFile",
"logLevel",
"safari.options",
"ensureCleanSession",
]
| valid_data = [('acceptInsecureCerts', [False, None]), ('browserName', [None]), ('browserVersion', [None]), ('platformName', [None]), ('pageLoadStrategy', [None, 'none', 'eager', 'normal']), ('proxy', [None]), ('timeouts', [None, {}, {'script': 0, 'pageLoad': 2.0, 'implicit': 2 ** 53 - 1}, {'script': 50, 'pageLoad': 25}, {'script': 500}]), ('unhandledPromptBehavior', ['dismiss', 'accept', None]), ('test:extension', [None, False, 'abc', 123, [], {'key': 'value'}])]
invalid_data = [('acceptInsecureCerts', [1, [], {}, 'false']), ('browserName', [1, [], {}, False]), ('browserVersion', [1, [], {}, False]), ('platformName', [1, [], {}, False]), ('pageLoadStrategy', [1, [], {}, False, 'invalid', 'NONE', 'Eager', 'eagerblah', 'interactive', ' eager', 'eager ']), ('proxy', [1, [], '{}', {'proxyType': 'SYSTEM'}, {'proxyType': 'systemSomething'}, {'proxy type': 'pac'}, {'proxy-Type': 'system'}, {'proxy_type': 'system'}, {'proxytype': 'system'}, {'PROXYTYPE': 'system'}, {'proxyType': None}, {'proxyType': 1}, {'proxyType': []}, {'proxyType': {'value': 'system'}}, {' proxyType': 'system'}, {'proxyType ': 'system'}, {'proxyType ': ' system'}, {'proxyType': 'system '}]), ('timeouts', [1, [], '{}', False, {'invalid': 10}, {'PAGELOAD': 10}, {'page load': 10}, {' pageLoad': 10}, {'pageLoad ': 10}, {'pageLoad': None}, {'pageLoad': False}, {'pageLoad': []}, {'pageLoad': '10'}, {'pageLoad': 2.5}, {'pageLoad': -1}, {'pageLoad': 2 ** 53}, {'pageLoad': {'value': 10}}, {'pageLoad': 10, 'invalid': 10}]), ('unhandledPromptBehavior', [1, [], {}, False, 'DISMISS', 'dismissABC', 'Accept', ' dismiss', 'dismiss '])]
invalid_extensions = ['firefox', 'firefox_binary', 'firefoxOptions', 'chromeOptions', 'automaticInspection', 'automaticProfiling', 'platform', 'version', 'browser', 'platformVersion', 'javascriptEnabled', 'nativeEvents', 'seleniumProtocol', 'profile', 'trustAllSSLCertificates', 'initialBrowserUrl', 'requireWindowFocus', 'logFile', 'logLevel', 'safari.options', 'ensureCleanSession'] |
class CodesDict(object):
def __init__(self, codes):
self.__dict__.update(codes)
_codes = {
'waiting': 1,
'analysis': 2,
'paid': 3,
'available': 4,
'dispute': 5,
'returned': 6,
'canceled': 7,
}
codes = CodesDict(_codes)
| class Codesdict(object):
def __init__(self, codes):
self.__dict__.update(codes)
_codes = {'waiting': 1, 'analysis': 2, 'paid': 3, 'available': 4, 'dispute': 5, 'returned': 6, 'canceled': 7}
codes = codes_dict(_codes) |
class Monitor:
def __init__(self, controller, redis_address):
self.controller = controller
self.redis_address = redis_address
def _schedule(self, gid, nid, domain, name, args={}, cron='@every 1m'):
"""
Schedule the given jumpscript (domain/name) to run on the specified node according to cron specs
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:param args: jumpscript arguments
:param cron: cron specs according to https://godoc.org/github.com/robfig/cron#hdr-CRON_Expression_Format
:return:
"""
args = args.update({'redis': self.redis_address})
#
# key = '.'.join([str(gid), str(nid), domain, name])
# self.controller.schedule()
def _unschedule(self, gid, nid, domain, name):
"""
Unschedule the given jumpscript
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:return:
"""
def disk(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the disk monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def virtual_machine(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the vm monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def docker(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the docker monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def nic(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the nic monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def reality(self, gid, nid, args={}, cron='@every 10m'):
"""
Schedule the reality reader on the specified node. Reality jumpscript
will also use the aggregator client to report reality objects.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def logs(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the logs reader on the specified node. Logs jumpscript
will collects logs from various sources and use the aggregator client
to report logs.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
| class Monitor:
def __init__(self, controller, redis_address):
self.controller = controller
self.redis_address = redis_address
def _schedule(self, gid, nid, domain, name, args={}, cron='@every 1m'):
"""
Schedule the given jumpscript (domain/name) to run on the specified node according to cron specs
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:param args: jumpscript arguments
:param cron: cron specs according to https://godoc.org/github.com/robfig/cron#hdr-CRON_Expression_Format
:return:
"""
args = args.update({'redis': self.redis_address})
def _unschedule(self, gid, nid, domain, name):
"""
Unschedule the given jumpscript
:param gid: Grid id
:param nid: Node id
:param domain: jumpscript domain
:param name: jumpscript name
:return:
"""
def disk(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the disk monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def virtual_machine(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the vm monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def docker(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the docker monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def nic(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the nic monitor on the specified node.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def reality(self, gid, nid, args={}, cron='@every 10m'):
"""
Schedule the reality reader on the specified node. Reality jumpscript
will also use the aggregator client to report reality objects.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass
def logs(self, gid, nid, args={}, cron='@every 1m'):
"""
Schedule the logs reader on the specified node. Logs jumpscript
will collects logs from various sources and use the aggregator client
to report logs.
:param gid: Grid id
:param nid: Node id
:param args: jumpscript arguments
:param cron: cron specs
:return:
"""
pass |
senseiraw = {
"name": "SteelSeries Sensei RAW (Experimental)",
"vendor_id": 0x1038,
"product_id": 0x1369,
"interface_number": 0,
"commands": {
"set_logo_light_effect": {
"description": "Set the logo light effect",
"cli": ["-e", "--logo-light-effect"],
"command": [0x07, 0x01],
"value_type": "choice",
"choices": {
"steady": 0x01,
"breath": 0x03,
"off": 0x05,
0: 0x00,
1: 0x01,
2: 0x02,
3: 0x03,
4: 0x04,
5: 0x05,
},
"default": "steady",
},
},
}
| senseiraw = {'name': 'SteelSeries Sensei RAW (Experimental)', 'vendor_id': 4152, 'product_id': 4969, 'interface_number': 0, 'commands': {'set_logo_light_effect': {'description': 'Set the logo light effect', 'cli': ['-e', '--logo-light-effect'], 'command': [7, 1], 'value_type': 'choice', 'choices': {'steady': 1, 'breath': 3, 'off': 5, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}, 'default': 'steady'}}} |
def ordering_fries():
print("Can I have some fried potatoes please?")
def countries_papagias_preferes():
print("Albania-Bulgaria-Romania...!")
| def ordering_fries():
print('Can I have some fried potatoes please?')
def countries_papagias_preferes():
print('Albania-Bulgaria-Romania...!') |
"""
Description: find the area of triangle, given breadth and height
"""
# function definition of areatriangle
def areatriangle(breadth,height):
return (breadth*height)/2;
# input breadth and height
b = int(input("Enter the breadth of triangle: "))
h = int(input("Enter teh height of triangle: "))
print("The area of the triangle is: " + str(areatriangle(b,h)))
| """
Description: find the area of triangle, given breadth and height
"""
def areatriangle(breadth, height):
return breadth * height / 2
b = int(input('Enter the breadth of triangle: '))
h = int(input('Enter teh height of triangle: '))
print('The area of the triangle is: ' + str(areatriangle(b, h))) |
'''
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
4. get_next and set_function is again similar to the data function ; it would be to get and set the next node value respectively.
5. has_next fucntion returns a Boolean whether the node has a next pointer or not
2. Linked List class with operations:
1. init function to initilise the nodes
2. get_size to return the size of the Linked List
3. add function to add a node
4. remove function to remove a node
5. print_list to print the linked list
6. sort to sort the linked list
7. find function to find a item in a linked list
'''
class Node(object):
def __init__(self, data, nextNode=None):
self.data = data
self.nextNode = nextNode
def get_next(self):
''' get the next node value'''
return self.nextNode
def set_next(self, nextNode):
''' point the node to next node'''
self.nextNode = nextNode
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def has_next(self):
if self.nextNode == None:
return False
else:
return True
class LinkedList(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size(self):
return f"Size of the Linked List is : {self.size}"
def add(self, data):
newNode = Node(data, self.root)
self.root = newNode
self.size += 1
def remove(self, data):
r_node = self.root
prev_node = None
while r_node:
if r_node.get_data() == data:
if prev_node:
prev_node.set_next(r_node.get_next())
else:
self.root = r_node.get_next()
self.size -= 1
return True
else:
prev_node = r_node
r_node = r_node.get_next()
return False # item not found
def find(self, data):
find_data = self.root
while find_data:
if find_data.get_data() == data:
return f"Data found {data}"
elif find_data.get_next() == None:
return False # item not in list
else:
find_data = find_data.get_next()
return None
def print_list(self):
pass
def sort_list():
pass
linked = LinkedList()
linked.add(4)
linked.add(5)
linked.add(7)
linked.add(1)
print(linked.get_size())
print(str(linked.find(5)))
linked.add(9)
linked.add(0)
print(linked.get_size())
print(linked.find(0))
print(linked.remove(4))
print(linked.get_size())
print(linked.find(4))
| """
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
4. get_next and set_function is again similar to the data function ; it would be to get and set the next node value respectively.
5. has_next fucntion returns a Boolean whether the node has a next pointer or not
2. Linked List class with operations:
1. init function to initilise the nodes
2. get_size to return the size of the Linked List
3. add function to add a node
4. remove function to remove a node
5. print_list to print the linked list
6. sort to sort the linked list
7. find function to find a item in a linked list
"""
class Node(object):
def __init__(self, data, nextNode=None):
self.data = data
self.nextNode = nextNode
def get_next(self):
""" get the next node value"""
return self.nextNode
def set_next(self, nextNode):
""" point the node to next node"""
self.nextNode = nextNode
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def has_next(self):
if self.nextNode == None:
return False
else:
return True
class Linkedlist(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size(self):
return f'Size of the Linked List is : {self.size}'
def add(self, data):
new_node = node(data, self.root)
self.root = newNode
self.size += 1
def remove(self, data):
r_node = self.root
prev_node = None
while r_node:
if r_node.get_data() == data:
if prev_node:
prev_node.set_next(r_node.get_next())
else:
self.root = r_node.get_next()
self.size -= 1
return True
else:
prev_node = r_node
r_node = r_node.get_next()
return False
def find(self, data):
find_data = self.root
while find_data:
if find_data.get_data() == data:
return f'Data found {data}'
elif find_data.get_next() == None:
return False
else:
find_data = find_data.get_next()
return None
def print_list(self):
pass
def sort_list():
pass
linked = linked_list()
linked.add(4)
linked.add(5)
linked.add(7)
linked.add(1)
print(linked.get_size())
print(str(linked.find(5)))
linked.add(9)
linked.add(0)
print(linked.get_size())
print(linked.find(0))
print(linked.remove(4))
print(linked.get_size())
print(linked.find(4)) |
"""
create by hanxiao on
"""
__author__ = "hanxiao"
PRE_PAGE = 15
BEANS_UPLOAD_ONE_BOOK = 0.5
| """
create by hanxiao on
"""
__author__ = 'hanxiao'
pre_page = 15
beans_upload_one_book = 0.5 |
# This file was generated by wxPython's wscript.
VERSION_STRING = '4.0.7.post2'
MAJOR_VERSION = 4
MINOR_VERSION = 0
RELEASE_NUMBER = 7
BUILD_TYPE = 'release'
VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2')
| version_string = '4.0.7.post2'
major_version = 4
minor_version = 0
release_number = 7
build_type = 'release'
version = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2') |
## TASK 1 - here are the expected letter frequencies in the english language - convert them to a byte frequency table
expected_letter_frequencies = {'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.361, 'x': 0.150, 'y': 1.974, 'z': 0.074}
expected_byte_frequencies = {}
for letter, frequency in expected_letter_frequencies.items():
byte = letter.encode('latin1')[0]
expected_byte_frequencies[byte] = frequency
| expected_letter_frequencies = {'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.361, 'x': 0.15, 'y': 1.974, 'z': 0.074}
expected_byte_frequencies = {}
for (letter, frequency) in expected_letter_frequencies.items():
byte = letter.encode('latin1')[0]
expected_byte_frequencies[byte] = frequency |
def bracket_check(brackets):
'''function for checking a string of brackets'''
o = [ '{', '[', '(' ]
c = [ '}', ']', ')' ]
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else:
print('nah')
bracket_check('8x8y[E(x,y) ! [(P(x) ! P(y)) ! (P(y) ! P(a)]]')
| def bracket_check(brackets):
"""function for checking a string of brackets"""
o = ['{', '[', '(']
c = ['}', ']', ')']
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else:
print('nah')
bracket_check('8x8y[E(x,y) ! [(P(x) ! P(y)) ! (P(y) ! P(a)]]') |
class Utils:
@staticmethod
def fastModuloPow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = (num ** 2) % modulo
pow = pow // 2
else:
result = (num * result) % modulo
pow -= 1
return result
| class Utils:
@staticmethod
def fast_modulo_pow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = num ** 2 % modulo
pow = pow // 2
else:
result = num * result % modulo
pow -= 1
return result |
# https://leetcode.com/problems/satisfiability-of-equality-equations
class UnionFind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
return par
def unite(self, x, y):
x, y = self.find_par(x), self.find_par(y)
if x == y:
return
if x < y:
self.node2par[y] = x
else:
self.node2par[x] = y
class Solution:
def equationsPossible(self, equations):
uf = UnionFind()
neqs = []
for eq in equations:
if eq[1] == "=":
uf.unite(eq[0], eq[-1])
else:
neqs.append(eq)
for neq in neqs:
if uf.find_par(neq[0]) == uf.find_par(neq[-1]):
return False
return True
| class Unionfind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
return par
def unite(self, x, y):
(x, y) = (self.find_par(x), self.find_par(y))
if x == y:
return
if x < y:
self.node2par[y] = x
else:
self.node2par[x] = y
class Solution:
def equations_possible(self, equations):
uf = union_find()
neqs = []
for eq in equations:
if eq[1] == '=':
uf.unite(eq[0], eq[-1])
else:
neqs.append(eq)
for neq in neqs:
if uf.find_par(neq[0]) == uf.find_par(neq[-1]):
return False
return True |
#
# PySNMP MIB module A3COM-HUAWEI-DHCPSNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPSNOOP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:11 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)
#
hwdot1qVlanIndex, = mibBuilder.importSymbols("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex")
h3cCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "h3cCommon")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Counter64, ModuleIdentity, Unsigned32, ObjectIdentity, Counter32, iso, Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "ModuleIdentity", "Unsigned32", "ObjectIdentity", "Counter32", "iso", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "IpAddress", "TimeTicks", "Integer32")
TextualConvention, MacAddress, RowStatus, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "RowStatus", "DisplayString", "TruthValue")
h3cDhcpSnoop = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36))
if mibBuilder.loadTexts: h3cDhcpSnoop.setLastUpdated('200501140000Z')
if mibBuilder.loadTexts: h3cDhcpSnoop.setOrganization('Huawei-3com Technologies Co.,Ltd.')
if mibBuilder.loadTexts: h3cDhcpSnoop.setContactInfo('Platform Team Beijing Institute Huawei-3com Tech, Inc. Http:\\\\www.huawei-3com.com E-mail:support@huawei-3com.com')
if mibBuilder.loadTexts: h3cDhcpSnoop.setDescription('The private mib file includes the DHCP Snooping profile.')
h3cDhcpSnoopMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1))
h3cDhcpSnoopEnable = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setDescription('DHCP Snooping status (enable or disable).')
h3cDhcpSnoopTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2), )
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setDescription("The table containing information of DHCP clients listened by DHCP snooping and it's enabled or disabled by setting h3cDhcpSnoopEnable node.")
h3cDhcpSnoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddressType"), (0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddress"))
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setDescription('An entry containing information of DHCP clients.')
h3cDhcpSnoopClientIpAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 1), InetAddressType().clone('ipv4'))
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setDescription("DHCP clients' IP addresses type (IPv4 or IPv6).")
h3cDhcpSnoopClientIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setDescription("DHCP clients' IP addresses collected by DHCP snooping.")
h3cDhcpSnoopClientMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setDescription("DHCP clients' MAC addresses collected by DHCP snooping.")
h3cDhcpSnoopClientProperty = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setDescription('Method of getting IP addresses collected by DHCP snooping.')
h3cDhcpSnoopClientUnitNum = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setDescription('IRF (Intelligent Resilient Fabric) unit number via whom the clients get their IP addresses. The value 0 means this device does not support IRF.')
h3cDhcpSnoopTrustTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3), )
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setDescription('A table is used to configure and monitor port trusted status.')
h3cDhcpSnoopTrustEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setDescription('An entry containing information about trusted status of ports.')
h3cDhcpSnoopTrustStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("untrusted", 0), ("trusted", 1))).clone('untrusted')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setDescription('Trusted status of current port which supports both get and set operation.')
h3cDhcpSnoopVlanTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4), )
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setDescription('A table is used to configure and monitor DHCP Snooping status of VLANs.')
h3cDhcpSnoopVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopVlanIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setDescription('The entry information about h3cDhcpSnoopVlanTable.')
h3cDhcpSnoopVlanIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setDescription('Current VLAN index.')
h3cDhcpSnoopVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setDescription('DHCP Snooping status of current VLAN.')
h3cDhcpSnoopTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2))
h3cDhcpSnoopTrapsPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0))
h3cDhcpSnoopTrapsObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1))
h3cDhcpSnoopSpoofServerMac = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 1), MacAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setDescription('MAC address of the spoofing server and it is derived from link-layer header of offer packet. If the offer packet is relayed by dhcp relay entity, it may be the MAC address of relay entity. ')
h3cDhcpSnoopSpoofServerIP = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 2), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setDescription("IP address of the spoofing server and it is derived from IP header of offer packet. A tricksy host may send offer packet use other host's address, so this address can not always be trust. ")
h3cDhcpSnoopSpoofServerDetected = NotificationType((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0, 1)).setObjects(("IF-MIB", "ifIndex"), ("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerMac"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerIP"))
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setDescription('To detect unauthorized DHCP servers on a network, the DHCP snooping device sends DHCP-DISCOVER messages through its downstream port (which is connected to the DHCP clients). If any response (DHCP-OFFER message) is received from the downstream port, an unauthorized DHCP server is considered present, and then the device sends a trap. With unauthorized DHCP server detection enabled, the interface sends a DHCP-DISCOVER message to detect unauthorized DHCP servers on the network. If this interface receives a DHCP-OFFER message, the DHCP server which sent it is considered unauthorized. ')
mibBuilder.exportSymbols("A3COM-HUAWEI-DHCPSNOOP-MIB", h3cDhcpSnoopClientProperty=h3cDhcpSnoopClientProperty, h3cDhcpSnoopTraps=h3cDhcpSnoopTraps, h3cDhcpSnoopTrapsObject=h3cDhcpSnoopTrapsObject, h3cDhcpSnoopVlanEnable=h3cDhcpSnoopVlanEnable, h3cDhcpSnoopEnable=h3cDhcpSnoopEnable, h3cDhcpSnoopClientIpAddress=h3cDhcpSnoopClientIpAddress, h3cDhcpSnoopVlanEntry=h3cDhcpSnoopVlanEntry, h3cDhcpSnoopEntry=h3cDhcpSnoopEntry, PYSNMP_MODULE_ID=h3cDhcpSnoop, h3cDhcpSnoopTrapsPrefix=h3cDhcpSnoopTrapsPrefix, h3cDhcpSnoopClientIpAddressType=h3cDhcpSnoopClientIpAddressType, h3cDhcpSnoopSpoofServerMac=h3cDhcpSnoopSpoofServerMac, h3cDhcpSnoopTrustEntry=h3cDhcpSnoopTrustEntry, h3cDhcpSnoopSpoofServerIP=h3cDhcpSnoopSpoofServerIP, h3cDhcpSnoop=h3cDhcpSnoop, h3cDhcpSnoopTrustStatus=h3cDhcpSnoopTrustStatus, h3cDhcpSnoopClientUnitNum=h3cDhcpSnoopClientUnitNum, h3cDhcpSnoopTable=h3cDhcpSnoopTable, h3cDhcpSnoopTrustTable=h3cDhcpSnoopTrustTable, h3cDhcpSnoopSpoofServerDetected=h3cDhcpSnoopSpoofServerDetected, h3cDhcpSnoopVlanIndex=h3cDhcpSnoopVlanIndex, h3cDhcpSnoopClientMacAddress=h3cDhcpSnoopClientMacAddress, h3cDhcpSnoopMibObject=h3cDhcpSnoopMibObject, h3cDhcpSnoopVlanTable=h3cDhcpSnoopVlanTable)
| (hwdot1q_vlan_index,) = mibBuilder.importSymbols('A3COM-HUAWEI-LswVLAN-MIB', 'hwdot1qVlanIndex')
(h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddress', 'InetAddressType')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(gauge32, counter64, module_identity, unsigned32, object_identity, counter32, iso, bits, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, ip_address, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Counter64', 'ModuleIdentity', 'Unsigned32', 'ObjectIdentity', 'Counter32', 'iso', 'Bits', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'IpAddress', 'TimeTicks', 'Integer32')
(textual_convention, mac_address, row_status, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'MacAddress', 'RowStatus', 'DisplayString', 'TruthValue')
h3c_dhcp_snoop = module_identity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36))
if mibBuilder.loadTexts:
h3cDhcpSnoop.setLastUpdated('200501140000Z')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setOrganization('Huawei-3com Technologies Co.,Ltd.')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setContactInfo('Platform Team Beijing Institute Huawei-3com Tech, Inc. Http:\\\\www.huawei-3com.com E-mail:support@huawei-3com.com')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setDescription('The private mib file includes the DHCP Snooping profile.')
h3c_dhcp_snoop_mib_object = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1))
h3c_dhcp_snoop_enable = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopEnable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopEnable.setDescription('DHCP Snooping status (enable or disable).')
h3c_dhcp_snoop_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2))
if mibBuilder.loadTexts:
h3cDhcpSnoopTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTable.setDescription("The table containing information of DHCP clients listened by DHCP snooping and it's enabled or disabled by setting h3cDhcpSnoopEnable node.")
h3c_dhcp_snoop_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1)).setIndexNames((0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopClientIpAddressType'), (0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopClientIpAddress'))
if mibBuilder.loadTexts:
h3cDhcpSnoopEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopEntry.setDescription('An entry containing information of DHCP clients.')
h3c_dhcp_snoop_client_ip_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 1), inet_address_type().clone('ipv4'))
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddressType.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddressType.setDescription("DHCP clients' IP addresses type (IPv4 or IPv6).")
h3c_dhcp_snoop_client_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 2), inet_address())
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddress.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddress.setDescription("DHCP clients' IP addresses collected by DHCP snooping.")
h3c_dhcp_snoop_client_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 3), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientMacAddress.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientMacAddress.setDescription("DHCP clients' MAC addresses collected by DHCP snooping.")
h3c_dhcp_snoop_client_property = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('static', 1), ('dynamic', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientProperty.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientProperty.setDescription('Method of getting IP addresses collected by DHCP snooping.')
h3c_dhcp_snoop_client_unit_num = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientUnitNum.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientUnitNum.setDescription('IRF (Intelligent Resilient Fabric) unit number via whom the clients get their IP addresses. The value 0 means this device does not support IRF.')
h3c_dhcp_snoop_trust_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3))
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustTable.setDescription('A table is used to configure and monitor port trusted status.')
h3c_dhcp_snoop_trust_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustEntry.setDescription('An entry containing information about trusted status of ports.')
h3c_dhcp_snoop_trust_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('untrusted', 0), ('trusted', 1))).clone('untrusted')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustStatus.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustStatus.setDescription('Trusted status of current port which supports both get and set operation.')
h3c_dhcp_snoop_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanTable.setDescription('A table is used to configure and monitor DHCP Snooping status of VLANs.')
h3c_dhcp_snoop_vlan_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1)).setIndexNames((0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopVlanIndex'))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEntry.setDescription('The entry information about h3cDhcpSnoopVlanTable.')
h3c_dhcp_snoop_vlan_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647)))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanIndex.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanIndex.setDescription('Current VLAN index.')
h3c_dhcp_snoop_vlan_enable = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 2), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEnable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEnable.setDescription('DHCP Snooping status of current VLAN.')
h3c_dhcp_snoop_traps = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2))
h3c_dhcp_snoop_traps_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0))
h3c_dhcp_snoop_traps_object = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1))
h3c_dhcp_snoop_spoof_server_mac = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 1), mac_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerMac.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerMac.setDescription('MAC address of the spoofing server and it is derived from link-layer header of offer packet. If the offer packet is relayed by dhcp relay entity, it may be the MAC address of relay entity. ')
h3c_dhcp_snoop_spoof_server_ip = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 2), ip_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerIP.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerIP.setDescription("IP address of the spoofing server and it is derived from IP header of offer packet. A tricksy host may send offer packet use other host's address, so this address can not always be trust. ")
h3c_dhcp_snoop_spoof_server_detected = notification_type((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0, 1)).setObjects(('IF-MIB', 'ifIndex'), ('A3COM-HUAWEI-LswVLAN-MIB', 'hwdot1qVlanIndex'), ('A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopSpoofServerMac'), ('A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopSpoofServerIP'))
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerDetected.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerDetected.setDescription('To detect unauthorized DHCP servers on a network, the DHCP snooping device sends DHCP-DISCOVER messages through its downstream port (which is connected to the DHCP clients). If any response (DHCP-OFFER message) is received from the downstream port, an unauthorized DHCP server is considered present, and then the device sends a trap. With unauthorized DHCP server detection enabled, the interface sends a DHCP-DISCOVER message to detect unauthorized DHCP servers on the network. If this interface receives a DHCP-OFFER message, the DHCP server which sent it is considered unauthorized. ')
mibBuilder.exportSymbols('A3COM-HUAWEI-DHCPSNOOP-MIB', h3cDhcpSnoopClientProperty=h3cDhcpSnoopClientProperty, h3cDhcpSnoopTraps=h3cDhcpSnoopTraps, h3cDhcpSnoopTrapsObject=h3cDhcpSnoopTrapsObject, h3cDhcpSnoopVlanEnable=h3cDhcpSnoopVlanEnable, h3cDhcpSnoopEnable=h3cDhcpSnoopEnable, h3cDhcpSnoopClientIpAddress=h3cDhcpSnoopClientIpAddress, h3cDhcpSnoopVlanEntry=h3cDhcpSnoopVlanEntry, h3cDhcpSnoopEntry=h3cDhcpSnoopEntry, PYSNMP_MODULE_ID=h3cDhcpSnoop, h3cDhcpSnoopTrapsPrefix=h3cDhcpSnoopTrapsPrefix, h3cDhcpSnoopClientIpAddressType=h3cDhcpSnoopClientIpAddressType, h3cDhcpSnoopSpoofServerMac=h3cDhcpSnoopSpoofServerMac, h3cDhcpSnoopTrustEntry=h3cDhcpSnoopTrustEntry, h3cDhcpSnoopSpoofServerIP=h3cDhcpSnoopSpoofServerIP, h3cDhcpSnoop=h3cDhcpSnoop, h3cDhcpSnoopTrustStatus=h3cDhcpSnoopTrustStatus, h3cDhcpSnoopClientUnitNum=h3cDhcpSnoopClientUnitNum, h3cDhcpSnoopTable=h3cDhcpSnoopTable, h3cDhcpSnoopTrustTable=h3cDhcpSnoopTrustTable, h3cDhcpSnoopSpoofServerDetected=h3cDhcpSnoopSpoofServerDetected, h3cDhcpSnoopVlanIndex=h3cDhcpSnoopVlanIndex, h3cDhcpSnoopClientMacAddress=h3cDhcpSnoopClientMacAddress, h3cDhcpSnoopMibObject=h3cDhcpSnoopMibObject, h3cDhcpSnoopVlanTable=h3cDhcpSnoopVlanTable) |
#Copyright (c) 2020 Jan Kiefer
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
class ChatUsr:
def __init__(self, utfmsg):
self.wob_id = utfmsg.get_int_arg(1)
self.message = utfmsg.get_string_arg(2)
self.type = utfmsg.get_int_list_arg(0)[2]
self.mode = 0 if utfmsg.get_arg_count() <= 3 else utfmsg.get_int_arg(3)
self.overheard = False if utfmsg.get_arg_count() <= 4 else utfmsg.get_boolean_arg(4)
class ChatSrv:
def __init__(self, utfmsg):
self.message = utfmsg.get_string_arg(1) | class Chatusr:
def __init__(self, utfmsg):
self.wob_id = utfmsg.get_int_arg(1)
self.message = utfmsg.get_string_arg(2)
self.type = utfmsg.get_int_list_arg(0)[2]
self.mode = 0 if utfmsg.get_arg_count() <= 3 else utfmsg.get_int_arg(3)
self.overheard = False if utfmsg.get_arg_count() <= 4 else utfmsg.get_boolean_arg(4)
class Chatsrv:
def __init__(self, utfmsg):
self.message = utfmsg.get_string_arg(1) |
ast = int(input("Ingrese numero de asteroides"))
nom =input("Ingrese nombre de asteroides")
print("Los",ast,"asteroides",nom,"caen del cielo") | ast = int(input('Ingrese numero de asteroides'))
nom = input('Ingrese nombre de asteroides')
print('Los', ast, 'asteroides', nom, 'caen del cielo') |
#!/usr/bin/env python
compsys={
'Artisan':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
'Central Office user':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
}
| compsys = {'Artisan': {'db': 'file-store', 'objects': ['Artisan', 'Product', 'Order', 'Customer']}, 'Central Office user': {'db': 'file-store', 'objects': ['Artisan', 'Product', 'Order', 'Customer']}} |
def main():
my_integ_loop.getIntegrator( trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == "__main__":
main()
| def main():
my_integ_loop.getIntegrator(trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == '__main__':
main() |
S_ASK_DOWNLOAD = 0
C_ANSWER_YES = 1
C_ANSWER_NO = 2
S_ASK_UPLOAD = 3
S_ASK_WAIT = 4
S_BEGIN = 5
| s_ask_download = 0
c_answer_yes = 1
c_answer_no = 2
s_ask_upload = 3
s_ask_wait = 4
s_begin = 5 |
#!/usr/bin/env python3
n = 4
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
b = [0, 1, 2, 3]
# Gauss elim
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
# External stability
print("External stability")
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
db = 0.3
da = 0.3
dA = [[da for j in range(n)] for i in range(n)]
b = [db for i in range(n)]
for i in range(n):
for j in range(n):
b[i] -= dA[i][j] * x[j]
print("new b:", b)
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
| n = 4
a = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2], [2, 1e-05, 1, 0.4]]
b = [0, 1, 2, 3]
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print('A:', A)
print('b:', b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print('x:', x)
print('External stability')
a = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2], [2, 1e-05, 1, 0.4]]
db = 0.3
da = 0.3
d_a = [[da for j in range(n)] for i in range(n)]
b = [db for i in range(n)]
for i in range(n):
for j in range(n):
b[i] -= dA[i][j] * x[j]
print('new b:', b)
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print('A:', A)
print('b:', b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print('x:', x) |
depends = ["unittest"]
description = """
Plug and play integration with the Jenkins Coninuous Integration server.
For more information, visit:
http://www.jenkins-ci.org/
""" | depends = ['unittest']
description = '\nPlug and play integration with the Jenkins Coninuous Integration server.\n\nFor more information, visit:\nhttp://www.jenkins-ci.org/\n' |
def keyExtract(array, key):
"""Returns values of specific key from list of dicts.
Args:
array (list): List to be processed.
key (str): Key to extract.
Returns:
list: List of extracted values.
Example:
>>> keyExtract([
{'a': 0, ...}, {'a': 1, ...}, {'a': 2, ...}, ...
], 'a')
<<< [0, 1, 2]
"""
res = list()
for item in array:
res.append(item[key])
return res
def unduplicate(words):
"""Deletes duplicates from list.
Args:
words (list): List of hashable data.
Returns:
list: Unduplicated list.
Raises:
TypeError: Data of the list is not hashable (list, for example).
"""
return list(
set(words)
)
def reorder(li: list, a: int, b: int):
"""Reorder li[a] with li[b].
Args:
li (list): List to process.
a (int): Index of first item.
b (int): Index of second item.
Returns:
list: List of reordered items.
Example:
>>> reorder([a, b, c], 0, 1)
<<< [b, a, c]
"""
li[a], li[b] = li[b], li[a]
return li
def isSupsetTo(d: dict, what: dict):
"""Check whether one `d` dict is supset or equal to `what` dict. This means
that all the items from `what` is equal to `d`.
Args:
d, what (dict): Dicts to compare.
Returns:
bool: True if d > what, False otherwise.
"""
for key, value in what.items():
if d[key] != value:
return False
return True
def findIn(d: dict, equal):
"""Find and return record in dictionary which is associated with `equal`.
May be useful for searching unique objects in large amounts of data.
Args:
d (dict): Dictionary where to search in.
equal (*): What to look for. If it's a dict, item which is supset for
the given will be found.
Returns:
namedtuple: DictItem(key=..., item=...)
Example:
>>> findIn({'a': 0, 'b': 1}, 1)
<<< DictItem(key='b', item=1)
>>> findIn({'a': {'b': 'c', 'd': 'e'}}, {'d': 'e'})
<<< DictItem(key='a', item={'b': 'c', 'd': 'e'})
"""
for key, item in d.items():
if (
type(equal) is dict and isSupsetTo(item, equal)
) or item == equal:
return {"key": key, "item": item}
raise KeyError("Value was not found")
| def key_extract(array, key):
"""Returns values of specific key from list of dicts.
Args:
array (list): List to be processed.
key (str): Key to extract.
Returns:
list: List of extracted values.
Example:
>>> keyExtract([
{'a': 0, ...}, {'a': 1, ...}, {'a': 2, ...}, ...
], 'a')
<<< [0, 1, 2]
"""
res = list()
for item in array:
res.append(item[key])
return res
def unduplicate(words):
"""Deletes duplicates from list.
Args:
words (list): List of hashable data.
Returns:
list: Unduplicated list.
Raises:
TypeError: Data of the list is not hashable (list, for example).
"""
return list(set(words))
def reorder(li: list, a: int, b: int):
"""Reorder li[a] with li[b].
Args:
li (list): List to process.
a (int): Index of first item.
b (int): Index of second item.
Returns:
list: List of reordered items.
Example:
>>> reorder([a, b, c], 0, 1)
<<< [b, a, c]
"""
(li[a], li[b]) = (li[b], li[a])
return li
def is_supset_to(d: dict, what: dict):
"""Check whether one `d` dict is supset or equal to `what` dict. This means
that all the items from `what` is equal to `d`.
Args:
d, what (dict): Dicts to compare.
Returns:
bool: True if d > what, False otherwise.
"""
for (key, value) in what.items():
if d[key] != value:
return False
return True
def find_in(d: dict, equal):
"""Find and return record in dictionary which is associated with `equal`.
May be useful for searching unique objects in large amounts of data.
Args:
d (dict): Dictionary where to search in.
equal (*): What to look for. If it's a dict, item which is supset for
the given will be found.
Returns:
namedtuple: DictItem(key=..., item=...)
Example:
>>> findIn({'a': 0, 'b': 1}, 1)
<<< DictItem(key='b', item=1)
>>> findIn({'a': {'b': 'c', 'd': 'e'}}, {'d': 'e'})
<<< DictItem(key='a', item={'b': 'c', 'd': 'e'})
"""
for (key, item) in d.items():
if type(equal) is dict and is_supset_to(item, equal) or item == equal:
return {'key': key, 'item': item}
raise key_error('Value was not found') |
#Pat McDonald - 8/2/2018
#Exercise 3: Collatz conjecture
#Week 3 of Programming and Scripting
#Inspired by Reddit!: https://www.reddit.com/r/Python/comments/57r6bf/collatz_conjecture_program/?st=jdhil1j5&sh=ba8fd995
n = int(input("Type an integer: "))
print(n)
while n != 1:
if (n % 2 == 0):
#(n / 2) outputs a float , so I tried //
n = n // 2
print(n)
else:
n = (3 * n) + 1
print(n)
| n = int(input('Type an integer: '))
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
print(n)
else:
n = 3 * n + 1
print(n) |
n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0,qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0,n):
menor = 100000
for j in range(0,len(indice)):
temp = abs(i - indice[j])
if(temp < menor):
menor = temp
if menor >= 9:
print("9",end=" ")
else:
print(menor,end=" ")
| n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0, qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0, n):
menor = 100000
for j in range(0, len(indice)):
temp = abs(i - indice[j])
if temp < menor:
menor = temp
if menor >= 9:
print('9', end=' ')
else:
print(menor, end=' ') |
"""Codewars: Happy Numbers
6 kyu
URL:https://www.codewars.com/kata/59d53c3039c23b404200007e/train/python
Math geeks and computer nerds love to anthropomorphize numbers and
assign emotions and personalities to them. Thus there is defined the
concept of a "happy" number. A happy number is defined as an integer
in which the following sequence ends with the number 1.
Start with the number itself.
Calculate the sum of the square of each individual digit.
If the sum is equal to 1, then the number is happy. If the sum is not
equal to 1, then repeat steps 1 and 2. A number is considered unhappy
once the same number occurs multiple times in a sequence because this
means there is a loop and it will never reach 1.
For example, the number 7 is a "happy" number:
(7 ** 2)
7^2 = 49 --> 42 + 92 = 97 --> 92 + 72 = 130 --> 12 + 32 + 02 =
10 --> 12 + 02 = 1
Once the sequence reaches the number 1, it will stay there forever
since 12 = 1
On the other hand, the number 6 is not a happy number as the sequence
that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29,
85, 89, 145, 42, 20, 4, 16, 37, 52, 29
Once the same number occurs twice in the sequence, the sequence is
guaranteed to go on infinitely, never hitting the number 1, since it
repeat this cycle.
Your task is to write a program which will print a list of all happy
numbers between 1 and x (both inclusive), where:
2 <= x <= 5000
"""
def _sum_squares(num):
ss = 0
while num > 0:
div, digit = num // 10, num % 10
ss += digit * digit
num = div
return ss
def _is_happy_number(num):
# Check if num is happy number.
seens = set()
while num > 1: # stop when num == 1
ss = _sum_squares(num)
if ss in seens:
return False
seens.add(ss)
num = ss
return True
def happy_numbers(n):
result = []
for num in range(1, n + 1):
# Check if a num is happy number.
if _is_happy_number(num):
result.append(num)
return result
def main():
# Output: [1, 7, 10]
n = 10
print(happy_numbers(n))
# assert happy_numbers(10) == [1, 7, 10]
# assert happy_numbers(50) == [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
# assert happy_numbers(100) == [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
if __name__ == '__main__':
main()
| """Codewars: Happy Numbers
6 kyu
URL:https://www.codewars.com/kata/59d53c3039c23b404200007e/train/python
Math geeks and computer nerds love to anthropomorphize numbers and
assign emotions and personalities to them. Thus there is defined the
concept of a "happy" number. A happy number is defined as an integer
in which the following sequence ends with the number 1.
Start with the number itself.
Calculate the sum of the square of each individual digit.
If the sum is equal to 1, then the number is happy. If the sum is not
equal to 1, then repeat steps 1 and 2. A number is considered unhappy
once the same number occurs multiple times in a sequence because this
means there is a loop and it will never reach 1.
For example, the number 7 is a "happy" number:
(7 ** 2)
7^2 = 49 --> 42 + 92 = 97 --> 92 + 72 = 130 --> 12 + 32 + 02 =
10 --> 12 + 02 = 1
Once the sequence reaches the number 1, it will stay there forever
since 12 = 1
On the other hand, the number 6 is not a happy number as the sequence
that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29,
85, 89, 145, 42, 20, 4, 16, 37, 52, 29
Once the same number occurs twice in the sequence, the sequence is
guaranteed to go on infinitely, never hitting the number 1, since it
repeat this cycle.
Your task is to write a program which will print a list of all happy
numbers between 1 and x (both inclusive), where:
2 <= x <= 5000
"""
def _sum_squares(num):
ss = 0
while num > 0:
(div, digit) = (num // 10, num % 10)
ss += digit * digit
num = div
return ss
def _is_happy_number(num):
seens = set()
while num > 1:
ss = _sum_squares(num)
if ss in seens:
return False
seens.add(ss)
num = ss
return True
def happy_numbers(n):
result = []
for num in range(1, n + 1):
if _is_happy_number(num):
result.append(num)
return result
def main():
n = 10
print(happy_numbers(n))
if __name__ == '__main__':
main() |
N = int(input())
S = str(input())
flag = False
half = (N+1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print("Yes")
else:
print("No") | n = int(input())
s = str(input())
flag = False
half = (N + 1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print('Yes')
else:
print('No') |
#!/usr/bin/env python
weight = input("your weight is? ")
height = input("your height is? ")
bmi = float(weight) / ( float(height) ** 2 )
print(f"your bmi: {bmi:.2f}")
if bmi <= 18.5:
print("you are so thin!")
elif bmi <= 25 and bmi > 18.5:
print("well, you are fit.")
elif bmi <= 28 and bmi > 25:
print("it looks you are a little heavy.")
elif bmi <= 32 and bmi > 28:
print("you are fat, what about doing exercise?")
else:
print("i dont want to tell the truth, but could you active? otherwise you may die of you fat")
| weight = input('your weight is? ')
height = input('your height is? ')
bmi = float(weight) / float(height) ** 2
print(f'your bmi: {bmi:.2f}')
if bmi <= 18.5:
print('you are so thin!')
elif bmi <= 25 and bmi > 18.5:
print('well, you are fit.')
elif bmi <= 28 and bmi > 25:
print('it looks you are a little heavy.')
elif bmi <= 32 and bmi > 28:
print('you are fat, what about doing exercise?')
else:
print('i dont want to tell the truth, but could you active? otherwise you may die of you fat') |
#!/usr/bin/env conda-execute
# conda execute
# env:
# - python ==3.5
# - conda-build
# - pygithub >=1.29
# - pyyaml
# - requests
# - setuptools
# - tqdm
# channels:
# - conda-forge
# run_with: python
# TODO take package or list of packages
# TODO take github url or github urls
# TODO If user doesn't have a fork of conda-forge create one
# TODO if user doesn't have a branch for this package, create one
# TODO run conda smithy pypi package
# TODO If successful, parse generated meta.yaml
# TODO Drop any meta.yaml build reqs
# TODO Drop any test reqs
# TODO Add sections to bring in line with the standard template
# TODO Add variable to bring in line with the standard template
# TODO change the setup script based on whether or not setuptools is required
# TODO deal with license file
# TODO commit the modified meta.yaml to user/staged-recipes:branch
# TODO submit pull request to conda-forge/staged-recipes:master as a new recipe.
def main():
return
if __init__ == "__main__":
main()
| def main():
return
if __init__ == '__main__':
main() |
class SvResponseBase:
def __init__(self, cl_request):
self.cl_request = cl_request
def payload():
""" OVERRIDE THIS TO IMPLEMENT """
raise
| class Svresponsebase:
def __init__(self, cl_request):
self.cl_request = cl_request
def payload():
""" OVERRIDE THIS TO IMPLEMENT """
raise |
#! env\bin\python
# Ryan Simmons
# Coffee Machine Project
class CoffeeMachine:
# the values in supplies refers to 1-1 with this
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink):
# Money is represented as the value taken (negative) there always less than and should not cause an error
for i in range(len(drink)):
if drink[i] > self.supplies[i]:
print(f'Sorry not enough {self.supply_str[i]} !')
break
else:
for i in range(len(drink)):
self.supplies[i] -= drink[i] # Completes the transaction for the drink
print('I have enough resources, making you a coffee!')
def drink_maker(self):
drink = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ")
# Inputs the value for particular drinks into supply_checker()
if drink == '1':
espresso = [250, 0, 16, 1, -4]
self.supply_checker(espresso)
elif drink == '2':
latte = [350, 75, 20, 1, -7]
self.supply_checker(latte)
elif drink == '3':
cappuccino = [200, 100, 12, 1, -6]
self.supply_checker(cappuccino)
else:
return
def filler(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
self.supplies[0] += int(input(f'Write how many ml of {self.supply_str[0]} do you want to add: '))
self.supplies[1] += int(input(f'Write how many ml of {self.supply_str[1]} do you want to add: '))
self.supplies[2] += int(input(f'Write how many grams of {self.supply_str[2]} do you want to add: '))
self.supplies[3] += int(input(f'Write how many {self.supply_str[3]} of coffee do you want to add: '))
def remaining(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
print('The coffee machine has:')
for i in range(len(self.supplies)):
print(f'{self.supplies[i]} of {self.supply_str[i]}')
# Only method that user should have to interact with, Like a real cafe!
def barista(self):
while True:
action = input('Write action (buy, fill, take, remaining, exit): ')
if action == 'buy':
self.drink_maker()
elif action == 'fill':
self.filler()
elif action == 'take':
print(f'I gave you ${self.supplies[4]}')
self.supplies[4] = 0
elif action == 'remaining':
self.remaining()
elif action == 'exit':
break
print()
# Debugging
my_supplies = [400, 540, 120, 9, 550]
my_coffee = CoffeeMachine(my_supplies)
my_coffee.barista()
| class Coffeemachine:
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink):
for i in range(len(drink)):
if drink[i] > self.supplies[i]:
print(f'Sorry not enough {self.supply_str[i]} !')
break
else:
for i in range(len(drink)):
self.supplies[i] -= drink[i]
print('I have enough resources, making you a coffee!')
def drink_maker(self):
drink = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ')
if drink == '1':
espresso = [250, 0, 16, 1, -4]
self.supply_checker(espresso)
elif drink == '2':
latte = [350, 75, 20, 1, -7]
self.supply_checker(latte)
elif drink == '3':
cappuccino = [200, 100, 12, 1, -6]
self.supply_checker(cappuccino)
else:
return
def filler(self):
self.supplies[0] += int(input(f'Write how many ml of {self.supply_str[0]} do you want to add: '))
self.supplies[1] += int(input(f'Write how many ml of {self.supply_str[1]} do you want to add: '))
self.supplies[2] += int(input(f'Write how many grams of {self.supply_str[2]} do you want to add: '))
self.supplies[3] += int(input(f'Write how many {self.supply_str[3]} of coffee do you want to add: '))
def remaining(self):
print('The coffee machine has:')
for i in range(len(self.supplies)):
print(f'{self.supplies[i]} of {self.supply_str[i]}')
def barista(self):
while True:
action = input('Write action (buy, fill, take, remaining, exit): ')
if action == 'buy':
self.drink_maker()
elif action == 'fill':
self.filler()
elif action == 'take':
print(f'I gave you ${self.supplies[4]}')
self.supplies[4] = 0
elif action == 'remaining':
self.remaining()
elif action == 'exit':
break
print()
my_supplies = [400, 540, 120, 9, 550]
my_coffee = coffee_machine(my_supplies)
my_coffee.barista() |
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of
favorite restaurants represented by strings. You need to help them find out their common interest
with the least list index sum. If there is a choice tie between answers, output all of them with
no order requirement. You could assume there always exists an answer.
Example 1:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index
sum 1 (0+1).
Note:
1. The length of both lists will be in the range of [1, 1000].
2. The length of strings in both lists will be in the range of [1, 30].
3. The index is starting from 0 to the list length minus 1.
4. No duplicates in both lists.
"""
class Solution:
def findRestaurant(self, list1, list2):
d = {}
for i, x in enumerate(list1):
d[x] = i
res = {}
for j, y in enumerate(list2):
if y in d:
res[y] = d[y] + j
tmp = sorted(res, key=res.get)
return [x for x in tmp if res[x] == res[tmp[0]]]
| """
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of
favorite restaurants represented by strings. You need to help them find out their common interest
with the least list index sum. If there is a choice tie between answers, output all of them with
no order requirement. You could assume there always exists an answer.
Example 1:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index
sum 1 (0+1).
Note:
1. The length of both lists will be in the range of [1, 1000].
2. The length of strings in both lists will be in the range of [1, 30].
3. The index is starting from 0 to the list length minus 1.
4. No duplicates in both lists.
"""
class Solution:
def find_restaurant(self, list1, list2):
d = {}
for (i, x) in enumerate(list1):
d[x] = i
res = {}
for (j, y) in enumerate(list2):
if y in d:
res[y] = d[y] + j
tmp = sorted(res, key=res.get)
return [x for x in tmp if res[x] == res[tmp[0]]] |
# Write a program to print the pattern
def pattern(a):
print("Output :")
for i in range(1, a+1):
c = 1
for k in range(a, i, -1):
print(" ", end="")
for j in range(1, 2*i):
if j < i:
print(c, end="")
c += 1
else:
print(c, end="")
c -= 1
print()
a = int(input("Input : "))
pattern(a)
| def pattern(a):
print('Output :')
for i in range(1, a + 1):
c = 1
for k in range(a, i, -1):
print(' ', end='')
for j in range(1, 2 * i):
if j < i:
print(c, end='')
c += 1
else:
print(c, end='')
c -= 1
print()
a = int(input('Input : '))
pattern(a) |
# O(n ^ 4)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# ans = 0
# for a in range(n - 3):
# for b in range(a + 1, n - 2):
# for c in range(b + 1, n -1):
# for d in range(c + 1, n):
# if nums[a] + nums[b] + nums[c] == nums[d]:
# ans += 1
# return ans
# O(n ^ 3)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# cnt = defaultdict(int)
# ans = 0
# for c in range(n - 2, 1, -1):
# cnt[nums[c + 1]] += 1
# for a in range(c - 1):
# for b in range(a + 1, c):
# ans += cnt[nums[a] + nums[b] + nums[c]]
# return ans
# O(n ^ 2)
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
ans = 0
for b in range(n - 3, 0, -1):
for d in range(b + 2, n):
cnt[nums[d] - nums[b + 1]] += 1
for a in range(b):
ans += cnt[nums[a] + nums[b]]
return ans
| class Solution:
def count_quadruplets(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
ans = 0
for b in range(n - 3, 0, -1):
for d in range(b + 2, n):
cnt[nums[d] - nums[b + 1]] += 1
for a in range(b):
ans += cnt[nums[a] + nums[b]]
return ans |
# Constants
#
# Device Variables
VAR_BILLINGPERIODDURATION = 'zigbee:BillingPeriodDuration'
VAR_BILLINGPERIODSTART = 'zigbee:BillingPeriodStart'
VAR_BLOCK1PRICE = 'zigbee:Block1Price'
VAR_BLOCK1THRESHOLD = 'zigbee:Block1Threshold'
VAR_BLOCK2PRICE = 'zigbee:Block2Price'
VAR_BLOCK2THRESHOLD = 'zigbee:Block2Threshold'
VAR_BLOCK3PRICE = 'zigbee:Block3Price'
VAR_BLOCK3THRESHOLD = 'zigbee:Block3Threshold'
VAR_BLOCK4PRICE = 'zigbee:Block4Price'
VAR_BLOCK4THRESHOLD = 'zigbee:Block4Threshold'
VAR_BLOCK5PRICE = 'zigbee:Block5Price'
VAR_BLOCK5THRESHOLD = 'zigbee:Block5Threshold'
VAR_BLOCK6PRICE = 'zigbee:Block6Price'
VAR_BLOCK6THRESHOLD = 'zigbee:Block6Threshold'
VAR_BLOCK7PRICE = 'zigbee:Block7Price'
VAR_BLOCK7THRESHOLD = 'zigbee:Block7Threshold'
VAR_BLOCK8PRICE = 'zigbee:Block8Price'
VAR_BLOCK8THRESHOLD = 'zigbee:Block8Threshold'
VAR_BLOCKNPRICE = 'zigbee:Block{}Price'
VAR_BLOCKNTHRESHOLD = 'zigbee:Block{}Threshold'
VAR_BLOCKPERIODCONSUMPTION = 'zigbee:BlockPeriodConsumption'
VAR_BLOCKPERIODDURATION = 'zigbee:BlockPeriodDuration'
VAR_BLOCKPERIODNUMBEROFBLOCKS = 'zigbee:BlockPeriodNumberOfBlocks'
VAR_BLOCKPERIODSTART = 'zigbee:BlockPeriodStart'
VAR_BLOCKTHRESHOLDDIVISOR = 'zigbee:BlockThresholdDivisor'
VAR_BLOCKTHRESHOLDMULTIPLIER = 'zigbee:BlockThresholdMultiplier'
VAR_CURRENCY = 'zigbee:Currency'
VAR_CURRENTSUMMATIONDELIVERED = 'zigbee:CurrentSummationDelivered'
VAR_CURRENTSUMMATIONRECEIVED = 'zigbee:CurrentSummationReceived'
VAR_DIVISOR = 'zigbee:Divisor'
VAR_INSTANTANEOUSDEMAND = 'zigbee:InstantaneousDemand'
VAR_MESSAGE = 'zigbee:Message'
VAR_MESSAGECONFIRMATIONREQUIRED = 'zigbee:MessageConfirmationRequired'
VAR_MESSAGECONFIRMED = 'zigbee:MessageConfirmed'
VAR_MESSAGEDURATIONINMINUTES = 'zigbee:MessageDurationInMinutes'
VAR_MESSAGEID = 'zigbee:MessageId'
VAR_MESSAGEPRIORITY = 'zigbee:MessagePriority'
VAR_MESSAGESTARTTIME = 'zigbee:MessageStartTime'
VAR_MULTIPLIER = 'zigbee:Multiplier'
VAR_PRICE = 'zigbee:Price'
VAR_PRICEDURATION = 'zigbee:PriceDuration'
VAR_PRICESTARTTIME = 'zigbee:PriceStartTime'
VAR_PRICETIER = 'zigbee:PriceTier'
VAR_RATELABEL = 'zigbee:RateLabel'
VAR_TRAILINGDIGITS = 'zigbee:TrailingDigits'
| var_billingperiodduration = 'zigbee:BillingPeriodDuration'
var_billingperiodstart = 'zigbee:BillingPeriodStart'
var_block1_price = 'zigbee:Block1Price'
var_block1_threshold = 'zigbee:Block1Threshold'
var_block2_price = 'zigbee:Block2Price'
var_block2_threshold = 'zigbee:Block2Threshold'
var_block3_price = 'zigbee:Block3Price'
var_block3_threshold = 'zigbee:Block3Threshold'
var_block4_price = 'zigbee:Block4Price'
var_block4_threshold = 'zigbee:Block4Threshold'
var_block5_price = 'zigbee:Block5Price'
var_block5_threshold = 'zigbee:Block5Threshold'
var_block6_price = 'zigbee:Block6Price'
var_block6_threshold = 'zigbee:Block6Threshold'
var_block7_price = 'zigbee:Block7Price'
var_block7_threshold = 'zigbee:Block7Threshold'
var_block8_price = 'zigbee:Block8Price'
var_block8_threshold = 'zigbee:Block8Threshold'
var_blocknprice = 'zigbee:Block{}Price'
var_blocknthreshold = 'zigbee:Block{}Threshold'
var_blockperiodconsumption = 'zigbee:BlockPeriodConsumption'
var_blockperiodduration = 'zigbee:BlockPeriodDuration'
var_blockperiodnumberofblocks = 'zigbee:BlockPeriodNumberOfBlocks'
var_blockperiodstart = 'zigbee:BlockPeriodStart'
var_blockthresholddivisor = 'zigbee:BlockThresholdDivisor'
var_blockthresholdmultiplier = 'zigbee:BlockThresholdMultiplier'
var_currency = 'zigbee:Currency'
var_currentsummationdelivered = 'zigbee:CurrentSummationDelivered'
var_currentsummationreceived = 'zigbee:CurrentSummationReceived'
var_divisor = 'zigbee:Divisor'
var_instantaneousdemand = 'zigbee:InstantaneousDemand'
var_message = 'zigbee:Message'
var_messageconfirmationrequired = 'zigbee:MessageConfirmationRequired'
var_messageconfirmed = 'zigbee:MessageConfirmed'
var_messagedurationinminutes = 'zigbee:MessageDurationInMinutes'
var_messageid = 'zigbee:MessageId'
var_messagepriority = 'zigbee:MessagePriority'
var_messagestarttime = 'zigbee:MessageStartTime'
var_multiplier = 'zigbee:Multiplier'
var_price = 'zigbee:Price'
var_priceduration = 'zigbee:PriceDuration'
var_pricestarttime = 'zigbee:PriceStartTime'
var_pricetier = 'zigbee:PriceTier'
var_ratelabel = 'zigbee:RateLabel'
var_trailingdigits = 'zigbee:TrailingDigits' |
# Bit manipulation
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
for i in range(1 << len(nums)):
tmp = []
for j in range(len(nums)):
if i >> j & 1:
tmp.append(nums[j])
result.append(tmp)
return result
# Backtrack
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(result, 0, nums, [])
return result
def backtrack(self, result, idx, nums, path):
result.append(path)
for i in range(idx, len(nums)):
self.backtrack(result, i + 1, nums, path + [nums[i]])
| class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
for i in range(1 << len(nums)):
tmp = []
for j in range(len(nums)):
if i >> j & 1:
tmp.append(nums[j])
result.append(tmp)
return result
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(result, 0, nums, [])
return result
def backtrack(self, result, idx, nums, path):
result.append(path)
for i in range(idx, len(nums)):
self.backtrack(result, i + 1, nums, path + [nums[i]]) |
"""Utility queries for create, drop tables and insert data."""
# DROP TABLES
songplay_table_drop = "drop table if exists songplays"
user_table_drop = "drop table if exists users"
song_table_drop = "drop table if exists songs"
artist_table_drop = "drop table if exists artists"
time_table_drop = "drop table if exists time"
# CREATE TABLES
songplay_table_create = """
create table if not exists songplays
(
songplay_id bigserial NOT NULL -- bigserial == default nextval('fact_songplays_id')
,start_time bigint
,user_id integer REFERENCES users (user_id)
,level varchar(4) -- paid or free
,song_id varchar(30) NULL REFERENCES songs (song_id)
,artist_id varchar(30) NULL REFERENCES artists (artist_id)
,session_id integer
,location varchar(60)
,user_agent varchar(400)
,PRIMARY KEY (songplay_id)
);
"""
user_table_create = """
create table if not exists users
(
user_id integer -- can have up to 2.147.483.647 users
,first_name varchar(60)
,last_name varchar(60)
,gender varchar(1)
,level varchar(4) -- paid or free
,PRIMARY KEY (user_id)
);
"""
song_table_create = """
create table if not exists songs
(
song_id varchar(30)
,title varchar(60)
,artist_id varchar(30)
,year smallint
,duration numeric(9,6) -- ex: 218.93179
,PRIMARY KEY (song_id)
);
"""
artist_table_create = """
create table if not exists artists
(
artist_id varchar(30)
,name varchar(120)
,location varchar(120)
,latitude numeric(9,6) -- ex: 35.14968
,longitude numeric(9,6) -- ex: -90.04892
,PRIMARY KEY (artist_id)
);
"""
time_table_create = """
create table if not exists time
(
start_time bigint not null -- represent the timestamp where one song was played
,hour smallint not null
,day smallint not null
,week smallint not null
,month smallint not null
,year smallint not null
,weekday smallint not null
,PRIMARY KEY (start_time)
);
"""
# INSERT RECORDS
songplay_table_insert = """
INSERT INTO songplays
(start_time, user_id, "level", song_id, artist_id, session_id, "location", user_agent)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s);
"""
user_table_insert = """
INSERT INTO users
(user_id, first_name, last_name, gender, "level")
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (user_id) DO UPDATE
SET first_name=EXCLUDED.first_name
,last_name=EXCLUDED.last_name
,gender=EXCLUDED.gender
,"level"=EXCLUDED."level"
"""
# artist_id artist_latitude artist_location artist_longitude artist_name duration num_songs song_id title year
# ('ARD7TVE1187B99BFB1', '', 'California - LA', '', 'Casual', 218.93179, 1, 'SOMZWCG12A8C13C480', "I Didn't Mean To", 0)
song_table_insert = """
INSERT INTO songs
(song_id, title, artist_id, "year", duration)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (song_id) DO UPDATE
SET title=EXCLUDED.title
,artist_id=EXCLUDED.artist_id
,"year"=EXCLUDED.year
,duration=EXCLUDED.duration
"""
artist_table_insert = """
INSERT INTO artists
(artist_id, "name", "location", latitude, longitude)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT (artist_id) DO UPDATE
SET name=EXCLUDED.name
,location=EXCLUDED.location
,latitude=EXCLUDED.latitude
,longitude=EXCLUDED.longitude
"""
"""
-- https://www.postgresql.org/docs/13/sql-insert.html
INSERT INTO distributors (did, dname)
VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
"""
time_table_insert = """
INSERT INTO "time"
(start_time, "hour", "day", week, "month", "year", weekday)
VALUES(%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (start_time) DO UPDATE
SET hour=EXCLUDED.hour
,day=EXCLUDED.day
,week=EXCLUDED.week
,month=EXCLUDED.month
,year=EXCLUDED.year
,weekday=EXCLUDED.weekday
;
"""
# FIND SONGS
# Implement the song_select query in sql_queries.py to find the song ID and artist ID based on the title, artist name, and duration of a song.
# Select the timestamp, user ID, level, song ID, artist ID, session ID, location, and user agent and set to songplay_data
# get songid and artistid from song and artist tables
song_select = """
select s.song_id, s.artist_id from songs s
join artists a on a.artist_id=s.artist_id
where s.title=%s and a.name=%s and s.duration=%s
"""
# to check if etl run ok
count_tables = """
SELECT count(0), 'songplays' as "table" FROM public.songplays
UNION all
SELECT count(0), 'songplays_with_song_id' as "table" FROM public.songplays where song_id is not null
UNION ALL
SELECT count(0), 'artists' as "table" FROM public.artists
UNION ALL
SELECT count(0), 'artists' as "table" FROM public.songs
UNION ALL
SELECT count(0), 'users' as "table" FROM public.users
UNION ALL
SELECT count(0), 'time' as "table" FROM public.time
;
"""
# QUERY LISTS
create_table_queries = [
user_table_create,
song_table_create,
artist_table_create,
time_table_create,
songplay_table_create,
]
drop_table_queries = [
songplay_table_drop,
user_table_drop,
song_table_drop,
artist_table_drop,
time_table_drop,
]
| """Utility queries for create, drop tables and insert data."""
songplay_table_drop = 'drop table if exists songplays'
user_table_drop = 'drop table if exists users'
song_table_drop = 'drop table if exists songs'
artist_table_drop = 'drop table if exists artists'
time_table_drop = 'drop table if exists time'
songplay_table_create = "\ncreate table if not exists songplays\n(\n songplay_id bigserial NOT NULL -- bigserial == default nextval('fact_songplays_id')\n ,start_time bigint\n ,user_id integer REFERENCES users (user_id)\n ,level varchar(4) -- paid or free\n ,song_id varchar(30) NULL REFERENCES songs (song_id)\n ,artist_id varchar(30) NULL REFERENCES artists (artist_id)\n ,session_id integer\n ,location varchar(60)\n ,user_agent varchar(400)\n ,PRIMARY KEY (songplay_id)\n);\n"
user_table_create = '\ncreate table if not exists users\n(\n user_id integer -- can have up to 2.147.483.647 users\n ,first_name varchar(60)\n ,last_name varchar(60)\n ,gender varchar(1)\n ,level varchar(4) -- paid or free\n ,PRIMARY KEY (user_id)\n);\n'
song_table_create = '\ncreate table if not exists songs\n(\n song_id varchar(30)\n ,title varchar(60)\n ,artist_id varchar(30)\n ,year smallint\n ,duration numeric(9,6) -- ex: 218.93179\n ,PRIMARY KEY (song_id)\n);\n\n'
artist_table_create = '\ncreate table if not exists artists\n(\n artist_id varchar(30)\n ,name varchar(120)\n ,location varchar(120)\n ,latitude numeric(9,6) -- ex: 35.14968\n ,longitude numeric(9,6) -- ex: -90.04892\n ,PRIMARY KEY (artist_id)\n);\n'
time_table_create = '\ncreate table if not exists time\n(\n start_time bigint not null -- represent the timestamp where one song was played\n ,hour smallint not null\n ,day smallint not null\n ,week smallint not null\n ,month smallint not null\n ,year smallint not null\n ,weekday smallint not null\n ,PRIMARY KEY (start_time)\n);\n'
songplay_table_insert = '\nINSERT INTO songplays\n(start_time, user_id, "level", song_id, artist_id, session_id, "location", user_agent)\nVALUES(%s, %s, %s, %s, %s, %s, %s, %s);\n'
user_table_insert = '\nINSERT INTO users\n(user_id, first_name, last_name, gender, "level")\nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT (user_id) DO UPDATE\n SET first_name=EXCLUDED.first_name\n ,last_name=EXCLUDED.last_name\n ,gender=EXCLUDED.gender\n ,"level"=EXCLUDED."level"\n'
song_table_insert = '\nINSERT INTO songs\n(song_id, title, artist_id, "year", duration)\nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT (song_id) DO UPDATE\n SET title=EXCLUDED.title\n ,artist_id=EXCLUDED.artist_id\n ,"year"=EXCLUDED.year\n ,duration=EXCLUDED.duration\n'
artist_table_insert = '\nINSERT INTO artists\n(artist_id, "name", "location", latitude, longitude)\nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT (artist_id) DO UPDATE\n SET name=EXCLUDED.name\n ,location=EXCLUDED.location\n ,latitude=EXCLUDED.latitude\n ,longitude=EXCLUDED.longitude\n'
"\n-- https://www.postgresql.org/docs/13/sql-insert.html\nINSERT INTO distributors (did, dname)\n VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')\n ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;\n"
time_table_insert = '\nINSERT INTO "time"\n(start_time, "hour", "day", week, "month", "year", weekday)\nVALUES(%s, %s, %s, %s, %s, %s, %s)\nON CONFLICT (start_time) DO UPDATE\n SET hour=EXCLUDED.hour\n ,day=EXCLUDED.day\n ,week=EXCLUDED.week\n ,month=EXCLUDED.month\n ,year=EXCLUDED.year\n ,weekday=EXCLUDED.weekday\n;\n'
song_select = '\nselect s.song_id, s.artist_id from songs s\njoin artists a on a.artist_id=s.artist_id\nwhere s.title=%s and a.name=%s and s.duration=%s\n'
count_tables = '\nSELECT count(0), \'songplays\' as "table" FROM public.songplays\nUNION all\nSELECT count(0), \'songplays_with_song_id\' as "table" FROM public.songplays where song_id is not null\nUNION ALL\nSELECT count(0), \'artists\' as "table" FROM public.artists\nUNION ALL\nSELECT count(0), \'artists\' as "table" FROM public.songs\nUNION ALL\nSELECT count(0), \'users\' as "table" FROM public.users\nUNION ALL\nSELECT count(0), \'time\' as "table" FROM public.time\n;\n'
create_table_queries = [user_table_create, song_table_create, artist_table_create, time_table_create, songplay_table_create]
drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop] |
def load_file_list(f_list):
lines=[]
for fp in f_list:
with open(fp,'r',encoding='utf-8') as f:
for line in f:
strs=line.strip().split('\t')
lines.append([float(strs[0]),len(lines),strs[1]])
return lines
def build_id_dict(list):
dic={}
for l in list:
dic[len(dic)]=l
return dic
def select_data_by_lm_score(inf_path,fm_path,top_rate=0.1,bottom_rate=0.1,suffix='.filtered_by_lm'):
inf_ori=load_file_list([inf_path])
fm_ori=load_file_list([fm_path])
inf_dic=build_id_dict(inf_ori)
fm_dic=build_id_dict(fm_ori)
inf_sorted=sorted(inf_ori,key=lambda x:x[0],reverse=True)
fm_sorted = sorted(fm_ori, key=lambda x: x[0], reverse=True)
data_num=len(inf_ori)
start_id=int(top_rate*data_num)
end_id=int((1-bottom_rate)*data_num)
fm_top_score=fm_sorted[start_id][0]
fm_bottom_score=fm_sorted[end_id-1][0]
selected_inf=inf_sorted[start_id:end_id]
fw_inf=open(inf_path+suffix,'w',encoding='utf-8')
fw_fm=open(fm_path+suffix,'w',encoding='utf-8')
for item in selected_inf:
fm_item=fm_dic[item[1]]
if fm_item[0]>=fm_bottom_score and fm_item[0]<=fm_top_score:
fw_inf.write(item[2]+'\n')
fw_fm.write(fm_item[2]+'\n')
fw_inf.close()
fw_fm.close()
if __name__=='__main__':
select_data_by_lm_score('../new_exp_fr/add_data/informal.add.rule.bpe.bpe_len_filtered.score',
'../new_exp_fr/add_data/formal.add.rule.bpe.bpe_len_filtered.score')
print('all work has finished')
| def load_file_list(f_list):
lines = []
for fp in f_list:
with open(fp, 'r', encoding='utf-8') as f:
for line in f:
strs = line.strip().split('\t')
lines.append([float(strs[0]), len(lines), strs[1]])
return lines
def build_id_dict(list):
dic = {}
for l in list:
dic[len(dic)] = l
return dic
def select_data_by_lm_score(inf_path, fm_path, top_rate=0.1, bottom_rate=0.1, suffix='.filtered_by_lm'):
inf_ori = load_file_list([inf_path])
fm_ori = load_file_list([fm_path])
inf_dic = build_id_dict(inf_ori)
fm_dic = build_id_dict(fm_ori)
inf_sorted = sorted(inf_ori, key=lambda x: x[0], reverse=True)
fm_sorted = sorted(fm_ori, key=lambda x: x[0], reverse=True)
data_num = len(inf_ori)
start_id = int(top_rate * data_num)
end_id = int((1 - bottom_rate) * data_num)
fm_top_score = fm_sorted[start_id][0]
fm_bottom_score = fm_sorted[end_id - 1][0]
selected_inf = inf_sorted[start_id:end_id]
fw_inf = open(inf_path + suffix, 'w', encoding='utf-8')
fw_fm = open(fm_path + suffix, 'w', encoding='utf-8')
for item in selected_inf:
fm_item = fm_dic[item[1]]
if fm_item[0] >= fm_bottom_score and fm_item[0] <= fm_top_score:
fw_inf.write(item[2] + '\n')
fw_fm.write(fm_item[2] + '\n')
fw_inf.close()
fw_fm.close()
if __name__ == '__main__':
select_data_by_lm_score('../new_exp_fr/add_data/informal.add.rule.bpe.bpe_len_filtered.score', '../new_exp_fr/add_data/formal.add.rule.bpe.bpe_len_filtered.score')
print('all work has finished') |
# -------------
# netrecon info
# --------------
__name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: avery.rozar@trolleyesecurity.com'
| __name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: avery.rozar@trolleyesecurity.com' |
def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.aim = self.aim + y
def up(self, y):
self.aim = self.aim - y
def get_multiplied(self):
return self.horizontal * self.depth
if __name__ == "__main__":
submarine = Submarine()
content = read_puzzle("puzzle_input.txt")
for line in content:
commands = line.split(" ")
if commands[0] == "forward":
submarine.forward(int(commands[1]))
elif commands[0] == "down":
submarine.down(int(commands[1]))
elif commands[0] == "up":
submarine.up(int(commands[1]))
print("Final location of the submarine: Horizontal: " + str(submarine.horizontal) + ", Depth: " + str(submarine.depth) +
", Multiplied: " + str(submarine.get_multiplied()))
| def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.aim = self.aim + y
def up(self, y):
self.aim = self.aim - y
def get_multiplied(self):
return self.horizontal * self.depth
if __name__ == '__main__':
submarine = submarine()
content = read_puzzle('puzzle_input.txt')
for line in content:
commands = line.split(' ')
if commands[0] == 'forward':
submarine.forward(int(commands[1]))
elif commands[0] == 'down':
submarine.down(int(commands[1]))
elif commands[0] == 'up':
submarine.up(int(commands[1]))
print('Final location of the submarine: Horizontal: ' + str(submarine.horizontal) + ', Depth: ' + str(submarine.depth) + ', Multiplied: ' + str(submarine.get_multiplied())) |
class FieldDimension:
def __init__(self, dimension, indexes):
self.dimension = dimension
self.indexes = indexes
@classmethod
def to_index(cls, t):
"""
:param t: t look like "1" or "4-7"
:return: tuple either size of 1 or 2 (1) or (4, 7)
"""
a = t.split('-')
return tuple((int(i) for i in a))
@classmethod
def to_field_dimension(cls, dimension_str, v_str):
dimension = int(dimension_str)
indexes = [cls.to_index(t) for t in v_str.split(',')]
return FieldDimension(dimension, indexes)
def __str__(self):
return "%s:%s" % (self.indexes, self.dimension) | class Fielddimension:
def __init__(self, dimension, indexes):
self.dimension = dimension
self.indexes = indexes
@classmethod
def to_index(cls, t):
"""
:param t: t look like "1" or "4-7"
:return: tuple either size of 1 or 2 (1) or (4, 7)
"""
a = t.split('-')
return tuple((int(i) for i in a))
@classmethod
def to_field_dimension(cls, dimension_str, v_str):
dimension = int(dimension_str)
indexes = [cls.to_index(t) for t in v_str.split(',')]
return field_dimension(dimension, indexes)
def __str__(self):
return '%s:%s' % (self.indexes, self.dimension) |
for t in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and not flag:
counter = 1
flag = True
elif i == 1 and counter < 6 :
result = False
break
elif i == 1 and counter >= 6:
counter = 1
else:
counter += 1
if result:
print("YES")
else:
print("NO")
| for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and (not flag):
counter = 1
flag = True
elif i == 1 and counter < 6:
result = False
break
elif i == 1 and counter >= 6:
counter = 1
else:
counter += 1
if result:
print('YES')
else:
print('NO') |
"""
Topic modeling is a type of statistical modeling for discovering the abstract 'topics' that occur in
a collection of documents, Latent Dirichlet Allocation is an example of topic model and is used to
classify text in a document to a particular topic. It builds a topic per document model and words per
topic model, modeled as Dirichlet distributions.
""" | """
Topic modeling is a type of statistical modeling for discovering the abstract 'topics' that occur in
a collection of documents, Latent Dirichlet Allocation is an example of topic model and is used to
classify text in a document to a particular topic. It builds a topic per document model and words per
topic model, modeled as Dirichlet distributions.
""" |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
s = 0
while n > 0:
if n % 2 == 1:
s += 1
n = n // 2
return s
def test_0():
assert Solution().hammingWeight(11) == 3
assert Solution().hammingWeight(128) == 1
| class Solution(object):
def hamming_weight(self, n):
"""
:type n: int
:rtype: int
"""
s = 0
while n > 0:
if n % 2 == 1:
s += 1
n = n // 2
return s
def test_0():
assert solution().hammingWeight(11) == 3
assert solution().hammingWeight(128) == 1 |
"""
NAME : DIBANSA, RAHMANI P.
NAME : BELGA, EMJAY
COURSE : BSCPE 2-2
ACADEMIC YEAR : 2019-2020
PROGRAM'S SUMMARY: THIS PROGRAM WOULD MIMIC A STACK OF NOTEBOOKS THAT WOULD BE CHECKED. THIS PROGRAM RECORDS THE NAME
OF THE NOTEBOOK'S OWNER AND ADDS THE NOTEBOOK ON THE TOP OF THE STACK. AS THE USER CHECKS THE STACK, THE NOTEBOOK AT
THE TOP OF THE STACK WOULD BE REMOVED. FURTHERMORE, THE USER COULD ALSO OPT FOR THE 'CHECK ALL' BUTTON THAT REMOVES
EVERY NOTEBOOK IN THE STACK. IN ADDITION, THE USER COULD ALSO PEEK AT THE NOTEBOOK ON TOP OF THE STACK.
"""
# This stack class mimics a stack of notebooks.
class stcks:
# The program would be initializing the allocated storage for the notebook's stack and the truth value
# of isStackEmpty.
def __init__( self ) :
self.stackStorage = []
self.isStackEmpty = True
# This function checks if the stack is empty or not.
# The program would be updating the truth value of isStackEmpty depending on the result of the process.
def is_empty ( self ) :
self.tempLen = len ( self.stackStorage )
if self.tempLen == 0:
self.isStackEmpty = True
else:
self.isStackEmpty = False
# This function adds another book on top of the stack.
def addNotebook ( self , ownerName ) :
self.ownerName = ownerName
self.stackStorage.append ( self.ownerName )
# If the notebook stack isn't empty, this function would remove the last added notebook in the stack.
def checkNotebook ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.stackStorage.pop ( len ( self.stackStorage ) - 1 )
# If the notebook stack isn't empty, this function would take the name of the owner of the last inputted
# notebook in the stack, and the program would return the name of the notebook's owner back to wherever it has
# been called.
def peekAtNotebook ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.notebookOwner = self.stackStorage[ len ( self.stackStorage ) - 1 ]
return self.notebookOwner
# If the notebook stack isn't empty, this function would take all the names of the notebook owners and record it
# following the order of the stack.
def checkAll ( self ) :
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.result = ""
self.tempStackStorage = self.stackStorage.copy()
for i in range ( len ( self.tempStackStorage ) ) :
if i != ( len( self.tempStackStorage) - 1 ) :
self.result += self.tempStackStorage[i] + ", "
else:
self.result += self.tempStackStorage[i] + "."
return self.result
# This is an extension of the checkAll function above, all this does is remove all the elements within the
# program's stack.
def checkedAll ( self ) :
self.stackStorage = []
| """
NAME : DIBANSA, RAHMANI P.
NAME : BELGA, EMJAY
COURSE : BSCPE 2-2
ACADEMIC YEAR : 2019-2020
PROGRAM'S SUMMARY: THIS PROGRAM WOULD MIMIC A STACK OF NOTEBOOKS THAT WOULD BE CHECKED. THIS PROGRAM RECORDS THE NAME
OF THE NOTEBOOK'S OWNER AND ADDS THE NOTEBOOK ON THE TOP OF THE STACK. AS THE USER CHECKS THE STACK, THE NOTEBOOK AT
THE TOP OF THE STACK WOULD BE REMOVED. FURTHERMORE, THE USER COULD ALSO OPT FOR THE 'CHECK ALL' BUTTON THAT REMOVES
EVERY NOTEBOOK IN THE STACK. IN ADDITION, THE USER COULD ALSO PEEK AT THE NOTEBOOK ON TOP OF THE STACK.
"""
class Stcks:
def __init__(self):
self.stackStorage = []
self.isStackEmpty = True
def is_empty(self):
self.tempLen = len(self.stackStorage)
if self.tempLen == 0:
self.isStackEmpty = True
else:
self.isStackEmpty = False
def add_notebook(self, ownerName):
self.ownerName = ownerName
self.stackStorage.append(self.ownerName)
def check_notebook(self):
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.stackStorage.pop(len(self.stackStorage) - 1)
def peek_at_notebook(self):
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.notebookOwner = self.stackStorage[len(self.stackStorage) - 1]
return self.notebookOwner
def check_all(self):
self.is_empty()
if self.isStackEmpty == True:
return None
else:
self.result = ''
self.tempStackStorage = self.stackStorage.copy()
for i in range(len(self.tempStackStorage)):
if i != len(self.tempStackStorage) - 1:
self.result += self.tempStackStorage[i] + ', '
else:
self.result += self.tempStackStorage[i] + '.'
return self.result
def checked_all(self):
self.stackStorage = [] |
# https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
if 0 <= dic[word[i]] - dic[word[i - 1]] <= 1 and dp[i - 1] > 0:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1 if word[i] == 'a' else 0
res = [v for i, v in enumerate(dp) if word[i] == 'u']
return max([v for i, v in enumerate(dp) if word[i] == 'u'], default=0)
s = Solution()
print(s.longestBeautifulSubstring('uuuuu')) # 0
print(s.longestBeautifulSubstring('aeiaaioaaaaeiiiiouuuooaauuaeiu')) # 13
print(s.longestBeautifulSubstring('aeeeiiiioooauuuaeiou')) # 5
| class Solution:
def longest_beautiful_substring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
if 0 <= dic[word[i]] - dic[word[i - 1]] <= 1 and dp[i - 1] > 0:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1 if word[i] == 'a' else 0
res = [v for (i, v) in enumerate(dp) if word[i] == 'u']
return max([v for (i, v) in enumerate(dp) if word[i] == 'u'], default=0)
s = solution()
print(s.longestBeautifulSubstring('uuuuu'))
print(s.longestBeautifulSubstring('aeiaaioaaaaeiiiiouuuooaauuaeiu'))
print(s.longestBeautifulSubstring('aeeeiiiioooauuuaeiou')) |
# flake8: noqa
def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source()
| def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source() |
"""A collection of command-related exceptions."""
__all__ = ('CommandError', 'ArgumentError', 'MissingArgumentError', 'UnusedArgumentsError', 'AuthorizationError',
'ComplexityError')
class CommandError(Exception):
"""Raised on any command processing error."""
class ArgumentError(CommandError):
"""Raised when there is something wrong with user input."""
class MissingArgumentError(ArgumentError):
"""Raised when the user has not provided enough arguments."""
class UnusedArgumentsError(ArgumentError):
"""Raised when there are unused arguments."""
class AuthorizationError(Exception):
"""Raised when the user does not have sufficient permissions."""
class ComplexityError(Exception):
"""Raised if a command is too complex to complete completely."""
| """A collection of command-related exceptions."""
__all__ = ('CommandError', 'ArgumentError', 'MissingArgumentError', 'UnusedArgumentsError', 'AuthorizationError', 'ComplexityError')
class Commanderror(Exception):
"""Raised on any command processing error."""
class Argumenterror(CommandError):
"""Raised when there is something wrong with user input."""
class Missingargumenterror(ArgumentError):
"""Raised when the user has not provided enough arguments."""
class Unusedargumentserror(ArgumentError):
"""Raised when there are unused arguments."""
class Authorizationerror(Exception):
"""Raised when the user does not have sufficient permissions."""
class Complexityerror(Exception):
"""Raised if a command is too complex to complete completely.""" |
with open("3.txt") as f:
nums = [x for x in f.read().split("\n")]
totals = [0] * len(nums[0])
for n in nums:
for i, c in enumerate(n):
totals[i] += 1 if c == "1" else -1
gamma = int("".join(map(lambda x: "1" if x > 0 else "0", totals)), 2)
epsilon = int("".join(map(lambda x: "1" if x <= 0 else "0", totals)), 2)
print("part 1: {}".format(gamma * epsilon))
nums = sorted(nums)
def process(nums, flip):
for i in range(len(nums[0])):
index = next((j for j, n in enumerate(nums) if n[i] == "1"), len(nums))
cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2
nums = nums[index:] if cmp else nums[:index]
if len(nums) == 1:
return int(nums[0], 2)
print("part 2: {}".format(process(nums, True) * process(nums, False)))
| with open('3.txt') as f:
nums = [x for x in f.read().split('\n')]
totals = [0] * len(nums[0])
for n in nums:
for (i, c) in enumerate(n):
totals[i] += 1 if c == '1' else -1
gamma = int(''.join(map(lambda x: '1' if x > 0 else '0', totals)), 2)
epsilon = int(''.join(map(lambda x: '1' if x <= 0 else '0', totals)), 2)
print('part 1: {}'.format(gamma * epsilon))
nums = sorted(nums)
def process(nums, flip):
for i in range(len(nums[0])):
index = next((j for (j, n) in enumerate(nums) if n[i] == '1'), len(nums))
cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2
nums = nums[index:] if cmp else nums[:index]
if len(nums) == 1:
return int(nums[0], 2)
print('part 2: {}'.format(process(nums, True) * process(nums, False))) |
"""
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
"""
# solved through caterpillar method
def get_contigous_sum(k, arr):
front = 0
total = 0
for back in range(len(arr)):
while front < len(arr) and total + arr[front] <= k:
total += arr[front]
front += 1
if total == k:
return arr[back:front]
total -= arr[back]
return None
if __name__ == '__main__':
print(get_contigous_sum(9, [1, 2, 3, 4, 5])) # [2, 3, 4]
print(get_contigous_sum(12, [6, 2, 7, 4, 1, 3, 6])) # [7, 4, 1] | """
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
"""
def get_contigous_sum(k, arr):
front = 0
total = 0
for back in range(len(arr)):
while front < len(arr) and total + arr[front] <= k:
total += arr[front]
front += 1
if total == k:
return arr[back:front]
total -= arr[back]
return None
if __name__ == '__main__':
print(get_contigous_sum(9, [1, 2, 3, 4, 5]))
print(get_contigous_sum(12, [6, 2, 7, 4, 1, 3, 6])) |
# define inception block layer
def InceptBlock(filters, strides):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
filters1, filters2, filters3 = filters
conv1x1 = stax.serial(stax.Conv(filters1, (1,1), strides, padding="SAME"))
conv3x3 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding="SAME"),
stax.Conv(filters2, (3,3), strides, padding="SAME"))
conv5x5 = stax.serial(stax.Conv(filters1, (1,1), strides=None, padding="SAME"),
stax.Conv(filters3, (5,5), strides, padding="SAME"))
return stax.serial(
stax.FanOut(2), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, conv5x5),
stax.FanInConcat(), stax.LeakyRelu)
def InceptBlock2(filters, strides, dims=2, do_5x5=True, do_3x3=True):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
filters1, filters2, filters3 = filters
#strides = ()
dim_nums = ("NCHWZ", "OIHWZ", "NCHWZ")
conv1x1 = stax.serial(stax.GeneralConv(dim_nums,
filters1,
filter_shape=(1,)*dims,
strides=strides, padding="SAME"))
filters4 = filters2
conv3x3 = stax.serial(stax.GeneralConv(dim_nums,
filters2,
filter_shape=(1,)*dims,
strides=None, padding="SAME"),
stax.GeneralConv(dim_nums,
filters4,
filter_shape=(3,)*dims,
strides=strides, padding="SAME"))
filters5 = filters3
conv5x5 = stax.serial(stax.GeneralConv(dim_nums,
filters3,
filter_shape=(1,)*dims,
strides=None, padding="SAME"),
stax.GeneralConv(dim_nums,
filters5,
filter_shape=(5,)*dims,
strides=strides, padding="SAME"))
maxpool = stax.serial(stax.MaxPool((3,)*dims, padding="SAME"),
stax.GeneralConv(dim_nums,
filters4,
filter_shape=(1,)*dims,
strides=strides, padding="SAME"))
if do_3x3:
if do_5x5:
return stax.serial(
stax.FanOut(4), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, conv5x5, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
else:
return stax.serial(
stax.FanOut(3), # should num=3 or 2 here ?
stax.parallel(conv1x1, conv3x3, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
else:
return stax.serial(
stax.FanOut(2), # should num=3 or 2 here ?
stax.parallel(conv1x1, maxpool),
stax.FanInConcat(),
stax.LeakyRelu)
dim_nums = ("NCHWZ", "OIHWZ", "NCHWZ")
model = stax.serial(
InceptBlock2((fs,fs,fs), strides=(4,4,4), dims=3, do_5x5=False), # output: 8,8
#InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3), # output: 2,2
InceptBlock2((fs,fs,fs), strides=(4,4,4), dims=3, do_5x5=False), # output: 2,2
#InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3, do_5x5=False, do_3x3=False), # output 2,2
InceptBlock2((fs,fs,fs), strides=(2,2,2), dims=3, do_5x5=False, do_3x3=False), # output 1,1
stax.GeneralConv(dim_nums, n_summaries,
filter_shape=(1,1,1),
strides=(1,1,1), padding="SAME"),
stax.Flatten
) | def incept_block(filters, strides):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
(filters1, filters2, filters3) = filters
conv1x1 = stax.serial(stax.Conv(filters1, (1, 1), strides, padding='SAME'))
conv3x3 = stax.serial(stax.Conv(filters1, (1, 1), strides=None, padding='SAME'), stax.Conv(filters2, (3, 3), strides, padding='SAME'))
conv5x5 = stax.serial(stax.Conv(filters1, (1, 1), strides=None, padding='SAME'), stax.Conv(filters3, (5, 5), strides, padding='SAME'))
return stax.serial(stax.FanOut(2), stax.parallel(conv1x1, conv3x3, conv5x5), stax.FanInConcat(), stax.LeakyRelu)
def incept_block2(filters, strides, dims=2, do_5x5=True, do_3x3=True):
"""InceptNet convolutional striding block.
filters: tuple: (f1,f2,f3)
filters1: for conv1x1
filters2: for conv1x1,conv3x3
filters3L for conv1x1,conv5x5"""
(filters1, filters2, filters3) = filters
dim_nums = ('NCHWZ', 'OIHWZ', 'NCHWZ')
conv1x1 = stax.serial(stax.GeneralConv(dim_nums, filters1, filter_shape=(1,) * dims, strides=strides, padding='SAME'))
filters4 = filters2
conv3x3 = stax.serial(stax.GeneralConv(dim_nums, filters2, filter_shape=(1,) * dims, strides=None, padding='SAME'), stax.GeneralConv(dim_nums, filters4, filter_shape=(3,) * dims, strides=strides, padding='SAME'))
filters5 = filters3
conv5x5 = stax.serial(stax.GeneralConv(dim_nums, filters3, filter_shape=(1,) * dims, strides=None, padding='SAME'), stax.GeneralConv(dim_nums, filters5, filter_shape=(5,) * dims, strides=strides, padding='SAME'))
maxpool = stax.serial(stax.MaxPool((3,) * dims, padding='SAME'), stax.GeneralConv(dim_nums, filters4, filter_shape=(1,) * dims, strides=strides, padding='SAME'))
if do_3x3:
if do_5x5:
return stax.serial(stax.FanOut(4), stax.parallel(conv1x1, conv3x3, conv5x5, maxpool), stax.FanInConcat(), stax.LeakyRelu)
else:
return stax.serial(stax.FanOut(3), stax.parallel(conv1x1, conv3x3, maxpool), stax.FanInConcat(), stax.LeakyRelu)
else:
return stax.serial(stax.FanOut(2), stax.parallel(conv1x1, maxpool), stax.FanInConcat(), stax.LeakyRelu)
dim_nums = ('NCHWZ', 'OIHWZ', 'NCHWZ')
model = stax.serial(incept_block2((fs, fs, fs), strides=(4, 4, 4), dims=3, do_5x5=False), incept_block2((fs, fs, fs), strides=(4, 4, 4), dims=3, do_5x5=False), incept_block2((fs, fs, fs), strides=(2, 2, 2), dims=3, do_5x5=False, do_3x3=False), stax.GeneralConv(dim_nums, n_summaries, filter_shape=(1, 1, 1), strides=(1, 1, 1), padding='SAME'), stax.Flatten) |
class PackageInstaller(object):
"""
Installs packages
"""
def __init__(self, connector, packages)-> None:
self.__packages_installed = 0
self.__packages = packages
self.__bash_connector = connector
for package in self.__packages:
self.__run_package_installer(package)
@classmethod
def found_char(cls, string: str, char: str)-> bool:
"""
It is looking for a particular char
in a string
:param string: the string
:param char: the char it is looking for
:return: boolean
"""
str_version = str(string)
# try to find substring
find = str_version.find(char)
if find == -1:
# if not found
return False
else:
# found
return True
@classmethod
def split_string(cls, string: str, char: str)-> str:
"""
Splits string and returns
the first part
:param string: the string to be split
:param char: delimiter
:return: the first part of the string
"""
string = string.split(char, 1)[0]
return string
@classmethod
def sanitize_str(cls, string: str)-> str:
"""
Removes 'b' and ' from a string
:param string: the string to be sanitized
:return: newly created string
"""
# convert to string
string = str(string)
# remove "b"
string = string.replace("b'", "")
# remove '
string = string.replace("'", "")
return string
@classmethod
def remove_chars(cls, string: str)-> str:
"""
Removes unnecessary characters from
the string.
:param string: the string to be manipulated
:return: newly created string
"""
# sanitize the string
string = cls.sanitize_str(string)
# remove unnecessary things
if cls.found_char(string, "-"):
string = string.split("-", 1)[0]
elif cls.found_char(string, "ubuntu"):
string = string.split("ubuntu", 1)[0]
if cls.found_char(string, "+"):
string = string.split("+", 1)[0]
return string
def __install(self, package)-> None:
"""
Wrapper around install_package
:param package: json object representing package
:return: void
"""
i = 0
for command in package['commands']:
i += 1
print("Command Description " + str(i) + ": " + str(command['commandDescription']))
print("Command :" + str(command['command']))
self.__bash_connector.install_package(command)
# increment the number of installed packages
self.__packages_installed = self.__packages_installed + 1
@classmethod
def __is_installed(cls, version: str)-> bool:
"""
Checks if package is installed.
:param version: string version of the package
:return: boolean true/false
"""
if not version or version == "'b'":
return False
is_non_in_version = cls.found_char(version, "none")
if is_non_in_version:
return False
return True
@classmethod
def __extract_version(cls, output: str):
"""
Gets the version of the package
:param output: string containing the version
or 'b if there is none
:return: the version of the package
"""
# split the output and extract the
# installed part as:
# Installed: 1.6-2
if not output:
return 0
tmp = output.split()
version = tmp[2]
return version
@classmethod
def __print_info(cls, package)-> None:
# print some info
print("###################################################")
print("Installing : " + package['name'])
print("Comments : " + package['comment'])
print("Version : " + package['version'])
def __run_package_installer(self, package):
if not package:
return
# print info
PackageInstaller.__print_info(package)
# execute apt-cache
output = self.__bash_connector.apt_cache(package)
# get the version
version = self.__extract_version(output)
# check if installed
if not self.__is_installed(version):
# if not, installed it
self.__bash_connector.update()
self.__install(package)
else:
# else, just address the user
# remove certain chars
version = PackageInstaller.remove_chars(version)
print("This Package is already installed! Version is " + version + "\n")
def get_num_installed_packages(self)-> int:
return self.__packages_installed
| class Packageinstaller(object):
"""
Installs packages
"""
def __init__(self, connector, packages) -> None:
self.__packages_installed = 0
self.__packages = packages
self.__bash_connector = connector
for package in self.__packages:
self.__run_package_installer(package)
@classmethod
def found_char(cls, string: str, char: str) -> bool:
"""
It is looking for a particular char
in a string
:param string: the string
:param char: the char it is looking for
:return: boolean
"""
str_version = str(string)
find = str_version.find(char)
if find == -1:
return False
else:
return True
@classmethod
def split_string(cls, string: str, char: str) -> str:
"""
Splits string and returns
the first part
:param string: the string to be split
:param char: delimiter
:return: the first part of the string
"""
string = string.split(char, 1)[0]
return string
@classmethod
def sanitize_str(cls, string: str) -> str:
"""
Removes 'b' and ' from a string
:param string: the string to be sanitized
:return: newly created string
"""
string = str(string)
string = string.replace("b'", '')
string = string.replace("'", '')
return string
@classmethod
def remove_chars(cls, string: str) -> str:
"""
Removes unnecessary characters from
the string.
:param string: the string to be manipulated
:return: newly created string
"""
string = cls.sanitize_str(string)
if cls.found_char(string, '-'):
string = string.split('-', 1)[0]
elif cls.found_char(string, 'ubuntu'):
string = string.split('ubuntu', 1)[0]
if cls.found_char(string, '+'):
string = string.split('+', 1)[0]
return string
def __install(self, package) -> None:
"""
Wrapper around install_package
:param package: json object representing package
:return: void
"""
i = 0
for command in package['commands']:
i += 1
print('Command Description ' + str(i) + ': ' + str(command['commandDescription']))
print('Command :' + str(command['command']))
self.__bash_connector.install_package(command)
self.__packages_installed = self.__packages_installed + 1
@classmethod
def __is_installed(cls, version: str) -> bool:
"""
Checks if package is installed.
:param version: string version of the package
:return: boolean true/false
"""
if not version or version == "'b'":
return False
is_non_in_version = cls.found_char(version, 'none')
if is_non_in_version:
return False
return True
@classmethod
def __extract_version(cls, output: str):
"""
Gets the version of the package
:param output: string containing the version
or 'b if there is none
:return: the version of the package
"""
if not output:
return 0
tmp = output.split()
version = tmp[2]
return version
@classmethod
def __print_info(cls, package) -> None:
print('###################################################')
print('Installing : ' + package['name'])
print('Comments : ' + package['comment'])
print('Version : ' + package['version'])
def __run_package_installer(self, package):
if not package:
return
PackageInstaller.__print_info(package)
output = self.__bash_connector.apt_cache(package)
version = self.__extract_version(output)
if not self.__is_installed(version):
self.__bash_connector.update()
self.__install(package)
else:
version = PackageInstaller.remove_chars(version)
print('This Package is already installed! Version is ' + version + '\n')
def get_num_installed_packages(self) -> int:
return self.__packages_installed |
count = 0
count2 = 0
while True:
questions = set()
# 2nd part
everyone = set()
fst = True
try:
person = input()
while person != "":
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(x)
else:
this = set()
for x in person:
this.add(x)
everyone = everyone.intersection(this)
person = input()
fst = False
count += len(questions)
count2 += len(everyone)
except:
break
#print(questions)
count += len(questions)
count2 += len(everyone)
print(count)
print(count2) | count = 0
count2 = 0
while True:
questions = set()
everyone = set()
fst = True
try:
person = input()
while person != '':
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(x)
else:
this = set()
for x in person:
this.add(x)
everyone = everyone.intersection(this)
person = input()
fst = False
count += len(questions)
count2 += len(everyone)
except:
break
count += len(questions)
count2 += len(everyone)
print(count)
print(count2) |
class SerializerError(Exception):
def __init__(self, message):
self._message = message
class ValidationError(SerializerError):
pass
class InvalidSerializer(SerializerError):
pass
| class Serializererror(Exception):
def __init__(self, message):
self._message = message
class Validationerror(SerializerError):
pass
class Invalidserializer(SerializerError):
pass |
n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row))
# For the record, I feel dumb because it could be
# done with a single line of code
# a = [[abs(i - j) for j in range(n)] for i in range(n)]
| n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row)) |
#!/usr/bin/env python3
# https://abc102.contest.atcoder.jp/tasks/abc102_b
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
| n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0]) |
# Spiegelmann (9071005) | In Monster Park Maps
response = sm.sendAskYesNo("Do you want to leave?")
if response:
sm.warpInstanceOut(951000000)
| response = sm.sendAskYesNo('Do you want to leave?')
if response:
sm.warpInstanceOut(951000000) |
#!/usr/local/bin/python3
def main():
# Test suite
tests = [
[None, None], # Should throw a TypeError
[-1, None], # Should throw a ValueError
[0, 0],
[9, 9],
[138, 3],
[65536, 7]
]
print('Testing add_digits')
for item in tests:
try:
temp_result = add_digits(item[0])
if temp_result == item[1]:
print('PASSED: add_digits({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
print('\nTesting add_digits_digital_root')
for item in tests:
try:
temp_result = add_digits_digital_root(item[0])
if temp_result == item[1]:
print('PASSED: add_digits_digital_root({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits_digital_root({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
return 0
def add_digits(val):
'''
Sums the digits of an integer until it reduces to one digit
Input: val is non-negative integer
Output: single digit integer
Assumes no other data structure can be used
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
digit_sum = val
while digit_sum > 9:
# Sum the digits in integer
temp_sum = 0
while digit_sum > 0:
temp_sum += digit_sum % 10
digit_sum = digit_sum // 10
digit_sum = temp_sum
return digit_sum
def add_digits_digital_root(val):
'''
This is a digital root, can be solved taking % 9
Time: O(1)
Complexity: O(1)
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
if val == 0:
return 0
elif val % 9 == 0:
return 9
else:
return val % 9
if __name__ == '__main__':
main()
| def main():
tests = [[None, None], [-1, None], [0, 0], [9, 9], [138, 3], [65536, 7]]
print('Testing add_digits')
for item in tests:
try:
temp_result = add_digits(item[0])
if temp_result == item[1]:
print('PASSED: add_digits({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
print('\nTesting add_digits_digital_root')
for item in tests:
try:
temp_result = add_digits_digital_root(item[0])
if temp_result == item[1]:
print('PASSED: add_digits_digital_root({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits_digital_root({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
return 0
def add_digits(val):
"""
Sums the digits of an integer until it reduces to one digit
Input: val is non-negative integer
Output: single digit integer
Assumes no other data structure can be used
"""
if type(val) is not int:
raise type_error('Input must be an integer')
if val < 0:
raise value_error('Input must be non-negative')
digit_sum = val
while digit_sum > 9:
temp_sum = 0
while digit_sum > 0:
temp_sum += digit_sum % 10
digit_sum = digit_sum // 10
digit_sum = temp_sum
return digit_sum
def add_digits_digital_root(val):
"""
This is a digital root, can be solved taking % 9
Time: O(1)
Complexity: O(1)
"""
if type(val) is not int:
raise type_error('Input must be an integer')
if val < 0:
raise value_error('Input must be non-negative')
if val == 0:
return 0
elif val % 9 == 0:
return 9
else:
return val % 9
if __name__ == '__main__':
main() |
"""
Rules for representing package from package managers.
"""
_PACKAGE_JSON_TEMPLATE = "\"package\": \"{package}\", \"version\": \"{version}\", \"sum\": \"{sum}\""
def _package_json_impl(ctx):
ctx.actions.write(
output = ctx.outputs.manifest,
content = "{" + _PACKAGE_JSON_TEMPLATE.format(
package = ctx.attr.package,
version = ctx.attr.version,
sum = ctx.attr.sum,
) + "}",
)
package_json = rule(
implementation = _package_json_impl,
attrs = {
"package": attr.string(mandatory = True),
"version": attr.string(mandatory = True),
"sum": attr.string(mandatory = True),
},
outputs = {"manifest": "%{name}.json"},
)
| """
Rules for representing package from package managers.
"""
_package_json_template = '"package": "{package}", "version": "{version}", "sum": "{sum}"'
def _package_json_impl(ctx):
ctx.actions.write(output=ctx.outputs.manifest, content='{' + _PACKAGE_JSON_TEMPLATE.format(package=ctx.attr.package, version=ctx.attr.version, sum=ctx.attr.sum) + '}')
package_json = rule(implementation=_package_json_impl, attrs={'package': attr.string(mandatory=True), 'version': attr.string(mandatory=True), 'sum': attr.string(mandatory=True)}, outputs={'manifest': '%{name}.json'}) |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Most digits
#Problem level: 7 kyu
def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))]
| def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))] |
#!/usr/bin/env python3
def main():
# initialize round counter to 0 and answer to blank
round = 0
answer = " "
# set up loop
while round < 3 and (answer.lower() != "brian" and answer.lower() != "shrubbery"):
# increment round
round += 1
answer = input("Finish the movie title, \"Monty Python\'s The Life of ______: ")
# correct answer given
if answer.lower() == 'brian':
print('Correct')
elif answer.lower() == "shrubbery":
print("You gave the super secret answer")
# reached end of game with no correct answer
elif round==3:
print("Sorry, the answer was Brian.")
# loop back to beginning of while loop
else:
print("Sorry! Try again!")
main()
| def main():
round = 0
answer = ' '
while round < 3 and (answer.lower() != 'brian' and answer.lower() != 'shrubbery'):
round += 1
answer = input('Finish the movie title, "Monty Python\'s The Life of ______: ')
if answer.lower() == 'brian':
print('Correct')
elif answer.lower() == 'shrubbery':
print('You gave the super secret answer')
elif round == 3:
print('Sorry, the answer was Brian.')
else:
print('Sorry! Try again!')
main() |
def sentence_maker(phrase):
interrogatives = ("why","how","what")
capitalized = phrase.capitalize()
#startswith function checks whether the string starts with the given values
if phrase.startswith(interrogatives):
return f"{capitalized}?"
else:
return f"{capitalized}."
conversation = []
while True:
userInput = input("Say something: ")
if userInput == "\end":
if conversation.__len__() >= 0:
break
else:
conversation.append(sentence_maker(userInput))
print(" ".join(conversation)) | def sentence_maker(phrase):
interrogatives = ('why', 'how', 'what')
capitalized = phrase.capitalize()
if phrase.startswith(interrogatives):
return f'{capitalized}?'
else:
return f'{capitalized}.'
conversation = []
while True:
user_input = input('Say something: ')
if userInput == '\\end':
if conversation.__len__() >= 0:
break
else:
conversation.append(sentence_maker(userInput))
print(' '.join(conversation)) |
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
# O(n + m) time | O(1) space
# where 'n' is the length of row and 'm' is the length on column
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < row:
row += 1
else:
return [row, col]
return [-1, -1]
| def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < row:
row += 1
else:
return [row, col]
return [-1, -1] |
def get_variables():
return {
'SPECIAL_FUNC': {'hoge': 'fuga'}
}
| def get_variables():
return {'SPECIAL_FUNC': {'hoge': 'fuga'}} |
n=int(input())
numSwaps=0
a=list(map(int, input().strip().split()))
for i in range(n-1):
for j in range(n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
numSwaps+=1
print(f"Array is Sorted in {numSwaps} swaps")
print(f"First Element: {a[j]}")
print(f"Last Element: {a[j-1]}") | n = int(input())
num_swaps = 0
a = list(map(int, input().strip().split()))
for i in range(n - 1):
for j in range(n - i - 1):
if a[j] > a[j + 1]:
(a[j], a[j + 1]) = (a[j + 1], a[j])
num_swaps += 1
print(f'Array is Sorted in {numSwaps} swaps')
print(f'First Element: {a[j]}')
print(f'Last Element: {a[j - 1]}') |
"""
https://leetcode.com/problems/roman-to-integer/
"""
def roman_to_integer(s):
"""
This implementation passed all tests on submission January 18, 2022.
There's not too much any other way of implementing this, am I right? You
really just have encode each of the rules that are stated.
"""
o = list()
did_a_skip = False
for index, item in enumerate(s):
if did_a_skip:
did_a_skip = not did_a_skip
continue
if item == 'V':
o.append(5)
elif item == 'L':
o.append(50)
elif item == 'D':
o.append(500)
if item == 'I':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'V':
o.append(4)
did_a_skip = True
elif next_value == 'X':
o.append(9)
did_a_skip = True
else:
o.append(1)
else:
o.append(1)
elif item == 'X':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'L':
o.append(40)
did_a_skip = True
elif next_value == 'C':
o.append(90)
did_a_skip = True
else:
o.append(10)
else:
o.append(10)
elif item == 'C':
if (index+1) != len(s):
next_value = s[index+1]
if next_value == 'D':
o.append(400)
did_a_skip = True
elif next_value == 'M':
o.append(900)
did_a_skip = True
else:
o.append(100)
else:
o.append(100)
elif item == 'M':
o.append(1000)
return sum(o)
if __name__ == '__main__':
assert roman_to_integer("III") == 3
assert roman_to_integer("MCMXCIV") == 1994
assert roman_to_integer("DCXXI") == 621
| """
https://leetcode.com/problems/roman-to-integer/
"""
def roman_to_integer(s):
"""
This implementation passed all tests on submission January 18, 2022.
There's not too much any other way of implementing this, am I right? You
really just have encode each of the rules that are stated.
"""
o = list()
did_a_skip = False
for (index, item) in enumerate(s):
if did_a_skip:
did_a_skip = not did_a_skip
continue
if item == 'V':
o.append(5)
elif item == 'L':
o.append(50)
elif item == 'D':
o.append(500)
if item == 'I':
if index + 1 != len(s):
next_value = s[index + 1]
if next_value == 'V':
o.append(4)
did_a_skip = True
elif next_value == 'X':
o.append(9)
did_a_skip = True
else:
o.append(1)
else:
o.append(1)
elif item == 'X':
if index + 1 != len(s):
next_value = s[index + 1]
if next_value == 'L':
o.append(40)
did_a_skip = True
elif next_value == 'C':
o.append(90)
did_a_skip = True
else:
o.append(10)
else:
o.append(10)
elif item == 'C':
if index + 1 != len(s):
next_value = s[index + 1]
if next_value == 'D':
o.append(400)
did_a_skip = True
elif next_value == 'M':
o.append(900)
did_a_skip = True
else:
o.append(100)
else:
o.append(100)
elif item == 'M':
o.append(1000)
return sum(o)
if __name__ == '__main__':
assert roman_to_integer('III') == 3
assert roman_to_integer('MCMXCIV') == 1994
assert roman_to_integer('DCXXI') == 621 |
# Has the same id
a = [1, 2, 3]
c = a
print(id(a), id(c))
# Has a different id
b = 42
print(id(b))
b = '42'
print(id(b))
| a = [1, 2, 3]
c = a
print(id(a), id(c))
b = 42
print(id(b))
b = '42'
print(id(b)) |
class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0. if higher else 1. for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self.scores
def update(self, scores, epoch):
self.present = scores
self.epoch = epoch
self.best = [max(best, score) if self.highers[idx] else min(best, score) for idx, (best, score) in enumerate(zip(self.best, scores))]
self.best_epoch = [epoch if present == best else best_epoch for present, best, best_epoch in zip(self.present, self.best, self.best_epoch)]
saves = [epoch == best_epoch for best_epoch in self.best_epoch]
return saves
def print_present(self):
m_str = '{} : {:.4f}, {} : {:.4f} on ' + self.name
m_list = []
for metric, present in zip(self.metrics, self.present):
m_list.append(metric)
m_list.append(present)
print(m_str.format(*m_list))
def print_best(self):
m_str = 'Best score: {}_{} : {:.4f}, {}_{} : {:.4f} on ' + self.name
m_list = []
for metric, best, best_epoch in zip(self.metrics, self.best, self.best_epoch):
m_list.append(metric)
m_list.append(best_epoch)
m_list.append(best)
print(m_str.format(*m_list))
| class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0.0 if higher else 1.0 for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self.scores
def update(self, scores, epoch):
self.present = scores
self.epoch = epoch
self.best = [max(best, score) if self.highers[idx] else min(best, score) for (idx, (best, score)) in enumerate(zip(self.best, scores))]
self.best_epoch = [epoch if present == best else best_epoch for (present, best, best_epoch) in zip(self.present, self.best, self.best_epoch)]
saves = [epoch == best_epoch for best_epoch in self.best_epoch]
return saves
def print_present(self):
m_str = '{} : {:.4f}, {} : {:.4f} on ' + self.name
m_list = []
for (metric, present) in zip(self.metrics, self.present):
m_list.append(metric)
m_list.append(present)
print(m_str.format(*m_list))
def print_best(self):
m_str = 'Best score: {}_{} : {:.4f}, {}_{} : {:.4f} on ' + self.name
m_list = []
for (metric, best, best_epoch) in zip(self.metrics, self.best, self.best_epoch):
m_list.append(metric)
m_list.append(best_epoch)
m_list.append(best)
print(m_str.format(*m_list)) |
mysql = {
'user': 'scott',
'password': 'password',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
}
| mysql = {'user': 'scott', 'password': 'password', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True} |
# Author: allannozomu
# Runtime: 544 ms
# Memory: 19.8 MB
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if (A[0] < A[-1]):
ordered = sorted(A)
else:
ordered = sorted(A, reverse = True)
return ordered == A
| class Solution:
def is_monotonic(self, A: List[int]) -> bool:
if A[0] < A[-1]:
ordered = sorted(A)
else:
ordered = sorted(A, reverse=True)
return ordered == A |
def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[" " for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1,2,2,2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) / 2)
i = 0
x = pivot
y = pivot
while len(slowo):
elem = slowo[:kon[i]]
for j in range(len(elem)):
ukl[y][x] = elem[j]
ii = i
if j == len(elem) - 1 and i != 0:
ii += 1
if ii % 4 == 0:
y += 1
elif ii % 4 == 1:
x += 1
elif ii % 4 == 2:
y -= 1
elif ii % 4 == 3:
x -= 1
slowo = slowo[kon[i]:]
i += 1
wynik = ""
for line in ukl[::-1]:
for l in line:
if l != ' ':
wynik += l
return wynik
| def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[' ' for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1, 2, 2, 2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) / 2)
i = 0
x = pivot
y = pivot
while len(slowo):
elem = slowo[:kon[i]]
for j in range(len(elem)):
ukl[y][x] = elem[j]
ii = i
if j == len(elem) - 1 and i != 0:
ii += 1
if ii % 4 == 0:
y += 1
elif ii % 4 == 1:
x += 1
elif ii % 4 == 2:
y -= 1
elif ii % 4 == 3:
x -= 1
slowo = slowo[kon[i]:]
i += 1
wynik = ''
for line in ukl[::-1]:
for l in line:
if l != ' ':
wynik += l
return wynik |
class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
# list of dicts with passenger attributes
self.passengers = []
def __getattr__(self, item):
"""
Called when unknown attribute is about to be fetched
:param item:
:return:
"""
# Always raise this error in common situations
raise AttributeError
def __getattribute__(self, item):
"""
Called when any attribute is about to be fetched
:param item:
:return:
"""
# You can get attributes in a different way here
# When an unknown attribute called, this method calls the above method
print(f'Getting {item}')
return object.__getattribute__(self, item)
def __setattr__(self, key, value):
"""
Setting the attribute with key - value
:param key:
:param value:
:return:
"""
print(f'Setting {key} with {value}')
super().__setattr__(key, value)
def __delattr__(self, item):
"""
Removes attribute from the class instance
:param item:
:return:
"""
# This method will be called on "del attribute_name"
super().__delattr__(item)
# Vessel methods
def pump_in_fuel(self, quantity: float):
self.fuel += quantity
def pump_out_fuel(self):
self.fuel = 0.0
def discharge_passengers(self):
self.passengers = []
if __name__ == '__main__':
# Runtime tests will be here
vsl = Vessel('Casandra')
vsl.pump_in_fuel(10.5)
vsl.passengers = [
{
'name': 'Peter'
},
{
'name': 'Jessika'
}
]
| class Vessel:
def __init__(self, name: str):
"""
Initializing class instance with vessel name
:param name:
"""
self.name = name
self.fuel = 0.0
self.passengers = []
def __getattr__(self, item):
"""
Called when unknown attribute is about to be fetched
:param item:
:return:
"""
raise AttributeError
def __getattribute__(self, item):
"""
Called when any attribute is about to be fetched
:param item:
:return:
"""
print(f'Getting {item}')
return object.__getattribute__(self, item)
def __setattr__(self, key, value):
"""
Setting the attribute with key - value
:param key:
:param value:
:return:
"""
print(f'Setting {key} with {value}')
super().__setattr__(key, value)
def __delattr__(self, item):
"""
Removes attribute from the class instance
:param item:
:return:
"""
super().__delattr__(item)
def pump_in_fuel(self, quantity: float):
self.fuel += quantity
def pump_out_fuel(self):
self.fuel = 0.0
def discharge_passengers(self):
self.passengers = []
if __name__ == '__main__':
vsl = vessel('Casandra')
vsl.pump_in_fuel(10.5)
vsl.passengers = [{'name': 'Peter'}, {'name': 'Jessika'}] |
class Error(Exception):
pass
class InvalidTypeError(Error):
pass
class InvalidArgumentError(Error):
pass
| class Error(Exception):
pass
class Invalidtypeerror(Error):
pass
class Invalidargumenterror(Error):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.