content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
"""
Continuing from following challenge and using subroutines where appropriate:
1. Create a text file with the following data:
James,Jones,01/01/99
Sarah,Smith,12/12/99
Bobby,Ball,04/04/99
Harry.Hall,06/06/99
2. Create a subroutine to ask the user for the name of the file that they wish to read from
3. Use a loop to read and output each line.
"""
def getFileName():
my_file = input("What is the name of the file you would like to read from?: ")
return my_file + ".txt"
the_file = getFileName()
try:
# opens the file
fileName = open(the_file, "r")
except IOError as e:
# the exception is stored in the variable e
print("The exception", e, "was raised.")
else:
fileRead = fileName.readlines()
for line in fileRead:
print(line, end="")
fileName.close()
|
"""
Continuing from following challenge and using subroutines where appropriate:
1. Create a text file with the following data:
James,Jones,01/01/99
Sarah,Smith,12/12/99
Bobby,Ball,04/04/99
Harry.Hall,06/06/99
2. Create a subroutine to ask the user for the name of the file that they wish to read from
3. Use a loop to read and output each line.
"""
def get_file_name():
my_file = input('What is the name of the file you would like to read from?: ')
return my_file + '.txt'
the_file = get_file_name()
try:
file_name = open(the_file, 'r')
except IOError as e:
print('The exception', e, 'was raised.')
else:
file_read = fileName.readlines()
for line in fileRead:
print(line, end='')
fileName.close()
|
n = 0
try:
i = 0
while True:
m = input()
if m[0] == '+':
n += 1
elif m[0] == '-':
n -= 1
else:
i += (len(m.split(':')[1]) * n)
except:
pass
print(i)
|
n = 0
try:
i = 0
while True:
m = input()
if m[0] == '+':
n += 1
elif m[0] == '-':
n -= 1
else:
i += len(m.split(':')[1]) * n
except:
pass
print(i)
|
def box(m):
m = m.lower() # converting lowercase
arr = [0] * len(m) # initializing array with same length as the length
i = 0
for n in m:
if not ('a' <= n <= 'z'): # excluding special characters
continue
arr[i] = ord(n) - ord('a') # subtracting ascii character values by a so we can map it to 0-25
i += 1
arr_f = arr[0:i] # array final - to exclude the special character in the array
return arr_f
def lock(arr_f, y):
a = len(arr_f)
k = box(y)
b = 1
while b < a: # using the loop to make the keys array
k.append(k[b - 1])
b += 1
enc = [0] * len(arr_f) # initializing array
i = 0
for x in arr_f:
enc[i] = (x + k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a
i += 1
enc_f = enc[0:i]
return enc_f
def unbox(enc_f):
m = ""
for x in enc_f:
m += chr(x + ord('a'))
return m
def encrypt(m, k):
arr = box(m)
enc = lock(arr, k)
c = unbox(enc)
return c
def decrypt(c, y):
cipher = box(c)
a = len(c)
k = box(y)
b = 1
while b < a: # using the loop to make the keys array
k.append(k[b - 1])
b += 1
dec = [0] * len(c) # initializing array
i = 0
for x in cipher:
dec[i] = (x - k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a
i += 1
dec_f = dec[0:i]
plain = unbox(dec_f)
return plain
def prob(m):
a = box(m)
b = len(a)
arr = [0] * 26
arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001]
# arr1 is the probability distribution for general english taken from a study resource (professor's video online)
j = 0
while j < 26: #these loops are counting the number of letters in the message
ctr = 0
i = 0
while i < b:
if a[i] == j:
ctr += 1
arr[j] = ctr
i += 1
j += 1
k = 0
while k < 26:
arr[k] = (arr[k]/b) * (arr1[k])
k += 1
return arr
def prob1(m):
a = box(m)
b = len(a)
arr = [0] * 26
arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001]
# arr1 is the probability distribution for general english taken from a study resource (professor's video online)
j = 0
while j < 26: #these loops are counting the number of letters in the message
ctr = 0
i = 0
while i < b:
if a[i] == j:
ctr += 1
arr[j] = ctr
i += 1
j += 1
k = 0
while k < 26:
arr[k] = (arr[k]/b) * (arr[k]/b)
k += 1
return arr
def sum_prob(arr):
s = 0
for i in arr:
s = s + i
return s
def seperate(m, size):
source = box(m) # putting the message in the array
return [source[i::size] for i in range(size)] # (Condensed everything in one line) seperating that array into a nested array of the specified size chunks
|
def box(m):
m = m.lower()
arr = [0] * len(m)
i = 0
for n in m:
if not 'a' <= n <= 'z':
continue
arr[i] = ord(n) - ord('a')
i += 1
arr_f = arr[0:i]
return arr_f
def lock(arr_f, y):
a = len(arr_f)
k = box(y)
b = 1
while b < a:
k.append(k[b - 1])
b += 1
enc = [0] * len(arr_f)
i = 0
for x in arr_f:
enc[i] = (x + k[i]) % 26
i += 1
enc_f = enc[0:i]
return enc_f
def unbox(enc_f):
m = ''
for x in enc_f:
m += chr(x + ord('a'))
return m
def encrypt(m, k):
arr = box(m)
enc = lock(arr, k)
c = unbox(enc)
return c
def decrypt(c, y):
cipher = box(c)
a = len(c)
k = box(y)
b = 1
while b < a:
k.append(k[b - 1])
b += 1
dec = [0] * len(c)
i = 0
for x in cipher:
dec[i] = (x - k[i]) % 26
i += 1
dec_f = dec[0:i]
plain = unbox(dec_f)
return plain
def prob(m):
a = box(m)
b = len(a)
arr = [0] * 26
arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024, 0.067, 0.075, 0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01, 0.023, 0.001, 0.02, 0.001]
j = 0
while j < 26:
ctr = 0
i = 0
while i < b:
if a[i] == j:
ctr += 1
arr[j] = ctr
i += 1
j += 1
k = 0
while k < 26:
arr[k] = arr[k] / b * arr1[k]
k += 1
return arr
def prob1(m):
a = box(m)
b = len(a)
arr = [0] * 26
arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024, 0.067, 0.075, 0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01, 0.023, 0.001, 0.02, 0.001]
j = 0
while j < 26:
ctr = 0
i = 0
while i < b:
if a[i] == j:
ctr += 1
arr[j] = ctr
i += 1
j += 1
k = 0
while k < 26:
arr[k] = arr[k] / b * (arr[k] / b)
k += 1
return arr
def sum_prob(arr):
s = 0
for i in arr:
s = s + i
return s
def seperate(m, size):
source = box(m)
return [source[i::size] for i in range(size)]
|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
class Job:
def __init__(self, job: dict):
self.display_name = job.get("displayName")
self.id = job.get("id")
self.group = job.get("group")
self.status = job.get("status")
self.data = job.get("data")
self.description = job.get("description")
self.batch = job.get("batch")
self.cancellation_threshold = job.get("cancellationThreshold")
|
class Job:
def __init__(self, job: dict):
self.display_name = job.get('displayName')
self.id = job.get('id')
self.group = job.get('group')
self.status = job.get('status')
self.data = job.get('data')
self.description = job.get('description')
self.batch = job.get('batch')
self.cancellation_threshold = job.get('cancellationThreshold')
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def grpc_rules_repository():
http_archive(
name = "rules_proto_grpc",
urls = ["https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz"],
sha256 = "d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33",
strip_prefix = "rules_proto_grpc-2.0.0",
)
|
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def grpc_rules_repository():
http_archive(name='rules_proto_grpc', urls=['https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz'], sha256='d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33', strip_prefix='rules_proto_grpc-2.0.0')
|
class Embed:
def __init__(self, **kwargs):
allowed_args = ("title", "description", "color")
for key, value in kwargs.items():
if key in allowed_args:
setattr(self, key, value)
def set_image(self, *, url: str):
self.image = {"url": url}
def set_thumbnail(self, *, url: str):
self.thumbnail = {"url": url}
def set_footer(self, *, text: str, icon_url: str = None):
self.footer = {"text": text}
if icon_url:
self.footer["icon_url"] = icon_url
def set_author(self, *, name: str, icon_url: str = None):
self.author = {"name": name}
if icon_url:
self.author["icon_url"] = icon_url
def add_field(self, *, name: str, value: str, inline: bool = False):
if not hasattr(self, "fields"):
self.fields = []
self.fields.append({
"name": name,
"value": value,
"inline": inline
})
|
class Embed:
def __init__(self, **kwargs):
allowed_args = ('title', 'description', 'color')
for (key, value) in kwargs.items():
if key in allowed_args:
setattr(self, key, value)
def set_image(self, *, url: str):
self.image = {'url': url}
def set_thumbnail(self, *, url: str):
self.thumbnail = {'url': url}
def set_footer(self, *, text: str, icon_url: str=None):
self.footer = {'text': text}
if icon_url:
self.footer['icon_url'] = icon_url
def set_author(self, *, name: str, icon_url: str=None):
self.author = {'name': name}
if icon_url:
self.author['icon_url'] = icon_url
def add_field(self, *, name: str, value: str, inline: bool=False):
if not hasattr(self, 'fields'):
self.fields = []
self.fields.append({'name': name, 'value': value, 'inline': inline})
|
a = 7
b = 3
def func1(c,d):
e = c + d
e += c
e *= d
return e
f = func1(a,b)
print (f)
|
a = 7
b = 3
def func1(c, d):
e = c + d
e += c
e *= d
return e
f = func1(a, b)
print(f)
|
a: str
a: bool = True
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
|
a: str
a: bool = True
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
|
class Edge(object):
def __init__(self, u, v, w):
self.__orig = u
self.__dest = v
self.__w = w
def getOrig(self):
return self.__orig
def getDest(self):
return self.__dest
def getW(self):
return self.__w
|
class Edge(object):
def __init__(self, u, v, w):
self.__orig = u
self.__dest = v
self.__w = w
def get_orig(self):
return self.__orig
def get_dest(self):
return self.__dest
def get_w(self):
return self.__w
|
"""
Subtree of Another Tree:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
https://leetcode.com/problems/subtree-of-another-tree/
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
return self.traverse(s, t)
def traverse(self, s, t):
if self.checkSubTreeFunction(s, t) == True:
return True
if s is None:
return False
return self.traverse(s.left, t) or self.traverse(s.right, t)
def checkSubTreeFunction(self, s, t):
if s == None and t == None:
return True
elif s == None or t == None or s.val != t.val:
return False
return self.checkSubTreeFunction(s.left, t.left) and self.checkSubTreeFunction(s.right, t.right)
|
"""
Subtree of Another Tree:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
https://leetcode.com/problems/subtree-of-another-tree/
"""
class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_subtree(self, s: TreeNode, t: TreeNode) -> bool:
return self.traverse(s, t)
def traverse(self, s, t):
if self.checkSubTreeFunction(s, t) == True:
return True
if s is None:
return False
return self.traverse(s.left, t) or self.traverse(s.right, t)
def check_sub_tree_function(self, s, t):
if s == None and t == None:
return True
elif s == None or t == None or s.val != t.val:
return False
return self.checkSubTreeFunction(s.left, t.left) and self.checkSubTreeFunction(s.right, t.right)
|
class UltrasonicSensor:
def __init__(self, megapi, slot):
self._megapi = megapi
self._slot = slot
self._last_val = 400
def read(self):
self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read)
def get_value(self):
return self._last_val
def _on_forward_ultrasonic_read(self, val):
self._last_val = val
|
class Ultrasonicsensor:
def __init__(self, megapi, slot):
self._megapi = megapi
self._slot = slot
self._last_val = 400
def read(self):
self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read)
def get_value(self):
return self._last_val
def _on_forward_ultrasonic_read(self, val):
self._last_val = val
|
def f(t):
# relation between f and t
return value
def rxn1(C,t):
return np.array([f(t)*C0/v-f(t)*C[0]/v-k*C[0], f(t)*C[0]/v-f(t)*C[1]/v-k*C[1]])
|
def f(t):
return value
def rxn1(C, t):
return np.array([f(t) * C0 / v - f(t) * C[0] / v - k * C[0], f(t) * C[0] / v - f(t) * C[1] / v - k * C[1]])
|
#Three Restaurant:
class Restaurant():
"""A simple attempt to make class restaurant. """
def __init__(self, restaurant_name, cuisine_type):
""" This is to initialize name and type of restaurant"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
""" This method describes the Restaurant"""
print("Restaurant name :",self.restaurant_name.title())
print("Its Cuisine Type:",self.cuisine_type.title())
def open_restaurant(self):
print("The restaurant is open.")
restaurant1 = Restaurant('startbucks','coffee')
restaurant2 = Restaurant('macdonalds','burger')
restaurant3 = Restaurant('meghana','biryani')
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
|
class Restaurant:
"""A simple attempt to make class restaurant. """
def __init__(self, restaurant_name, cuisine_type):
""" This is to initialize name and type of restaurant"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
""" This method describes the Restaurant"""
print('Restaurant name :', self.restaurant_name.title())
print('Its Cuisine Type:', self.cuisine_type.title())
def open_restaurant(self):
print('The restaurant is open.')
restaurant1 = restaurant('startbucks', 'coffee')
restaurant2 = restaurant('macdonalds', 'burger')
restaurant3 = restaurant('meghana', 'biryani')
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
|
name = input("what is your name? ")
age = int(input("how old are you {0}? ".format(name)))
if (18 <= age < 31):
print("welcome to holiday")
else:
print("you are not 18-30")
|
name = input('what is your name? ')
age = int(input('how old are you {0}? '.format(name)))
if 18 <= age < 31:
print('welcome to holiday')
else:
print('you are not 18-30')
|
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single quotes to enclose the formatted code block.
"""
challenge_code = '''aux = [0, 1]
main = 2
all_bits = range(3)
dev = qml.device("default.qubit", wires=all_bits)
# Part (i)
@qml.qnode(dev)
def first_approx(t):
##################
# YOUR CODE HERE #
##################
return qml.state()
# Part (ii)
@qml.qnode(dev)
def second_approx(t):
##################
# YOUR CODE HERE #
##################
return qml.state()
# Part (iii)
@qml.qnode(dev)
def full_series(t):
##################
# YOUR CODE HERE #
##################
return qml.state()
##################
# HIT SUBMIT FOR #
# PLOTTING MAGIC #
##################
'''
|
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single quotes to enclose the formatted code block.
"""
challenge_code = 'aux = [0, 1]\nmain = 2\nall_bits = range(3)\ndev = qml.device("default.qubit", wires=all_bits)\n\n# Part (i)\n\n@qml.qnode(dev)\ndef first_approx(t):\n ##################\n # YOUR CODE HERE #\n ##################\n return qml.state()\n\n# Part (ii)\n\n@qml.qnode(dev)\ndef second_approx(t):\n ##################\n # YOUR CODE HERE #\n ##################\n return qml.state()\n\n# Part (iii)\n\n@qml.qnode(dev)\ndef full_series(t):\n ##################\n # YOUR CODE HERE #\n ##################\n return qml.state()\n\n##################\n# HIT SUBMIT FOR #\n# PLOTTING MAGIC #\n##################\n'
|
a,b = map(int,input().split())
def multiply(a,b):
return a*b
print(multiply(a,b))
|
(a, b) = map(int, input().split())
def multiply(a, b):
return a * b
print(multiply(a, b))
|
class CoordLinkedList:
# a linked list object
def __init__ (self,node=None,y=None,x=None,up=None,down=None,left=None,right=None):
self.up = up
self.down = down
self.left = left
self.right = right
if isinstance(node,(list,set,tuple)) and len(node) == 2:
self.node = tuple(node)
elif x and y:
self.node = (y,x)
def receive (self,nodes):
if not isinstance(nodes,(list,set,tuple)):
nodes = {nodes}
for n in nodes:
if isinstance(n,(tuple)) and len(n) == 2:
if n == (self.node[0]-1,self.node[1]):
self.up = n
elif n == (self.node[0]+1,self.node[1]):
self.down = n
elif n == (self.node[0],self.node[1]+1):
self.right = n
elif n == (self.node[0],self.node[1]-1):
self.left = n
def send(self,nodes=None):
if not nodes:
nodes = []
returnlist = []
if self.down:
returnlist.append(self.down)
if self.up:
returnlist.append(self.up)
if self.left:
returnlist.append(self.left)
if self.right:
returnlist.append(self.right)
return [x for x in returnlist if x not in nodes]
|
class Coordlinkedlist:
def __init__(self, node=None, y=None, x=None, up=None, down=None, left=None, right=None):
self.up = up
self.down = down
self.left = left
self.right = right
if isinstance(node, (list, set, tuple)) and len(node) == 2:
self.node = tuple(node)
elif x and y:
self.node = (y, x)
def receive(self, nodes):
if not isinstance(nodes, (list, set, tuple)):
nodes = {nodes}
for n in nodes:
if isinstance(n, tuple) and len(n) == 2:
if n == (self.node[0] - 1, self.node[1]):
self.up = n
elif n == (self.node[0] + 1, self.node[1]):
self.down = n
elif n == (self.node[0], self.node[1] + 1):
self.right = n
elif n == (self.node[0], self.node[1] - 1):
self.left = n
def send(self, nodes=None):
if not nodes:
nodes = []
returnlist = []
if self.down:
returnlist.append(self.down)
if self.up:
returnlist.append(self.up)
if self.left:
returnlist.append(self.left)
if self.right:
returnlist.append(self.right)
return [x for x in returnlist if x not in nodes]
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
data = []
def traverse(node):
if node.left:
traverse(node.left)
data.append(node.val)
if node.right:
traverse(node.right)
traverse(root)
return data[k - 1]
|
class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
data = []
def traverse(node):
if node.left:
traverse(node.left)
data.append(node.val)
if node.right:
traverse(node.right)
traverse(root)
return data[k - 1]
|
# List custom images
def list_custom_images_subparser(subparser):
list_images = subparser.add_parser(
'list-custom-images',
description=('***List custom'
' saved images of'
' producers/consumers'
' account'),
help=('List custom'
' saved images of'
' producers/consumers'
' account'))
group_key = list_images.add_mutually_exclusive_group(required=True)
group_key.add_argument('-pn',
'--producer-username',
help="Producer\'s(source account) username")
group_key.add_argument('-cn',
'--consumer-username',
dest='producer_username',
metavar='CONSUMER_USERNAME',
help="Consumer\'s(destination account) username")
group_apikey = list_images.add_mutually_exclusive_group(required=True)
group_apikey.add_argument('-pa',
'--producer-apikey',
help="Producer\'s(source account) apikey")
group_apikey.add_argument('-ca',
'--consumer-apikey',
dest='producer_apikey',
metavar='CONSUMER_APIKEY',
help="Consumer\'s(destination account) apikey")
list_images.add_argument('-u',
'--uuid',
help="Image ID number")
|
def list_custom_images_subparser(subparser):
list_images = subparser.add_parser('list-custom-images', description='***List custom saved images of producers/consumers account', help='List custom saved images of producers/consumers account')
group_key = list_images.add_mutually_exclusive_group(required=True)
group_key.add_argument('-pn', '--producer-username', help="Producer's(source account) username")
group_key.add_argument('-cn', '--consumer-username', dest='producer_username', metavar='CONSUMER_USERNAME', help="Consumer's(destination account) username")
group_apikey = list_images.add_mutually_exclusive_group(required=True)
group_apikey.add_argument('-pa', '--producer-apikey', help="Producer's(source account) apikey")
group_apikey.add_argument('-ca', '--consumer-apikey', dest='producer_apikey', metavar='CONSUMER_APIKEY', help="Consumer's(destination account) apikey")
list_images.add_argument('-u', '--uuid', help='Image ID number')
|
"""
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. There's actually a cool trick for this! Feel free to look at the solutions if you can't figure it out.
"""
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
# 0 1 2
# 3 4 5
# 6 7 8
# 9 10 11
#
# Transpose : [data]^T
#
# 0 3 6 9
# 1 4 7 10
# 2 5 8 11
data_transpose = tuple(zip(*data))
print(data)
print(data_transpose)
|
"""
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. There's actually a cool trick for this! Feel free to look at the solutions if you can't figure it out.
"""
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data)
print(data_transpose)
|
#
# @lc app=leetcode id=543 lang=python3
#
# [543] Diameter of Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
self.ans = 0
self.pathfinder(root)
return self.ans
def pathfinder(self, root):
if root is None:
return 0
lh = self.pathfinder(root.left)
rh = self.pathfinder(root.right)
self.ans = max(self.ans, lh + rh)
return max(lh, rh) + 1
# @lc code=end
|
class Solution:
def diameter_of_binary_tree(self, root):
self.ans = 0
self.pathfinder(root)
return self.ans
def pathfinder(self, root):
if root is None:
return 0
lh = self.pathfinder(root.left)
rh = self.pathfinder(root.right)
self.ans = max(self.ans, lh + rh)
return max(lh, rh) + 1
|
VISUALIZATION_CONFIG = {
'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'],
'visualization_name': 'datagramas.cartogram',
'figure_id': None,
'container_type': 'svg',
'data': {
'geometry': None,
'area_dataframe': None,
},
'options': {
},
'variables': {
'width': 960,
'height': 500,
'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0},
'feature_id': 'id',
'label': True,
'path_opacity': 1.0,
'path_stroke': 'gray',
'path_stroke_width': 1.0,
'fill_color': 'none',
'area_value': 'value',
'area_feature_name': 'id',
'area_opacity': 0.75,
'area_transition_delay': 0,
'feature_name': None,
'label_font_size': 10,
'label_color': 'black',
'bounding_box': None,
'na_value': 0.000001
},
'colorables': {
'area_color': {'value': None, 'palette': None, 'scale': None, 'n_colors': None, 'legend': False},
},
'auxiliary': {
'path',
'projection',
'original_geometry',
'area_colors',
'area_carto_values'
}
}
|
visualization_config = {'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'], 'visualization_name': 'datagramas.cartogram', 'figure_id': None, 'container_type': 'svg', 'data': {'geometry': None, 'area_dataframe': None}, 'options': {}, 'variables': {'width': 960, 'height': 500, 'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}, 'feature_id': 'id', 'label': True, 'path_opacity': 1.0, 'path_stroke': 'gray', 'path_stroke_width': 1.0, 'fill_color': 'none', 'area_value': 'value', 'area_feature_name': 'id', 'area_opacity': 0.75, 'area_transition_delay': 0, 'feature_name': None, 'label_font_size': 10, 'label_color': 'black', 'bounding_box': None, 'na_value': 1e-06}, 'colorables': {'area_color': {'value': None, 'palette': None, 'scale': None, 'n_colors': None, 'legend': False}}, 'auxiliary': {'path', 'projection', 'original_geometry', 'area_colors', 'area_carto_values'}}
|
class Solution(object):
def reconstructQueue(self, people):
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
m = int(input())
k = Solution()
array_input = []
for x in range(m):
array_input.append([int(y) for y in input().split()])
gh =k.reconstructQueue(array_input)
for s in gh:
print(*s)
|
class Solution(object):
def reconstruct_queue(self, people):
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
m = int(input())
k = solution()
array_input = []
for x in range(m):
array_input.append([int(y) for y in input().split()])
gh = k.reconstructQueue(array_input)
for s in gh:
print(*s)
|
def pent_d(n=1, pents=set()):
while True:
p_n = n*(3*n - 1)//2
for p in pents:
if p_n - p in pents and 2*p - p_n in pents:
return 2*p - p_n
pents.add(p_n)
n += 1
print(pent_d())
# Copyright Junipyr. All rights reserved.
# https://github.com/Junipyr
|
def pent_d(n=1, pents=set()):
while True:
p_n = n * (3 * n - 1) // 2
for p in pents:
if p_n - p in pents and 2 * p - p_n in pents:
return 2 * p - p_n
pents.add(p_n)
n += 1
print(pent_d())
|
n = int(input())
for i in range(n):
vet = list(map(int, input().split()))
partida = vet[0]
qtd = vet[1]
if partida % 2 == 0:
partida += 1
soma = 0
for j in range(qtd):
soma += partida
partida += 2
print(soma)
|
n = int(input())
for i in range(n):
vet = list(map(int, input().split()))
partida = vet[0]
qtd = vet[1]
if partida % 2 == 0:
partida += 1
soma = 0
for j in range(qtd):
soma += partida
partida += 2
print(soma)
|
# Scrapy settings for Scrapy project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'scrapy_demo'
SPIDER_MODULES = ['Scrapy.spiders'] # look for spiders here
NEWSPIDER_MODULE = 'Scrapy.spiders' # create new spiders here
LOG_LEVEL='INFO'
# enable following lines for testing ---
CLOSESPIDER_PAGECOUNT = 20 # test a few pages
# ---
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Scrapy Demo'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Image pipelin settings
IMAGES_EXPIRES = 1 # 1 days of delay for images expiration
IMAGES_STORE = './images'
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'scrapy.pipelines.images.ImagesPipeline': 1,
'Scrapy.pipelines.BookPipeline': 300
}
|
bot_name = 'scrapy_demo'
spider_modules = ['Scrapy.spiders']
newspider_module = 'Scrapy.spiders'
log_level = 'INFO'
closespider_pagecount = 20
user_agent = 'Scrapy Demo'
robotstxt_obey = False
images_expires = 1
images_store = './images'
item_pipelines = {'scrapy.pipelines.images.ImagesPipeline': 1, 'Scrapy.pipelines.BookPipeline': 300}
|
# Copyright 2020 Adobe. All rights reserved.
# This file is licensed to you 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 REPRESENTATIONS
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
load("@io_bazel_rules_docker//container:providers.bzl", "PushInfo")
load(
"@io_bazel_rules_docker//skylib:path.bzl",
_get_runfile_path = "runfile",
)
load("//skylib:providers.bzl", "ImagePushesInfo")
load("//skylib/workspace:aspect.bzl", "pushable_aspect")
def _file_to_runfile(ctx, file):
return file.owner.workspace_root or ctx.workspace_name + "/" + file.short_path
def _workspace_impl(ctx):
transitive_executables = []
transitive_runfiles = []
transitive_data = []
for t in ctx.attr.data:
transitive_data.append(t[DefaultInfo].files)
# flatten & 'uniquify' our list of asset files
data = depset(transitive = transitive_data).to_list()
runfiles = depset(transitive = transitive_runfiles).to_list()
files = []
tars = []
for src in ctx.attr.srcs:
tar = src.files.to_list()[0]
tars.append(tar)
rf = ctx.runfiles(files = runfiles + data + tars + ctx.files._bash_runfiles)
trans_img_pushes = []
if ctx.attr.push:
trans_img_pushes = depset(transitive = [
obj[ImagePushesInfo].image_pushes
for obj in ctx.attr.srcs
if ImagePushesInfo in obj
]).to_list()
files += [obj.files_to_run.executable for obj in trans_img_pushes]
for obj in trans_img_pushes:
rf = rf.merge(obj[DefaultInfo].default_runfiles)
ctx.actions.expand_template(
template = ctx.file._template,
substitutions = {
"%{workspace_tar_targets}": " ".join([json.encode(_file_to_runfile(ctx, t)) for t in tars]),
"%{push_targets}": " ".join([json.encode(_file_to_runfile(ctx, exe.files_to_run.executable)) for exe in trans_img_pushes]),
# "async $(rlocation metered/%s)" % exe.files_to_run.executable.short_path
},
output = ctx.outputs.executable,
)
return [
DefaultInfo(
files = depset(files),
runfiles = rf,
),
ImagePushesInfo(
image_pushes = depset(
transitive = [
obj[ImagePushesInfo].image_pushes
for obj in ctx.attr.srcs
if ImagePushesInfo in obj
],
),
),
]
workspace = rule(
implementation = _workspace_impl,
attrs = {
"srcs": attr.label_list(
# cfg = "host",
# allow_files = True,
aspects = [pushable_aspect],
),
"push": attr.bool(default = True),
"data": attr.label_list(
# cfg = "host",
allow_files = True,
),
"_template": attr.label(
default = Label("//skylib/workspace:workspace.sh.tpl"),
allow_single_file = True,
),
"_bash_runfiles": attr.label(
allow_files = True,
default = "@bazel_tools//tools/bash/runfiles",
),
},
executable = True,
)
|
load('@io_bazel_rules_docker//container:providers.bzl', 'PushInfo')
load('@io_bazel_rules_docker//skylib:path.bzl', _get_runfile_path='runfile')
load('//skylib:providers.bzl', 'ImagePushesInfo')
load('//skylib/workspace:aspect.bzl', 'pushable_aspect')
def _file_to_runfile(ctx, file):
return file.owner.workspace_root or ctx.workspace_name + '/' + file.short_path
def _workspace_impl(ctx):
transitive_executables = []
transitive_runfiles = []
transitive_data = []
for t in ctx.attr.data:
transitive_data.append(t[DefaultInfo].files)
data = depset(transitive=transitive_data).to_list()
runfiles = depset(transitive=transitive_runfiles).to_list()
files = []
tars = []
for src in ctx.attr.srcs:
tar = src.files.to_list()[0]
tars.append(tar)
rf = ctx.runfiles(files=runfiles + data + tars + ctx.files._bash_runfiles)
trans_img_pushes = []
if ctx.attr.push:
trans_img_pushes = depset(transitive=[obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj]).to_list()
files += [obj.files_to_run.executable for obj in trans_img_pushes]
for obj in trans_img_pushes:
rf = rf.merge(obj[DefaultInfo].default_runfiles)
ctx.actions.expand_template(template=ctx.file._template, substitutions={'%{workspace_tar_targets}': ' '.join([json.encode(_file_to_runfile(ctx, t)) for t in tars]), '%{push_targets}': ' '.join([json.encode(_file_to_runfile(ctx, exe.files_to_run.executable)) for exe in trans_img_pushes])}, output=ctx.outputs.executable)
return [default_info(files=depset(files), runfiles=rf), image_pushes_info(image_pushes=depset(transitive=[obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj]))]
workspace = rule(implementation=_workspace_impl, attrs={'srcs': attr.label_list(aspects=[pushable_aspect]), 'push': attr.bool(default=True), 'data': attr.label_list(allow_files=True), '_template': attr.label(default=label('//skylib/workspace:workspace.sh.tpl'), allow_single_file=True), '_bash_runfiles': attr.label(allow_files=True, default='@bazel_tools//tools/bash/runfiles')}, executable=True)
|
def changecode():
file1=input("Enter your file name1")
file2=input("Enter your file name2")
with open(file1,"r") as a:
data_a = a.read()
with open(file2,"r") as b:
data_b = b.read()
with open(file1,"w") as a:
a.write(data_b)
with open(file2,"w") as b:
b.write(data_a)
changecode()
|
def changecode():
file1 = input('Enter your file name1')
file2 = input('Enter your file name2')
with open(file1, 'r') as a:
data_a = a.read()
with open(file2, 'r') as b:
data_b = b.read()
with open(file1, 'w') as a:
a.write(data_b)
with open(file2, 'w') as b:
b.write(data_a)
changecode()
|
"""
1119. Remove Vowels from a String
Easy
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Note:
S consists of lowercase English letters only.
1 <= S.length <= 1000
"""
vowels = set(['a', 'e', 'i', 'o', 'u'])
class Solution:
"""
could also assemble a list of characters and join at the end ...
"""
def removeVowels(self, S: str) -> str:
returned = ""
for ch in S:
if ch not in vowels:
returned += ch
return returned
if __name__ == "__main__":
s = Solution()
assert s.removeVowels("leetcodeisacommunityforcoders") == "ltcdscmmntyfrcdrs"
|
"""
1119. Remove Vowels from a String
Easy
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Note:
S consists of lowercase English letters only.
1 <= S.length <= 1000
"""
vowels = set(['a', 'e', 'i', 'o', 'u'])
class Solution:
"""
could also assemble a list of characters and join at the end ...
"""
def remove_vowels(self, S: str) -> str:
returned = ''
for ch in S:
if ch not in vowels:
returned += ch
return returned
if __name__ == '__main__':
s = solution()
assert s.removeVowels('leetcodeisacommunityforcoders') == 'ltcdscmmntyfrcdrs'
|
ll=range(5, 20, 5)
for i in ll:
print(i)
print (ll)
x = 'Python'
for i in range(len(x)) :
print(x[i])
|
ll = range(5, 20, 5)
for i in ll:
print(i)
print(ll)
x = 'Python'
for i in range(len(x)):
print(x[i])
|
# Function returns nth element of Padovan sequence
def padovan(n):
p = 0
if n > 2:
p = padovan(n-2) + padovan(n-3)
return p
else:
p = 1
return p
def main():
while True:
n = int(input("Enter a number: "))
if n >= 0:
break
print("Invalid number,try again")
print(f"P({n}) = {padovan(n)}")
main()
|
def padovan(n):
p = 0
if n > 2:
p = padovan(n - 2) + padovan(n - 3)
return p
else:
p = 1
return p
def main():
while True:
n = int(input('Enter a number: '))
if n >= 0:
break
print('Invalid number,try again')
print(f'P({n}) = {padovan(n)}')
main()
|
li = []
for x in range (21):
li.append(x)
print(li)
del(li[4])
print(li)
|
li = []
for x in range(21):
li.append(x)
print(li)
del li[4]
print(li)
|
routes = {
'{"command": "stats"}' : {"STATUS":[{"STATUS":"S","When":1553711204,"Code":70,"Msg":"BMMiner stats","Description":"bmminer 1.0.0"}],"STATS":[{"BMMiner":"2.0.0","Miner":"16.8.1.3","CompileTime":"Fri Nov 17 17:37:49 CST 2017","Type":"Antminer S9"},{"STATS":0,"ID":"BC50","Elapsed":248,"Calls":0,"Wait":0.000000,"Max":0.000000,"Min":99999999.000000,"GHS 5s":"13604.84","GHS av":13884.11,"miner_count":3,"frequency":"650","fan_num":2,"fan1":0,"fan2":0,"fan3":5880,"fan4":0,"fan5":0,"fan6":5760,"fan7":0,"fan8":0,"temp_num":3,"temp1":0,"temp2":0,"temp3":0,"temp4":0,"temp5":0,"temp6":62,"temp7":60,"temp8":60,"temp9":0,"temp10":0,"temp11":0,"temp12":0,"temp13":0,"temp14":0,"temp15":0,"temp16":0,"temp2_1":0,"temp2_2":0,"temp2_3":0,"temp2_4":0,"temp2_5":0,"temp2_6":77,"temp2_7":75,"temp2_8":75,"temp2_9":0,"temp2_10":0,"temp2_11":0,"temp2_12":0,"temp2_13":0,"temp2_14":0,"temp2_15":0,"temp2_16":0,"temp3_1":0,"temp3_2":0,"temp3_3":0,"temp3_4":0,"temp3_5":0,"temp3_6":0,"temp3_7":0,"temp3_8":0,"temp3_9":0,"temp3_10":0,"temp3_11":0,"temp3_12":0,"temp3_13":0,"temp3_14":0,"temp3_15":0,"temp3_16":0,"freq_avg1":0.00,"freq_avg2":0.00,"freq_avg3":0.00,"freq_avg4":0.00,"freq_avg5":0.00,"freq_avg6":642.06,"freq_avg7":606.00,"freq_avg8":645.77,"freq_avg9":0.00,"freq_avg10":0.00,"freq_avg11":0.00,"freq_avg12":0.00,"freq_avg13":0.00,"freq_avg14":0.00,"freq_avg15":0.00,"freq_avg16":0.00,"total_rateideal":13501.26,"total_freqavg":631.28,"total_acn":189,"total_rate":13604.84,"chain_rateideal1":0.00,"chain_rateideal2":0.00,"chain_rateideal3":0.00,"chain_rateideal4":0.00,"chain_rateideal5":0.00,"chain_rateideal6":4512.30,"chain_rateideal7":4352.29,"chain_rateideal8":4636.67,"chain_rateideal9":0.00,"chain_rateideal10":0.00,"chain_rateideal11":0.00,"chain_rateideal12":0.00,"chain_rateideal13":0.00,"chain_rateideal14":0.00,"chain_rateideal15":0.00,"chain_rateideal16":0.00,"temp_max":62,"Device Hardware%":0.0000,"no_matching_work":0,"chain_acn1":0,"chain_acn2":0,"chain_acn3":0,"chain_acn4":0,"chain_acn5":0,"chain_acn6":63,"chain_acn7":63,"chain_acn8":63,"chain_acn9":0,"chain_acn10":0,"chain_acn11":0,"chain_acn12":0,"chain_acn13":0,"chain_acn14":0,"chain_acn15":0,"chain_acn16":0,"chain_acs1":"","chain_acs2":"","chain_acs3":"","chain_acs4":"","chain_acs5":"","chain_acs6":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs7":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs8":" oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo","chain_acs9":"","chain_acs10":"","chain_acs11":"","chain_acs12":"","chain_acs13":"","chain_acs14":"","chain_acs15":"","chain_acs16":"","chain_hw1":0,"chain_hw2":0,"chain_hw3":0,"chain_hw4":0,"chain_hw5":0,"chain_hw6":0,"chain_hw7":0,"chain_hw8":0,"chain_hw9":0,"chain_hw10":0,"chain_hw11":0,"chain_hw12":0,"chain_hw13":0,"chain_hw14":0,"chain_hw15":0,"chain_hw16":0,"chain_rate1":"","chain_rate2":"","chain_rate3":"","chain_rate4":"","chain_rate5":"","chain_rate6":"4631.20","chain_rate7":"4279.31","chain_rate8":"4694.33","chain_rate9":"","chain_rate10":"","chain_rate11":"","chain_rate12":"","chain_rate13":"","chain_rate14":"","chain_rate15":"","chain_rate16":"","chain_xtime6":"{}","chain_xtime7":"{}","chain_xtime8":"{}","chain_offside_6":"0","chain_offside_7":"0","chain_offside_8":"0","chain_opencore_6":"1","chain_opencore_7":"1","chain_opencore_8":"1","miner_version":"16.8.1.3","miner_id":"80108c8c6880881c"}],"id":1},
'{"command": "pools"}' : {"STATUS":[{"STATUS":"S","When":1553711204,"Code":7,"Msg":"3 Pool(s)","Description":"bmminer 1.0.0"}],"POOLS":[{"POOL":0,"URL":"stratum+tcp://sha256.usa.nicehash.com:3334","Status":"Alive","Priority":0,"Quota":1,"Long Poll":"N","Getworks":12,"Accepted":0,"Rejected":0,"Discarded":137,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwAAAA","Last Share Time":"0","Diff":"500K","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":True,"Stratum URL":"sha256.usa.nicehash.com","Has GBT":False,"Best Share":845408,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":1,"URL":"stratum+tcp://stratum.antpool.com:3333","Status":"Alive","Priority":1,"Quota":1,"Long Poll":"N","Getworks":1,"Accepted":0,"Rejected":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"antminer_1","Last Share Time":"0","Diff":"","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":2,"URL":"stratum+tcp://cn.ss.btc.com:3333","Status":"Dead","Priority":2,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"antminer.1","Last Share Time":"0","Diff":"","Diff1 Shares":0,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0,"Pool Rejected%":0.0000,"Pool Stale%":0.0000}],"id":1}
}
|
routes = {'{"command": "stats"}': {'STATUS': [{'STATUS': 'S', 'When': 1553711204, 'Code': 70, 'Msg': 'BMMiner stats', 'Description': 'bmminer 1.0.0'}], 'STATS': [{'BMMiner': '2.0.0', 'Miner': '16.8.1.3', 'CompileTime': 'Fri Nov 17 17:37:49 CST 2017', 'Type': 'Antminer S9'}, {'STATS': 0, 'ID': 'BC50', 'Elapsed': 248, 'Calls': 0, 'Wait': 0.0, 'Max': 0.0, 'Min': 99999999.0, 'GHS 5s': '13604.84', 'GHS av': 13884.11, 'miner_count': 3, 'frequency': '650', 'fan_num': 2, 'fan1': 0, 'fan2': 0, 'fan3': 5880, 'fan4': 0, 'fan5': 0, 'fan6': 5760, 'fan7': 0, 'fan8': 0, 'temp_num': 3, 'temp1': 0, 'temp2': 0, 'temp3': 0, 'temp4': 0, 'temp5': 0, 'temp6': 62, 'temp7': 60, 'temp8': 60, 'temp9': 0, 'temp10': 0, 'temp11': 0, 'temp12': 0, 'temp13': 0, 'temp14': 0, 'temp15': 0, 'temp16': 0, 'temp2_1': 0, 'temp2_2': 0, 'temp2_3': 0, 'temp2_4': 0, 'temp2_5': 0, 'temp2_6': 77, 'temp2_7': 75, 'temp2_8': 75, 'temp2_9': 0, 'temp2_10': 0, 'temp2_11': 0, 'temp2_12': 0, 'temp2_13': 0, 'temp2_14': 0, 'temp2_15': 0, 'temp2_16': 0, 'temp3_1': 0, 'temp3_2': 0, 'temp3_3': 0, 'temp3_4': 0, 'temp3_5': 0, 'temp3_6': 0, 'temp3_7': 0, 'temp3_8': 0, 'temp3_9': 0, 'temp3_10': 0, 'temp3_11': 0, 'temp3_12': 0, 'temp3_13': 0, 'temp3_14': 0, 'temp3_15': 0, 'temp3_16': 0, 'freq_avg1': 0.0, 'freq_avg2': 0.0, 'freq_avg3': 0.0, 'freq_avg4': 0.0, 'freq_avg5': 0.0, 'freq_avg6': 642.06, 'freq_avg7': 606.0, 'freq_avg8': 645.77, 'freq_avg9': 0.0, 'freq_avg10': 0.0, 'freq_avg11': 0.0, 'freq_avg12': 0.0, 'freq_avg13': 0.0, 'freq_avg14': 0.0, 'freq_avg15': 0.0, 'freq_avg16': 0.0, 'total_rateideal': 13501.26, 'total_freqavg': 631.28, 'total_acn': 189, 'total_rate': 13604.84, 'chain_rateideal1': 0.0, 'chain_rateideal2': 0.0, 'chain_rateideal3': 0.0, 'chain_rateideal4': 0.0, 'chain_rateideal5': 0.0, 'chain_rateideal6': 4512.3, 'chain_rateideal7': 4352.29, 'chain_rateideal8': 4636.67, 'chain_rateideal9': 0.0, 'chain_rateideal10': 0.0, 'chain_rateideal11': 0.0, 'chain_rateideal12': 0.0, 'chain_rateideal13': 0.0, 'chain_rateideal14': 0.0, 'chain_rateideal15': 0.0, 'chain_rateideal16': 0.0, 'temp_max': 62, 'Device Hardware%': 0.0, 'no_matching_work': 0, 'chain_acn1': 0, 'chain_acn2': 0, 'chain_acn3': 0, 'chain_acn4': 0, 'chain_acn5': 0, 'chain_acn6': 63, 'chain_acn7': 63, 'chain_acn8': 63, 'chain_acn9': 0, 'chain_acn10': 0, 'chain_acn11': 0, 'chain_acn12': 0, 'chain_acn13': 0, 'chain_acn14': 0, 'chain_acn15': 0, 'chain_acn16': 0, 'chain_acs1': '', 'chain_acs2': '', 'chain_acs3': '', 'chain_acs4': '', 'chain_acs5': '', 'chain_acs6': ' oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo', 'chain_acs7': ' oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo', 'chain_acs8': ' oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo oooooooo ooooooo', 'chain_acs9': '', 'chain_acs10': '', 'chain_acs11': '', 'chain_acs12': '', 'chain_acs13': '', 'chain_acs14': '', 'chain_acs15': '', 'chain_acs16': '', 'chain_hw1': 0, 'chain_hw2': 0, 'chain_hw3': 0, 'chain_hw4': 0, 'chain_hw5': 0, 'chain_hw6': 0, 'chain_hw7': 0, 'chain_hw8': 0, 'chain_hw9': 0, 'chain_hw10': 0, 'chain_hw11': 0, 'chain_hw12': 0, 'chain_hw13': 0, 'chain_hw14': 0, 'chain_hw15': 0, 'chain_hw16': 0, 'chain_rate1': '', 'chain_rate2': '', 'chain_rate3': '', 'chain_rate4': '', 'chain_rate5': '', 'chain_rate6': '4631.20', 'chain_rate7': '4279.31', 'chain_rate8': '4694.33', 'chain_rate9': '', 'chain_rate10': '', 'chain_rate11': '', 'chain_rate12': '', 'chain_rate13': '', 'chain_rate14': '', 'chain_rate15': '', 'chain_rate16': '', 'chain_xtime6': '{}', 'chain_xtime7': '{}', 'chain_xtime8': '{}', 'chain_offside_6': '0', 'chain_offside_7': '0', 'chain_offside_8': '0', 'chain_opencore_6': '1', 'chain_opencore_7': '1', 'chain_opencore_8': '1', 'miner_version': '16.8.1.3', 'miner_id': '80108c8c6880881c'}], 'id': 1}, '{"command": "pools"}': {'STATUS': [{'STATUS': 'S', 'When': 1553711204, 'Code': 7, 'Msg': '3 Pool(s)', 'Description': 'bmminer 1.0.0'}], 'POOLS': [{'POOL': 0, 'URL': 'stratum+tcp://sha256.usa.nicehash.com:3334', 'Status': 'Alive', 'Priority': 0, 'Quota': 1, 'Long Poll': 'N', 'Getworks': 12, 'Accepted': 0, 'Rejected': 0, 'Discarded': 137, 'Stale': 0, 'Get Failures': 0, 'Remote Failures': 0, 'User': '3J6HNskoH271PVPFvfAmBqUmarMFjwAAAA', 'Last Share Time': '0', 'Diff': '500K', 'Diff1 Shares': 0, 'Proxy Type': '', 'Proxy': '', 'Difficulty Accepted': 0.0, 'Difficulty Rejected': 0.0, 'Difficulty Stale': 0.0, 'Last Share Difficulty': 0.0, 'Has Stratum': True, 'Stratum Active': True, 'Stratum URL': 'sha256.usa.nicehash.com', 'Has GBT': False, 'Best Share': 845408, 'Pool Rejected%': 0.0, 'Pool Stale%': 0.0}, {'POOL': 1, 'URL': 'stratum+tcp://stratum.antpool.com:3333', 'Status': 'Alive', 'Priority': 1, 'Quota': 1, 'Long Poll': 'N', 'Getworks': 1, 'Accepted': 0, 'Rejected': 0, 'Discarded': 0, 'Stale': 0, 'Get Failures': 0, 'Remote Failures': 0, 'User': 'antminer_1', 'Last Share Time': '0', 'Diff': '', 'Diff1 Shares': 0, 'Proxy Type': '', 'Proxy': '', 'Difficulty Accepted': 0.0, 'Difficulty Rejected': 0.0, 'Difficulty Stale': 0.0, 'Last Share Difficulty': 0.0, 'Has Stratum': True, 'Stratum Active': False, 'Stratum URL': '', 'Has GBT': False, 'Best Share': 0, 'Pool Rejected%': 0.0, 'Pool Stale%': 0.0}, {'POOL': 2, 'URL': 'stratum+tcp://cn.ss.btc.com:3333', 'Status': 'Dead', 'Priority': 2, 'Quota': 1, 'Long Poll': 'N', 'Getworks': 0, 'Accepted': 0, 'Rejected': 0, 'Discarded': 0, 'Stale': 0, 'Get Failures': 0, 'Remote Failures': 0, 'User': 'antminer.1', 'Last Share Time': '0', 'Diff': '', 'Diff1 Shares': 0, 'Proxy Type': '', 'Proxy': '', 'Difficulty Accepted': 0.0, 'Difficulty Rejected': 0.0, 'Difficulty Stale': 0.0, 'Last Share Difficulty': 0.0, 'Has Stratum': True, 'Stratum Active': False, 'Stratum URL': '', 'Has GBT': False, 'Best Share': 0, 'Pool Rejected%': 0.0, 'Pool Stale%': 0.0}], 'id': 1}}
|
class DatabaseNotConnectedException(Exception):
"""This exception is raised when collection is accessed however database is
not connected.
"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
|
class Databasenotconnectedexception(Exception):
"""This exception is raised when collection is accessed however database is
not connected.
"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
|
def folder_to_dict(folder):
return {
'id': folder.folder_id,
'name': folder.name,
'class': folder.folder_class,
'total_count': folder.total_count,
'child_folder_count': folder.child_folder_count,
'unread_count': folder.unread_count
}
def item_to_dict(item, include_body=False):
result = {
'id': item.item_id,
'changekeyid': item.changekey,
'subject': item.subject,
'sensitivity': item.sensitivity,
'text_body': item.text_body,
'body': item.body,
'attachments': len(item.attachments),
'datetime_received': item.datetime_received.ewsformat() if item.datetime_received else None,
'categories': item.categories,
'importance': item.importance,
'is_draft': item.is_draft,
'datetime_sent': item.datetime_sent.ewsformat() if item.datetime_sent else None,
'datetime_created': item.datetime_created.ewsformat() if item.datetime_created else None,
'reminder_is_set': item.reminder_is_set,
'reminder_due_by': item.reminder_due_by.ewsformat() if item.reminder_due_by else None,
'reminder_minutes_before_start': item.reminder_minutes_before_start,
'last_modified_name': item.last_modified_name
}
if not include_body:
del result['body']
del result['text_body']
return result
|
def folder_to_dict(folder):
return {'id': folder.folder_id, 'name': folder.name, 'class': folder.folder_class, 'total_count': folder.total_count, 'child_folder_count': folder.child_folder_count, 'unread_count': folder.unread_count}
def item_to_dict(item, include_body=False):
result = {'id': item.item_id, 'changekeyid': item.changekey, 'subject': item.subject, 'sensitivity': item.sensitivity, 'text_body': item.text_body, 'body': item.body, 'attachments': len(item.attachments), 'datetime_received': item.datetime_received.ewsformat() if item.datetime_received else None, 'categories': item.categories, 'importance': item.importance, 'is_draft': item.is_draft, 'datetime_sent': item.datetime_sent.ewsformat() if item.datetime_sent else None, 'datetime_created': item.datetime_created.ewsformat() if item.datetime_created else None, 'reminder_is_set': item.reminder_is_set, 'reminder_due_by': item.reminder_due_by.ewsformat() if item.reminder_due_by else None, 'reminder_minutes_before_start': item.reminder_minutes_before_start, 'last_modified_name': item.last_modified_name}
if not include_body:
del result['body']
del result['text_body']
return result
|
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
# the names j2, j3, and j4 are the white banks on sweetberry
# Note that here the bank name in the mux position is optional
# as it only gets used to generate a docstring help message
inas = [
('sweetberry', '0x40:3', 'j2_1' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:1', 'j2_2' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:2', 'j2_3' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x40:0', 'j2_4' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:3', 'j2_5' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:1', 'j2_6' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:2', 'j2_7' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x41:0', 'j2_8' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:3', 'j2_9' , 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:1', 'j2_10', 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:2', 'j2_11', 5.0, 0.010, 'j2', False),
('sweetberry', '0x42:0', 'j2_12', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:3', 'j2_13', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:1', 'j2_14', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:2', 'j2_15', 5.0, 0.010, 'j2', False),
('sweetberry', '0x43:0', 'j2_16', 5.0, 0.010, 'j2', False),
('sweetberry', '0x44:3', 'j3_1' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:1', 'j3_2' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:2', 'j3_3' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x44:0', 'j3_4' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:3', 'j3_5' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:1', 'j3_6' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:2', 'j3_7' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x45:0', 'j3_8' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:3', 'j3_9' , 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:1', 'j3_10', 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:2', 'j3_11', 5.0, 0.010, 'j3', False),
('sweetberry', '0x46:0', 'j3_12', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:3', 'j3_13', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:1', 'j3_14', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:2', 'j3_15', 5.0, 0.010, 'j3', False),
('sweetberry', '0x47:0', 'j3_16', 5.0, 0.010, 'j3', False),
('sweetberry', '0x48:3', 'j4_1' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:1', 'j4_2' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:2', 'j4_3' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x48:0', 'j4_4' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:3', 'j4_5' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:1', 'j4_6' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:2', 'j4_7' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x49:0', 'j4_8' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:3', 'j4_9' , 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:1', 'j4_10', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:2', 'j4_11', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4a:0', 'j4_12', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:3', 'j4_13', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:1', 'j4_14', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:2', 'j4_15', 5.0, 0.010, 'j4', False),
('sweetberry', '0x4b:0', 'j4_16', 5.0, 0.010, 'j4', False),
]
|
config_type = 'sweetberry'
inas = [('sweetberry', '0x40:3', 'j2_1', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:1', 'j2_2', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:2', 'j2_3', 5.0, 0.01, 'j2', False), ('sweetberry', '0x40:0', 'j2_4', 5.0, 0.01, 'j2', False), ('sweetberry', '0x41:3', 'j2_5', 5.0, 0.01, 'j2', False), ('sweetberry', '0x41:1', 'j2_6', 5.0, 0.01, 'j2', False), ('sweetberry', '0x41:2', 'j2_7', 5.0, 0.01, 'j2', False), ('sweetberry', '0x41:0', 'j2_8', 5.0, 0.01, 'j2', False), ('sweetberry', '0x42:3', 'j2_9', 5.0, 0.01, 'j2', False), ('sweetberry', '0x42:1', 'j2_10', 5.0, 0.01, 'j2', False), ('sweetberry', '0x42:2', 'j2_11', 5.0, 0.01, 'j2', False), ('sweetberry', '0x42:0', 'j2_12', 5.0, 0.01, 'j2', False), ('sweetberry', '0x43:3', 'j2_13', 5.0, 0.01, 'j2', False), ('sweetberry', '0x43:1', 'j2_14', 5.0, 0.01, 'j2', False), ('sweetberry', '0x43:2', 'j2_15', 5.0, 0.01, 'j2', False), ('sweetberry', '0x43:0', 'j2_16', 5.0, 0.01, 'j2', False), ('sweetberry', '0x44:3', 'j3_1', 5.0, 0.01, 'j3', False), ('sweetberry', '0x44:1', 'j3_2', 5.0, 0.01, 'j3', False), ('sweetberry', '0x44:2', 'j3_3', 5.0, 0.01, 'j3', False), ('sweetberry', '0x44:0', 'j3_4', 5.0, 0.01, 'j3', False), ('sweetberry', '0x45:3', 'j3_5', 5.0, 0.01, 'j3', False), ('sweetberry', '0x45:1', 'j3_6', 5.0, 0.01, 'j3', False), ('sweetberry', '0x45:2', 'j3_7', 5.0, 0.01, 'j3', False), ('sweetberry', '0x45:0', 'j3_8', 5.0, 0.01, 'j3', False), ('sweetberry', '0x46:3', 'j3_9', 5.0, 0.01, 'j3', False), ('sweetberry', '0x46:1', 'j3_10', 5.0, 0.01, 'j3', False), ('sweetberry', '0x46:2', 'j3_11', 5.0, 0.01, 'j3', False), ('sweetberry', '0x46:0', 'j3_12', 5.0, 0.01, 'j3', False), ('sweetberry', '0x47:3', 'j3_13', 5.0, 0.01, 'j3', False), ('sweetberry', '0x47:1', 'j3_14', 5.0, 0.01, 'j3', False), ('sweetberry', '0x47:2', 'j3_15', 5.0, 0.01, 'j3', False), ('sweetberry', '0x47:0', 'j3_16', 5.0, 0.01, 'j3', False), ('sweetberry', '0x48:3', 'j4_1', 5.0, 0.01, 'j4', False), ('sweetberry', '0x48:1', 'j4_2', 5.0, 0.01, 'j4', False), ('sweetberry', '0x48:2', 'j4_3', 5.0, 0.01, 'j4', False), ('sweetberry', '0x48:0', 'j4_4', 5.0, 0.01, 'j4', False), ('sweetberry', '0x49:3', 'j4_5', 5.0, 0.01, 'j4', False), ('sweetberry', '0x49:1', 'j4_6', 5.0, 0.01, 'j4', False), ('sweetberry', '0x49:2', 'j4_7', 5.0, 0.01, 'j4', False), ('sweetberry', '0x49:0', 'j4_8', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4a:3', 'j4_9', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4a:1', 'j4_10', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4a:2', 'j4_11', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4a:0', 'j4_12', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4b:3', 'j4_13', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4b:1', 'j4_14', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4b:2', 'j4_15', 5.0, 0.01, 'j4', False), ('sweetberry', '0x4b:0', 'j4_16', 5.0, 0.01, 'j4', False)]
|
# Project Euler Problem 4
# Pranav Mital
# function to check if a number is a palindrome
def isPalindrome(n):
flag = 0
str_n = str(n)
for i in range((len(str_n)//2)):
if str_n[i] != str_n[len(str_n)-1-i]:
flag += 1
if flag != 0:
return False
else:
return True
# main script
largest_palindrome = 0
for i in range(100,1000): #nested for loop to try all combinations of 3-digit numbers
for j in range(100,1000):
num_p = i*j
if isPalindrome(num_p):
if num_p>largest_palindrome:
largest_palindrome = num_p
print("The largest palindrome made from the product of two 3-digit numbers is:",largest_palindrome)
|
def is_palindrome(n):
flag = 0
str_n = str(n)
for i in range(len(str_n) // 2):
if str_n[i] != str_n[len(str_n) - 1 - i]:
flag += 1
if flag != 0:
return False
else:
return True
largest_palindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
num_p = i * j
if is_palindrome(num_p):
if num_p > largest_palindrome:
largest_palindrome = num_p
print('The largest palindrome made from the product of two 3-digit numbers is:', largest_palindrome)
|
def f(var=("""
str
""",1)):
pass
anothervar=1
|
def f(var=('\nstr\n', 1)):
pass
anothervar = 1
|
class PyFileBuilder:
def __init__(self, name):
self._import_line = None
self._file_funcs = []
self.name = name
def add_imports(self, *modules_names):
import_list = []
for module in modules_names:
import_list.append("import " + module)
if len(import_list) != 0:
self._import_line = "\n".join(import_list)
def add_func(self, str_func):
self._file_funcs.append(str_func)
def get_content(self):
if len(self._file_funcs) == 0:
raise Exception("There are no functions in this file")
content = "\n\n\n".join(self._file_funcs)
if self._import_line is not None:
content = self._import_line + "\n\n\n" + content
return content
|
class Pyfilebuilder:
def __init__(self, name):
self._import_line = None
self._file_funcs = []
self.name = name
def add_imports(self, *modules_names):
import_list = []
for module in modules_names:
import_list.append('import ' + module)
if len(import_list) != 0:
self._import_line = '\n'.join(import_list)
def add_func(self, str_func):
self._file_funcs.append(str_func)
def get_content(self):
if len(self._file_funcs) == 0:
raise exception('There are no functions in this file')
content = '\n\n\n'.join(self._file_funcs)
if self._import_line is not None:
content = self._import_line + '\n\n\n' + content
return content
|
# Create a program such that when given a non-negative number input, output whether or not if the number is 2 away from a multiple of 10.
# input
num = int(input('Enter a positive number: '))
# processing & output
if (num + 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
elif (num - 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
else:
print(num, 'is not 2 away from a multiple of 10.')
|
num = int(input('Enter a positive number: '))
if (num + 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
elif (num - 2) % 10 == 0:
print(num, 'is 2 away from a multiple of 10.')
else:
print(num, 'is not 2 away from a multiple of 10.')
|
#URL:https://www.hackerrank.com/challenges/balanced-brackets/problem?h_r=profile
def check_close(top, ch):
if ch =="(" and top ==")":
return True
if ch =="[" and top =="]":
return True
if ch =="{" and top =="}":
return True
return False
def isBalanced(s):
stack=[]
for ch in s:
#print("stack = ",stack)
if ch == "(" or ch == "[" or ch =="{":
stack.append(ch)
else:
#print("in")
stop = ""
if stack:
stop = stack.pop()
else:
return "NO"
if not check_close(ch, stop):
return "NO"
if stack:
return "NO"
return "YES"
|
def check_close(top, ch):
if ch == '(' and top == ')':
return True
if ch == '[' and top == ']':
return True
if ch == '{' and top == '}':
return True
return False
def is_balanced(s):
stack = []
for ch in s:
if ch == '(' or ch == '[' or ch == '{':
stack.append(ch)
else:
stop = ''
if stack:
stop = stack.pop()
else:
return 'NO'
if not check_close(ch, stop):
return 'NO'
if stack:
return 'NO'
return 'YES'
|
def tickets(disabled,users):
'''
cheks if disabeld or not
'''
a = input("are you disabled or not: ")
if a == 'disabled':
disabled = 200
return disabled
elif a == 'not':
users = 500
return users
tickets(200,500)
|
def tickets(disabled, users):
"""
cheks if disabeld or not
"""
a = input('are you disabled or not: ')
if a == 'disabled':
disabled = 200
return disabled
elif a == 'not':
users = 500
return users
tickets(200, 500)
|
class Solution:
# 1st solution, Lagrange's four square theorem
# O(sqart(n)) time | O(1) space
def numSquares(self, n: int) -> int:
if int(sqrt(n))**2 == n: return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j*j))**2 == n - j*j: return 2
while n % 4 == 0:
n >>= 2
if n % 8 == 7: return 4
return 3
# 2nd solution
# O(n^2) time | O(n^2) space
def numSquares(self, n: int) -> int:
squareSet = set()
k = 1
while k * k <= n:
squareSet.add(k * k)
k += 1
count = 0
stack = set([n])
while stack:
count += 1
newStack = set()
for val in stack:
for sq in squareSet:
if sq < val:
newStack.add(val - sq)
elif sq == val:
return count
stack = newStack
|
class Solution:
def num_squares(self, n: int) -> int:
if int(sqrt(n)) ** 2 == n:
return 1
for j in range(int(sqrt(n)) + 1):
if int(sqrt(n - j * j)) ** 2 == n - j * j:
return 2
while n % 4 == 0:
n >>= 2
if n % 8 == 7:
return 4
return 3
def num_squares(self, n: int) -> int:
square_set = set()
k = 1
while k * k <= n:
squareSet.add(k * k)
k += 1
count = 0
stack = set([n])
while stack:
count += 1
new_stack = set()
for val in stack:
for sq in squareSet:
if sq < val:
newStack.add(val - sq)
elif sq == val:
return count
stack = newStack
|
#
# PySNMP MIB module CISCO-ATM-SWITCH-FR-RM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SWITCH-FR-RM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
iso, ObjectIdentity, Integer32, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Gauge32, TimeTicks, MibIdentifier, Counter64, Unsigned32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "ObjectIdentity", "Integer32", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Gauge32", "TimeTicks", "MibIdentifier", "Counter64", "Unsigned32", "Bits")
DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention")
ciscoAtmSwitchFrRmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 110))
if mibBuilder.loadTexts: ciscoAtmSwitchFrRmMIB.setLastUpdated('9807200000Z')
if mibBuilder.loadTexts: ciscoAtmSwitchFrRmMIB.setOrganization('Cisco Systems')
ciscoAtmSwitchFrRmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1))
cfaAdapter = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1))
cfaInterwork = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2))
class CfaInterworkServiceCategory(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vbrNrt", 1), ("abr", 2), ("ubr", 3))
cfaAdapterIfVcQThresholdTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1), )
if mibBuilder.loadTexts: cfaAdapterIfVcQThresholdTable.setStatus('current')
cfaAdapterIfVcQThresholdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQService"))
if mibBuilder.loadTexts: cfaAdapterIfVcQThresholdEntry.setStatus('current')
cfaAdapterIfVcQService = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 1), CfaInterworkServiceCategory())
if mibBuilder.loadTexts: cfaAdapterIfVcQService.setStatus('current')
cfaAdapterIfVcQInqDiscThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQInqDiscThresh.setStatus('current')
cfaAdapterIfVcQOutqDiscThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQOutqDiscThresh.setStatus('current')
cfaAdapterIfVcQInqMarkThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQInqMarkThresh.setStatus('current')
cfaAdapterIfVcQOutqMarkThresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVcQOutqMarkThresh.setStatus('current')
cfaAdapterIfVbrServOflowTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2), )
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflowTable.setStatus('current')
cfaAdapterIfVbrServOflowEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflowEntry.setStatus('current')
cfaAdapterIfVbrServOflow = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1, 1), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfVbrServOflow.setStatus('current')
cfaAdapterIfFrConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3), )
if mibBuilder.loadTexts: cfaAdapterIfFrConfigTable.setStatus('current')
cfaAdapterIfFrConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cfaAdapterIfFrConfigEntry.setStatus('current')
cfaAdapterIfOverbooking = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 1000)).clone(100)).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cfaAdapterIfOverbooking.setStatus('current')
cfaInterworkIfResourceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1), )
if mibBuilder.loadTexts: cfaInterworkIfResourceTable.setStatus('current')
cfaInterworkIfResourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfVcQService"))
if mibBuilder.loadTexts: cfaInterworkIfResourceEntry.setStatus('current')
cfaInterworkIfVcQService = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 1), CfaInterworkServiceCategory())
if mibBuilder.loadTexts: cfaInterworkIfVcQService.setStatus('current')
cfaInterworkIfRxAvailRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 2), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfRxAvailRate.setStatus('current')
cfaInterworkIfTxAvailRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 3), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfTxAvailRate.setStatus('current')
cfaInterworkIfRxAllocRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 4), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfRxAllocRate.setStatus('current')
cfaInterworkIfTxAllocRate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 5), Gauge32()).setUnits('bits-per-second').setMaxAccess("readonly")
if mibBuilder.loadTexts: cfaInterworkIfTxAllocRate.setStatus('current')
ciscoAtmSwitchFrRmMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 2))
ciscoAtmSwitchFrRmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3))
ciscoAtmSwitchFrRmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1))
ciscoAtmSwitchFrRmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2))
ciscoAtmSwitchFrRmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1, 1)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterGroup"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoAtmSwitchFrRmMIBCompliance = ciscoAtmSwitchFrRmMIBCompliance.setStatus('current')
cfaAdapterGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 1)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQInqDiscThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQOutqDiscThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQInqMarkThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVcQOutqMarkThresh"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfVbrServOflow"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaAdapterIfOverbooking"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfaAdapterGroup = cfaAdapterGroup.setStatus('current')
cfaInterworkGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 2)).setObjects(("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfRxAvailRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfTxAvailRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfRxAllocRate"), ("CISCO-ATM-SWITCH-FR-RM-MIB", "cfaInterworkIfTxAllocRate"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfaInterworkGroup = cfaInterworkGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-ATM-SWITCH-FR-RM-MIB", cfaAdapterIfVcQOutqDiscThresh=cfaAdapterIfVcQOutqDiscThresh, PYSNMP_MODULE_ID=ciscoAtmSwitchFrRmMIB, cfaAdapterGroup=cfaAdapterGroup, cfaAdapterIfVcQThresholdEntry=cfaAdapterIfVcQThresholdEntry, cfaAdapterIfVbrServOflowEntry=cfaAdapterIfVbrServOflowEntry, cfaInterworkIfTxAvailRate=cfaInterworkIfTxAvailRate, ciscoAtmSwitchFrRmMIBConformance=ciscoAtmSwitchFrRmMIBConformance, cfaAdapterIfVbrServOflowTable=cfaAdapterIfVbrServOflowTable, cfaInterworkGroup=cfaInterworkGroup, ciscoAtmSwitchFrRmMIB=ciscoAtmSwitchFrRmMIB, cfaInterworkIfTxAllocRate=cfaInterworkIfTxAllocRate, cfaInterwork=cfaInterwork, ciscoAtmSwitchFrRmMIBGroups=ciscoAtmSwitchFrRmMIBGroups, cfaInterworkIfResourceTable=cfaInterworkIfResourceTable, ciscoAtmSwitchFrRmMIBCompliance=ciscoAtmSwitchFrRmMIBCompliance, ciscoAtmSwitchFrRmMIBNotifications=ciscoAtmSwitchFrRmMIBNotifications, cfaInterworkIfRxAvailRate=cfaInterworkIfRxAvailRate, ciscoAtmSwitchFrRmMIBCompliances=ciscoAtmSwitchFrRmMIBCompliances, cfaAdapter=cfaAdapter, cfaAdapterIfVcQThresholdTable=cfaAdapterIfVcQThresholdTable, cfaAdapterIfFrConfigEntry=cfaAdapterIfFrConfigEntry, cfaAdapterIfOverbooking=cfaAdapterIfOverbooking, cfaInterworkIfResourceEntry=cfaInterworkIfResourceEntry, cfaAdapterIfVcQInqMarkThresh=cfaAdapterIfVcQInqMarkThresh, cfaAdapterIfFrConfigTable=cfaAdapterIfFrConfigTable, cfaAdapterIfVcQInqDiscThresh=cfaAdapterIfVcQInqDiscThresh, cfaAdapterIfVcQOutqMarkThresh=cfaAdapterIfVcQOutqMarkThresh, ciscoAtmSwitchFrRmMIBObjects=ciscoAtmSwitchFrRmMIBObjects, cfaInterworkIfVcQService=cfaInterworkIfVcQService, cfaInterworkIfRxAllocRate=cfaInterworkIfRxAllocRate, cfaAdapterIfVcQService=cfaAdapterIfVcQService, cfaAdapterIfVbrServOflow=cfaAdapterIfVbrServOflow, CfaInterworkServiceCategory=CfaInterworkServiceCategory)
|
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(iso, object_identity, integer32, ip_address, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, module_identity, gauge32, time_ticks, mib_identifier, counter64, unsigned32, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'ObjectIdentity', 'Integer32', 'IpAddress', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ModuleIdentity', 'Gauge32', 'TimeTicks', 'MibIdentifier', 'Counter64', 'Unsigned32', 'Bits')
(display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TruthValue', 'TextualConvention')
cisco_atm_switch_fr_rm_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 110))
if mibBuilder.loadTexts:
ciscoAtmSwitchFrRmMIB.setLastUpdated('9807200000Z')
if mibBuilder.loadTexts:
ciscoAtmSwitchFrRmMIB.setOrganization('Cisco Systems')
cisco_atm_switch_fr_rm_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1))
cfa_adapter = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1))
cfa_interwork = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2))
class Cfainterworkservicecategory(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3))
named_values = named_values(('vbrNrt', 1), ('abr', 2), ('ubr', 3))
cfa_adapter_if_vc_q_threshold_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1))
if mibBuilder.loadTexts:
cfaAdapterIfVcQThresholdTable.setStatus('current')
cfa_adapter_if_vc_q_threshold_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVcQService'))
if mibBuilder.loadTexts:
cfaAdapterIfVcQThresholdEntry.setStatus('current')
cfa_adapter_if_vc_q_service = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 1), cfa_interwork_service_category())
if mibBuilder.loadTexts:
cfaAdapterIfVcQService.setStatus('current')
cfa_adapter_if_vc_q_inq_disc_thresh = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfVcQInqDiscThresh.setStatus('current')
cfa_adapter_if_vc_q_outq_disc_thresh = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 100)).clone(87)).setUnits('percent').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfVcQOutqDiscThresh.setStatus('current')
cfa_adapter_if_vc_q_inq_mark_thresh = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfVcQInqMarkThresh.setStatus('current')
cfa_adapter_if_vc_q_outq_mark_thresh = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 100)).clone(75)).setUnits('percent').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfVcQOutqMarkThresh.setStatus('current')
cfa_adapter_if_vbr_serv_oflow_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2))
if mibBuilder.loadTexts:
cfaAdapterIfVbrServOflowTable.setStatus('current')
cfa_adapter_if_vbr_serv_oflow_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
cfaAdapterIfVbrServOflowEntry.setStatus('current')
cfa_adapter_if_vbr_serv_oflow = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 2, 1, 1), truth_value().clone('true')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfVbrServOflow.setStatus('current')
cfa_adapter_if_fr_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3))
if mibBuilder.loadTexts:
cfaAdapterIfFrConfigTable.setStatus('current')
cfa_adapter_if_fr_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
cfaAdapterIfFrConfigEntry.setStatus('current')
cfa_adapter_if_overbooking = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(100, 1000)).clone(100)).setUnits('percent').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cfaAdapterIfOverbooking.setStatus('current')
cfa_interwork_if_resource_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1))
if mibBuilder.loadTexts:
cfaInterworkIfResourceTable.setStatus('current')
cfa_interwork_if_resource_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkIfVcQService'))
if mibBuilder.loadTexts:
cfaInterworkIfResourceEntry.setStatus('current')
cfa_interwork_if_vc_q_service = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 1), cfa_interwork_service_category())
if mibBuilder.loadTexts:
cfaInterworkIfVcQService.setStatus('current')
cfa_interwork_if_rx_avail_rate = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 2), gauge32()).setUnits('bits-per-second').setMaxAccess('readonly')
if mibBuilder.loadTexts:
cfaInterworkIfRxAvailRate.setStatus('current')
cfa_interwork_if_tx_avail_rate = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 3), gauge32()).setUnits('bits-per-second').setMaxAccess('readonly')
if mibBuilder.loadTexts:
cfaInterworkIfTxAvailRate.setStatus('current')
cfa_interwork_if_rx_alloc_rate = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 4), gauge32()).setUnits('bits-per-second').setMaxAccess('readonly')
if mibBuilder.loadTexts:
cfaInterworkIfRxAllocRate.setStatus('current')
cfa_interwork_if_tx_alloc_rate = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 110, 1, 2, 1, 1, 5), gauge32()).setUnits('bits-per-second').setMaxAccess('readonly')
if mibBuilder.loadTexts:
cfaInterworkIfTxAllocRate.setStatus('current')
cisco_atm_switch_fr_rm_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 2))
cisco_atm_switch_fr_rm_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3))
cisco_atm_switch_fr_rm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1))
cisco_atm_switch_fr_rm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2))
cisco_atm_switch_fr_rm_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 1, 1)).setObjects(('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterGroup'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_atm_switch_fr_rm_mib_compliance = ciscoAtmSwitchFrRmMIBCompliance.setStatus('current')
cfa_adapter_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 1)).setObjects(('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVcQInqDiscThresh'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVcQOutqDiscThresh'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVcQInqMarkThresh'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVcQOutqMarkThresh'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfVbrServOflow'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaAdapterIfOverbooking'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfa_adapter_group = cfaAdapterGroup.setStatus('current')
cfa_interwork_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 110, 3, 2, 2)).setObjects(('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkIfRxAvailRate'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkIfTxAvailRate'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkIfRxAllocRate'), ('CISCO-ATM-SWITCH-FR-RM-MIB', 'cfaInterworkIfTxAllocRate'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cfa_interwork_group = cfaInterworkGroup.setStatus('current')
mibBuilder.exportSymbols('CISCO-ATM-SWITCH-FR-RM-MIB', cfaAdapterIfVcQOutqDiscThresh=cfaAdapterIfVcQOutqDiscThresh, PYSNMP_MODULE_ID=ciscoAtmSwitchFrRmMIB, cfaAdapterGroup=cfaAdapterGroup, cfaAdapterIfVcQThresholdEntry=cfaAdapterIfVcQThresholdEntry, cfaAdapterIfVbrServOflowEntry=cfaAdapterIfVbrServOflowEntry, cfaInterworkIfTxAvailRate=cfaInterworkIfTxAvailRate, ciscoAtmSwitchFrRmMIBConformance=ciscoAtmSwitchFrRmMIBConformance, cfaAdapterIfVbrServOflowTable=cfaAdapterIfVbrServOflowTable, cfaInterworkGroup=cfaInterworkGroup, ciscoAtmSwitchFrRmMIB=ciscoAtmSwitchFrRmMIB, cfaInterworkIfTxAllocRate=cfaInterworkIfTxAllocRate, cfaInterwork=cfaInterwork, ciscoAtmSwitchFrRmMIBGroups=ciscoAtmSwitchFrRmMIBGroups, cfaInterworkIfResourceTable=cfaInterworkIfResourceTable, ciscoAtmSwitchFrRmMIBCompliance=ciscoAtmSwitchFrRmMIBCompliance, ciscoAtmSwitchFrRmMIBNotifications=ciscoAtmSwitchFrRmMIBNotifications, cfaInterworkIfRxAvailRate=cfaInterworkIfRxAvailRate, ciscoAtmSwitchFrRmMIBCompliances=ciscoAtmSwitchFrRmMIBCompliances, cfaAdapter=cfaAdapter, cfaAdapterIfVcQThresholdTable=cfaAdapterIfVcQThresholdTable, cfaAdapterIfFrConfigEntry=cfaAdapterIfFrConfigEntry, cfaAdapterIfOverbooking=cfaAdapterIfOverbooking, cfaInterworkIfResourceEntry=cfaInterworkIfResourceEntry, cfaAdapterIfVcQInqMarkThresh=cfaAdapterIfVcQInqMarkThresh, cfaAdapterIfFrConfigTable=cfaAdapterIfFrConfigTable, cfaAdapterIfVcQInqDiscThresh=cfaAdapterIfVcQInqDiscThresh, cfaAdapterIfVcQOutqMarkThresh=cfaAdapterIfVcQOutqMarkThresh, ciscoAtmSwitchFrRmMIBObjects=ciscoAtmSwitchFrRmMIBObjects, cfaInterworkIfVcQService=cfaInterworkIfVcQService, cfaInterworkIfRxAllocRate=cfaInterworkIfRxAllocRate, cfaAdapterIfVcQService=cfaAdapterIfVcQService, cfaAdapterIfVbrServOflow=cfaAdapterIfVbrServOflow, CfaInterworkServiceCategory=CfaInterworkServiceCategory)
|
# Credentials for your Twitter bot account
# 1. Sign into Twitter or create new account
# 2. Make sure your mobile number is listed at twitter.com/settings/devices
# 3. Head to apps.twitter.com and select Keys and Access Tokens
CONSUMER_KEY = '6gTma2ITYHEh7MZMRJaflnxK7'
CONSUMER_SECRET = 'a20hHEbN1qudaR6RAdMCHtPKdOjpjiiNKabXjhj52Ajb4uHz2S'
# Create a new Access Token
ACCESS_TOKEN = '1051987549487534081-quzVSEUw33JJiImQ7mSnyvZvdTsmln'
ACCESS_SECRET = 'Uz5w4bC3heTN3efnA5yuh7lOZZMzYzkZYThykqRgnZUtu'
|
consumer_key = '6gTma2ITYHEh7MZMRJaflnxK7'
consumer_secret = 'a20hHEbN1qudaR6RAdMCHtPKdOjpjiiNKabXjhj52Ajb4uHz2S'
access_token = '1051987549487534081-quzVSEUw33JJiImQ7mSnyvZvdTsmln'
access_secret = 'Uz5w4bC3heTN3efnA5yuh7lOZZMzYzkZYThykqRgnZUtu'
|
numbers=list(range(1,21,2))
for i in range(len(numbers)):
print(numbers[i])
|
numbers = list(range(1, 21, 2))
for i in range(len(numbers)):
print(numbers[i])
|
#for c in range(2, 52, 2):
#print(c, end=' ')
#print('Acabo')
for c in range(1, 11):
print(c +c)
|
for c in range(1, 11):
print(c + c)
|
class Table:
def __init__(self, table):
self._table = table
@property
def name(self):
return self._table.__name__
@property
def thead(self):
all_fields = self._table._meta.fields
return [
field.verbose_name for field in all_fields if field.verbose_name != "ID"
]
@property
def tbody_sorted(self):
columns = {}
for row in self._table.objects.all().order_by("time__hour"):
key, data = row.get_record()
columns[key] = data
return columns
@property
def tbody(self):
columns = {}
for row in self._table.objects.all():
key, data = row.get_record()
columns[key] = data
return columns
@property
def inputFields(self):
return self._table.inputFields
|
class Table:
def __init__(self, table):
self._table = table
@property
def name(self):
return self._table.__name__
@property
def thead(self):
all_fields = self._table._meta.fields
return [field.verbose_name for field in all_fields if field.verbose_name != 'ID']
@property
def tbody_sorted(self):
columns = {}
for row in self._table.objects.all().order_by('time__hour'):
(key, data) = row.get_record()
columns[key] = data
return columns
@property
def tbody(self):
columns = {}
for row in self._table.objects.all():
(key, data) = row.get_record()
columns[key] = data
return columns
@property
def input_fields(self):
return self._table.inputFields
|
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_test_examples(self, data_dir, data_file_name, size=-1):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
|
class Dataprocessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise not_implemented_error()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise not_implemented_error()
def get_test_examples(self, data_dir, data_file_name, size=-1):
"""Gets a collection of `InputExample`s for the dev set."""
raise not_implemented_error()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise not_implemented_error()
|
class AmazonAnsible:
"""Main class to generate Ansible playbooks from Amazon
Args:
debug (bool, optional): debug option. Defaults to False.
from_file (str, optional): Optional file with all data. Defaults to ''.
"""
class AmazonAnsibleCalculation:
"""Class to generate all Ansible playbooks.
Args:
data (dict): Amazon info data to be used to generate the playbooks.
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, data, debug=False):
self.debug = debug
self.data = data
class AmazonInfo:
"""Retrieve information about Amazon cloud
Args:
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, debug=False):
self.debug = debug
self.data = {}
|
class Amazonansible:
"""Main class to generate Ansible playbooks from Amazon
Args:
debug (bool, optional): debug option. Defaults to False.
from_file (str, optional): Optional file with all data. Defaults to ''.
"""
class Amazonansiblecalculation:
"""Class to generate all Ansible playbooks.
Args:
data (dict): Amazon info data to be used to generate the playbooks.
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, data, debug=False):
self.debug = debug
self.data = data
class Amazoninfo:
"""Retrieve information about Amazon cloud
Args:
debug (bool, optional): debug option. Defaults to False.
"""
def __init__(self, debug=False):
self.debug = debug
self.data = {}
|
"""
Given an array of size n where all elements are distinct and in range from 0 to n-1,
change contents of arr[] so that arr[i] = j is changed to arr[j] = i.
"""
def rearrange(arr: list) -> list:
"""
Simplest approach would be to create and fill a temp array.
But it would require extra space.
In case there is only one cycle (test case 1), it is easy to do it
in one loop.
In case of multiple cycles(test case 2), the solution becomes more convulated
We can convert the processed values as -ve of the values and use some special value for 0.
We can also increment the values by 1 and save as -ve...
Afterwards we revert them
Time Complexity: O(n)
Space Complexity: O(1)
"""
l, i = len(arr), 0
while i < l: # let's use -l for 0
if arr[i] >= 0: # unprocessed
j = arr[i]
k = i
while j != i:
temp = arr[j]
arr[j] = -(k if k != 0 else l)
j, k = temp, j
arr[i] = -(k if k != 0 else l)
i += 1
for i in range(l):
arr[i] = -arr[i] % l
return arr
if __name__ == "__main__":
assert rearrange([1, 3, 0, 2]) == [2, 0, 3, 1]
assert rearrange([2, 0, 1, 4, 5, 3]) == [1, 2, 0, 5, 3, 4]
|
"""
Given an array of size n where all elements are distinct and in range from 0 to n-1,
change contents of arr[] so that arr[i] = j is changed to arr[j] = i.
"""
def rearrange(arr: list) -> list:
"""
Simplest approach would be to create and fill a temp array.
But it would require extra space.
In case there is only one cycle (test case 1), it is easy to do it
in one loop.
In case of multiple cycles(test case 2), the solution becomes more convulated
We can convert the processed values as -ve of the values and use some special value for 0.
We can also increment the values by 1 and save as -ve...
Afterwards we revert them
Time Complexity: O(n)
Space Complexity: O(1)
"""
(l, i) = (len(arr), 0)
while i < l:
if arr[i] >= 0:
j = arr[i]
k = i
while j != i:
temp = arr[j]
arr[j] = -(k if k != 0 else l)
(j, k) = (temp, j)
arr[i] = -(k if k != 0 else l)
i += 1
for i in range(l):
arr[i] = -arr[i] % l
return arr
if __name__ == '__main__':
assert rearrange([1, 3, 0, 2]) == [2, 0, 3, 1]
assert rearrange([2, 0, 1, 4, 5, 3]) == [1, 2, 0, 5, 3, 4]
|
in_data = {
u'deliveryOrder': {
u'warehouseCode': u'OTHER',
u'deliveryOrderCode': u'3600120100000',
u'receiverInfo': {
u'detailAddress': u'\u5927\u5382\u680818\u53f7101',
u'city': u'\u4e94\u8fde',
u'province': u'\u5c71\u4e1c',
u'area': u'\u5927\u5382'
},
u'senderInfo': {
u'detailAddress': u'\u6587\u4e09\u8def172\u53f7',
u'city': u'\u676d\u5dde',
},
},
u'orderLines': {
u'orderLine': [
{
u'itemId': u'0192010101',
u'planQty': u'20',
},
{
u'itemId': u'0192010102',
u'planQty': u'30',
}]
}
}
mapping = [
([u'deliveryOrder', u'warehouseCode'], 'warehouse_code'),
([u'deliveryOrder', u'deliveryOrderCode'], 'express_code'),
([u'deliveryOrder', u'receiverInfo', u'area'], 'receiver_area'),
([u'deliveryOrder', u'receiverInfo', u'province'], 'receiver_province'),
([u'deliveryOrder', u'receiverInfo', u'detailAddress'], 'receiver_address'),
([u'deliveryOrder', u'receiverInfo', u'city'], 'receiver_city'),
([u'deliveryOrder', u'senderInfo', u'city'], 'sender_city'),
([u'deliveryOrder', u'senderInfo', u'detailAddress'], 'sender_address'),
([u'orderLines', u'orderLine'], 'lines', [
([u'itemId'], 'item_id'),
([u'planQty'], 'product_qty'),
])
]
|
in_data = {u'deliveryOrder': {u'warehouseCode': u'OTHER', u'deliveryOrderCode': u'3600120100000', u'receiverInfo': {u'detailAddress': u'大厂栈18号101', u'city': u'五连', u'province': u'山东', u'area': u'大厂'}, u'senderInfo': {u'detailAddress': u'文三路172号', u'city': u'杭州'}}, u'orderLines': {u'orderLine': [{u'itemId': u'0192010101', u'planQty': u'20'}, {u'itemId': u'0192010102', u'planQty': u'30'}]}}
mapping = [([u'deliveryOrder', u'warehouseCode'], 'warehouse_code'), ([u'deliveryOrder', u'deliveryOrderCode'], 'express_code'), ([u'deliveryOrder', u'receiverInfo', u'area'], 'receiver_area'), ([u'deliveryOrder', u'receiverInfo', u'province'], 'receiver_province'), ([u'deliveryOrder', u'receiverInfo', u'detailAddress'], 'receiver_address'), ([u'deliveryOrder', u'receiverInfo', u'city'], 'receiver_city'), ([u'deliveryOrder', u'senderInfo', u'city'], 'sender_city'), ([u'deliveryOrder', u'senderInfo', u'detailAddress'], 'sender_address'), ([u'orderLines', u'orderLine'], 'lines', [([u'itemId'], 'item_id'), ([u'planQty'], 'product_qty')])]
|
pkgname = "firmware-ipw2100"
pkgver = "1.3"
pkgrel = 0
pkgdesc = "Firmware for the Intel PRO/Wireless 2100 wifi cards"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:ipw2100"
url = "http://ipw2100.sourceforge.net"
source = f"http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz"
sha256 = "e1107c455e48d324a616b47a622593bc8413dcce72026f72731c0b03dae3a7a2"
options = ["!strip", "foreignelf"]
def do_install(self):
for f in self.cwd.glob("*.fw"):
self.install_file(f, "usr/lib/firmware")
self.install_license("LICENSE")
|
pkgname = 'firmware-ipw2100'
pkgver = '1.3'
pkgrel = 0
pkgdesc = 'Firmware for the Intel PRO/Wireless 2100 wifi cards'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'custom:ipw2100'
url = 'http://ipw2100.sourceforge.net'
source = f'http://firmware.openbsd.org/firmware-dist/ipw2100-fw-{pkgver}.tgz'
sha256 = 'e1107c455e48d324a616b47a622593bc8413dcce72026f72731c0b03dae3a7a2'
options = ['!strip', 'foreignelf']
def do_install(self):
for f in self.cwd.glob('*.fw'):
self.install_file(f, 'usr/lib/firmware')
self.install_license('LICENSE')
|
'''Generates a javascript string to display flot graphs.
Please read README_flot_grapher.txt
Eliane Stampfer: eliane.stampfer@gmail.com
April 2009'''
class FlotGraph(object):
#constructor. Accepts an array of data, a title, an array of toggle-able data, and the
#width and height of the graph. All of these values are set to defaults if they are not provided.
def __init__(self, data=[], title='', toggle_data=[], width='600', height='300'):
self.display_title = title
self.title = title.replace(" ", "_")
self.data = data
self.height = height
self.width = width
self.xaxis_options=''
self.toggle_data = toggle_data
self.markings = []
self.enable_zoom = 1
self.zoomable = self.enable_zoom
self.enable_tooltip = 1
self.show_tooltip = self.enable_tooltip
self.xaxis_mode = "null"
self.yaxis_mode = "null"
self.xaxis_min = "null"
self.xaxis_max = "null"
self.yaxis_min = "null"
self.yaxis_max = "null"
self.time_format = "%d/%m/%y"
self.key_outside = 1
self.key_position = self.key_outside
self.javascript_string = ""
#/constructor
#Getters and Setters
#1 sets the key to outside the graph, anything else sets it to inside the graph.
def set_key_position(self, key_position):
self.key_position = key_position
def get_key_position(self):
return self.key_position
#1 enables zoom, anything else disables it
def set_zoomable(self, zoomable):
self.zoomable = zoomable
def get_zoomable(self):
return self.zoomable
#1 enables showing the tooltip, anything else disables it
def set_show_tooltip(self, tooltip):
self.show_tooltip = tooltip
def get_show_tooltip(self):
return self.show_tooltip
def set_markings(self, markings_array):
self.markings = markings_array
def get_markings(self):
return self.markings
def set_display_title(self, display_title):
self.display_title = display_title
def get_display_title(self):
return self.display_title
def set_title(self, title):
self.title = title.replace(" ", "_")
def get_title(self):
return self.title
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_toggle_data(self, toggle_data):
self.toggle_data = toggle_data
def get_toggle_data(self):
return self.toggle_data
def set_height(self, height):
self.height = height
def get_height(self):
return self.height
def set_width(self, width):
self.width = width
def get_width(self):
return self.width
def set_xaxis_min(self, xaxis_min):
self.xaxis_min = xaxis_min
def get_xaxis_min(self):
return self.xaxis_min
def set_xaxis_max(self, xaxis_max):
self.xaxis_max = xaxis_max
def get_xaxis_max(self):
return self.xaxis_max
def set_yaxis_min(self, yaxis_min):
self.yaxis_min = yaxis_min
def get_yaxis_min(self):
return self.yaxis_min
def set_yaxis_max(self, yaxis_max):
self.yaxis_max = yaxis_max
def get_yaxis_max(self):
return self.yaxis_max
def set_xaxis_mode(self, xaxis_mode):
if xaxis_mode == "time":
self.xaxis_mode = "\"" + xaxis_mode + "\""
if xaxis_mode == "null":
self.xaxis_mode = "null"
def get_xaxis_mode(self):
return self.xaxis_mode
def set_yaxis_mode(self, yaxis_mode):
if yaxis_mode == "time":
self.yaxis_mode = "\"" + yaxis_mode + "\""
if yaxis_mode == "null":
self.yaxis_mode = "null"
def get_yaxis_mode(self):
return self.yaxis_mode
def set_time_format(self, time_format):
self.time_format = time_format
def get_time_format(self):
return self.time_format
def get_plot_div(self):
return "plot_" + self.get_title()
#/getters and setters
#Methods that create the javascript string
#called by generate_javascript()
def get_heading_string(self):
string = "<h1>"+self.display_title+"</h1> \n"
string += "<div style=\"float:left\"> \n"
string += "\t<div id=\""+self.get_plot_div()+"\"></div>\n\t<p id=\""+self.get_title()+"_choices\">\n"
string += "<p id=\"message\"></p>"
string += "\t</p>\n"
if(self.get_zoomable() == self.enable_zoom):
string += "\t<p> <span id=\""+self.get_title()+"_xselection\"></span></p>\n"
string += "\t<p> <span id=\""+self.get_title()+"_yselection\"></span></p>\n"
string += "</div> \n"
string += "<div id=\""+self.get_plot_div()+"_miniature\" style=\"float:left;margin-left:20px;margin-top:50px\"> \n"
string += "\t<div id=\""+self.get_plot_div()+"_overview\" style=\"width:166px;height:100px\"></div> \n"
string += "\t<p id=\""+self.get_plot_div()+"_overviewLegend\" style=\"margin-left:10px\"></p>\n </div> \n\
<script id=\"source\" language=\"javascript\" type=\"text/javascript\">\n\
$(function(){\n"
return string;
#called by get_options_string()
def get_markings_string(self):
string = "\t\t\t\t\tmarkings: [\n"
for mark_area in self.markings:
string += "\t\t\t\t\t\t{"
if('xaxis' in mark_area):
xaxis = mark_area['xaxis']
if('from' in xaxis and 'to' in xaxis):
string += "xaxis: {from: "+xaxis['from']+", to: "+xaxis['to']+"}, "
if('yaxis' in mark_area):
yaxis = mark_area['yaxis']
if('from' in yaxis and 'to' in yaxis):
string += "yaxis: {from: "+yaxis['from']+", to: "+yaxis['to']+"}, "
if('color' in mark_area):
string += "color: \""+ mark_area['color']+"\""
if('label' in mark_area):
series_data = self.get_data()
series_data.append({'data': [], 'label': mark_area['label'], 'color': mark_area['color']})
self.set_data(series_data)
string += "},\n"
string += "\t\t\t\t\t],\n"
return string
#called by generate_javascript()
def get_options_string(self):
string = "\n\
var options = {\n\
legend: {\n"
if (self.get_zoomable() == self.enable_zoom):
string += "\t\t\t\t\tshow: false,\n"
string += "\t\t\t\t\tmargin: 5,\n\
backgroundOpacity:.05,\n"
if (not(self.get_zoomable() == self.enable_zoom)):
if (self.get_key_position() == self.key_outside):
string += "\t\t\t\t\tcontainer: $(\"#"+self.get_plot_div()+"_overviewLegend\")\n"
string +="\t\t\t\t},\n\
grid: { \n\
clickable: true,\n\
hoverable: true,\n"
string += self.get_markings_string()
string += "\t\t\t\t},\n\
selection: { \n\
mode: \"xy\"\n\
},\n"
string += self.get_axis_options()
string += "\n\
};\n"
return string
#called by get_options_string()
def get_axis_options(self):
string = "\n\
xaxis: {\n\
mode: "+ self.get_xaxis_mode()+",\n\
timeformat: \""+ self.time_format +"\",\n\
min: "+self.get_xaxis_min()+",\n\
max: "+self.get_xaxis_max()+", \n\
},"
string += "\n\
yaxis: {\n\
mode: "+ self.get_yaxis_mode()+",\n\
timeformat: \""+ self.time_format +"\",\n\
min: "+self.get_yaxis_min()+",\n\
max: "+self.get_yaxis_max()+", \n\
},"
return string
#called by generate_javascript()
def get_toggle_datasets_string(self):
string = "\n\nvar datasets = {"
counter = 0
string += self.get_series_string(self.toggle_data, 1)
#hard-code color indices to prevent them from shifting as
#series are turned on/off
string += "}\n"
string += "var i = "+ str(len(self.data)) + ";\n\
$.each(datasets, function(key, val) {\n\
val.color = i;\n\
++i;\n\
});\n"
return string
#called by generate_javascript()
def get_choice_container_string(self):
return "var choiceContainer = $(\"#"+self.get_title()+"_choices\");\n\
$.each(datasets, function(key, val) {\n\
choiceContainer.append('<br/><input type=\"checkbox\" name=\"' + key +\n\
'\" checked=\"checked\" >' + val.label + '</input>');\n\
});\n\
choiceContainer.find(\"input\").click(plotGraph);\n"
#called by generate_javascript()
def get_plot_area_string(self):
string = "\n\
var plotarea = $(\"#" + self.get_plot_div() + "\");\n\
plotarea.css(\"height\", \"" + str(self.get_height()) + "px\");\n\
plotarea.css(\"width\", \"" + str(self.get_width())+ "px\");\n\n"
return string
#called by get_plot_choices_string() and get_toggle_datasets_string()
def get_series_string(self, data_array, toggle=0):
counter = 1
string = ""
for series in data_array:
if('label' in series):
name = series['label']
else:
name = "series "+str(counter)
counter += 1
if(toggle == 1):
name_internal = name.lower()
string += " \n \t\t\t\"" + name_internal.replace(" ", "_") + "\":"
string += "{\n\
label: \"" + name + "\",\n"
if('lines' in series):
lines_dict = series['lines']
string += "\t\t\t\tlines: {\n\t\t\t\t\tshow: true, \n"
if('lineWidth' in lines_dict and lines_dict['lineWidth'].isdigit()):
string += "\t\t\t\t\tlineWidth: "+ str(lines_dict['lineWidth']) +",\n"
if('fill' in lines_dict):
string += "\t\t\t\t\tfill: "+str(lines_dict['fill']) +",\n"
string += "\t\t\t\t},\n"
if('bars' in series):
bars_dict = series['bars']
string += "\t\t\t\tbars: {\n\t\t\t\t\tshow: true, \n"
if('barWidth' in bars_dict):
string += "\t\t\t\t\tbarWidth: "+str(bars_dict['barWidth']) +",\n"
if('align' in bars_dict and (bars_dict['align'] == "left" or bars_dict['align'] == "center")):
string += "\t\t\t\t\talign: \""+str(bars_dict['align']) +"\",\n"
if('fill' in bars_dict):
string += "\t\t\t\t\tfill: "+str(bars_dict['fill']) +",\n"
string += "\t\t\t\t},\n"
if('points' in series):
points_dict = series['points']
string += "\t\t\t\tpoints: {\n\t\t\t\t\tshow: true, \n"
if('radius' in points_dict and points_dict['radius'].isdigit()):
string += "\t\t\t\t\tradius: "+ str(points_dict['radius']) +",\n"
string += "\t\t\t\t},\n"
if(not('lines' in series) and not('bars' in series) and not ('points' in series)):
string += "\t\t\t\tlines: {\n\t\t\t\t\tshow: true\n\t\t\t\t}, \n\t\t\t\tpoints: {\n\t\t\t\t\tshow: true\n\t\t\t\t},\n"
if('color' in series):
string += "\t\t\t\tcolor: \""+series['color']+"\",\n"
string += "\t\t\t\tdata: [\n\t\t\t\t\t"
for point in series['data']:
string += "[" + str(point[0]) +", " + str(point[1]) + "],"
string += "\n\t\t\t\t]\n\t\t\t},"
return string
#/get_series_string
#called by generate_javascript()
def get_plot_choices_string(self):
string = "function getChoices() {\n\
\n\
var data = ["
string += self.get_series_string(self.data)
string += "];\n\
choiceContainer.find(\"input:checked\").each(function () {\n\
var key = $(this).attr(\"name\");\n\
if (key && datasets[key])\n\
data.push(datasets[key]);\n\
});\n\
\n\
return data;\n\
}\n"
return string
#called by generate_javascript() if the tooltip is enabled.
def get_show_tooltip_string(self):
string = "function showTooltip(x, y, contents) {\n\
$('<div id=\""+self.get_title()+"_tooltip\">' + contents + '</div>').css( {\n\
position: 'absolute',\n\
display: 'none',\n\
top: y + 5,\n\
left: x + 5,\n\
border: '1px solid #fdd',\n\
padding: '2px',\n\
'background-color': '#fee',\n\
opacity: 0.80\n\
}).appendTo(\"body\").fadeIn(200);\n\
}\n"
string += "var previousPoint = null;\n\
$(\"#" + self.get_plot_div() + "\").bind(\"plothover\", function (event, pos, item) {\n\
$(\"#x\").text(pos.x.toFixed(2));\n\
$(\"#y\").text(pos.y.toFixed(2));\n"
string += "if (item) {\n\
if (previousPoint != item.datapoint) {\n\
previousPoint = item.datapoint;\n"
string += "\n $(\"#"+self.get_title()+"_tooltip\").remove();\n\
var x = item.datapoint[0].toFixed(2),\n\
y = item.datapoint[1].toFixed(2);\n\n\
showTooltip(item.pageX, item.pageY, item.series.label + \": (\" + x + \", \" + y+ \")\");\n\
}\n\
}\n\
else {\n\
$(\"#"+self.get_title()+"_tooltip\").remove();\n"
string += "previousPoint = null;\n }\n });"
return string
#called by generate_javascript()
def get_plot_graph_string(self):
string = "var first = 0;\n\
function plotGraph(min_x, max_x, min_y, max_y){\n\
data = getChoices();\n\
if (min_x != null && max_x != null && min_y != null && max_y != null){\n\
$(\"#"+self.get_title()+"_selection\").text(\" \");\n\
graph_obj = $.plot(plotarea, data,\n\
$.extend(true, {}, options, {\n\
xaxis: { min: min_x, max: max_x},\n\
yaxis: { min: min_y, max: max_y},\n\
}));\n\
\n\
}\n\
else\n\
var flot_plot = $.plot(plotarea, data, options);\n\
}\n\
plotGraph();\n\
plotOver();\n"
return string
#called by generate_javascript()
def get_zoom_with_overview(self):
string = "function plotOver(){\nvar data_over = getChoices();\n\
overview = $.plot($(\"#"+self.get_plot_div()+"_overview\"), data_over, {\n\
legend: { show: true, container: $(\"#"+self.get_plot_div()+"_overviewLegend\"), },\n\
shadowSize: 0,\n\
xaxis: { ticks: 4, min: "+self.get_xaxis_min()+", max: "+self.get_xaxis_max()+",},\n\
yaxis: { ticks: 3, min: "+self.get_yaxis_min()+", max: "+self.get_yaxis_max()+",},\n\
grid: {clickable: true, autoHighlight: false, " +self.get_markings_string()+"},\n\
selection: { mode: \"xy\" }\n\
});\n}\n"
string += " $(\"#"+self.get_plot_div()+"\").bind(\"plotselected\", function (event, ranges){ \n"
string += "\n\
// clamp the zooming to prevent eternal zoom \n\
if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)\n\
ranges.xaxis.to = ranges.xaxis.from + 0.00001;\n\
if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)\n\
ranges.yaxis.to = ranges.yaxis.from + 0.00001;\n\
\n\
// do the zooming\n\
plotGraph(ranges.xaxis.from, ranges.xaxis.to, ranges.yaxis.from, ranges.yaxis.to);\n\
$(\"#"+self.get_title()+"_xselection\").text(\"x-axis: \" +ranges.xaxis.from.toFixed(1) + \" to \" +ranges.xaxis.to.toFixed(1))\n"
string += "$(\"#"+self.get_title()+"_yselection\").text(\"y-axis: \" +ranges.yaxis.from.toFixed(1) + \" to \" +ranges.yaxis.to.toFixed(1))\n\
// don't fire event on the overview to prevent eternal loop\n\
overview.setSelection(ranges, true);\n\
});\n"
string += "$(\"#"+self.get_plot_div()+"_overview\").bind(\"plotselected\", function (event, ranges) {\n\
plot.setSelection(ranges);\n\
});\n"
string += "$(\"#"+self.get_plot_div()+"_overview\").bind(\"plotclick\", function (event, pos) {\n\
var axes = overview.getAxes();\n\
var y_min = axes.yaxis.min;\n\
var y_max = axes.yaxis.max;\n\
var x_min = axes.xaxis.min;\n\
var x_max = axes.xaxis.max;\n\
plotGraph(x_min, x_max, y_min, y_max);\n\
});\n"
return string
#called by generate_javascript()
def get_footer_string(self):
return " });\n\
</script>"
#assembles the javascript string
def generate_javascript(self):
javascript_string = self.get_heading_string()
javascript_string += self.get_options_string()
javascript_string += self.get_toggle_datasets_string()
javascript_string += self.get_choice_container_string()
javascript_string += self.get_plot_area_string()
javascript_string += self.get_plot_choices_string()
if(self.get_show_tooltip() == self.enable_tooltip):
javascript_string += self.get_show_tooltip_string()
javascript_string += self.get_plot_graph_string()
if(self.get_zoomable() == self.enable_zoom):
javascript_string += self.get_zoom_with_overview()
javascript_string += self.get_footer_string()
javascript_string.replace("\\n", "\n")
javascript_string.replace("\\t", "\t")
self.javascript_string = javascript_string
return javascript_string
|
"""Generates a javascript string to display flot graphs.
Please read README_flot_grapher.txt
Eliane Stampfer: eliane.stampfer@gmail.com
April 2009"""
class Flotgraph(object):
def __init__(self, data=[], title='', toggle_data=[], width='600', height='300'):
self.display_title = title
self.title = title.replace(' ', '_')
self.data = data
self.height = height
self.width = width
self.xaxis_options = ''
self.toggle_data = toggle_data
self.markings = []
self.enable_zoom = 1
self.zoomable = self.enable_zoom
self.enable_tooltip = 1
self.show_tooltip = self.enable_tooltip
self.xaxis_mode = 'null'
self.yaxis_mode = 'null'
self.xaxis_min = 'null'
self.xaxis_max = 'null'
self.yaxis_min = 'null'
self.yaxis_max = 'null'
self.time_format = '%d/%m/%y'
self.key_outside = 1
self.key_position = self.key_outside
self.javascript_string = ''
def set_key_position(self, key_position):
self.key_position = key_position
def get_key_position(self):
return self.key_position
def set_zoomable(self, zoomable):
self.zoomable = zoomable
def get_zoomable(self):
return self.zoomable
def set_show_tooltip(self, tooltip):
self.show_tooltip = tooltip
def get_show_tooltip(self):
return self.show_tooltip
def set_markings(self, markings_array):
self.markings = markings_array
def get_markings(self):
return self.markings
def set_display_title(self, display_title):
self.display_title = display_title
def get_display_title(self):
return self.display_title
def set_title(self, title):
self.title = title.replace(' ', '_')
def get_title(self):
return self.title
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_toggle_data(self, toggle_data):
self.toggle_data = toggle_data
def get_toggle_data(self):
return self.toggle_data
def set_height(self, height):
self.height = height
def get_height(self):
return self.height
def set_width(self, width):
self.width = width
def get_width(self):
return self.width
def set_xaxis_min(self, xaxis_min):
self.xaxis_min = xaxis_min
def get_xaxis_min(self):
return self.xaxis_min
def set_xaxis_max(self, xaxis_max):
self.xaxis_max = xaxis_max
def get_xaxis_max(self):
return self.xaxis_max
def set_yaxis_min(self, yaxis_min):
self.yaxis_min = yaxis_min
def get_yaxis_min(self):
return self.yaxis_min
def set_yaxis_max(self, yaxis_max):
self.yaxis_max = yaxis_max
def get_yaxis_max(self):
return self.yaxis_max
def set_xaxis_mode(self, xaxis_mode):
if xaxis_mode == 'time':
self.xaxis_mode = '"' + xaxis_mode + '"'
if xaxis_mode == 'null':
self.xaxis_mode = 'null'
def get_xaxis_mode(self):
return self.xaxis_mode
def set_yaxis_mode(self, yaxis_mode):
if yaxis_mode == 'time':
self.yaxis_mode = '"' + yaxis_mode + '"'
if yaxis_mode == 'null':
self.yaxis_mode = 'null'
def get_yaxis_mode(self):
return self.yaxis_mode
def set_time_format(self, time_format):
self.time_format = time_format
def get_time_format(self):
return self.time_format
def get_plot_div(self):
return 'plot_' + self.get_title()
def get_heading_string(self):
string = '<h1>' + self.display_title + '</h1> \n'
string += '<div style="float:left"> \n'
string += '\t<div id="' + self.get_plot_div() + '"></div>\n\t<p id="' + self.get_title() + '_choices">\n'
string += '<p id="message"></p>'
string += '\t</p>\n'
if self.get_zoomable() == self.enable_zoom:
string += '\t<p> <span id="' + self.get_title() + '_xselection"></span></p>\n'
string += '\t<p> <span id="' + self.get_title() + '_yselection"></span></p>\n'
string += '</div> \n'
string += '<div id="' + self.get_plot_div() + '_miniature" style="float:left;margin-left:20px;margin-top:50px"> \n'
string += '\t<div id="' + self.get_plot_div() + '_overview" style="width:166px;height:100px"></div> \n'
string += '\t<p id="' + self.get_plot_div() + '_overviewLegend" style="margin-left:10px"></p>\n </div> \n\t\t<script id="source" language="javascript" type="text/javascript">\n\t\t$(function(){\n'
return string
def get_markings_string(self):
string = '\t\t\t\t\tmarkings: [\n'
for mark_area in self.markings:
string += '\t\t\t\t\t\t{'
if 'xaxis' in mark_area:
xaxis = mark_area['xaxis']
if 'from' in xaxis and 'to' in xaxis:
string += 'xaxis: {from: ' + xaxis['from'] + ', to: ' + xaxis['to'] + '}, '
if 'yaxis' in mark_area:
yaxis = mark_area['yaxis']
if 'from' in yaxis and 'to' in yaxis:
string += 'yaxis: {from: ' + yaxis['from'] + ', to: ' + yaxis['to'] + '}, '
if 'color' in mark_area:
string += 'color: "' + mark_area['color'] + '"'
if 'label' in mark_area:
series_data = self.get_data()
series_data.append({'data': [], 'label': mark_area['label'], 'color': mark_area['color']})
self.set_data(series_data)
string += '},\n'
string += '\t\t\t\t\t],\n'
return string
def get_options_string(self):
string = '\n\t\tvar options = {\n\t\t\t\tlegend: {\n'
if self.get_zoomable() == self.enable_zoom:
string += '\t\t\t\t\tshow: false,\n'
string += '\t\t\t\t\tmargin: 5,\n\t\t\t\t\tbackgroundOpacity:.05,\n'
if not self.get_zoomable() == self.enable_zoom:
if self.get_key_position() == self.key_outside:
string += '\t\t\t\t\tcontainer: $("#' + self.get_plot_div() + '_overviewLegend")\n'
string += '\t\t\t\t},\n\t\t\t\tgrid: { \n\t\t\t\t\tclickable: true,\n\t\t\t\t\thoverable: true,\n'
string += self.get_markings_string()
string += '\t\t\t\t},\n\t\t\t\tselection: { \n\t\t\t\t\tmode: "xy"\n\t\t\t\t},\n'
string += self.get_axis_options()
string += '\n\t\t};\n'
return string
def get_axis_options(self):
string = '\n\t\t\t\txaxis: {\n\t\t\t\t\tmode: ' + self.get_xaxis_mode() + ',\n\t\t\t\t\ttimeformat: "' + self.time_format + '",\n\t\t\t\t\tmin: ' + self.get_xaxis_min() + ',\n\t\t\t\t\tmax: ' + self.get_xaxis_max() + ', \n\t\t\t\t},'
string += '\n\t\t\t\tyaxis: {\n\t\t\t\t\tmode: ' + self.get_yaxis_mode() + ',\n\t\t\t\t\ttimeformat: "' + self.time_format + '",\n\t\t\t\t\tmin: ' + self.get_yaxis_min() + ',\n\t\t\t\t\tmax: ' + self.get_yaxis_max() + ', \n\t\t\t\t},'
return string
def get_toggle_datasets_string(self):
string = '\n\nvar datasets = {'
counter = 0
string += self.get_series_string(self.toggle_data, 1)
string += '}\n'
string += 'var i = ' + str(len(self.data)) + ';\n $.each(datasets, function(key, val) {\n val.color = i;\n ++i;\n });\n'
return string
def get_choice_container_string(self):
return 'var choiceContainer = $("#' + self.get_title() + '_choices");\n \t\t$.each(datasets, function(key, val) {\n \tchoiceContainer.append(\'<br/><input type="checkbox" name="\' + key +\n \'" checked="checked" >\' + val.label + \'</input>\');\n \t\t});\n \t\tchoiceContainer.find("input").click(plotGraph);\n'
def get_plot_area_string(self):
string = '\n\t\t\tvar plotarea = $("#' + self.get_plot_div() + '");\n \t\t\tplotarea.css("height", "' + str(self.get_height()) + 'px");\n \t\tplotarea.css("width", "' + str(self.get_width()) + 'px");\n\n'
return string
def get_series_string(self, data_array, toggle=0):
counter = 1
string = ''
for series in data_array:
if 'label' in series:
name = series['label']
else:
name = 'series ' + str(counter)
counter += 1
if toggle == 1:
name_internal = name.lower()
string += ' \n \t\t\t"' + name_internal.replace(' ', '_') + '":'
string += '{\n\t\t\t\tlabel: "' + name + '",\n'
if 'lines' in series:
lines_dict = series['lines']
string += '\t\t\t\tlines: {\n\t\t\t\t\tshow: true, \n'
if 'lineWidth' in lines_dict and lines_dict['lineWidth'].isdigit():
string += '\t\t\t\t\tlineWidth: ' + str(lines_dict['lineWidth']) + ',\n'
if 'fill' in lines_dict:
string += '\t\t\t\t\tfill: ' + str(lines_dict['fill']) + ',\n'
string += '\t\t\t\t},\n'
if 'bars' in series:
bars_dict = series['bars']
string += '\t\t\t\tbars: {\n\t\t\t\t\tshow: true, \n'
if 'barWidth' in bars_dict:
string += '\t\t\t\t\tbarWidth: ' + str(bars_dict['barWidth']) + ',\n'
if 'align' in bars_dict and (bars_dict['align'] == 'left' or bars_dict['align'] == 'center'):
string += '\t\t\t\t\talign: "' + str(bars_dict['align']) + '",\n'
if 'fill' in bars_dict:
string += '\t\t\t\t\tfill: ' + str(bars_dict['fill']) + ',\n'
string += '\t\t\t\t},\n'
if 'points' in series:
points_dict = series['points']
string += '\t\t\t\tpoints: {\n\t\t\t\t\tshow: true, \n'
if 'radius' in points_dict and points_dict['radius'].isdigit():
string += '\t\t\t\t\tradius: ' + str(points_dict['radius']) + ',\n'
string += '\t\t\t\t},\n'
if not 'lines' in series and (not 'bars' in series) and (not 'points' in series):
string += '\t\t\t\tlines: {\n\t\t\t\t\tshow: true\n\t\t\t\t}, \n\t\t\t\tpoints: {\n\t\t\t\t\tshow: true\n\t\t\t\t},\n'
if 'color' in series:
string += '\t\t\t\tcolor: "' + series['color'] + '",\n'
string += '\t\t\t\tdata: [\n\t\t\t\t\t'
for point in series['data']:
string += '[' + str(point[0]) + ', ' + str(point[1]) + '],'
string += '\n\t\t\t\t]\n\t\t\t},'
return string
def get_plot_choices_string(self):
string = 'function getChoices() {\n\t\t\t\n\t\t\tvar data = ['
string += self.get_series_string(self.data)
string += '];\n choiceContainer.find("input:checked").each(function () {\n var key = $(this).attr("name");\n if (key && datasets[key])\n data.push(datasets[key]);\n });\n\t\t\t\n return data;\n }\n'
return string
def get_show_tooltip_string(self):
string = 'function showTooltip(x, y, contents) {\n $(\'<div id="' + self.get_title() + '_tooltip">\' + contents + \'</div>\').css( {\n position: \'absolute\',\n display: \'none\',\n top: y + 5,\n left: x + 5,\n border: \'1px solid #fdd\',\n padding: \'2px\',\n \'background-color\': \'#fee\',\n opacity: 0.80\n }).appendTo("body").fadeIn(200);\n }\n'
string += 'var previousPoint = null;\n $("#' + self.get_plot_div() + '").bind("plothover", function (event, pos, item) {\n $("#x").text(pos.x.toFixed(2));\n $("#y").text(pos.y.toFixed(2));\n'
string += 'if (item) {\n if (previousPoint != item.datapoint) {\n previousPoint = item.datapoint;\n'
string += '\n $("#' + self.get_title() + '_tooltip").remove();\n var x = item.datapoint[0].toFixed(2),\n y = item.datapoint[1].toFixed(2);\n\n showTooltip(item.pageX, item.pageY, item.series.label + ": (" + x + ", " + y+ ")");\n }\n }\n else {\n $("#' + self.get_title() + '_tooltip").remove();\n'
string += 'previousPoint = null;\n }\n });'
return string
def get_plot_graph_string(self):
string = 'var first = 0;\nfunction plotGraph(min_x, max_x, min_y, max_y){\n\tdata = getChoices();\n\tif (min_x != null && max_x != null && min_y != null && max_y != null){\n\t\t$("#' + self.get_title() + '_selection").text(" ");\n\t\tgraph_obj = $.plot(plotarea, data,\n\t\t$.extend(true, {}, options, {\n\t\txaxis: { min: min_x, max: max_x},\n\t\tyaxis: { min: min_y, max: max_y},\n\t\t}));\n \t\n\t}\n\telse\n\t\tvar flot_plot = $.plot(plotarea, data, options);\n}\nplotGraph();\nplotOver();\n'
return string
def get_zoom_with_overview(self):
string = 'function plotOver(){\nvar data_over = getChoices();\n\t\toverview = $.plot($("#' + self.get_plot_div() + '_overview"), data_over, {\n legend: { show: true, container: $("#' + self.get_plot_div() + '_overviewLegend"), },\n shadowSize: 0,\n xaxis: { ticks: 4, min: ' + self.get_xaxis_min() + ', max: ' + self.get_xaxis_max() + ',},\n yaxis: { ticks: 3, min: ' + self.get_yaxis_min() + ', max: ' + self.get_yaxis_max() + ',},\n\t\t grid: {clickable: true, autoHighlight: false, ' + self.get_markings_string() + '},\n selection: { mode: "xy" }\n });\n}\n'
string += ' $("#' + self.get_plot_div() + '").bind("plotselected", function (event, ranges){ \n'
string += '\n // clamp the zooming to prevent eternal zoom \n if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)\n ranges.xaxis.to = ranges.xaxis.from + 0.00001;\n if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)\n ranges.yaxis.to = ranges.yaxis.from + 0.00001;\n \n // do the zooming\n\t\t plotGraph(ranges.xaxis.from, ranges.xaxis.to, ranges.yaxis.from, ranges.yaxis.to);\n\t\t $("#' + self.get_title() + '_xselection").text("x-axis: " +ranges.xaxis.from.toFixed(1) + " to " +ranges.xaxis.to.toFixed(1))\n'
string += '$("#' + self.get_title() + '_yselection").text("y-axis: " +ranges.yaxis.from.toFixed(1) + " to " +ranges.yaxis.to.toFixed(1))\n // don\'t fire event on the overview to prevent eternal loop\n overview.setSelection(ranges, true);\n });\n'
string += '$("#' + self.get_plot_div() + '_overview").bind("plotselected", function (event, ranges) {\n plot.setSelection(ranges);\n });\n'
string += '$("#' + self.get_plot_div() + '_overview").bind("plotclick", function (event, pos) {\n\t\t\tvar axes = overview.getAxes();\n\t\t\tvar y_min = axes.yaxis.min;\n\t\t\tvar y_max = axes.yaxis.max;\n\t\t\tvar x_min = axes.xaxis.min;\n\t\t\tvar x_max = axes.xaxis.max;\n\t\t plotGraph(x_min, x_max, y_min, y_max);\n });\n'
return string
def get_footer_string(self):
return ' });\n\t\t</script>'
def generate_javascript(self):
javascript_string = self.get_heading_string()
javascript_string += self.get_options_string()
javascript_string += self.get_toggle_datasets_string()
javascript_string += self.get_choice_container_string()
javascript_string += self.get_plot_area_string()
javascript_string += self.get_plot_choices_string()
if self.get_show_tooltip() == self.enable_tooltip:
javascript_string += self.get_show_tooltip_string()
javascript_string += self.get_plot_graph_string()
if self.get_zoomable() == self.enable_zoom:
javascript_string += self.get_zoom_with_overview()
javascript_string += self.get_footer_string()
javascript_string.replace('\\n', '\n')
javascript_string.replace('\\t', '\t')
self.javascript_string = javascript_string
return javascript_string
|
def merge(seq, first, mid, last):
(left, right) = (seq[first: mid], seq[mid: last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
seq[curr] = right[r]
r += 1
curr += 1
(x, rest) = (r, right) if (l == left_size) else (l, left)
while x != len(rest):
seq[curr] = rest[x]
(x, curr) = (x+1, curr+1)
def merge_sort(seq, first, last):
if first + 1 < last:
mid = first + (last-first)//2
merge_sort(seq, first, mid)
merge_sort(seq, mid, last)
merge(seq, first, mid, last)
li = [3, 2, 1, 88, 1000, -1]
merge_sort(li, 0, len(li))
print(li)
ls = ["aaa", "1234", "hello", "google", "hi"]
merge_sort(ls, 0, len(ls))
print(ls)
"""
output:
[1, 2, 3, 4]
['1234', 'aaa', 'google', 'hello', 'hi']
"""
|
def merge(seq, first, mid, last):
(left, right) = (seq[first:mid], seq[mid:last])
(l, r, curr) = (0, 0, first)
(left_size, right_size) = (len(left), len(right))
while l != left_size and r != right_size:
if left[l] < right[r]:
seq[curr] = left[l]
l += 1
else:
seq[curr] = right[r]
r += 1
curr += 1
(x, rest) = (r, right) if l == left_size else (l, left)
while x != len(rest):
seq[curr] = rest[x]
(x, curr) = (x + 1, curr + 1)
def merge_sort(seq, first, last):
if first + 1 < last:
mid = first + (last - first) // 2
merge_sort(seq, first, mid)
merge_sort(seq, mid, last)
merge(seq, first, mid, last)
li = [3, 2, 1, 88, 1000, -1]
merge_sort(li, 0, len(li))
print(li)
ls = ['aaa', '1234', 'hello', 'google', 'hi']
merge_sort(ls, 0, len(ls))
print(ls)
"\noutput:\n[1, 2, 3, 4]\n['1234', 'aaa', 'google', 'hello', 'hi']\n"
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Decode:
def __init__(self, length, K, n, weight):
self.K = K
self.length = length
self.n = n
self.weight = weight
self.solution = [False for i in range(0, n + 1)]
def Search(self):
# Initialize
insert = [[False for k in range(0, self.K + 2)]for i in range(0, self.n + 2)]
score = [[0 for k in range(0, self.K + 2)]for i in range(0, self.n + 2)]
# Loop
for i in range(1, self.n + 1):
for k in range(1, self.K + 1):
if self.length[i] <= k and score[i - 1][k] <= score[i - 1][k - self.length[i]] + self.weight[i]:
insert[i][k] = True
score[i][k] = score[i - 1][k - self.length[i]] + self.weight[i]
else:
score[i][k] = score[i - 1][k]
# Trace
k = self.K
for i in range(self.n, 0, -1):
if insert[i][k] == True:
k = k - self.length[i]
self.solution[i] = True
def GetSolution(self):
return self.solution
if __name__ == '__main__':
pass
|
class Decode:
def __init__(self, length, K, n, weight):
self.K = K
self.length = length
self.n = n
self.weight = weight
self.solution = [False for i in range(0, n + 1)]
def search(self):
insert = [[False for k in range(0, self.K + 2)] for i in range(0, self.n + 2)]
score = [[0 for k in range(0, self.K + 2)] for i in range(0, self.n + 2)]
for i in range(1, self.n + 1):
for k in range(1, self.K + 1):
if self.length[i] <= k and score[i - 1][k] <= score[i - 1][k - self.length[i]] + self.weight[i]:
insert[i][k] = True
score[i][k] = score[i - 1][k - self.length[i]] + self.weight[i]
else:
score[i][k] = score[i - 1][k]
k = self.K
for i in range(self.n, 0, -1):
if insert[i][k] == True:
k = k - self.length[i]
self.solution[i] = True
def get_solution(self):
return self.solution
if __name__ == '__main__':
pass
|
lines = []
with open('input.txt','r') as INPUT:
lines = INPUT.readlines()
M = int(lines[0])
stack = [None]*M
stack_head = -1
with open('output.txt', 'w') as OUTPUT:
for op in lines[1:]:
if op.startswith('+'):
stack_head += 1
stack[stack_head] = op[2:]
elif op.startswith('-'):
OUTPUT.write(stack[stack_head])
stack_head -= 1
print(op, stack)
|
lines = []
with open('input.txt', 'r') as input:
lines = INPUT.readlines()
m = int(lines[0])
stack = [None] * M
stack_head = -1
with open('output.txt', 'w') as output:
for op in lines[1:]:
if op.startswith('+'):
stack_head += 1
stack[stack_head] = op[2:]
elif op.startswith('-'):
OUTPUT.write(stack[stack_head])
stack_head -= 1
print(op, stack)
|
class BaseScraper:
pass
|
class Basescraper:
pass
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 17:12:03 2020
@author: kanukuma
"""
def popularNFeatures(numFeatures, topFeatures, possibleFeatures,
numFeatureRequests, featureRequests):
ngramsList = []
resultList = []
for featureRequest in featureRequests:
ngramsList.append( featureRequest.split())
print(ngramsList)
for feature in possibleFeatures:
for ngrams in ngramsList:
print(feature)
flag = feature in ngrams
print(flag)
if flag ==True:
resultList.append((feature, ngrams.count(feature)))
return resultList;
lst = ["abc","cde","def","efg"]
lst2 = ["abc is good then bcd","bcd is bad then cde, def","cde is good then bcd","def is good then all"]
print(popularNFeatures(4, 2, lst, 4, lst2));
|
"""
Created on Sun Jun 14 17:12:03 2020
@author: kanukuma
"""
def popular_n_features(numFeatures, topFeatures, possibleFeatures, numFeatureRequests, featureRequests):
ngrams_list = []
result_list = []
for feature_request in featureRequests:
ngramsList.append(featureRequest.split())
print(ngramsList)
for feature in possibleFeatures:
for ngrams in ngramsList:
print(feature)
flag = feature in ngrams
print(flag)
if flag == True:
resultList.append((feature, ngrams.count(feature)))
return resultList
lst = ['abc', 'cde', 'def', 'efg']
lst2 = ['abc is good then bcd', 'bcd is bad then cde, def', 'cde is good then bcd', 'def is good then all']
print(popular_n_features(4, 2, lst, 4, lst2))
|
def is_sequence(x):
""" Returns whether x is a sequence (tuple, list).
:param x: a value to check
:returns: (boolean)
"""
return (not hasattr(x, 'strip') and
hasattr(x, '__getitem__') or
hasattr(x, '__iter__'))
|
def is_sequence(x):
""" Returns whether x is a sequence (tuple, list).
:param x: a value to check
:returns: (boolean)
"""
return not hasattr(x, 'strip') and hasattr(x, '__getitem__') or hasattr(x, '__iter__')
|
k = int(input())
s = input()
prevlen = 0
ans = 0
for i in range(k, len(s)):
if s[i] == s[i - k]:
prevlen += 1
ans += prevlen
else:
prevlen = 0
print(ans)
|
k = int(input())
s = input()
prevlen = 0
ans = 0
for i in range(k, len(s)):
if s[i] == s[i - k]:
prevlen += 1
ans += prevlen
else:
prevlen = 0
print(ans)
|
##########################################################################
# Gene prediction pipeline
#
# $Id: AGP.py 2781 2009-09-10 11:33:14Z andreas $
#
# Copyright (C) 2005 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##########################################################################
"""AGP.py - working with AGP files
=====================================================
This module contains a parser for reading from :term:`agp` formatted
files.
Code
----
"""
class ObjectPosition(object):
def map(self, start, end):
if self.mOrientation:
return start + self.start, end + self.start
else:
return end + self.start, start + self.start
class AGP(object):
"""Parser for AGP formatted files."""
def readFromFile(self, infile):
"""read an agp file.
Example line::
scaffold_1 1 1199 1 W contig_13 1 1199 +
This method converts coordinates to zero-based coordinates
using open/closed notation.
In AGP nomenclature
(http://www.ncbi.nlm.nih.gov/genome/guide/Assembly/AGP_Specification.html)
objects (obj) like scaffolds are assembled from components
(com) like contigs.
Component types are
W
WGS sequence
N
gap of specified length.
"""
self.mMapComponent2Object = {}
self.mMapObject2Component = {}
for line in infile:
if line[0] == "#":
continue
data = line[:-1].split("\t")
obj_id, obj_start, obj_end, ncoms, com_type, com_id = data[:6]
if com_type == "N":
continue
com_start, com_end, orientation = data[6:9]
obj_start, obj_end = int(obj_start) - 1, int(obj_end)
com_start, com_end = int(com_start) - 1, int(com_end)
orientation = orientation in ("+", "0", "na")
if com_start != 0:
raise "beware, non zero com_start"
object = ObjectPosition()
object.mId = obj_id
object.start = obj_start
object.end = obj_end
object.mOrientation = orientation
self.mMapComponent2Object[com_id] = object
def mapLocation(self, id, start, end):
"""map a genomic location.
Raises
------
KeyError
If `id` is not present.
"""
if id not in self.mMapComponent2Object:
raise KeyError("id %s is not known" % (id))
pos = self.mMapComponent2Object[id]
return (pos.mId, ) + pos.map(start, end)
|
"""AGP.py - working with AGP files
=====================================================
This module contains a parser for reading from :term:`agp` formatted
files.
Code
----
"""
class Objectposition(object):
def map(self, start, end):
if self.mOrientation:
return (start + self.start, end + self.start)
else:
return (end + self.start, start + self.start)
class Agp(object):
"""Parser for AGP formatted files."""
def read_from_file(self, infile):
"""read an agp file.
Example line::
scaffold_1 1 1199 1 W contig_13 1 1199 +
This method converts coordinates to zero-based coordinates
using open/closed notation.
In AGP nomenclature
(http://www.ncbi.nlm.nih.gov/genome/guide/Assembly/AGP_Specification.html)
objects (obj) like scaffolds are assembled from components
(com) like contigs.
Component types are
W
WGS sequence
N
gap of specified length.
"""
self.mMapComponent2Object = {}
self.mMapObject2Component = {}
for line in infile:
if line[0] == '#':
continue
data = line[:-1].split('\t')
(obj_id, obj_start, obj_end, ncoms, com_type, com_id) = data[:6]
if com_type == 'N':
continue
(com_start, com_end, orientation) = data[6:9]
(obj_start, obj_end) = (int(obj_start) - 1, int(obj_end))
(com_start, com_end) = (int(com_start) - 1, int(com_end))
orientation = orientation in ('+', '0', 'na')
if com_start != 0:
raise 'beware, non zero com_start'
object = object_position()
object.mId = obj_id
object.start = obj_start
object.end = obj_end
object.mOrientation = orientation
self.mMapComponent2Object[com_id] = object
def map_location(self, id, start, end):
"""map a genomic location.
Raises
------
KeyError
If `id` is not present.
"""
if id not in self.mMapComponent2Object:
raise key_error('id %s is not known' % id)
pos = self.mMapComponent2Object[id]
return (pos.mId,) + pos.map(start, end)
|
# Equality checks should behave the same way as assignment
# Variable equality check
bar == {'a': 1, 'b':2}
bar == {
'a': 1,
'b': 2,
}
# Function equality check
foo() == {
'a': 1,
'b': 2,
'c': 3,
}
foo(1, 2, 3) == {
'a': 1,
'b': 2,
'c': 3,
}
|
bar == {'a': 1, 'b': 2}
bar == {'a': 1, 'b': 2}
foo() == {'a': 1, 'b': 2, 'c': 3}
foo(1, 2, 3) == {'a': 1, 'b': 2, 'c': 3}
|
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0) # here to make sure stack pop off
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
heights.pop()
return ans
'''The stack maintain the indexes of buildings with ascending height. Before adding a new building pop the building who is taller than the new one. The building popped out represent the height of a rectangle with the new building as the right boundary and the current stack top as the left boundary. Calculate its area and update ans of maximum area. Boundary is handled using dummy buildings.'''
|
class Solution:
def largest_rectangle_area(self, heights: List[int]) -> int:
heights.append(0)
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
heights.pop()
return ans
'The stack maintain the indexes of buildings with ascending height. Before adding a new building pop the building who is taller than the new one. The building popped out represent the height of a rectangle with the new building as the right boundary and the current stack top as the left boundary. Calculate its area and update ans of maximum area. Boundary is handled using dummy buildings.'
|
class TicTacToe:
def __init__(self):
self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]]
# Vertical lines list, to be divided in 3 inner lists:
self.v_lines = []
# Diagonal lines:
self.d1_line = [self.matrix[0][0], self.matrix[1][1],
self.matrix[2][2]]
self.d2_line = [self.matrix[0][2], self.matrix[1][1],
self.matrix[2][0]]
self.x_list = ['X', 'X', 'X']
self.o_list = ['O', 'O', 'O']
self.turn_counter = 0
self.end_game = False
self.coord_input = ''
def vertical_lines_list(self): # Transforming vertical sequences in list.
for c in range(3):
self.v_lines.append([self.matrix[0][c], self.matrix[1][c],
self.matrix[2][c]])
def game_start(self):
self.vertical_lines_list()
self.display()
self.game_mechanism()
def check_input(self, input_):
forbidden = '4567890'
if input_.replace(' ', '').isalpha():
print('You should enter numbers!')
self.game_mechanism() # Start over again, if wrong.
elif len(input_.replace(' ', '')) < 2: # When only one number digited.
print('Coordinates must have 2 numbers!')
self.game_mechanism()
elif input_[0] in forbidden or input_[2] in forbidden:
print('Coordinates should be from 1 to 3!')
self.game_mechanism()
else:
# If input is ok, converted to integer.
self.coord_input = [int(i) for i in input_.replace(' ', '')]
return self.coord_input
def game_mechanism(self):
while not self.end_game:
user = input('Enter coordinates: ')
self.check_input(user)
# Coordinates:
# (1, 3)(2, 3)(3, 3)
# (1, 2)(2, 2)(3, 2)
# (1, 1)(2, 1)(3, 1)
# This following loop works to convert inputs into indexes,
# at the same time it helps to validate results:
for c in range(1, 4):
if not self.end_game: # Used to stop some for loops later,
# that were showing messages 3 times.
if self.coord_input == [c, 3]: # Line 1.
if self.matrix[0][c - 1] == 'X' or \
self.matrix[0][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0: # 'O' is put when
# turn_counter is even.
self.matrix[0][c - 1] = 'O' # Hr. ln. check.
self.v_lines[c - 1][0] = 'O' # Vt. ln. check.
if c == 1:
self.d1_line[0] = 'O'
elif c == 3:
self.d2_line[2] = 'O'
else:
self.matrix[0][c - 1] = 'X'
self.v_lines[c - 1][0] = 'X'
if c == 1:
self.d1_line[0] = 'X'
elif c == 3:
self.d2_line[2] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw() # Verifying results after each vert. line.
elif self.coord_input == [c, 2]: # Line 2.
if self.matrix[1][c - 1] == 'X' or \
self.matrix[1][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[1][c - 1] = 'O'
self.v_lines[c - 1][1] = 'O'
if c == 2:
self.d1_line[1] = 'O'
self.d2_line[1] = 'O'
else:
self.matrix[1][c - 1] = 'X'
self.v_lines[c - 1][1] = 'X'
if c == 2:
self.d1_line[1] = 'X'
self.d2_line[1] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
elif self.coord_input == [c, 1]: # Line 3.
if self.matrix[2][c - 1] == 'X' or \
self.matrix[2][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[2][c - 1] = 'O'
self.v_lines[c - 1][2] = 'O'
if c == 3:
self.d1_line[2] = 'O'
elif c == 1:
self.d2_line[0] = 'O'
else:
self.matrix[2][c - 1] = 'X'
self.v_lines[c - 1][2] = 'X'
if c == 3:
self.d1_line[2] = 'X'
elif c == 1:
self.d2_line[0] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
def display(self):
print('-' * 9)
print(f'| {" ".join(self.matrix[0])} |')
print(f'| {" ".join(self.matrix[1])} |')
print(f'| {" ".join(self.matrix[2])} |')
print('-' * 9)
# Results analysis methods:
def x_win(self):
# Diagonal:
if self.d1_line == self.x_list or self.d2_line == self.x_list:
print('X wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game: # Used to stop for loops
# when condition achieved.
if self.matrix[c] == self.x_list or \
self.v_lines[c] == self.x_list:
print('X wins')
self.end_game = True
def o_win(self):
# Diagonal:
if self.d1_line == self.o_list or \
self.d2_line == self.o_list:
print('O wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game: # Used to stop for loops when
# condition achieved.
if self.matrix[c] == self.o_list or \
self.v_lines[c] == self.o_list:
print('O wins')
self.end_game = True
def draw(self):
if not self.end_game:
if self.turn_counter == 9:
print('Draw')
self.end_game = True
tictactoe = TicTacToe()
tictactoe.game_start()
# Have a nice day!
|
class Tictactoe:
def __init__(self):
self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]]
self.v_lines = []
self.d1_line = [self.matrix[0][0], self.matrix[1][1], self.matrix[2][2]]
self.d2_line = [self.matrix[0][2], self.matrix[1][1], self.matrix[2][0]]
self.x_list = ['X', 'X', 'X']
self.o_list = ['O', 'O', 'O']
self.turn_counter = 0
self.end_game = False
self.coord_input = ''
def vertical_lines_list(self):
for c in range(3):
self.v_lines.append([self.matrix[0][c], self.matrix[1][c], self.matrix[2][c]])
def game_start(self):
self.vertical_lines_list()
self.display()
self.game_mechanism()
def check_input(self, input_):
forbidden = '4567890'
if input_.replace(' ', '').isalpha():
print('You should enter numbers!')
self.game_mechanism()
elif len(input_.replace(' ', '')) < 2:
print('Coordinates must have 2 numbers!')
self.game_mechanism()
elif input_[0] in forbidden or input_[2] in forbidden:
print('Coordinates should be from 1 to 3!')
self.game_mechanism()
else:
self.coord_input = [int(i) for i in input_.replace(' ', '')]
return self.coord_input
def game_mechanism(self):
while not self.end_game:
user = input('Enter coordinates: ')
self.check_input(user)
for c in range(1, 4):
if not self.end_game:
if self.coord_input == [c, 3]:
if self.matrix[0][c - 1] == 'X' or self.matrix[0][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[0][c - 1] = 'O'
self.v_lines[c - 1][0] = 'O'
if c == 1:
self.d1_line[0] = 'O'
elif c == 3:
self.d2_line[2] = 'O'
else:
self.matrix[0][c - 1] = 'X'
self.v_lines[c - 1][0] = 'X'
if c == 1:
self.d1_line[0] = 'X'
elif c == 3:
self.d2_line[2] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
elif self.coord_input == [c, 2]:
if self.matrix[1][c - 1] == 'X' or self.matrix[1][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[1][c - 1] = 'O'
self.v_lines[c - 1][1] = 'O'
if c == 2:
self.d1_line[1] = 'O'
self.d2_line[1] = 'O'
else:
self.matrix[1][c - 1] = 'X'
self.v_lines[c - 1][1] = 'X'
if c == 2:
self.d1_line[1] = 'X'
self.d2_line[1] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
elif self.coord_input == [c, 1]:
if self.matrix[2][c - 1] == 'X' or self.matrix[2][c - 1] == 'O':
print('This cell is occupied! Choose another one!')
else:
self.turn_counter += 1
if self.turn_counter % 2 == 0:
self.matrix[2][c - 1] = 'O'
self.v_lines[c - 1][2] = 'O'
if c == 3:
self.d1_line[2] = 'O'
elif c == 1:
self.d2_line[0] = 'O'
else:
self.matrix[2][c - 1] = 'X'
self.v_lines[c - 1][2] = 'X'
if c == 3:
self.d1_line[2] = 'X'
elif c == 1:
self.d2_line[0] = 'X'
self.display()
self.x_win()
self.o_win()
self.draw()
def display(self):
print('-' * 9)
print(f"| {' '.join(self.matrix[0])} |")
print(f"| {' '.join(self.matrix[1])} |")
print(f"| {' '.join(self.matrix[2])} |")
print('-' * 9)
def x_win(self):
if self.d1_line == self.x_list or self.d2_line == self.x_list:
print('X wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game:
if self.matrix[c] == self.x_list or self.v_lines[c] == self.x_list:
print('X wins')
self.end_game = True
def o_win(self):
if self.d1_line == self.o_list or self.d2_line == self.o_list:
print('O wins')
self.end_game = True
else:
for c in range(3):
if not self.end_game:
if self.matrix[c] == self.o_list or self.v_lines[c] == self.o_list:
print('O wins')
self.end_game = True
def draw(self):
if not self.end_game:
if self.turn_counter == 9:
print('Draw')
self.end_game = True
tictactoe = tic_tac_toe()
tictactoe.game_start()
|
#coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
class CITestingTaskPropertyNavBar(object):
'''
classdocs
'''
def __init__(self,request,**args):
self.request=request
self.ci_task=args['ci_task']
if args['property_nav_action'] == 'history':
self.result_active="left_sub_meun_active"
if args['property_nav_action'] == 'config':
self.config_active="left_sub_meun_active"
if args['property_nav_action'] == 'parameter':
self.parameter_active="left_sub_meun_active"
if args['property_nav_action'] == 'build':
self.build_active="left_sub_meun_active"
if args['property_nav_action'] == 'build_clean':
self.build_clean_active="left_sub_meun_active"
class CITaskPropertyNavBar(object):
'''
classdocs
'''
def __init__(self,request,**args):
self.request=request
self.ci_task=args['ci_task']
if args['property_nav_action'] == 'history':
self.history_active="left_sub_meun_active"
if args['property_nav_action'] == 'unittest_history':
self.unittest_active="left_sub_meun_active"
if args['property_nav_action'] == 'config':
self.config_active="left_sub_meun_active"
if args['property_nav_action'] == 'parameter':
self.parameter_active="left_sub_meun_active"
if args['property_nav_action'] == 'build':
self.build_active="left_sub_meun_active"
if args['property_nav_action'] == 'changelog':
self.changelog_active="left_sub_meun_active"
if args['property_nav_action'] == 'build_clean':
self.build_clean_active="left_sub_meun_active"
|
"""
Created on 2015-9-24
@author: Devuser
"""
class Citestingtaskpropertynavbar(object):
"""
classdocs
"""
def __init__(self, request, **args):
self.request = request
self.ci_task = args['ci_task']
if args['property_nav_action'] == 'history':
self.result_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'config':
self.config_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'parameter':
self.parameter_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'build':
self.build_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'build_clean':
self.build_clean_active = 'left_sub_meun_active'
class Citaskpropertynavbar(object):
"""
classdocs
"""
def __init__(self, request, **args):
self.request = request
self.ci_task = args['ci_task']
if args['property_nav_action'] == 'history':
self.history_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'unittest_history':
self.unittest_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'config':
self.config_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'parameter':
self.parameter_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'build':
self.build_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'changelog':
self.changelog_active = 'left_sub_meun_active'
if args['property_nav_action'] == 'build_clean':
self.build_clean_active = 'left_sub_meun_active'
|
msg = str(input('Digite uma mensagem'))
n = 0
n = len(msg)
def escreva():
print('-'*n)
print(msg)
print('-'*n)
escreva()
|
msg = str(input('Digite uma mensagem'))
n = 0
n = len(msg)
def escreva():
print('-' * n)
print(msg)
print('-' * n)
escreva()
|
class UVWarpModifier:
axis_u = None
axis_v = None
bone_from = None
bone_to = None
center = None
object_from = None
object_to = None
uv_layer = None
vertex_group = None
|
class Uvwarpmodifier:
axis_u = None
axis_v = None
bone_from = None
bone_to = None
center = None
object_from = None
object_to = None
uv_layer = None
vertex_group = None
|
#
# Copyright Cloudlab URV 2020
#
# 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.
#
_set = set
# General lithops.multiprocessing parameters
LITHOPS_CONFIG = 'LITHOPS_CONFIG'
STREAM_STDOUT = 'STREAM_STDOUT'
# Redis specific parameters
REDIS_EXPIRY_TIME = 'REDIS_EXPIRY_TIME'
REDIS_CONNECTION_TYPE = 'REDIS_CONNECTION_TYPE'
_DEFAULT_CONFIG = {
LITHOPS_CONFIG: {},
STREAM_STDOUT: False,
REDIS_EXPIRY_TIME: 300,
REDIS_CONNECTION_TYPE: 'pubsubconn'
}
_config = _DEFAULT_CONFIG
def set(config_dic=None, **configurations):
if config_dic is None:
config_dic = {}
_config.update(config_dic)
_config.update(configurations)
def set_parameter(key, value):
if key in _config:
_config[key] = value
else:
raise KeyError(key)
def get_parameter(parameter):
return _config[parameter]
|
_set = set
lithops_config = 'LITHOPS_CONFIG'
stream_stdout = 'STREAM_STDOUT'
redis_expiry_time = 'REDIS_EXPIRY_TIME'
redis_connection_type = 'REDIS_CONNECTION_TYPE'
_default_config = {LITHOPS_CONFIG: {}, STREAM_STDOUT: False, REDIS_EXPIRY_TIME: 300, REDIS_CONNECTION_TYPE: 'pubsubconn'}
_config = _DEFAULT_CONFIG
def set(config_dic=None, **configurations):
if config_dic is None:
config_dic = {}
_config.update(config_dic)
_config.update(configurations)
def set_parameter(key, value):
if key in _config:
_config[key] = value
else:
raise key_error(key)
def get_parameter(parameter):
return _config[parameter]
|
class NotAllowed(Exception):
"""when change class.id"""
class DatabaseException(Exception):
"""Database error"""
class ColumnTypeUnknown(Exception):
"""Variable type unknown"""
class NoFieldException(Exception):
"""Class has no variables"""
class WhereUsageException(Exception):
"""Detected error when you use class.where"""
|
class Notallowed(Exception):
"""when change class.id"""
class Databaseexception(Exception):
"""Database error"""
class Columntypeunknown(Exception):
"""Variable type unknown"""
class Nofieldexception(Exception):
"""Class has no variables"""
class Whereusageexception(Exception):
"""Detected error when you use class.where"""
|
'''
Vasya the Hipster
red blue socks
simple one
'''
socks = list(map(int, input().split(' ')))
socks.sort()
diff = socks[0]
left = socks[1]-socks[0]
same = left//2
#output format
s = str(diff) + ' ' + str(same)
print(s)
|
"""
Vasya the Hipster
red blue socks
simple one
"""
socks = list(map(int, input().split(' ')))
socks.sort()
diff = socks[0]
left = socks[1] - socks[0]
same = left // 2
s = str(diff) + ' ' + str(same)
print(s)
|
def fun(a, b, c, d):
return a + b + c + d
def inc(a):
return a + 1
def add(a, b):
return a + b
|
def fun(a, b, c, d):
return a + b + c + d
def inc(a):
return a + 1
def add(a, b):
return a + b
|
x_arr = []
y_arr = []
for _ in range(3):
x, y = map(int, input().split())
x_arr.append(x)
y_arr.append(y)
for i in range(3):
if x_arr.count(x_arr[i]) == 1:
x4 = x_arr[i]
if y_arr.count(y_arr[i]) == 1:
y4 = y_arr[i]
print(f'{x4} {y4}')
|
x_arr = []
y_arr = []
for _ in range(3):
(x, y) = map(int, input().split())
x_arr.append(x)
y_arr.append(y)
for i in range(3):
if x_arr.count(x_arr[i]) == 1:
x4 = x_arr[i]
if y_arr.count(y_arr[i]) == 1:
y4 = y_arr[i]
print(f'{x4} {y4}')
|
# Methods of Tuple in Python:
# Declaring tuple
tuple = (3, 4, 6, 8, 10, 1, 67)
# Code for printing the length of a tuple
tuple2 = ('Apple', 'Bannana', 'Kiwi')
print('length of tuple2 :', len(tuple2))
# Deleting the tuple
del tuple2
# Printing tuple till 2 index excluding 2
print('tuple[0:2]:', tuple[0:2])
# Displaying tuple in reverse order
print('tuple[::-1]:', tuple[::-1])
# Printing element with maximum value from tuple
print('maximum element in tuple:', max(tuple))
# Printing element with maximum value from tuple
print('minimum element in tuple:', min(tuple))
# printing number of times a specified element
print('Number of times 7 repeated:', tuple.count("7"))
|
tuple = (3, 4, 6, 8, 10, 1, 67)
tuple2 = ('Apple', 'Bannana', 'Kiwi')
print('length of tuple2 :', len(tuple2))
del tuple2
print('tuple[0:2]:', tuple[0:2])
print('tuple[::-1]:', tuple[::-1])
print('maximum element in tuple:', max(tuple))
print('minimum element in tuple:', min(tuple))
print('Number of times 7 repeated:', tuple.count('7'))
|
encoded_bytes=bytes.fromhex("664B564276757A7274796D477A4D4C7A545057456D47575971566F75585A694F4F454B677771647053544E5452654C6F434C544F6E702E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E3E20284E6F74203C6C6F636B746F6B656E3A7772697465313E29203C687474703A2F2F3139322E3136382E36382E313A38302F666A4D6A62656A4B6352474463557342446B4448784673736A476A6C616B714F78584B4F61616A6A41576E48726D45596D586E6F4B432E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E56565941494149414941494149414941494149414941494149414941494149416A5841514144415A41424152414C41594149415141494151414941684141415A3141494149414A31314149414941424142414251493141495149414951493131314149414A5159415A4241424142414241426B4D4147423975344A42596C486861726D30697049705330753969554D6159307154744B42304E50526B71424C4C426B50524D44626B73426C686C4F77474D7A6D564E516B4F546C6D6C5151716C6C424C6C4D504751566F5A6D6A6146675862496272324E77526B31427A70444B6D7A4F4C744B504C6A7171684A4361387A6138515051744B61496D5049716763744B4D795A786B334D6A6E69526B4D64644B4D3136766E51596F564C6661584F6A6D397175775038577030756C364C43716D39684F4B616D4E44434547746E78426B4F684D544B5156733246744B4C4C504B644B4E784B6C59715A33744B4C44444B59715850644971346E446E446F6B714B53317059314A6231796F4B304F6F314F514A626B5A72486B726D614D62484C734C7259706B504248525772536C72614F314453386E6C62576D566B57396F4855747856304D31497079704B7969344E74623062484E497530306B7970696F49454E704E70505032303130323061306E705338786A4C4F476F6770496F77654637506A6B5553385570773831346E3550684C4269706A71714C72695866715A6C5072366237706833697465616471514B4F77654355457064344A6C596F704E39786255486C30687A50574556425236796F6675306A3970515A6B54714652376F784B52794966686F6F396F4855444B703633515A56704B7148304F6E72626D6C4E324A6D706F784D304E3079704B503051524A697070687058364430536B35696F4765426D445839706B5139704D30723352367050424A4B5030566233423733384B5278594668314F496F4855397155734E4955763165686E514B71496F6D72354F673449594F67784C506B504D307970306B5339524C706C6155543232563255424C44345255716273354C714D624F43314E70316750646A6B4E55704255396B3171386F79706D3139704D304E51794B39726D4C39777359657273504B324C4F6A626B6C6D46344A7A746B5744466A746D4F62684D444977796E3930534537784D61376B4B4E375059726D4C7977635A4E34497753565A744D4F71786C544C4749726E346B6F317A4B646E3750304235497070456D7942556A45614F55734141")
decoded_bytes = bytearray([])
for i in range(len(encoded_bytes)//2):
block=encoded_bytes[i*2:i*2+2]
decoded_byte_low = block[1] & 0x0F
decoded_byte_high = (((block[1]) >> 4) + ((block[0]) & 0x0F)) & 0x0F
decoded_byte=decoded_byte_low + (decoded_byte_high <<4)
decoded_bytes.append(decoded_byte)
with open("decrypted.bin", "wb") as f:
f.write(decoded_bytes)
|
encoded_bytes = bytes.fromhex('664B564276757A7274796D477A4D4C7A545057456D47575971566F75585A694F4F454B677771647053544E5452654C6F434C544F6E702E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E3E20284E6F74203C6C6F636B746F6B656E3A7772697465313E29203C687474703A2F2F3139322E3136382E36382E313A38302F666A4D6A62656A4B6352474463557342446B4448784673736A476A6C616B714F78584B4F61616A6A41576E48726D45596D586E6F4B432E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E56565941494149414941494149414941494149414941494149414941494149416A5841514144415A41424152414C41594149415141494151414941684141415A3141494149414A31314149414941424142414251493141495149414951493131314149414A5159415A4241424142414241426B4D4147423975344A42596C486861726D30697049705330753969554D6159307154744B42304E50526B71424C4C426B50524D44626B73426C686C4F77474D7A6D564E516B4F546C6D6C5151716C6C424C6C4D504751566F5A6D6A6146675862496272324E77526B31427A70444B6D7A4F4C744B504C6A7171684A4361387A6138515051744B61496D5049716763744B4D795A786B334D6A6E69526B4D64644B4D3136766E51596F564C6661584F6A6D397175775038577030756C364C43716D39684F4B616D4E44434547746E78426B4F684D544B5156733246744B4C4C504B644B4E784B6C59715A33744B4C44444B59715850644971346E446E446F6B714B53317059314A6231796F4B304F6F314F514A626B5A72486B726D614D62484C734C7259706B504248525772536C72614F314453386E6C62576D566B57396F4855747856304D31497079704B7969344E74623062484E497530306B7970696F49454E704E70505032303130323061306E705338786A4C4F476F6770496F77654637506A6B5553385570773831346E3550684C4269706A71714C72695866715A6C5072366237706833697465616471514B4F77654355457064344A6C596F704E39786255486C30687A50574556425236796F6675306A3970515A6B54714652376F784B52794966686F6F396F4855444B703633515A56704B7148304F6E72626D6C4E324A6D706F784D304E3079704B503051524A697070687058364430536B35696F4765426D445839706B5139704D30723352367050424A4B5030566233423733384B5278594668314F496F4855397155734E4955763165686E514B71496F6D72354F673449594F67784C506B504D307970306B5339524C706C6155543232563255424C44345255716273354C714D624F43314E70316750646A6B4E55704255396B3171386F79706D3139704D304E51794B39726D4C39777359657273504B324C4F6A626B6C6D46344A7A746B5744466A746D4F62684D444977796E3930534537784D61376B4B4E375059726D4C7977635A4E34497753565A744D4F71786C544C4749726E346B6F317A4B646E3750304235497070456D7942556A45614F55734141')
decoded_bytes = bytearray([])
for i in range(len(encoded_bytes) // 2):
block = encoded_bytes[i * 2:i * 2 + 2]
decoded_byte_low = block[1] & 15
decoded_byte_high = (block[1] >> 4) + (block[0] & 15) & 15
decoded_byte = decoded_byte_low + (decoded_byte_high << 4)
decoded_bytes.append(decoded_byte)
with open('decrypted.bin', 'wb') as f:
f.write(decoded_bytes)
|
def solve(data):
result = 0
# Iterates through each value of the list and sums it to the result
for number in data:
result += number
# Returns result (total sum)
return result
|
def solve(data):
result = 0
for number in data:
result += number
return result
|
A = int(input())
B = int(input())
PROD = A*B
print("PROD = " + str(PROD))
|
a = int(input())
b = int(input())
prod = A * B
print('PROD = ' + str(PROD))
|
def get_metadata(accessions, metadata_database):
#Quirk - metadata accession has .1 as a part of the accession id
accessions_fixed = []
for accession in accessions:
accessions_fixed.append(accession+'.1')
accessions_data = metadata_database.loc[metadata_database['acc'].isin(accessions_fixed)]
return accessions_data
def calc_sens_spec(start, end, genus_regions, blastdb_regions, genus_blastdb_map, blast_results):
def calc_sensitivity(start, end, genus_regions, amplified_accs):
#For sensitivity calculation:
#1) Determine possible desired genus targets by checking assay start
# and assay end against the genus_regions
#2) Check each possible desired genus target in amplified_accs and record
# which ones were successfully amplified
#3) Sensitivity calculation:
# TP / (TP + FN)
# where
# TP = succesfully amplified accessions
# FN = possible accessions that were not amplified
# TP + FN = total number of possible desired genus targets
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if (
region_start <= start
and region_end >= end
):
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index%1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
amplified_targets = []
possible_genus_targets = check_within_regions(genus_regions, start, end)
for accession in possible_genus_targets:
if accession in amplified_accs:
amplified_targets.append(accession)
sensitivity = len(amplified_targets)/len(possible_genus_targets)
return (sensitivity, amplified_targets)
def calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accs):
#For specificity calculation
#1) From blastdb_regions.keys(), subtract any accession present in the genus alignment.
# This yields a list of accessions that are only non-target.
#2) From amplified_accessions, subtract any accession present in the genus alignment.
# This yields a list of accessions that are only non-target.
#3) For each non-target accession in blastdb_regions, identify possible non-target accessions
# by checking assay start and assay end against blastdb_regions.
#4) Specificity calculation:
# TN / (TN + FP)
# where
# TN = non-target accessions that were not amplified
# TN = (total non-target) - (amplified non-target)
# FP = amplified non-target
# ((Total non-target) - (amplified non-target)) / total non-target
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if (
region_start <= start
and region_end >= end
):
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index%1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
non_target_blastdb_accs = []
non_target_amplified = amplified_accs.copy()
for accession in blastdb_regions.keys():
non_target_blastdb_accs.append(accession)
#Delete target accessions in blastdb and amplified_accs
for accession in genus_regions.keys():
if accession in non_target_blastdb_accs:
del non_target_blastdb_accs[non_target_blastdb_accs.index(accession)]
if accession in non_target_amplified:
non_target_amplified.remove(accession)
#Identify possible non-target accession
mapped_oligo_start = genus_blastdb_map[start]
mapped_oligo_end = genus_blastdb_map[end]
possible_non_target_blastdb = check_within_regions(blastdb_regions, mapped_oligo_start, mapped_oligo_end)
#Specificity calculation
specificity = (len(possible_non_target_blastdb) - len(non_target_amplified))/(len(possible_non_target_blastdb))
return (specificity, non_target_amplified)
amplified_accessions = set(blast_results.loc[:,'sacc'])
sens, targets = calc_sensitivity(start, end, genus_regions, amplified_accessions)
spec, non_targets = calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accessions)
return (sens, targets, spec, non_targets)
|
def get_metadata(accessions, metadata_database):
accessions_fixed = []
for accession in accessions:
accessions_fixed.append(accession + '.1')
accessions_data = metadata_database.loc[metadata_database['acc'].isin(accessions_fixed)]
return accessions_data
def calc_sens_spec(start, end, genus_regions, blastdb_regions, genus_blastdb_map, blast_results):
def calc_sensitivity(start, end, genus_regions, amplified_accs):
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if region_start <= start and region_end >= end:
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index % 1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
amplified_targets = []
possible_genus_targets = check_within_regions(genus_regions, start, end)
for accession in possible_genus_targets:
if accession in amplified_accs:
amplified_targets.append(accession)
sensitivity = len(amplified_targets) / len(possible_genus_targets)
return (sensitivity, amplified_targets)
def calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accs):
def check_within_regions(sequence_regions, start, end):
"""Identify which sequences contain the target region.
Note that the target region is considered continuous from
the specified start and end coordinates.
Parameters:
sequence_regions - dictionary returned from get_sequence_regions
[accession_id]:(seq_start, seq_end)
start - start of target regoin
end - end of target region
Output:
traversed_regions - list of accession IDs that contain
the target region
"""
traversed_regions = []
curr_index = 0
for accession in sequence_regions:
region_start = sequence_regions[accession][0]
region_end = sequence_regions[accession][1]
if region_start <= start and region_end >= end:
traversed_regions.append(accession)
curr_index = curr_index + 1
if curr_index % 1000 == 0:
print(f'Current progress: {curr_index}')
return traversed_regions
non_target_blastdb_accs = []
non_target_amplified = amplified_accs.copy()
for accession in blastdb_regions.keys():
non_target_blastdb_accs.append(accession)
for accession in genus_regions.keys():
if accession in non_target_blastdb_accs:
del non_target_blastdb_accs[non_target_blastdb_accs.index(accession)]
if accession in non_target_amplified:
non_target_amplified.remove(accession)
mapped_oligo_start = genus_blastdb_map[start]
mapped_oligo_end = genus_blastdb_map[end]
possible_non_target_blastdb = check_within_regions(blastdb_regions, mapped_oligo_start, mapped_oligo_end)
specificity = (len(possible_non_target_blastdb) - len(non_target_amplified)) / len(possible_non_target_blastdb)
return (specificity, non_target_amplified)
amplified_accessions = set(blast_results.loc[:, 'sacc'])
(sens, targets) = calc_sensitivity(start, end, genus_regions, amplified_accessions)
(spec, non_targets) = calc_specificity(start, end, blastdb_regions, genus_regions, genus_blastdb_map, amplified_accessions)
return (sens, targets, spec, non_targets)
|
def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for key, value in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json
|
def clean_dict(json):
"""
Remove keys with the value None from the dictionary
"""
for (key, value) in list(json.items()):
if value is None:
del json[key]
elif isinstance(value, dict):
clean_dict(value)
return json
|
def towerOfHanoi(n, source, auxiliary, destination):
if n == 0:
return 0
# Move n-1 from source to auxiliary using destination
stepCnt1 = towerOfHanoi(n-1, source, destination, auxiliary)
# Move nth disc from source to destination
print(f"{n} {source} -> {destination}")
# move n-1 from auxiliary to destination using source
stepCnt2 = towerOfHanoi(n-1, auxiliary, source, destination)
# Return Total Number of Steps
return 1 + stepCnt1 + stepCnt2
towerOfHanoi(10, "A", "B", "C")
|
def tower_of_hanoi(n, source, auxiliary, destination):
if n == 0:
return 0
step_cnt1 = tower_of_hanoi(n - 1, source, destination, auxiliary)
print(f'{n} {source} -> {destination}')
step_cnt2 = tower_of_hanoi(n - 1, auxiliary, source, destination)
return 1 + stepCnt1 + stepCnt2
tower_of_hanoi(10, 'A', 'B', 'C')
|
# Manas Dash
# 24th July 2020
# the usage of set and max function
# which number is repeated most number of time
numbers = [1, 3, 4, 6, 3, 7, 3, 8, 6, 5, 9, 5, 3, 6, 3, 2, 3]
max_repeated = max(set(numbers), key=numbers.count)
print(f"The number {max_repeated} is repeated maximum number of time in the given list")
# The number 3 is repeated maximum number of time in the given list
|
numbers = [1, 3, 4, 6, 3, 7, 3, 8, 6, 5, 9, 5, 3, 6, 3, 2, 3]
max_repeated = max(set(numbers), key=numbers.count)
print(f'The number {max_repeated} is repeated maximum number of time in the given list')
|
class ZileanBackuper(object):
def __init__(self):
self._machines = None
self._linked_databases = None
@classmethod
def backup_linked_databases(cls):
pass
@classmethod
def backup_database(cls, db):
pass
|
class Zileanbackuper(object):
def __init__(self):
self._machines = None
self._linked_databases = None
@classmethod
def backup_linked_databases(cls):
pass
@classmethod
def backup_database(cls, db):
pass
|
# Copyright 2020 The Private Cardinality Estimation Framework Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Set Generator Base Classes"""
class _SetSizeGenerator(object):
"""Get set_size_list from set_size (fixed for each set) and num_sets."""
def __init__(self, num_sets, set_size):
self.num_sets = num_sets
self.set_size = set_size
def __iter__(self):
for _ in range(self.num_sets):
yield self.set_size
class SetGeneratorBase(object):
"""Base object for generating test sets."""
def __next__(self):
raise NotImplementedError()
@classmethod
def get_generator_factory_with_num_and_size(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise NotImplementedError()
_ = f
# In an implementation, you would return f here
# return f
raise NotImplementedError()
@classmethod
def get_generator_factory_with_set_size_list(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise NotImplementedError()
_ = f
# In an implementation, you would return f here
# return f
raise NotImplementedError()
|
"""Set Generator Base Classes"""
class _Setsizegenerator(object):
"""Get set_size_list from set_size (fixed for each set) and num_sets."""
def __init__(self, num_sets, set_size):
self.num_sets = num_sets
self.set_size = set_size
def __iter__(self):
for _ in range(self.num_sets):
yield self.set_size
class Setgeneratorbase(object):
"""Base object for generating test sets."""
def __next__(self):
raise not_implemented_error()
@classmethod
def get_generator_factory_with_num_and_size(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise not_implemented_error()
_ = f
raise not_implemented_error()
@classmethod
def get_generator_factory_with_set_size_list(cls):
"""Returns a function Handle which takes a np.random.RandomState as an arg.
This function handle, when called, will return a fully-formed SetGenerator
object, ready to generate sets.
"""
def f(random_state):
_ = random_state
raise not_implemented_error()
_ = f
raise not_implemented_error()
|
def test_content_create(api_client_authenticated):
response = api_client_authenticated.post(
"/content/",
json={
"title": "hello test",
"text": "this is just a test",
"published": True,
"tags": ["test", "hello"],
},
)
assert response.status_code == 200
result = response.json()
assert result["slug"] == "hello-test"
def test_content_list(api_client_authenticated):
response = api_client_authenticated.get("/content/")
assert response.status_code == 200
result = response.json()
assert result[0]["slug"] == "hello-test"
|
def test_content_create(api_client_authenticated):
response = api_client_authenticated.post('/content/', json={'title': 'hello test', 'text': 'this is just a test', 'published': True, 'tags': ['test', 'hello']})
assert response.status_code == 200
result = response.json()
assert result['slug'] == 'hello-test'
def test_content_list(api_client_authenticated):
response = api_client_authenticated.get('/content/')
assert response.status_code == 200
result = response.json()
assert result[0]['slug'] == 'hello-test'
|
[
[0.26982777, 0.20175242, 0.10614473, 0.17290444, 0.22056401],
[0.18268971, 0.2363915, 0.26958793, 0.29282782, 0.36225248],
[0.31735855, 0.30254544, 0.28661105, 0.33136132, 0.40489719],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.15203597, 0.32214688, 0.40445594, 0.45318467, 0.44650059],
[0.20070068, 0.31904263, 0.40822282, 0.48738756, 0.46520183],
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.24779961, 0.42250711, 0.49311729, 0.46756128, 0.49151833],
]
|
[[0.26982777, 0.20175242, 0.10614473, 0.17290444, 0.22056401], [0.18268971, 0.2363915, 0.26958793, 0.29282782, 0.36225248], [0.31735855, 0.30254544, 0.28661105, 0.33136132, 0.40489719], [0.0, 0.0, 0.0, 0.0, 0.0], [0.15203597, 0.32214688, 0.40445594, 0.45318467, 0.44650059], [0.20070068, 0.31904263, 0.40822282, 0.48738756, 0.46520183], [0.0, 0.0, 0.0, 0.0, 0.0], [0.24779961, 0.42250711, 0.49311729, 0.46756128, 0.49151833]]
|
t=int(input())
for k in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
stack=[]
res={}
for i in a:
res[i]=-1
for j in a:
if len(stack)==0:
stack.append(j)
else:
while len(stack)>0 and stack[-1]<j:
res[stack.pop()]=j
stack.append(j)
for p in a:
print(res[p],end=" ")
print()
|
t = int(input())
for k in range(t):
n = int(input())
a = list(map(int, input().strip().split()))
stack = []
res = {}
for i in a:
res[i] = -1
for j in a:
if len(stack) == 0:
stack.append(j)
else:
while len(stack) > 0 and stack[-1] < j:
res[stack.pop()] = j
stack.append(j)
for p in a:
print(res[p], end=' ')
print()
|
print(int('3') + 3)
print(float('3.2') + 3.5)
print(str(3) + '2')
|
print(int('3') + 3)
print(float('3.2') + 3.5)
print(str(3) + '2')
|
# Copyright 2019 Eficent Business and IT Consulting Services
# Copyright 2017-2018 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Purchase Stock Picking Return Invoicing",
"summary": "Add an option to refund returned pickings",
"version": "12.0.1.0.1",
"category": "Purchases",
"website": "https://github.com/OCA/account-invoicing",
"author": "Eficent,"
"Tecnativa,"
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"development_status": "Mature",
"depends": [
"purchase_stock",
],
"data": [
"views/account_invoice_view.xml",
"views/purchase_view.xml",
],
"maintainers": [
'pedrobaeza',
],
}
|
{'name': 'Purchase Stock Picking Return Invoicing', 'summary': 'Add an option to refund returned pickings', 'version': '12.0.1.0.1', 'category': 'Purchases', 'website': 'https://github.com/OCA/account-invoicing', 'author': 'Eficent,Tecnativa,Odoo Community Association (OCA)', 'license': 'AGPL-3', 'installable': True, 'development_status': 'Mature', 'depends': ['purchase_stock'], 'data': ['views/account_invoice_view.xml', 'views/purchase_view.xml'], 'maintainers': ['pedrobaeza']}
|
def get_regr_coeffs(X, y):
n = X.shape[0]
p = n*(X**2).sum() - X.sum()**2
a = ( n*(X*y).sum() - X.sum()*y.sum() ) / p
b = ( y.sum()*(X**2).sum() - X.sum()*(X*y).sum() ) / p
return a,b
|
def get_regr_coeffs(X, y):
n = X.shape[0]
p = n * (X ** 2).sum() - X.sum() ** 2
a = (n * (X * y).sum() - X.sum() * y.sum()) / p
b = (y.sum() * (X ** 2).sum() - X.sum() * (X * y).sum()) / p
return (a, b)
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
layer = [root]
res = 0
while layer:
node = layer.pop(0)
left = node.left
right = node.right
if left:
layer.append(left)
if not any([left.left, left.right]):
res += left.val
if right:
layer.append(right)
return res
|
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sum_of_left_leaves(self, root: TreeNode) -> int:
if root is None:
return 0
layer = [root]
res = 0
while layer:
node = layer.pop(0)
left = node.left
right = node.right
if left:
layer.append(left)
if not any([left.left, left.right]):
res += left.val
if right:
layer.append(right)
return res
|
# Binary Search Tree (BST) Implementation
class BSTNode:
def __init__(selfNode, nodeData): # Node Structure
selfNode.nodeData = nodeData
selfNode.left = None
selfNode.right = None
selfNode.parent = None
# Insertion Operation
def insert(selfNode, node):
if selfNode.nodeData > node.nodeData:
if selfNode.left is None:
selfNode.left = node
node.parent = selfNode
else:
selfNode.left.insert(node)
elif selfNode.nodeData < node.nodeData:
if selfNode.right is None:
selfNode.right = node
node.parent = selfNode
else:
selfNode.right.insert(node)
# Removal Operation Functions
def replace_node_of_parent(selfNode, new_node):
if selfNode.parent is not None:
if new_node is not None:
new_node.parent = selfNode.parent
if selfNode.parent.left == selfNode:
selfNode.parent.left = new_node
elif selfNode.parent.right == selfNode:
selfNode.parent.right = new_node
else:
selfNode.nodeData = new_node.nodeData
selfNode.left = new_node.left
selfNode.right = new_node.right
if new_node.left is not None:
new_node.left.parent = selfNode
if new_node.right is not None:
new_node.right.parent = selfNode
def find_min(selfNode):
current = selfNode
while current.left is not None:
current = current.left
return current
def remove(selfNode):
if (selfNode.left is not None and selfNode.right is not None):
successor = selfNode.right.find_min()
selfNode.nodeData = successor.nodeData
successor.remove()
elif selfNode.left is not None:
selfNode.replace_node_of_parent(selfNode.left)
elif selfNode.right is not None:
selfNode.replace_node_of_parent(selfNode.right)
else:
selfNode.replace_node_of_parent(None)
# Search required data within BST
def search(selfNode, nodeData):
if selfNode.nodeData > nodeData:
if selfNode.left is not None:
return selfNode.left.search(nodeData)
else:
return None
elif selfNode.nodeData < nodeData:
if selfNode.right is not None:
return selfNode.right.search(nodeData)
else:
return None
return selfNode
# InOrder Traversal Operation
def inorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
print(selfNode.nodeData, end=' ')
if selfNode.right is not None:
selfNode.right.inorder()
# PostOrder Traversal Operation
def postorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
print(selfNode.nodeData, end=' ')
# PreOrder Traversal Operation
def preorder(selfNode):
print(selfNode.nodeData, end=' ')
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
class BSTree: # Structure of Binary Search Tree
def __init__(selfNode):
selfNode.root = None
def inorder(selfNode):
if selfNode.root is not None:
selfNode.root.inorder()
def preorder(selfNode):
if selfNode.root is not None:
selfNode.root.preorder()
def postorder(selfNode):
if selfNode.root is not None:
selfNode.root.postorder()
def add(selfNode, nodeData):
new_node = BSTNode(nodeData)
if selfNode.root is None:
selfNode.root = new_node
else:
selfNode.root.insert(new_node)
def remove(selfNode, nodeData):
to_remove = selfNode.search(nodeData)
if (selfNode.root == to_remove and selfNode.root.left is None
and selfNode.root.right is None):
selfNode.root = None
else:
to_remove.remove()
def search(selfNode, nodeData):
if selfNode.root is not None:
return selfNode.root.search(nodeData)
bstree = BSTree() # Object of class BSTree
# Menu of Operations on BST Tree
print('BST Tree Operation Menu')
print('Add <data>')
print('Remove <data>')
print('Inorder')
print('Preorder')
print('Postorder')
print('Quit')
while True:
do = input('Enter your action => ').split()
operation = do[0].strip().lower()
if operation == 'add':
nodeData = int(do[1])
bstree.add(nodeData)
elif operation == 'remove':
nodeData = int(do[1])
bstree.remove(nodeData)
elif operation == 'inorder':
print('Inorder Traversal: ', end='')
bstree.inorder()
print()
elif operation == 'postorder':
print('Postorder Traversal: ', end='')
bstree.postorder()
print()
elif operation == 'preorder':
print('Preorder Traversal: ', end='')
bstree.preorder()
print()
elif operation == 'quit':
print("BST Tree Implementation finished.")
break
|
class Bstnode:
def __init__(selfNode, nodeData):
selfNode.nodeData = nodeData
selfNode.left = None
selfNode.right = None
selfNode.parent = None
def insert(selfNode, node):
if selfNode.nodeData > node.nodeData:
if selfNode.left is None:
selfNode.left = node
node.parent = selfNode
else:
selfNode.left.insert(node)
elif selfNode.nodeData < node.nodeData:
if selfNode.right is None:
selfNode.right = node
node.parent = selfNode
else:
selfNode.right.insert(node)
def replace_node_of_parent(selfNode, new_node):
if selfNode.parent is not None:
if new_node is not None:
new_node.parent = selfNode.parent
if selfNode.parent.left == selfNode:
selfNode.parent.left = new_node
elif selfNode.parent.right == selfNode:
selfNode.parent.right = new_node
else:
selfNode.nodeData = new_node.nodeData
selfNode.left = new_node.left
selfNode.right = new_node.right
if new_node.left is not None:
new_node.left.parent = selfNode
if new_node.right is not None:
new_node.right.parent = selfNode
def find_min(selfNode):
current = selfNode
while current.left is not None:
current = current.left
return current
def remove(selfNode):
if selfNode.left is not None and selfNode.right is not None:
successor = selfNode.right.find_min()
selfNode.nodeData = successor.nodeData
successor.remove()
elif selfNode.left is not None:
selfNode.replace_node_of_parent(selfNode.left)
elif selfNode.right is not None:
selfNode.replace_node_of_parent(selfNode.right)
else:
selfNode.replace_node_of_parent(None)
def search(selfNode, nodeData):
if selfNode.nodeData > nodeData:
if selfNode.left is not None:
return selfNode.left.search(nodeData)
else:
return None
elif selfNode.nodeData < nodeData:
if selfNode.right is not None:
return selfNode.right.search(nodeData)
else:
return None
return selfNode
def inorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
print(selfNode.nodeData, end=' ')
if selfNode.right is not None:
selfNode.right.inorder()
def postorder(selfNode):
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
print(selfNode.nodeData, end=' ')
def preorder(selfNode):
print(selfNode.nodeData, end=' ')
if selfNode.left is not None:
selfNode.left.inorder()
if selfNode.right is not None:
selfNode.right.inorder()
class Bstree:
def __init__(selfNode):
selfNode.root = None
def inorder(selfNode):
if selfNode.root is not None:
selfNode.root.inorder()
def preorder(selfNode):
if selfNode.root is not None:
selfNode.root.preorder()
def postorder(selfNode):
if selfNode.root is not None:
selfNode.root.postorder()
def add(selfNode, nodeData):
new_node = bst_node(nodeData)
if selfNode.root is None:
selfNode.root = new_node
else:
selfNode.root.insert(new_node)
def remove(selfNode, nodeData):
to_remove = selfNode.search(nodeData)
if selfNode.root == to_remove and selfNode.root.left is None and (selfNode.root.right is None):
selfNode.root = None
else:
to_remove.remove()
def search(selfNode, nodeData):
if selfNode.root is not None:
return selfNode.root.search(nodeData)
bstree = bs_tree()
print('BST Tree Operation Menu')
print('Add <data>')
print('Remove <data>')
print('Inorder')
print('Preorder')
print('Postorder')
print('Quit')
while True:
do = input('Enter your action => ').split()
operation = do[0].strip().lower()
if operation == 'add':
node_data = int(do[1])
bstree.add(nodeData)
elif operation == 'remove':
node_data = int(do[1])
bstree.remove(nodeData)
elif operation == 'inorder':
print('Inorder Traversal: ', end='')
bstree.inorder()
print()
elif operation == 'postorder':
print('Postorder Traversal: ', end='')
bstree.postorder()
print()
elif operation == 'preorder':
print('Preorder Traversal: ', end='')
bstree.preorder()
print()
elif operation == 'quit':
print('BST Tree Implementation finished.')
break
|
class Stack:
def __init__(self,size=None,limit=1000):
self.top_item = []
self.size = 0
self.limit = limit
def peek(self):
if not self.is_empty():
return self.value[-1]
else:
print("Stack is empty")
def push(self,value):
#print("Current stack:", self.top_item)
#print("size",len(self.top_item))
if self.has_space():
item = self.top_item.append(value)
self.size += 1
else:
print("No space!")
def set_next_node(self):
item = self.top_item.append(self.value)
item = self.top_item
def pop(self):
if not self.is_empty():
item_to_remove = self.top_item
top_item = self.top_item.pop()
self.size -=1
return top_item
else:
print("Stack is empty")
def has_space(self):
if self.limit > self.size:
return True
def is_empty(self):
return self.top_item == []
myStack = Stack()
print(myStack.push("Seema"))
print(myStack.push("Saharan"))
#print(myStack.pop())
print(myStack.peek())
print("empty",myStack.is_empty())
|
class Stack:
def __init__(self, size=None, limit=1000):
self.top_item = []
self.size = 0
self.limit = limit
def peek(self):
if not self.is_empty():
return self.value[-1]
else:
print('Stack is empty')
def push(self, value):
if self.has_space():
item = self.top_item.append(value)
self.size += 1
else:
print('No space!')
def set_next_node(self):
item = self.top_item.append(self.value)
item = self.top_item
def pop(self):
if not self.is_empty():
item_to_remove = self.top_item
top_item = self.top_item.pop()
self.size -= 1
return top_item
else:
print('Stack is empty')
def has_space(self):
if self.limit > self.size:
return True
def is_empty(self):
return self.top_item == []
my_stack = stack()
print(myStack.push('Seema'))
print(myStack.push('Saharan'))
print(myStack.peek())
print('empty', myStack.is_empty())
|
with open("part1.txt", "r") as file:
checksum = 0
for row in file:
large, small = 0, 9999
for entry in row.split("\t"):
entry = int(entry)
if entry > large:
large = entry
if entry < small:
small = entry
checksum += large - small
print(checksum)
|
with open('part1.txt', 'r') as file:
checksum = 0
for row in file:
(large, small) = (0, 9999)
for entry in row.split('\t'):
entry = int(entry)
if entry > large:
large = entry
if entry < small:
small = entry
checksum += large - small
print(checksum)
|
# BUILD FILE SYNTAX: SKYLARK
SE_VERSION = '3.141.59-atlassian-1'
|
se_version = '3.141.59-atlassian-1'
|
# Python translation of QuadTree from Risk.Platform.Standard
class QuadTree(object): # in decimal degrees dist from centroid to edge
def __init__(self, latDim, longDim, minLatCentroid, minLongCentroid, baseSize):
self.__longDim = longDim
self.__latDim = latDim
self.__minLong = minLongCentroid
self.__baseSize = baseSize
self.__minLat = minLatCentroid
self.__baseGrid = [[Quad("b" + str(latInx) + "-" + str(longInx) + "-", True, self.__baseSize,
latInx * 2 * self.__baseSize + self.__minLat,
longInx * 2 * self.__baseSize + self.__minLong) for longInx in range(0, longDim)] for
latInx in range(0, latDim)]
def Lookup(self, latitude, longitude):
latInx = self.LatInx(latitude)
longInx = self.LongInx(longitude)
if latInx < 0 or latInx >= self.__latDim or longInx < 0 or longInx >= self.__longDim:
return None
return self.__baseGrid[latInx][longInx].Lookup(latitude, longitude)
def LongInx(self, longitude):
return int((longitude - self.__minLong + self.__baseSize) / (2 * self.__baseSize))
def LatInx(self, latitude):
return int((latitude - self.__minLat + self.__baseSize) / (2 * self.__baseSize))
def Load(self, cellId, latitude, longitude, size):
latInx = self.LatInx(latitude)
longInx = self.LongInx(longitude)
self.__baseGrid[latInx][longInx].Load(cellId, latitude, longitude, size)
def PostLoadTest(self):
return all([y.IsValid() for x in self.__baseGrid for y in self.__baseGrid[x]])
class Quad(object):
def __init__(self, cellID, isLeaf, size, lat, lon):
self.CellID = cellID
self.IsLeaf = isLeaf
self.WasLoaded = False
self.Size = size # dist from centroid to edge (start at 2.56 degrees)
self.Lat = lat # centroid latitude
self.Long = lon # centroid longitude
self.Ne = None # children if not a leaf
self.Nw = None
self.Se = None
self.Sw = None
def Divide(self):
newSize = self.Size / 2
self.IsLeaf = False
self.Ne = Quad(self.CellID + "10", True, newSize, self.Lat + newSize, self.Long + newSize)
self.Nw = Quad(self.CellID + "00", True, newSize, self.Lat + newSize, self.Long - newSize)
self.Se = Quad(self.CellID + "11", True, newSize, self.Lat - newSize, self.Long + newSize)
self.Sw = Quad(self.CellID + "01", True, newSize, self.Lat - newSize, self.Long - newSize)
def Lookup(self, latitude, longitude):
if self.IsLeaf:
return self
if latitude <= self.Lat and longitude <= self.Long:
return self.Sw.Lookup(latitude, longitude)
if latitude > self.Lat and longitude > self.Long:
return self.Ne.Lookup(latitude, longitude)
if latitude > self.Lat and longitude <= self.Long:
return self.Nw.Lookup(latitude, longitude)
return self.Se.Lookup(latitude, longitude)
def Load(self, cellId, latitude, longitude, size):
if abs(size - self.Size) < 0.00001:
self.CellID = cellId
self.WasLoaded = True
return
if self.IsLeaf:
self.Divide()
if latitude <= self.Lat and longitude <= self.Long:
self.Sw.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude > self.Long:
self.Ne.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude <= self.Long:
self.Nw.Load(cellId, latitude, longitude, size)
if latitude <= self.Lat and longitude > self.Long:
self.Se.Load(cellId, latitude, longitude, size)
def IsValid(self):
if self.WasLoaded and self.IsLeaf:
return True
if self.WasLoaded and not self.IsLeaf:
return False
if not self.WasLoaded and self.IsLeaf:
return True
return self.Ne.IsValid() and self.Nw.IsValid() and self.Se.IsValid() and self.Sw.IsValid()
|
class Quadtree(object):
def __init__(self, latDim, longDim, minLatCentroid, minLongCentroid, baseSize):
self.__longDim = longDim
self.__latDim = latDim
self.__minLong = minLongCentroid
self.__baseSize = baseSize
self.__minLat = minLatCentroid
self.__baseGrid = [[quad('b' + str(latInx) + '-' + str(longInx) + '-', True, self.__baseSize, latInx * 2 * self.__baseSize + self.__minLat, longInx * 2 * self.__baseSize + self.__minLong) for long_inx in range(0, longDim)] for lat_inx in range(0, latDim)]
def lookup(self, latitude, longitude):
lat_inx = self.LatInx(latitude)
long_inx = self.LongInx(longitude)
if latInx < 0 or latInx >= self.__latDim or longInx < 0 or (longInx >= self.__longDim):
return None
return self.__baseGrid[latInx][longInx].Lookup(latitude, longitude)
def long_inx(self, longitude):
return int((longitude - self.__minLong + self.__baseSize) / (2 * self.__baseSize))
def lat_inx(self, latitude):
return int((latitude - self.__minLat + self.__baseSize) / (2 * self.__baseSize))
def load(self, cellId, latitude, longitude, size):
lat_inx = self.LatInx(latitude)
long_inx = self.LongInx(longitude)
self.__baseGrid[latInx][longInx].Load(cellId, latitude, longitude, size)
def post_load_test(self):
return all([y.IsValid() for x in self.__baseGrid for y in self.__baseGrid[x]])
class Quad(object):
def __init__(self, cellID, isLeaf, size, lat, lon):
self.CellID = cellID
self.IsLeaf = isLeaf
self.WasLoaded = False
self.Size = size
self.Lat = lat
self.Long = lon
self.Ne = None
self.Nw = None
self.Se = None
self.Sw = None
def divide(self):
new_size = self.Size / 2
self.IsLeaf = False
self.Ne = quad(self.CellID + '10', True, newSize, self.Lat + newSize, self.Long + newSize)
self.Nw = quad(self.CellID + '00', True, newSize, self.Lat + newSize, self.Long - newSize)
self.Se = quad(self.CellID + '11', True, newSize, self.Lat - newSize, self.Long + newSize)
self.Sw = quad(self.CellID + '01', True, newSize, self.Lat - newSize, self.Long - newSize)
def lookup(self, latitude, longitude):
if self.IsLeaf:
return self
if latitude <= self.Lat and longitude <= self.Long:
return self.Sw.Lookup(latitude, longitude)
if latitude > self.Lat and longitude > self.Long:
return self.Ne.Lookup(latitude, longitude)
if latitude > self.Lat and longitude <= self.Long:
return self.Nw.Lookup(latitude, longitude)
return self.Se.Lookup(latitude, longitude)
def load(self, cellId, latitude, longitude, size):
if abs(size - self.Size) < 1e-05:
self.CellID = cellId
self.WasLoaded = True
return
if self.IsLeaf:
self.Divide()
if latitude <= self.Lat and longitude <= self.Long:
self.Sw.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude > self.Long:
self.Ne.Load(cellId, latitude, longitude, size)
if latitude > self.Lat and longitude <= self.Long:
self.Nw.Load(cellId, latitude, longitude, size)
if latitude <= self.Lat and longitude > self.Long:
self.Se.Load(cellId, latitude, longitude, size)
def is_valid(self):
if self.WasLoaded and self.IsLeaf:
return True
if self.WasLoaded and (not self.IsLeaf):
return False
if not self.WasLoaded and self.IsLeaf:
return True
return self.Ne.IsValid() and self.Nw.IsValid() and self.Se.IsValid() and self.Sw.IsValid()
|
class FtpStyleUriParser(UriParser):
"""
A customizable parser based on the File Transfer Protocol (FTP) scheme.
FtpStyleUriParser()
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return FtpStyleUriParser()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
|
class Ftpstyleuriparser(UriParser):
"""
A customizable parser based on the File Transfer Protocol (FTP) scheme.
FtpStyleUriParser()
"""
def zzz(self):
"""hardcoded/mock instance of the class"""
return ftp_style_uri_parser()
instance = zzz()
'hardcoded/returns an instance of the class'
|
""" Tuple"""
names = ("rogers","Joan", "Doreen", "Liz", "Peter" )
print(names)
string_tuple = " ".join(str(name) for name in names)
print(string_tuple)
|
""" Tuple"""
names = ('rogers', 'Joan', 'Doreen', 'Liz', 'Peter')
print(names)
string_tuple = ' '.join((str(name) for name in names))
print(string_tuple)
|
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}", t2, l)
length(('1',(5,3)),2)
#Tuple {} length: ('1',(5,3)'1',(5,3)) 4
#note: here .format is missing
def length(t1, n):
t2=t1*n
l=len(t2)
print("Tuple {} has length: {}". format(t2, l))
length(('1',(5,3)),2)
#Tuple ('1',(5,3)'1',(5,3)) has length: 4
|
def length(t1, n):
t2 = t1 * n
l = len(t2)
print('Tuple {} has length: {}', t2, l)
length(('1', (5, 3)), 2)
def length(t1, n):
t2 = t1 * n
l = len(t2)
print('Tuple {} has length: {}'.format(t2, l))
length(('1', (5, 3)), 2)
|
def repeat(character: str, counter: int) -> str:
"""Repeat returns character repeated `counter` times."""
word = ""
for counter in range(counter):
word += character
return word
|
def repeat(character: str, counter: int) -> str:
"""Repeat returns character repeated `counter` times."""
word = ''
for counter in range(counter):
word += character
return word
|
__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-Dropbox test project'
__license__ = 'BSD License'
__version__ = '0.3'
|
__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>'
__description__ = 'Flask-Dropbox test project'
__license__ = 'BSD License'
__version__ = '0.3'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.