content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
channel = "test-channel"
feedtitle = "Discord Channel RSS"
feedlink = "github.com/gmemstr/webbot"
feeddescription = "Discord Channel RSS"
flaskdebug = True
flaskport = 5000 | channel = 'test-channel'
feedtitle = 'Discord Channel RSS'
feedlink = 'github.com/gmemstr/webbot'
feeddescription = 'Discord Channel RSS'
flaskdebug = True
flaskport = 5000 |
class Solution:
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# valid triangle sum of two smaller nums > largest num
nums.sort(reverse=True)
cnt, n = 0, len(nums)
for i in range(n - 2):
# if i > 0 and nums[i] == nums[i - 1]:
# continue
l, r = i + 1, n - 1
while l < r:
if nums[l] + nums[r] > nums[i]:
cnt += r - l
l += 1
else:
r -= 1
return cnt | class Solution:
def triangle_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort(reverse=True)
(cnt, n) = (0, len(nums))
for i in range(n - 2):
(l, r) = (i + 1, n - 1)
while l < r:
if nums[l] + nums[r] > nums[i]:
cnt += r - l
l += 1
else:
r -= 1
return cnt |
"""
Problem #1: Add Two Numbers
Leetcode URL: https://leetcode.com/problems/add-two-numbers/
Description on LeetCode:
"
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.""
"""
"""
1. Restate the problem:
Oh okay, so the the digits in each linked list need to be first reversed,
so that I know the value they really represent?
Then if I heard you correctly, the process is I have to add those two decimal
values (that just means a number in base ten), and then return that in a linked
list the same way as the numbers which we were given? Meaning that the number
(the digit value, not the whole value) is at the end the list, then preceded by
the digit that was to the RIGHT of it in the number, will be to the LEFT of it
in the linked list nodes?
2. Ask clarifying questions/State Assumptions
Ok this looks very interesting! Let me think for a second here... where would
we used this? This looks like it has some application in encoding and decoding
messages...
Can we assume this function needs to be able to handle linked lists of any
size, in terms of the number of nodes?
I'll assume so, since these are linked lists there's no restriction on the
size of the data we're receiving, save we run out of memory.
Are the two linked lists the same size as each other?
I'm assuming no, because we're decoding the values, and we should be able to
add any two decimal values regardless of their length.
And for right now, we're just concerned about summing 2 linked-lists right now?
I assume so - I know it says it right there in the problem, and that's what
I'll focus on for right now - but I'm totally down to improving it later to
handle more numbers (time permitting).
And what about the data type of the linked lists? I don't seem to recall a
built-in Python data structure for this, am I being provided with a Linked List
class here?
No? Okay, then I can just write up my own classes fairly simply.
It almost reminds me of the blockchain, you know? Linked lists and the
blockchain aren't exactly the same data structure - but maybe this function
could help us in same situation as Ethereum has, whenever they have to
verify a transaction. First we read in data from everyone's block, which in our
case is everyone's 2 or 3 sequence of linked list nodes, then we add up the
values stored in those pieces, then send off a new message encoded in a linked
list, before continuing with the rest of our process. I think it's really cool,
there's so many benefits to distributed systems in terms of scalability,
resistance to network failure, so on and so forth.
4a. Think out loud - Brainstorm solutions, explain rationale
Ok so in terms of our solution, when I look at the problem and I see the
example input you provided, there seems to be a really clear brute force
solution for this:
0. Write LinkedList and Node classes
1. "Decode" the first list - meaning we read in the number it represents
2. "Decode" the second list
3. Add the two values
4. "Encode" the sum value into a new linked list - convert it into what it
would look like in reverse, in terms of the nodes
5. return a new linked list
Everything here looks great so far - before coding it up we should probably
take a closer look at the decode() and encode() first, right?
decode() => it takes in a LinkedList as input right? Oh no, even better if we
just made it a property of the LinkedList class!
the steps of this method
we need to traverse the nodes
we can take the value from each node, and add it to a sum variable
(this can just keep incrementing, and that way even though it's out of order
we'll end up with the true decimal value at the end)
Oh, but we also have to make sure to be multiplying these by the power of ten,
based on which power of ten we're at in the problem!
Yeah - and that's fairly simple though, because the first value in the list
is in the ones place, followed by tens
so to speak, we can just keep another variable called exponent, and on each
iterative step through the list we can make sure to raise 10 by that value,
take that value and multiply it by the value in the Node, and THAT's what we
can increment sum by!
Here's the pseudocode then:
LinkedList.decode():
sum starts at 0
exponent starts at 1
data = grab next item from node, starting from the head
sum += 10**exponent * data
return the sum at the end
encode(sum):
going from left to right, grab digits from the sum
prepend them to the linkedlist (aka append them before the head node)
return the linkedlist at the end
Did that make sense so far? ok then, let's jump into the code!
"""
class Node(object):
def __init__(self, data):
self.data = data
self.next = None # pointer to the next Node in the list
class LinkedList(object):
def __init__(self, items=None):
self.size = 0 # property for number of Nodes, starts at zero default
self.head = self.tail = None
# create the nodes of the list, if they are initially passed in
if items is not None:
for item in items:
self.append(item)
def __str__(self):
"""Returns a string representation of the list nodes in order."""
# init return string
repr = ""
# traverse over nodes to build the string
node = self.head
while node is not Node:
data = node.data
# make the string to repesent the next node data in overall repr
if node == self.tail:
repr += f" {data}"
else:
repr += f"{data} -> "
node = node.next
return repr
def append(self, item):
"""Adds a new item to the list."""
# construct a new Node
node = Node(item)
# add it to the linkedlist (as the head no previous)
if self.size == 0:
self.head = node
# otherwise set it as the new tail
# if there's no current tail
elif self.size == 1:
self.head.next = node
# or if a tail already exists, set the node next to it
else:
self.tail.next = node
# no matter what, set the new tail of the list to the new node
self.tail = node
# increment the size of the list
self.size += 1
def prepend(self, item):
"""Adds an item at the front of a linked list."""
node = Node(item) # make a new Node
self.size += 1 # increment size of the list
current_head = self.head # save memory address of where head is now
node.next = current_head # ensure we don't lose the rest of the list
self.head = node # set the new node where it belongs
def decode(self):
"""Return the decimal value corresponding to the sequence of ints in
this list.
"""
# init return value
sum = 0
# counter for the exponent value at each node in the list
exponent = 1
# start traversal from the head node, (may be None)
node = self.head
# traverse the list
while node is not None:
# increment sum
sum += node.data * (10 ** exponent)
# move the next node
node = node.next
return sum
def delete(self, item):
"""Delete a node with the given item, or raise ValueError if not found.
Implementation left blank for now, because not needed to solve this
problem.
"""
pass
def encode(value):
"""Return the linkedlist representation of a nonegative decimal integer.
To implement this number, we need to slice off each integer, make a node
for it, and insert it into the list somewhere.
I see two ways of going about this:
1. Left to right: We start by grabbing digits from the highest place
value, then prepend each of them the linkedlist.
2. Right to left: We grab digits from the lowest place value, then
append them to the list.
In terms of tradeoffs, neither approach has any clear benefit over the
other. Both of these approaches scale in O(n) time, where n is the
number of digits in the value.
But since I'm left handed, I'll go with the first approach,
because it seems more familiar to write from L to R for me:
Google "cognitivie ease" if interested in learning more :)
"""
# to figure out the place value of the front digit, I will begin by
# modulo dividing the whole number by 10, and
# count how many times I need to do this until the quotient is 0
places = 0 # counter variable
decimal = value # copy of value, so we don't mdoify it
while decimal > 0:
places += 1
decimal %= 10
# next step: init a new linked list for the return value
ll = LinkedList()
# next step: adding nodes to the list
while decimal > 0:
# we take each integer off from the value
next_digit = decimal // (10 ** places)
# prepend to the list
ll.prepend(Node(next_digit))
# decrement places for the next iteration
places -= 1
# return the list at the end
return ll
"""
To the interviewer:
If this looks like a lot, don't worry my friend - I agree with you!
I acknowledge if this concerns you, and will be sure to test this at the end,
so we can see if it actually works or not.
"""
def combine_linked_lists(list1, list2):
"""Provide solution for the overall problem (see top)."""
# decode the lists
value1 = list1.decode()
value2 = list2.decode()
# find the sum
sum = value1 + value2
# return the encoded form of sum
return encode(sum)
"""
To the interviewer:
Whew, that was a lot of work - and all for just 4 lines of code at the end!
Ok, now I test this with the input you provided, and of course I'm sure we
can find some ways to improve it...
"""
if __name__ == "__main__":
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# By the way, is it ok to input values like this using lists?
# Sorry for not clarifying earlier!
list1 = LinkedList([2, 4, 3])
list2 = LinkedList([5, 6, 4])
# Output: 7 -> 0 -> 8
list3 = combine_linked_lists(list1, list2)
print(list3)
"""
To the interviewer:
Discuss tradeoffs/Suggest improvements
Oh that's weird! I am not sure why it's not working - I'm sure it's just a
small runtime error somewhere, such as I didn't implement the __str__ magic
function correctly - and if I was doing this for real I'm sure I could look up
the fix in the Python docs reasonably fast.
Other than that, I like how our solution turned out!
In terms of Big O complexity for combine_linked_lists:
decode operations - O(n1 + n2), where n1 and n2 are the number of digits in the
first and second linked lists being decoded, respectively
computing sum - O(1), so we don't reall need to worry about that asymptotically
encode - O(m) - scales linearly to the number of digits in the sum
Hmm, I'm not sure how I could improve the runtime - but in terms of the actual
engineering, I think we could definitely improve this using another data
structure!
I think perhaps if we used a queue, it might help us in terms of pulling apart
the digits from the lists - instead of figuring out all the math, we could just
enqueue and dequeue. Again, the runtime complexity wouldn't change, it'd still
be in linear time since we have to go through all the digits, but in terms of
simplicity of code and the actual computations we have to process, we might be
able to shave off some time in the real world - and you know these blockchain
apps need to be high performance if they're going to compete!
That's all I got for now. What do you think?
"""
| """
Problem #1: Add Two Numbers
Leetcode URL: https://leetcode.com/problems/add-two-numbers/
Description on LeetCode:
"
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.""
"""
'\n1. Restate the problem:\nOh okay, so the the digits in each linked list need to be first reversed,\nso that I know the value they really represent?\nThen if I heard you correctly, the process is I have to add those two decimal\nvalues (that just means a number in base ten), and then return that in a linked\nlist the same way as the numbers which we were given? Meaning that the number\n(the digit value, not the whole value) is at the end the list, then preceded by\nthe digit that was to the RIGHT of it in the number, will be to the LEFT of it\nin the linked list nodes?\n\n2. Ask clarifying questions/State Assumptions\nOk this looks very interesting! Let me think for a second here... where would\nwe used this? This looks like it has some application in encoding and decoding\nmessages...\n\nCan we assume this function needs to be able to handle linked lists of any\nsize, in terms of the number of nodes?\nI\'ll assume so, since these are linked lists there\'s no restriction on the\nsize of the data we\'re receiving, save we run out of memory.\n\nAre the two linked lists the same size as each other?\nI\'m assuming no, because we\'re decoding the values, and we should be able to\nadd any two decimal values regardless of their length.\n\nAnd for right now, we\'re just concerned about summing 2 linked-lists right now?\nI assume so - I know it says it right there in the problem, and that\'s what\nI\'ll focus on for right now - but I\'m totally down to improving it later to\nhandle more numbers (time permitting).\n\nAnd what about the data type of the linked lists? I don\'t seem to recall a\nbuilt-in Python data structure for this, am I being provided with a Linked List\nclass here?\nNo? Okay, then I can just write up my own classes fairly simply.\n\nIt almost reminds me of the blockchain, you know? Linked lists and the\nblockchain aren\'t exactly the same data structure - but maybe this function\ncould help us in same situation as Ethereum has, whenever they have to\nverify a transaction. First we read in data from everyone\'s block, which in our\ncase is everyone\'s 2 or 3 sequence of linked list nodes, then we add up the\nvalues stored in those pieces, then send off a new message encoded in a linked\nlist, before continuing with the rest of our process. I think it\'s really cool,\nthere\'s so many benefits to distributed systems in terms of scalability,\nresistance to network failure, so on and so forth.\n\n4a. Think out loud - Brainstorm solutions, explain rationale\n\nOk so in terms of our solution, when I look at the problem and I see the\nexample input you provided, there seems to be a really clear brute force\nsolution for this:\n\n0. Write LinkedList and Node classes\n1. "Decode" the first list - meaning we read in the number it represents\n2. "Decode" the second list\n3. Add the two values\n4. "Encode" the sum value into a new linked list - convert it into what it\nwould look like in reverse, in terms of the nodes\n5. return a new linked list\n\nEverything here looks great so far - before coding it up we should probably\ntake a closer look at the decode() and encode() first, right?\n\ndecode() => it takes in a LinkedList as input right? Oh no, even better if we\njust made it a property of the LinkedList class!\n\nthe steps of this method\n we need to traverse the nodes\n we can take the value from each node, and add it to a sum variable\n (this can just keep incrementing, and that way even though it\'s out of order\n we\'ll end up with the true decimal value at the end)\n\n Oh, but we also have to make sure to be multiplying these by the power of ten,\n based on which power of ten we\'re at in the problem!\n Yeah - and that\'s fairly simple though, because the first value in the list\n is in the ones place, followed by tens\n\n so to speak, we can just keep another variable called exponent, and on each\n iterative step through the list we can make sure to raise 10 by that value,\n take that value and multiply it by the value in the Node, and THAT\'s what we\n can increment sum by!\n\nHere\'s the pseudocode then:\n\nLinkedList.decode():\n sum starts at 0\n exponent starts at 1\n\n data = grab next item from node, starting from the head\n\n sum += 10**exponent * data\n\n return the sum at the end\n\n\nencode(sum):\n going from left to right, grab digits from the sum\n prepend them to the linkedlist (aka append them before the head node)\n return the linkedlist at the end\n\nDid that make sense so far? ok then, let\'s jump into the code!\n\n'
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist(object):
def __init__(self, items=None):
self.size = 0
self.head = self.tail = None
if items is not None:
for item in items:
self.append(item)
def __str__(self):
"""Returns a string representation of the list nodes in order."""
repr = ''
node = self.head
while node is not Node:
data = node.data
if node == self.tail:
repr += f' {data}'
else:
repr += f'{data} -> '
node = node.next
return repr
def append(self, item):
"""Adds a new item to the list."""
node = node(item)
if self.size == 0:
self.head = node
elif self.size == 1:
self.head.next = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def prepend(self, item):
"""Adds an item at the front of a linked list."""
node = node(item)
self.size += 1
current_head = self.head
node.next = current_head
self.head = node
def decode(self):
"""Return the decimal value corresponding to the sequence of ints in
this list.
"""
sum = 0
exponent = 1
node = self.head
while node is not None:
sum += node.data * 10 ** exponent
node = node.next
return sum
def delete(self, item):
"""Delete a node with the given item, or raise ValueError if not found.
Implementation left blank for now, because not needed to solve this
problem.
"""
pass
def encode(value):
"""Return the linkedlist representation of a nonegative decimal integer.
To implement this number, we need to slice off each integer, make a node
for it, and insert it into the list somewhere.
I see two ways of going about this:
1. Left to right: We start by grabbing digits from the highest place
value, then prepend each of them the linkedlist.
2. Right to left: We grab digits from the lowest place value, then
append them to the list.
In terms of tradeoffs, neither approach has any clear benefit over the
other. Both of these approaches scale in O(n) time, where n is the
number of digits in the value.
But since I'm left handed, I'll go with the first approach,
because it seems more familiar to write from L to R for me:
Google "cognitivie ease" if interested in learning more :)
"""
places = 0
decimal = value
while decimal > 0:
places += 1
decimal %= 10
ll = linked_list()
while decimal > 0:
next_digit = decimal // 10 ** places
ll.prepend(node(next_digit))
places -= 1
return ll
"\nTo the interviewer:\nIf this looks like a lot, don't worry my friend - I agree with you!\nI acknowledge if this concerns you, and will be sure to test this at the end,\nso we can see if it actually works or not.\n"
def combine_linked_lists(list1, list2):
"""Provide solution for the overall problem (see top)."""
value1 = list1.decode()
value2 = list2.decode()
sum = value1 + value2
return encode(sum)
"\nTo the interviewer:\nWhew, that was a lot of work - and all for just 4 lines of code at the end!\nOk, now I test this with the input you provided, and of course I'm sure we\ncan find some ways to improve it...\n"
if __name__ == '__main__':
list1 = linked_list([2, 4, 3])
list2 = linked_list([5, 6, 4])
list3 = combine_linked_lists(list1, list2)
print(list3)
"\nTo the interviewer:\nDiscuss tradeoffs/Suggest improvements\nOh that's weird! I am not sure why it's not working - I'm sure it's just a\nsmall runtime error somewhere, such as I didn't implement the __str__ magic\nfunction correctly - and if I was doing this for real I'm sure I could look up\nthe fix in the Python docs reasonably fast.\n\nOther than that, I like how our solution turned out!\nIn terms of Big O complexity for combine_linked_lists:\n\ndecode operations - O(n1 + n2), where n1 and n2 are the number of digits in the\n first and second linked lists being decoded, respectively\ncomputing sum - O(1), so we don't reall need to worry about that asymptotically\nencode - O(m) - scales linearly to the number of digits in the sum\n\nHmm, I'm not sure how I could improve the runtime - but in terms of the actual\nengineering, I think we could definitely improve this using another data\nstructure!\n\nI think perhaps if we used a queue, it might help us in terms of pulling apart\nthe digits from the lists - instead of figuring out all the math, we could just\nenqueue and dequeue. Again, the runtime complexity wouldn't change, it'd still\nbe in linear time since we have to go through all the digits, but in terms of\nsimplicity of code and the actual computations we have to process, we might be\nable to shave off some time in the real world - and you know these blockchain\napps need to be high performance if they're going to compete!\n\nThat's all I got for now. What do you think?\n\n" |
#: A dict contains permission's number as string and its corresponding meanings.
PERM_MAP = {
"1": "download and preview",
"2": "upload",
"3": "upload, download, preview, remove and move",
"4": "upload, download, preview, remove, move and change acls of others",
"5": "preview"
}
#: A set contains all available operation types.
OPERATION_TYPE = {
"SESSION_START",
"DOWNLOAD",
"UPLOAD",
"SHARE",
"MOVE",
"DELETE",
"RESTORE",
"PREVIEW",
"PURGE",
"PWD_ATTACK",
"VIRUS_INFECTED"
}
| perm_map = {'1': 'download and preview', '2': 'upload', '3': 'upload, download, preview, remove and move', '4': 'upload, download, preview, remove, move and change acls of others', '5': 'preview'}
operation_type = {'SESSION_START', 'DOWNLOAD', 'UPLOAD', 'SHARE', 'MOVE', 'DELETE', 'RESTORE', 'PREVIEW', 'PURGE', 'PWD_ATTACK', 'VIRUS_INFECTED'} |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: https://github.com/LFreedomDev
# Created on 2018-08-31
# pretask schema
{
'pretask': {
'taskid':str,
'project': str,
'url': str,
}
}
class PreTaskDB(object):
"""
database for pretask
"""
def insert(self,pretask):
raise NotImplementedError
def select(self,project):
raise NotImplementedError
def delete(self,taskid):
raise NotImplementedError
| {'pretask': {'taskid': str, 'project': str, 'url': str}}
class Pretaskdb(object):
"""
database for pretask
"""
def insert(self, pretask):
raise NotImplementedError
def select(self, project):
raise NotImplementedError
def delete(self, taskid):
raise NotImplementedError |
def _reduced_string(s):
if not s:
return "Empty String"
letters = list()
counts = list()
last = ""
counts_index = -1
for ch in s:
if last != ch:
letters.append(ch)
counts.append(1)
counts_index += 1
last = ch
else:
counts[counts_index] += 1
ans = list()
for i, val in enumerate(counts):
ans.append(val % 2 * letters[i])
ans = "".join(ans)
if not ans:
ans = "Empty String"
changed = s != ans
return ans, changed
def reduced_string(s):
ans, changed = _reduced_string(s)
while changed:
ans, changed = _reduced_string(ans)
return ans
def test_solution1():
s = "aaabccddd"
ans = "abd"
assert ans == reduced_string(s)
def test_solution2():
s = "baab"
ans = "Empty String"
assert ans == reduced_string(s)
def test_solution3():
s = "aabbccdd"
ans = "Empty String"
assert ans == reduced_string(s)
| def _reduced_string(s):
if not s:
return 'Empty String'
letters = list()
counts = list()
last = ''
counts_index = -1
for ch in s:
if last != ch:
letters.append(ch)
counts.append(1)
counts_index += 1
last = ch
else:
counts[counts_index] += 1
ans = list()
for (i, val) in enumerate(counts):
ans.append(val % 2 * letters[i])
ans = ''.join(ans)
if not ans:
ans = 'Empty String'
changed = s != ans
return (ans, changed)
def reduced_string(s):
(ans, changed) = _reduced_string(s)
while changed:
(ans, changed) = _reduced_string(ans)
return ans
def test_solution1():
s = 'aaabccddd'
ans = 'abd'
assert ans == reduced_string(s)
def test_solution2():
s = 'baab'
ans = 'Empty String'
assert ans == reduced_string(s)
def test_solution3():
s = 'aabbccdd'
ans = 'Empty String'
assert ans == reduced_string(s) |
# Config file for user settings
# Change anything as desired
''' Navigation Settings '''
PAN_DIST = 15
PAN_DIST_LARGE = 60
ZOOM_FACTOR = 1.35
'''Canvas Settings'''
SUB_COLOR = (1, 0, 0, 1)
PATH_COLOR = (0, 0, 0, 0.7)
GRID_COLOR = (0.4, 0, 0, 0.3)
TAG_COLOR = (0, 0, 1, 0.8)
ELEMENT_COLOR = (0, .5, 0, 1.0)
MAGNIFY = 40 #How many pixels correspond to 1 unit in shm
PATH_RES = 0.15 #Path resolution
SUB_SIZE = 8
TAG_SIZE = 5
PATH_LEN = -1 #neg. number indicates unbounded
GRID_LINES = 50
GRID_SPACE = 1. #in meters
SMOOTHING = True
PERIOD = .01 # Period of smooth updates, smaller <=> faster smoothing
''' Key bindings '''
# You can bind the control key with the format 'ctrl [key]'
# The same applies to the shift key: 'shift [key]'
# NOTE: Do not use uppercase letters, use shift + letter
# To include both control and shift, ctrl comes first: 'ctrl shift [key]'
bindings_on = True
key_binds = {}
key_binds["quit"] = "shift q"
key_binds["bindings toggle"] = "shift b"
key_binds["help"] = "h"
key_binds["follow sub"] = "shift f"
key_binds["follow position only"] = "f"
key_binds["reset path"] = "r"
key_binds["zoom in"] = "i"
key_binds["zoom out"] = "o"
key_binds["pan left"] = "left"
key_binds["pan left large"] = "shift left"
key_binds["pan right"] = "right"
key_binds["pan right large"] = "shift right"
key_binds["pan up"] = "up"
key_binds["pan up large"] = "shift up"
key_binds["pan down"] = "down"
key_binds["pan down large"] = "shift down"
key_binds["center view"] = "c"
key_binds["rotate cw"] = "ctrl left"
key_binds["rotate ccw"] = "ctrl right"
| """ Navigation Settings """
pan_dist = 15
pan_dist_large = 60
zoom_factor = 1.35
'Canvas Settings'
sub_color = (1, 0, 0, 1)
path_color = (0, 0, 0, 0.7)
grid_color = (0.4, 0, 0, 0.3)
tag_color = (0, 0, 1, 0.8)
element_color = (0, 0.5, 0, 1.0)
magnify = 40
path_res = 0.15
sub_size = 8
tag_size = 5
path_len = -1
grid_lines = 50
grid_space = 1.0
smoothing = True
period = 0.01
' Key bindings '
bindings_on = True
key_binds = {}
key_binds['quit'] = 'shift q'
key_binds['bindings toggle'] = 'shift b'
key_binds['help'] = 'h'
key_binds['follow sub'] = 'shift f'
key_binds['follow position only'] = 'f'
key_binds['reset path'] = 'r'
key_binds['zoom in'] = 'i'
key_binds['zoom out'] = 'o'
key_binds['pan left'] = 'left'
key_binds['pan left large'] = 'shift left'
key_binds['pan right'] = 'right'
key_binds['pan right large'] = 'shift right'
key_binds['pan up'] = 'up'
key_binds['pan up large'] = 'shift up'
key_binds['pan down'] = 'down'
key_binds['pan down large'] = 'shift down'
key_binds['center view'] = 'c'
key_binds['rotate cw'] = 'ctrl left'
key_binds['rotate ccw'] = 'ctrl right' |
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
path = []
res = []
candidates.sort()
def dfs(i,n,t):
if t == 0:
res.append(path[:])
while(i<n and candidates[i]<=t):
path.append(candidates[i])
dfs(i+1,n,t-candidates[i])
path.pop()
i += 1
while(i<n and candidates[i]==candidates[i-1]):
i += 1
dfs(0,len(candidates),target)
return res | class Solution(object):
def combination_sum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
path = []
res = []
candidates.sort()
def dfs(i, n, t):
if t == 0:
res.append(path[:])
while i < n and candidates[i] <= t:
path.append(candidates[i])
dfs(i + 1, n, t - candidates[i])
path.pop()
i += 1
while i < n and candidates[i] == candidates[i - 1]:
i += 1
dfs(0, len(candidates), target)
return res |
def find_peak(arr, begin=0, end=None, l=None):
'''find_peak is a recursive function that uses divide and conquer methodolology (similar to binary search)
to find the index of a peak element in O(log n) time complexity'''
# initialize values on first iteration
if end is None or l is None:
l = len(arr)
end = l-1
# find index of middle element
mid = int(begin + (end - begin) / 2) # truncate result to an int
try:
# base case: first check if middle is a peak element
# if it is, return it
if arr[mid] > arr[mid+1] and arr[mid] > arr[mid-1]:
return mid
# if left element is greater than mid, left half must contain a peak;
# run function again on left half of arr
if arr[mid-1] > arr[mid]:
return find_peak(arr, begin, mid-1, l)
# if right element is greater than mid, right half must contain a peak;
# run function again on right half of arr
if arr[mid+1] > arr[mid]:
return find_peak(arr, mid+1, end, l)
except IndexError:
# couldn't find a peak
# return either 1st or last element index depending on which is bigger
# peak will be equal to the corner case of begin or end
if arr[0] > arr[l-1]:
return 0
return l-1
## TEST ##
arr = [8, 9, 10, 11, 11, 12, 13, 14, 15, 18]
print(arr)
result = find_peak(arr)
print("Peak Index:", result)
print("Peak:", arr[result])
| def find_peak(arr, begin=0, end=None, l=None):
"""find_peak is a recursive function that uses divide and conquer methodolology (similar to binary search)
to find the index of a peak element in O(log n) time complexity"""
if end is None or l is None:
l = len(arr)
end = l - 1
mid = int(begin + (end - begin) / 2)
try:
if arr[mid] > arr[mid + 1] and arr[mid] > arr[mid - 1]:
return mid
if arr[mid - 1] > arr[mid]:
return find_peak(arr, begin, mid - 1, l)
if arr[mid + 1] > arr[mid]:
return find_peak(arr, mid + 1, end, l)
except IndexError:
if arr[0] > arr[l - 1]:
return 0
return l - 1
arr = [8, 9, 10, 11, 11, 12, 13, 14, 15, 18]
print(arr)
result = find_peak(arr)
print('Peak Index:', result)
print('Peak:', arr[result]) |
ECG_CHAN_1 = 0
ECG_CHAN_2 = 1
ECG_CHAN_3 = 2
LEAD_05_CHAN_1_DATA_SIZE = 9
LEAD_12_CHAN_1_DATA_SIZE = 6
LEAD_12_CHAN_2_DATA_SIZE = 9
LEAD_12_CHAN_3_DATA_SIZE = 9
TI_ADS1293_CONFIG_REG = 0x00 #/* Main Configuration */
TI_ADS1293_FLEX_CH1_CN_REG = 0x01 #/* Flex Routing Swich Control for Channel 1 */
TI_ADS1293_FLEX_CH2_CN_REG = 0x02 #/* Flex Routing Swich Control for Channel 2 */
TI_ADS1293_FLEX_CH3_CN_REG = 0x03 #/* Flex Routing Swich Control for Channel 3 */
TI_ADS1293_FLEX_PACE_CN_REG = 0x04 #/* Flex Routing Swich Control for Pace Channel */
TI_ADS1293_FLEX_VBAT_CN_REG = 0x05 #/* Flex Routing Swich Control for Battery Monitoriing */
TI_ADS1293_LOD_CN_REG = 0x06 #/* Lead Off Detect Control */
TI_ADS1293_LOD_EN_REG = 0x07 #/* Lead Off Detect Enable */
TI_ADS1293_LOD_CURRENT_REG = 0x08 #/* Lead Off Detect Current */
TI_ADS1293_LOD_AC_CN_REG = 0x09 #/* AC Lead Off Detect Current */
TI_ADS1293_CMDET_EN_REG = 0x0A #/* Common Mode Detect Enable */
TI_ADS1293_CMDET_CN_REG = 0x0B #/* Commond Mode Detect Control */
TI_ADS1293_RLD_CN_REG = 0x0C #/* Right Leg Drive Control */
TI_ADS1293_WILSON_EN1_REG = 0x0D #/* Wilson Reference Input one Selection */
TI_ADS1293_WILSON_EN2_REG = 0x0E #/* Wilson Reference Input two Selection */
TI_ADS1293_WILSON_EN3_REG = 0x0F #/* Wilson Reference Input three Selection */
TI_ADS1293_WILSON_CN_REG = 0x10 #/* Wilson Reference Input Control */
TI_ADS1293_REF_CN_REG = 0x11 #/* Internal Reference Voltage Control */
TI_ADS1293_OSC_CN_REG = 0x12 #/* Clock Source and Output Clock Control */
TI_ADS1293_AFE_RES_REG = 0x13 #/* Analog Front-End Frequency and Resolution */
TI_ADS1293_AFE_SHDN_CN_REG = 0x14 #/* Analog Front-End Shutdown Control */
TI_ADS1293_AFE_FAULT_CN_REG = 0x15 #/* Analog Front-End Fault Detection Control */
TI_ADS1293_AFE_DITHER_EN_REG = 0x16 #/* Enable Dithering in Signma-Delta */
TI_ADS1293_AFE_PACE_CN_REG = 0x17 #/* Analog Pace Channel Output Routing Control */
TI_ADS1293_ERROR_LOD_REG = 0x18 #/* Lead Off Detect Error Status */
TI_ADS1293_ERROR_STATUS_REG = 0x19 #/* Other Error Status */
TI_ADS1293_ERROR_RANGE1_REG = 0x1A #/* Channel 1 Amplifier Out of Range Status */
TI_ADS1293_ERROR_RANGE2_REG = 0x1B #/* Channel 1 Amplifier Out of Range Status */
TI_ADS1293_ERROR_RANGE3_REG = 0x1C #/* Channel 1 Amplifier Out of Range Status */
TI_ADS1293_ERROR_SYNC_REG = 0x1D #/* Synchronization Error */
TI_ADS1293_R2_RATE_REG = 0x21 #/* R2 Decimation Rate */
TI_ADS1293_R3_RATE1_REG = 0x22 #/* R3 Decimation Rate for Channel 1 */
TI_ADS1293_R3_RATE2_REG = 0x23 #/* R3 Decimation Rate for Channel 2 */
TI_ADS1293_R3_RATE3_REG = 0x24 #/* R3 Decimation Rate for Channel 3 */
TI_ADS1293_P_DRATE_REG = 0x25 #/* 2x Pace Data Rate */
TI_ADS1293_DIS_EFILTER_REG = 0x26 #/* ECG Filter Disable */
TI_ADS1293_DRDYB_SRC_REG = 0x27 #/* Data Ready Pin Source */
TI_ADS1293_SYNCOUTB_SRC_REG = 0x28 #/* Sync Out Pin Source */
TI_ADS1293_MASK_DRDYB_REG = 0x29 #/* Optional Mask Control for DRDYB Output */
TI_ADS1293_MASK_ERR_REG = 0x2A #/* Mask Error on ALARMB Pin */
TI_ADS1293_ALARM_FILTER_REG = 0x2E #/* Digital Filter for Analog Alarm Signals */
TI_ADS1293_CH_CNFG_REG = 0x2F #/* Configure Channel for Loop Read Back Mode */
TI_ADS1293_DATA_STATUS_REG = 0x30 #/* ECG and Pace Data Ready Status */
TI_ADS1293_DATA_CH1_PACE_H_REG = 0x31 #/* Channel1 Pace Data High [15:8] */
TI_ADS1293_DATA_CH1_PACE_L_REG = 0x32 #/* Channel1 Pace Data Low [7:0] */
TI_ADS1293_DATA_CH2_PACE_H_REG = 0x33 #/* Channel2 Pace Data High [15:8] */
TI_ADS1293_DATA_CH2_PACE_L_REG = 0x34 #/* Channel2 Pace Data Low [7:0] */
TI_ADS1293_DATA_CH3_PACE_H_REG = 0x35 #/* Channel3 Pace Data High [15:8] */
TI_ADS1293_DATA_CH3_PACE_L_REG = 0x36 #/* Channel3 Pace Data Low [7:0] */
TI_ADS1293_DATA_CH1_ECG_H_REG = 0x37 #/* Channel1 ECG Data High [23:16] */
TI_ADS1293_DATA_CH1_ECG_M_REG = 0x38 #/* Channel1 ECG Data Medium [15:8] */
TI_ADS1293_DATA_CH1_ECG_L_REG = 0x39 #/* Channel1 ECG Data Low [7:0] */
TI_ADS1293_DATA_CH2_ECG_H_REG = 0x3A #/* Channel2 ECG Data High [23:16] */
TI_ADS1293_DATA_CH2_ECG_M_REG = 0x3B #/* Channel2 ECG Data Medium [15:8] */
TI_ADS1293_DATA_CH2_ECG_L_REG = 0x3C #/* Channel2 ECG Data Low [7:0] */
TI_ADS1293_DATA_CH3_ECG_H_REG = 0x3D #/* Channel3 ECG Data High [23:16] */
TI_ADS1293_DATA_CH3_ECG_M_REG = 0x3E #/* Channel3 ECG Data Medium [15:8] */
TI_ADS1293_DATA_CH3_ECG_L_REG = 0x3F #/* Channel3 ECG Data Low [7:0] */
TI_ADS1293_REVID_REG = 0x40 #/* Revision ID */
TI_ADS1293_DATA_LOOP_REG = 0x50 #/* Loop Read Back Address */
#Useful definitions
ADS1293_READ_BIT = 0x80
ADS1293_WRITE_BIT = 0x7F | ecg_chan_1 = 0
ecg_chan_2 = 1
ecg_chan_3 = 2
lead_05_chan_1_data_size = 9
lead_12_chan_1_data_size = 6
lead_12_chan_2_data_size = 9
lead_12_chan_3_data_size = 9
ti_ads1293_config_reg = 0
ti_ads1293_flex_ch1_cn_reg = 1
ti_ads1293_flex_ch2_cn_reg = 2
ti_ads1293_flex_ch3_cn_reg = 3
ti_ads1293_flex_pace_cn_reg = 4
ti_ads1293_flex_vbat_cn_reg = 5
ti_ads1293_lod_cn_reg = 6
ti_ads1293_lod_en_reg = 7
ti_ads1293_lod_current_reg = 8
ti_ads1293_lod_ac_cn_reg = 9
ti_ads1293_cmdet_en_reg = 10
ti_ads1293_cmdet_cn_reg = 11
ti_ads1293_rld_cn_reg = 12
ti_ads1293_wilson_en1_reg = 13
ti_ads1293_wilson_en2_reg = 14
ti_ads1293_wilson_en3_reg = 15
ti_ads1293_wilson_cn_reg = 16
ti_ads1293_ref_cn_reg = 17
ti_ads1293_osc_cn_reg = 18
ti_ads1293_afe_res_reg = 19
ti_ads1293_afe_shdn_cn_reg = 20
ti_ads1293_afe_fault_cn_reg = 21
ti_ads1293_afe_dither_en_reg = 22
ti_ads1293_afe_pace_cn_reg = 23
ti_ads1293_error_lod_reg = 24
ti_ads1293_error_status_reg = 25
ti_ads1293_error_range1_reg = 26
ti_ads1293_error_range2_reg = 27
ti_ads1293_error_range3_reg = 28
ti_ads1293_error_sync_reg = 29
ti_ads1293_r2_rate_reg = 33
ti_ads1293_r3_rate1_reg = 34
ti_ads1293_r3_rate2_reg = 35
ti_ads1293_r3_rate3_reg = 36
ti_ads1293_p_drate_reg = 37
ti_ads1293_dis_efilter_reg = 38
ti_ads1293_drdyb_src_reg = 39
ti_ads1293_syncoutb_src_reg = 40
ti_ads1293_mask_drdyb_reg = 41
ti_ads1293_mask_err_reg = 42
ti_ads1293_alarm_filter_reg = 46
ti_ads1293_ch_cnfg_reg = 47
ti_ads1293_data_status_reg = 48
ti_ads1293_data_ch1_pace_h_reg = 49
ti_ads1293_data_ch1_pace_l_reg = 50
ti_ads1293_data_ch2_pace_h_reg = 51
ti_ads1293_data_ch2_pace_l_reg = 52
ti_ads1293_data_ch3_pace_h_reg = 53
ti_ads1293_data_ch3_pace_l_reg = 54
ti_ads1293_data_ch1_ecg_h_reg = 55
ti_ads1293_data_ch1_ecg_m_reg = 56
ti_ads1293_data_ch1_ecg_l_reg = 57
ti_ads1293_data_ch2_ecg_h_reg = 58
ti_ads1293_data_ch2_ecg_m_reg = 59
ti_ads1293_data_ch2_ecg_l_reg = 60
ti_ads1293_data_ch3_ecg_h_reg = 61
ti_ads1293_data_ch3_ecg_m_reg = 62
ti_ads1293_data_ch3_ecg_l_reg = 63
ti_ads1293_revid_reg = 64
ti_ads1293_data_loop_reg = 80
ads1293_read_bit = 128
ads1293_write_bit = 127 |
# field_subject on islandora 8 is configured to map to the following vocabs: Corporate, Family, Geographic Location,
# Person, Subject
class MemberOf:
def __init__(self):
self.drupal_fieldnames = {'memberof': 'field_member_of'}
self.memberof = 'Repository Item'
def get_memberof(self):
return self.memberof
def get_memberoffieldname(self):
return self.drupal_fieldnames['memberof'] | class Memberof:
def __init__(self):
self.drupal_fieldnames = {'memberof': 'field_member_of'}
self.memberof = 'Repository Item'
def get_memberof(self):
return self.memberof
def get_memberoffieldname(self):
return self.drupal_fieldnames['memberof'] |
# -*- coding: UTF-8 -*-
def read(file):
"""
Read the content of the file as a list
Args:
file: the name of the file with the path
"""
with open(file, 'r') as f:
return f.read().split("\n")
def write(file, text):
"""
Save the file into a specific directory
Args:
file: the name of the file with the path
text: the text to be written in the file
"""
with open(file, 'w') as f:
f.write(text)
| def read(file):
"""
Read the content of the file as a list
Args:
file: the name of the file with the path
"""
with open(file, 'r') as f:
return f.read().split('\n')
def write(file, text):
"""
Save the file into a specific directory
Args:
file: the name of the file with the path
text: the text to be written in the file
"""
with open(file, 'w') as f:
f.write(text) |
# Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""
Map of paths to build mode overrides.
Format is: {cell: {path: {'<mode>': <options>}}
"""
build_mode_overrides = {}
| """
Map of paths to build mode overrides.
Format is: {cell: {path: {'<mode>': <options>}}
"""
build_mode_overrides = {} |
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
diff = []
for item in a:
if item not in b:
diff.append(item)
for item in b:
if item not in a:
diff.append(item)
print(diff) | a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
diff = []
for item in a:
if item not in b:
diff.append(item)
for item in b:
if item not in a:
diff.append(item)
print(diff) |
#
# PySNMP MIB module ZYXEL-CPU-PROTECTION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CPU-PROTECTION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:49:18 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, Integer32, Bits, ObjectIdentity, Gauge32, IpAddress, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, iso, Counter32, Unsigned32, Counter64, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Integer32", "Bits", "ObjectIdentity", "Gauge32", "IpAddress", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "iso", "Counter32", "Unsigned32", "Counter64", "MibIdentifier")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt")
zyxelCpuProtection = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16))
if mibBuilder.loadTexts: zyxelCpuProtection.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts: zyxelCpuProtection.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts: zyxelCpuProtection.setContactInfo('')
if mibBuilder.loadTexts: zyxelCpuProtection.setDescription('The subtree for cpu protection')
zyxelCpuProtectionSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1))
zyxelCpuProtectionTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1), )
if mibBuilder.loadTexts: zyxelCpuProtectionTable.setStatus('current')
if mibBuilder.loadTexts: zyxelCpuProtectionTable.setDescription('The table contains CPU protection configuration.')
zyxelCpuProtectionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1), ).setIndexNames((0, "ZYXEL-CPU-PROTECTION-MIB", "zyCpuProtectionPort"), (0, "ZYXEL-CPU-PROTECTION-MIB", "zyCpuProtectionReasonType"))
if mibBuilder.loadTexts: zyxelCpuProtectionEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelCpuProtectionEntry.setDescription('An entry contains CPU protection configuration.')
zyCpuProtectionPort = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 1), Integer32())
if mibBuilder.loadTexts: zyCpuProtectionPort.setStatus('current')
if mibBuilder.loadTexts: zyCpuProtectionPort.setDescription('This field displays the port number.')
zyCpuProtectionReasonType = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("arp", 1), ("bpdu", 2), ("igmp", 3))))
if mibBuilder.loadTexts: zyCpuProtectionReasonType.setStatus('current')
if mibBuilder.loadTexts: zyCpuProtectionReasonType.setDescription('This field displays which type of control packets on the specified port.')
zyCpuProtectionRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 256))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyCpuProtectionRateLimit.setStatus('current')
if mibBuilder.loadTexts: zyCpuProtectionRateLimit.setDescription('Enter a number from 0 to 256 to specified how many control packets this port can receive or transmit per second. 0 means no rate limit.')
mibBuilder.exportSymbols("ZYXEL-CPU-PROTECTION-MIB", zyxelCpuProtectionEntry=zyxelCpuProtectionEntry, zyCpuProtectionReasonType=zyCpuProtectionReasonType, zyxelCpuProtectionSetup=zyxelCpuProtectionSetup, zyxelCpuProtectionTable=zyxelCpuProtectionTable, zyCpuProtectionPort=zyCpuProtectionPort, zyxelCpuProtection=zyxelCpuProtection, zyCpuProtectionRateLimit=zyCpuProtectionRateLimit, PYSNMP_MODULE_ID=zyxelCpuProtection)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(notification_type, integer32, bits, object_identity, gauge32, ip_address, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, iso, counter32, unsigned32, counter64, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Integer32', 'Bits', 'ObjectIdentity', 'Gauge32', 'IpAddress', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'iso', 'Counter32', 'Unsigned32', 'Counter64', 'MibIdentifier')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt')
zyxel_cpu_protection = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16))
if mibBuilder.loadTexts:
zyxelCpuProtection.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts:
zyxelCpuProtection.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts:
zyxelCpuProtection.setContactInfo('')
if mibBuilder.loadTexts:
zyxelCpuProtection.setDescription('The subtree for cpu protection')
zyxel_cpu_protection_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1))
zyxel_cpu_protection_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1))
if mibBuilder.loadTexts:
zyxelCpuProtectionTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelCpuProtectionTable.setDescription('The table contains CPU protection configuration.')
zyxel_cpu_protection_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1)).setIndexNames((0, 'ZYXEL-CPU-PROTECTION-MIB', 'zyCpuProtectionPort'), (0, 'ZYXEL-CPU-PROTECTION-MIB', 'zyCpuProtectionReasonType'))
if mibBuilder.loadTexts:
zyxelCpuProtectionEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelCpuProtectionEntry.setDescription('An entry contains CPU protection configuration.')
zy_cpu_protection_port = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 1), integer32())
if mibBuilder.loadTexts:
zyCpuProtectionPort.setStatus('current')
if mibBuilder.loadTexts:
zyCpuProtectionPort.setDescription('This field displays the port number.')
zy_cpu_protection_reason_type = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('arp', 1), ('bpdu', 2), ('igmp', 3))))
if mibBuilder.loadTexts:
zyCpuProtectionReasonType.setStatus('current')
if mibBuilder.loadTexts:
zyCpuProtectionReasonType.setDescription('This field displays which type of control packets on the specified port.')
zy_cpu_protection_rate_limit = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 16, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 256))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyCpuProtectionRateLimit.setStatus('current')
if mibBuilder.loadTexts:
zyCpuProtectionRateLimit.setDescription('Enter a number from 0 to 256 to specified how many control packets this port can receive or transmit per second. 0 means no rate limit.')
mibBuilder.exportSymbols('ZYXEL-CPU-PROTECTION-MIB', zyxelCpuProtectionEntry=zyxelCpuProtectionEntry, zyCpuProtectionReasonType=zyCpuProtectionReasonType, zyxelCpuProtectionSetup=zyxelCpuProtectionSetup, zyxelCpuProtectionTable=zyxelCpuProtectionTable, zyCpuProtectionPort=zyCpuProtectionPort, zyxelCpuProtection=zyxelCpuProtection, zyCpuProtectionRateLimit=zyCpuProtectionRateLimit, PYSNMP_MODULE_ID=zyxelCpuProtection) |
# GENERATED VERSION FILE
# TIME: Tue Oct 6 17:46:50 2020
__version__ = "0.3.0+0e6315d"
short_version = "0.3.0"
| __version__ = '0.3.0+0e6315d'
short_version = '0.3.0' |
class RequestLog:
def __init__(self):
self.url = None
self.request_headers = None
self.request_body = None
self.request_method = None
self.request_timestamp = None
self.status_code = None
self.response_headers = None
self.response_body = None
self.response_timestamp = None
self.error = None
| class Requestlog:
def __init__(self):
self.url = None
self.request_headers = None
self.request_body = None
self.request_method = None
self.request_timestamp = None
self.status_code = None
self.response_headers = None
self.response_body = None
self.response_timestamp = None
self.error = None |
#is_hot = True
#is_cold = False
#if is_hot:
#print("it's a hot day wear a vest")
#elif is_cold:
#print("its cold")
#else:
#print("die"1111111111111)
#good_credit = True
#price = 1000000
#if good_credit:
#print("you need to put down 10%")
#print("payment is " + "$" + str(0.1*price))
#else:
#print("you need to put down 20%")
#print("payment is " + "$" + str(0.2*price))
#good_credit = True
#price = 1000000
#if good_credit:
#down_payment = 0.1 * price
#else:
#down_payment = 0.2 * price
#print(f"the down payment: ${down_payment}")
# temperature = 30
# if temperature > 30:
# print ("it is hot")
# elif temperature < 20:
# print("it is kinda cold")
# else:
# print("aight i am not sure what temperature it is")
name = input()
name_character = len(name)
if name_character < 3:
print("your name character is too short")
elif name_character > 20:
print("your name character is too long")
else:
print("your name character are perfect") | name = input()
name_character = len(name)
if name_character < 3:
print('your name character is too short')
elif name_character > 20:
print('your name character is too long')
else:
print('your name character are perfect') |
def media_digitos(n):
num = list(map(int,str(n)))
return sum(num) / len(num)
n = int(input("digite o valor: "))
print(f"a media dos valores e: {media_digitos(n)}") | def media_digitos(n):
num = list(map(int, str(n)))
return sum(num) / len(num)
n = int(input('digite o valor: '))
print(f'a media dos valores e: {media_digitos(n)}') |
__title__ = "asent"
__version__ = "0.3.0" # the ONLY source of version ID
__download_url__ = "https://github.com/kennethenevoldsen/asent"
__documentation__ = "https://kennethenevoldsen.github.io/asent"
| __title__ = 'asent'
__version__ = '0.3.0'
__download_url__ = 'https://github.com/kennethenevoldsen/asent'
__documentation__ = 'https://kennethenevoldsen.github.io/asent' |
N = int(input())
T = [int(input()) for _ in range(N)]
total = sum(T)
ans = 1e10
for i in range(2 ** N):
tmp = 0
for j in range(N):
if i & (1 << j):
tmp += T[j]
ans = min(ans, max(tmp, total - tmp))
print(ans)
| n = int(input())
t = [int(input()) for _ in range(N)]
total = sum(T)
ans = 10000000000.0
for i in range(2 ** N):
tmp = 0
for j in range(N):
if i & 1 << j:
tmp += T[j]
ans = min(ans, max(tmp, total - tmp))
print(ans) |
x=int(input())
y=int(input())
i=int(1)
fact=int(1)
while i<=x :
fact=((fact%y)*(i%y))%y
i=i+1
print(fact) | x = int(input())
y = int(input())
i = int(1)
fact = int(1)
while i <= x:
fact = fact % y * (i % y) % y
i = i + 1
print(fact) |
class DLinkedNode():
def __init__(self, key: int = None, value: int = None, prev: 'DLinkedList' = None, next: 'DLinkedList' = None):
self.key = key
self.value = value
self.prev = prev
self.next = next
class DLinkedList():
def __init__(self):
self.head = DLinkedNode()
self.tail = DLinkedNode()
self.head.next = self.tail
self.tail.prev = self.head
def pop_tail(self) -> 'DLinkedList':
res = self.tail.prev
self.remove_node(res)
return res
def move_to_head(self, node: 'DLinkedList') -> None:
self.remove_node(node)
self.add_node(node)
def remove_node(self, node: 'DLinkedList') -> None:
prev = node.prev
new = node.next
prev.next = new
new.prev = prev
def add_node(self, node: 'DLinkedList') -> None:
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
class LRUCache():
def __init__(self, capacity: int):
self.size = 0
self.capacity = capacity
self.cache = {}
self.list = DLinkedList()
def get(self, key: int) -> int:
node = self.cache.get(key)
if not node: return -1
self.list.move_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
node = self.cache.get(key)
if not node:
node = DLinkedNode(key=key, value=value)
self.cache[key] = node
self.list.add_node(node)
self.size += 1
if self.size > self.capacity:
tail = self.list.pop_tail()
del self.cache[tail.key]
self.size -= 1
else:
node.value = value
self.list.move_to_head(node)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
| class Dlinkednode:
def __init__(self, key: int=None, value: int=None, prev: 'DLinkedList'=None, next: 'DLinkedList'=None):
self.key = key
self.value = value
self.prev = prev
self.next = next
class Dlinkedlist:
def __init__(self):
self.head = d_linked_node()
self.tail = d_linked_node()
self.head.next = self.tail
self.tail.prev = self.head
def pop_tail(self) -> 'DLinkedList':
res = self.tail.prev
self.remove_node(res)
return res
def move_to_head(self, node: 'DLinkedList') -> None:
self.remove_node(node)
self.add_node(node)
def remove_node(self, node: 'DLinkedList') -> None:
prev = node.prev
new = node.next
prev.next = new
new.prev = prev
def add_node(self, node: 'DLinkedList') -> None:
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
class Lrucache:
def __init__(self, capacity: int):
self.size = 0
self.capacity = capacity
self.cache = {}
self.list = d_linked_list()
def get(self, key: int) -> int:
node = self.cache.get(key)
if not node:
return -1
self.list.move_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
node = self.cache.get(key)
if not node:
node = d_linked_node(key=key, value=value)
self.cache[key] = node
self.list.add_node(node)
self.size += 1
if self.size > self.capacity:
tail = self.list.pop_tail()
del self.cache[tail.key]
self.size -= 1
else:
node.value = value
self.list.move_to_head(node) |
class TokenStream:
def __init__(self, tokens):
self.tokens = tokens
def lookahead(self, index):
return self.tokens[index]
def peek(self):
return self.tokens[0]
def advance(self):
return self.tokens.pop(0)
def defer(self, token):
self.tokens.insert(0, token)
| class Tokenstream:
def __init__(self, tokens):
self.tokens = tokens
def lookahead(self, index):
return self.tokens[index]
def peek(self):
return self.tokens[0]
def advance(self):
return self.tokens.pop(0)
def defer(self, token):
self.tokens.insert(0, token) |
# Definitions for Machine.Status
MACHINE_STATUS_BROKEN = 0
MACHINE_STATUS_ALIVE = 1
# The "prebaked" downage categories
PREBAKED_DOWNAGE_CATEGORY_TEXTS = [
'Software Problem',
'Hardware Problem',
'Machine Problem'
]
# TODO: remove this and actually query locations after basic demo
# x should be within [0-3] and y should be within [0-8]
STUB_LOCATION_DICT = {
'1': {
'x': 1,
'y': 2
},
'2': {
'x': 0,
'y': 3
},
'3': {
'x': 0,
'y': 4
},
'4': {
'x': 0,
'y': 5
},
'5': {
'x': 1,
'y': 6
},
'6': {
'x': 3,
'y': 6
},
'7': {
'x': 3,
'y': 5
},
'8': {
'x': 3,
'y': 4
},
'9': {
'x': 3,
'y': 3
},
'10': {
'x': 3,
'y': 2
},
}
| machine_status_broken = 0
machine_status_alive = 1
prebaked_downage_category_texts = ['Software Problem', 'Hardware Problem', 'Machine Problem']
stub_location_dict = {'1': {'x': 1, 'y': 2}, '2': {'x': 0, 'y': 3}, '3': {'x': 0, 'y': 4}, '4': {'x': 0, 'y': 5}, '5': {'x': 1, 'y': 6}, '6': {'x': 3, 'y': 6}, '7': {'x': 3, 'y': 5}, '8': {'x': 3, 'y': 4}, '9': {'x': 3, 'y': 3}, '10': {'x': 3, 'y': 2}} |
#CODE ARENA PLAYER
#Problem Link : https://www.hackerearth.com/practice/algorithms/searching/ternary-search/practice-problems/algorithm/small-factorials/
f = [1] * 105
for i in range(2,105):
f[i] = f[i-1] * i
t = int(input())
while t:
t-=1
n = int(input())
print(f[n])
| f = [1] * 105
for i in range(2, 105):
f[i] = f[i - 1] * i
t = int(input())
while t:
t -= 1
n = int(input())
print(f[n]) |
"""
Programacion orientad a objetos!
- conceptos que lo soportan!
1 - astraccion de datos: proceso mediante el cual somos capaces de escoger la implementacion
de un objeto que contenga o modele las propiedades en el problema.
2 - encapsulamiento: ocultar la representacion y el estado de las propiedades de un objeto! solamente
se puede modificar a traves de las operaciones definidas en una clase
3 - herencia:
4 - polimorfismo
CLASE: conjunto de objetos que comparten una estructura, comportamiento y semantica comun.
OBJETO: es una instancia o valor correspondiente a una clase! representacion astrabta de un concepto
"""
#persona = "jhon", "angela"
#print(persona)
#--------------------------------
| """
Programacion orientad a objetos!
- conceptos que lo soportan!
1 - astraccion de datos: proceso mediante el cual somos capaces de escoger la implementacion
de un objeto que contenga o modele las propiedades en el problema.
2 - encapsulamiento: ocultar la representacion y el estado de las propiedades de un objeto! solamente
se puede modificar a traves de las operaciones definidas en una clase
3 - herencia:
4 - polimorfismo
CLASE: conjunto de objetos que comparten una estructura, comportamiento y semantica comun.
OBJETO: es una instancia o valor correspondiente a una clase! representacion astrabta de un concepto
""" |
class Receiver1:
# action
def step_left(self):
print("Receiver1 steps left")
def step_right(self):
print("Receiver1 steps right")
class Receiver2:
# action
def step_forward(self):
print("Receiver2 steps forward")
def step_backward(self):
print("Receiver2 steps backwards")
| class Receiver1:
def step_left(self):
print('Receiver1 steps left')
def step_right(self):
print('Receiver1 steps right')
class Receiver2:
def step_forward(self):
print('Receiver2 steps forward')
def step_backward(self):
print('Receiver2 steps backwards') |
numero = int(input('Digite um numero: '))
if numero % 5 == 0:
print('Buzz')
else:
print(numero)
| numero = int(input('Digite um numero: '))
if numero % 5 == 0:
print('Buzz')
else:
print(numero) |
class WinData():
def __init__(self, wins=0, games=0):
assert games >= wins
self.wins = wins
self.games = games
def win_pct(self):
return f'{self.wins/self.games:.3%}' if self.games > 0 else 'N/A'
def incre_wins(self):
self.wins += 1
def incre_games(self):
self.games += 1
| class Windata:
def __init__(self, wins=0, games=0):
assert games >= wins
self.wins = wins
self.games = games
def win_pct(self):
return f'{self.wins / self.games:.3%}' if self.games > 0 else 'N/A'
def incre_wins(self):
self.wins += 1
def incre_games(self):
self.games += 1 |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 17:32:07 2021
@author: JohnZhong
"""
#Mad libs generator 2021/10/12
print("Tell us something about you and we can create a story just for you!")
print("Let's begin!")
noun1 = input("Enter a pet: ")
noun2 = input("Enter a noun: ")
if noun1 in ["dog", "DOG", "Dog"]:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said wan wan wan" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
elif noun1 in ["cat", "CAT", "Cat"]:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said miao miao miao" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
elif noun1 in ["Duck", "DUCK", "Duck", "Goose", "GOOSE", "goose"]:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said quack quack quack" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
elif noun1 in ["Bird", "BIRD", "bird"]:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said chir chir chir" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
elif noun1 in ["pig", "PIG", "Pig"]:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said oink oink oink" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
else:
story = "Five little " + noun1 + "s" + " went out oneday" + "\nOver the " + noun2 + " " + "and far away" + "\nMother " + noun1 + " " + "said hmn hmn hmn" + "\nBut only four little " + noun1 + "s" + " came back"
print(story)
| """
Created on Tue Oct 12 17:32:07 2021
@author: JohnZhong
"""
print('Tell us something about you and we can create a story just for you!')
print("Let's begin!")
noun1 = input('Enter a pet: ')
noun2 = input('Enter a noun: ')
if noun1 in ['dog', 'DOG', 'Dog']:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said wan wan wan' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story)
elif noun1 in ['cat', 'CAT', 'Cat']:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said miao miao miao' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story)
elif noun1 in ['Duck', 'DUCK', 'Duck', 'Goose', 'GOOSE', 'goose']:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said quack quack quack' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story)
elif noun1 in ['Bird', 'BIRD', 'bird']:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said chir chir chir' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story)
elif noun1 in ['pig', 'PIG', 'Pig']:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said oink oink oink' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story)
else:
story = 'Five little ' + noun1 + 's' + ' went out oneday' + '\nOver the ' + noun2 + ' ' + 'and far away' + '\nMother ' + noun1 + ' ' + 'said hmn hmn hmn' + '\nBut only four little ' + noun1 + 's' + ' came back'
print(story) |
#https://aonecode.com/amazon-online-assessment-zombie-matrix
ZOMBIE = 1
HUMAN = 0
DIRECTIONS = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def humanDays(matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
M = len(matrix)
if (M == 0):
return -1
N = len(matrix[0])
if (N == 0):
return -1
days = -1
queue = []
for i in range(M):
for j in range(N):
if matrix[i][j] == ZOMBIE:
queue.append([i,j])
while len(queue) > 0:
numNodes = len(queue)
while (numNodes > 0):
[curI, curJ] = queue.pop(0)
numNodes -= 1
if (matrix[curI][curJ] != ZOMBIE):
continue
for [iDelta, jDelta] in DIRECTIONS:
nextI = curI + iDelta
nextJ = curJ + jDelta
if (nextI < 0 or nextJ < 0 or nextI >= M or nextJ >= N):
continue
if matrix[nextI][nextJ] == HUMAN:
queue.append([nextI, nextJ])
matrix[nextI][nextJ] = ZOMBIE
days += 1
return days
print(humanDays([
[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0]])) #2
print(humanDays([[0,0]])) #-1 | zombie = 1
human = 0
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def human_days(matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
m = len(matrix)
if M == 0:
return -1
n = len(matrix[0])
if N == 0:
return -1
days = -1
queue = []
for i in range(M):
for j in range(N):
if matrix[i][j] == ZOMBIE:
queue.append([i, j])
while len(queue) > 0:
num_nodes = len(queue)
while numNodes > 0:
[cur_i, cur_j] = queue.pop(0)
num_nodes -= 1
if matrix[curI][curJ] != ZOMBIE:
continue
for [i_delta, j_delta] in DIRECTIONS:
next_i = curI + iDelta
next_j = curJ + jDelta
if nextI < 0 or nextJ < 0 or nextI >= M or (nextJ >= N):
continue
if matrix[nextI][nextJ] == HUMAN:
queue.append([nextI, nextJ])
matrix[nextI][nextJ] = ZOMBIE
days += 1
return days
print(human_days([[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0]]))
print(human_days([[0, 0]])) |
def exibirLista(lista):
for item in lista:
print(item)
numeros = [1, 56, 5, 7, 29]
exibirLista(numeros)
print("Ordenados")
numeros.sort()
exibirLista(numeros)
| def exibir_lista(lista):
for item in lista:
print(item)
numeros = [1, 56, 5, 7, 29]
exibir_lista(numeros)
print('Ordenados')
numeros.sort()
exibir_lista(numeros) |
class Solution:
def fib(self, n: int) -> int:
fib_0, fib_1 = 0, 1
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
fib_0, fib_1 = fib_1, fib_0+fib_1
return fib_1
| class Solution:
def fib(self, n: int) -> int:
(fib_0, fib_1) = (0, 1)
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n + 1):
(fib_0, fib_1) = (fib_1, fib_0 + fib_1)
return fib_1 |
#
# PySNMP MIB module GRPSVCEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GRPSVCEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:53 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)
#
grpsvcExt, = mibBuilder.importSymbols("APENT-MIB", "grpsvcExt")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, MibIdentifier, ModuleIdentity, IpAddress, NotificationType, Integer32, ObjectIdentity, Bits, Counter64, Unsigned32, Counter32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "MibIdentifier", "ModuleIdentity", "IpAddress", "NotificationType", "Integer32", "ObjectIdentity", "Bits", "Counter64", "Unsigned32", "Counter32", "TimeTicks")
TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString")
apGrpsvcExtMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 2467, 1, 19, 1))
if mibBuilder.loadTexts: apGrpsvcExtMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts: apGrpsvcExtMib.setOrganization('ArrowPoint Communications Inc.')
if mibBuilder.loadTexts: apGrpsvcExtMib.setContactInfo(' Postal: ArrowPoint Communications Inc. 50 Nagog Park Acton, Massachusetts 01720 Tel: +1 978-206-3000 option 1 E-Mail: support@arrowpoint.com')
if mibBuilder.loadTexts: apGrpsvcExtMib.setDescription('The MIB module used to describe the ArrowPoint Communications content rule table')
apGrpsvcTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2), )
if mibBuilder.loadTexts: apGrpsvcTable.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcTable.setDescription('A list of group rule entries.')
apGrpsvcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1), ).setIndexNames((0, "GRPSVCEXT-MIB", "apGrpsvcGrpName"), (0, "GRPSVCEXT-MIB", "apGrpsvcSvcName"))
if mibBuilder.loadTexts: apGrpsvcEntry.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcEntry.setDescription('A group of information to uniquely identify a source grouping.')
apGrpsvcGrpName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcGrpName.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcGrpName.setDescription('The name of the content rule.')
apGrpsvcSvcName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcSvcName.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcSvcName.setDescription('The name of the service.')
apGrpsvcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpsvcStatus.setStatus('current')
if mibBuilder.loadTexts: apGrpsvcStatus.setDescription('Status entry for this row ')
apGrpDestSvcTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3), )
if mibBuilder.loadTexts: apGrpDestSvcTable.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcTable.setDescription('A list of group destination service entries.')
apGrpDestSvcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1), ).setIndexNames((0, "GRPSVCEXT-MIB", "apGrpDestSvcGrpName"), (0, "GRPSVCEXT-MIB", "apGrpDestSvcSvcName"))
if mibBuilder.loadTexts: apGrpDestSvcEntry.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcEntry.setDescription('A group of information to uniquely identify a source grouping by a destination service.')
apGrpDestSvcGrpName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcGrpName.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcGrpName.setDescription('The name of the source group destination service.')
apGrpDestSvcSvcName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcSvcName.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcSvcName.setDescription('The name of the destination service.')
apGrpDestSvcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apGrpDestSvcStatus.setStatus('current')
if mibBuilder.loadTexts: apGrpDestSvcStatus.setDescription('Status entry for this row ')
mibBuilder.exportSymbols("GRPSVCEXT-MIB", apGrpDestSvcTable=apGrpDestSvcTable, apGrpDestSvcStatus=apGrpDestSvcStatus, apGrpsvcEntry=apGrpsvcEntry, PYSNMP_MODULE_ID=apGrpsvcExtMib, apGrpsvcStatus=apGrpsvcStatus, apGrpDestSvcEntry=apGrpDestSvcEntry, apGrpDestSvcGrpName=apGrpDestSvcGrpName, apGrpDestSvcSvcName=apGrpDestSvcSvcName, apGrpsvcTable=apGrpsvcTable, apGrpsvcSvcName=apGrpsvcSvcName, apGrpsvcExtMib=apGrpsvcExtMib, apGrpsvcGrpName=apGrpsvcGrpName)
| (grpsvc_ext,) = mibBuilder.importSymbols('APENT-MIB', 'grpsvcExt')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(iso, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, mib_identifier, module_identity, ip_address, notification_type, integer32, object_identity, bits, counter64, unsigned32, counter32, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'MibIdentifier', 'ModuleIdentity', 'IpAddress', 'NotificationType', 'Integer32', 'ObjectIdentity', 'Bits', 'Counter64', 'Unsigned32', 'Counter32', 'TimeTicks')
(textual_convention, row_status, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'RowStatus', 'DisplayString')
ap_grpsvc_ext_mib = module_identity((1, 3, 6, 1, 4, 1, 2467, 1, 19, 1))
if mibBuilder.loadTexts:
apGrpsvcExtMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setOrganization('ArrowPoint Communications Inc.')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setContactInfo(' Postal: ArrowPoint Communications Inc. 50 Nagog Park Acton, Massachusetts 01720 Tel: +1 978-206-3000 option 1 E-Mail: support@arrowpoint.com')
if mibBuilder.loadTexts:
apGrpsvcExtMib.setDescription('The MIB module used to describe the ArrowPoint Communications content rule table')
ap_grpsvc_table = mib_table((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2))
if mibBuilder.loadTexts:
apGrpsvcTable.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcTable.setDescription('A list of group rule entries.')
ap_grpsvc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1)).setIndexNames((0, 'GRPSVCEXT-MIB', 'apGrpsvcGrpName'), (0, 'GRPSVCEXT-MIB', 'apGrpsvcSvcName'))
if mibBuilder.loadTexts:
apGrpsvcEntry.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcEntry.setDescription('A group of information to uniquely identify a source grouping.')
ap_grpsvc_grp_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcGrpName.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcGrpName.setDescription('The name of the content rule.')
ap_grpsvc_svc_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcSvcName.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcSvcName.setDescription('The name of the service.')
ap_grpsvc_status = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 2, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpsvcStatus.setStatus('current')
if mibBuilder.loadTexts:
apGrpsvcStatus.setDescription('Status entry for this row ')
ap_grp_dest_svc_table = mib_table((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3))
if mibBuilder.loadTexts:
apGrpDestSvcTable.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcTable.setDescription('A list of group destination service entries.')
ap_grp_dest_svc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1)).setIndexNames((0, 'GRPSVCEXT-MIB', 'apGrpDestSvcGrpName'), (0, 'GRPSVCEXT-MIB', 'apGrpDestSvcSvcName'))
if mibBuilder.loadTexts:
apGrpDestSvcEntry.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcEntry.setDescription('A group of information to uniquely identify a source grouping by a destination service.')
ap_grp_dest_svc_grp_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcGrpName.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcGrpName.setDescription('The name of the source group destination service.')
ap_grp_dest_svc_svc_name = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcSvcName.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcSvcName.setDescription('The name of the destination service.')
ap_grp_dest_svc_status = mib_table_column((1, 3, 6, 1, 4, 1, 2467, 1, 19, 3, 1, 3), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
apGrpDestSvcStatus.setStatus('current')
if mibBuilder.loadTexts:
apGrpDestSvcStatus.setDescription('Status entry for this row ')
mibBuilder.exportSymbols('GRPSVCEXT-MIB', apGrpDestSvcTable=apGrpDestSvcTable, apGrpDestSvcStatus=apGrpDestSvcStatus, apGrpsvcEntry=apGrpsvcEntry, PYSNMP_MODULE_ID=apGrpsvcExtMib, apGrpsvcStatus=apGrpsvcStatus, apGrpDestSvcEntry=apGrpDestSvcEntry, apGrpDestSvcGrpName=apGrpDestSvcGrpName, apGrpDestSvcSvcName=apGrpDestSvcSvcName, apGrpsvcTable=apGrpsvcTable, apGrpsvcSvcName=apGrpsvcSvcName, apGrpsvcExtMib=apGrpsvcExtMib, apGrpsvcGrpName=apGrpsvcGrpName) |
class TracableObject:
def __init__(self, object_id, centroid):
# store the object ID, then initialize a list of centroids
# using the current centroid
self.object_id = object_id
self.centroids = [centroid]
# initializa a boolean used to indicate if the object has
# already been counted or not
self.counted = False
| class Tracableobject:
def __init__(self, object_id, centroid):
self.object_id = object_id
self.centroids = [centroid]
self.counted = False |
# Pytathon if Stement
# if Statement
sandwich_order = "Ham Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
# if else Statement
tab = 29.95
if tab > 20:
print("This user has a tab over $20 that needs to be paid.")
else:
print("This user's tab is below $20 that does not require immediate payment.")
# elif Statement
sandwich_order = "Bacon Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
elif sandwich_order == "Cheese Roll":
print("Price: $1.80")
elif sandwich_order == "Bacon Roll":
print("Price: $2.10")
else:
print("Price: $2.00")
# Nested if Statement
sandwich_order = "Other Filled Roll"
if sandwich_order != "Other Filled Roll":
if sandwich_order == "Ham Roll":
print("Price: $1.75")
if sandwich_order == "Cheese Roll":
print("Price: $1.80")
elif sandwich_order == "Bacon Roll":
print("Price: $2.10")
else:
print("Price: $2.00") | sandwich_order = 'Ham Roll'
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
tab = 29.95
if tab > 20:
print('This user has a tab over $20 that needs to be paid.')
else:
print("This user's tab is below $20 that does not require immediate payment.")
sandwich_order = 'Bacon Roll'
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
elif sandwich_order == 'Cheese Roll':
print('Price: $1.80')
elif sandwich_order == 'Bacon Roll':
print('Price: $2.10')
else:
print('Price: $2.00')
sandwich_order = 'Other Filled Roll'
if sandwich_order != 'Other Filled Roll':
if sandwich_order == 'Ham Roll':
print('Price: $1.75')
if sandwich_order == 'Cheese Roll':
print('Price: $1.80')
elif sandwich_order == 'Bacon Roll':
print('Price: $2.10')
else:
print('Price: $2.00') |
""" MOTOR PARAMETERS """
b_step_per_mm = 80
d_step_per_mm = 80
p_step_per_mm = 80
step_len_us = 1 # NOT CURRENTLY USED
disp_move_mm = 104
disp_vel_mmps = 50
disp_acc_mmps2 = 100
pusher_move_mm = 68
pusher_vel_mmps = 520
pusher_acc_mmps2 = 12500
bin_vel_mmps = 400
bin_acc_mmps2 = 3500
bin_heights_load_mm = [2.5, 10.2, 17.9, 25.6, 33.3, 41.0, 48.7, 56.4] # bin 0 (bottom) to bin n (top)
bin_unload_shift_mm = 30
""" DISPENSE PARAMETERS """
dc_motor_spin_down_dwell_s = 0.4
min_time_between_dispenses_s = 0.3
servo_min_pwm = 25
servo_max_pwm = 160
dispense_timeout_ms = 600
current_detect_freq_hz = 500
current_detect_window_ms = 100
current_threshold_factor = 1500 # Multiply by 1000, must be int
servo_return_time_ms = 500
dispense_max_attempts = 3
""" SHUFFLING PARAMETERS """
cards_per_shuffle_loop = 20 # Too many and it may fail to dispense
shuffle_loops = 4
max_cards_per_bin = 10
planned_shuffle_timeout = 150 # If this many cards were trashed and deck still isn't in order, give up
""" CAMERA PARAMETERS """
# Cropped region of card window
H_MIN = 75
H_MAX = 700
W_MIN = 550
W_MAX = 775
IMAGE_RESOLUTION = (1920,1080)
IMAGE_ROTATION_DEGS = 0
""" DETECTION PARAMETERS """
RANK_DIFF_MAX = 2000
SUIT_DIFF_MAX = 1000
RANK_WIDTH = 70
RANK_HEIGHT = 125
SUIT_WIDTH = 70
SUIT_HEIGHT = 100
MAX_CONTOURS_TO_CHECK = 5
USE_CAL_IMAGE = True
BW_THRESH = 15
""" FEATHER COMM PARAMETERS """
# Chars used for setting parameters on feather. All vars here must be int
Feather_Parameter_Chars = {
'a': step_len_us,
'b': servo_min_pwm,
'c': servo_max_pwm,
'd': dispense_timeout_ms,
'e': current_detect_freq_hz,
'f': current_detect_window_ms,
'g': current_threshold_factor,
'h': servo_return_time_ms,
'i': dispense_max_attempts
}
""" DEBUG PARAMS """
DEBUG_MODE = False
| """ MOTOR PARAMETERS """
b_step_per_mm = 80
d_step_per_mm = 80
p_step_per_mm = 80
step_len_us = 1
disp_move_mm = 104
disp_vel_mmps = 50
disp_acc_mmps2 = 100
pusher_move_mm = 68
pusher_vel_mmps = 520
pusher_acc_mmps2 = 12500
bin_vel_mmps = 400
bin_acc_mmps2 = 3500
bin_heights_load_mm = [2.5, 10.2, 17.9, 25.6, 33.3, 41.0, 48.7, 56.4]
bin_unload_shift_mm = 30
' DISPENSE PARAMETERS '
dc_motor_spin_down_dwell_s = 0.4
min_time_between_dispenses_s = 0.3
servo_min_pwm = 25
servo_max_pwm = 160
dispense_timeout_ms = 600
current_detect_freq_hz = 500
current_detect_window_ms = 100
current_threshold_factor = 1500
servo_return_time_ms = 500
dispense_max_attempts = 3
' SHUFFLING PARAMETERS '
cards_per_shuffle_loop = 20
shuffle_loops = 4
max_cards_per_bin = 10
planned_shuffle_timeout = 150
' CAMERA PARAMETERS '
h_min = 75
h_max = 700
w_min = 550
w_max = 775
image_resolution = (1920, 1080)
image_rotation_degs = 0
' DETECTION PARAMETERS '
rank_diff_max = 2000
suit_diff_max = 1000
rank_width = 70
rank_height = 125
suit_width = 70
suit_height = 100
max_contours_to_check = 5
use_cal_image = True
bw_thresh = 15
' FEATHER COMM PARAMETERS '
feather__parameter__chars = {'a': step_len_us, 'b': servo_min_pwm, 'c': servo_max_pwm, 'd': dispense_timeout_ms, 'e': current_detect_freq_hz, 'f': current_detect_window_ms, 'g': current_threshold_factor, 'h': servo_return_time_ms, 'i': dispense_max_attempts}
' DEBUG PARAMS '
debug_mode = False |
# Leetcode 198. House Robber
#
# Link: https://leetcode.com/problems/house-robber/
# Difficulty: Medium
# Solution using DP
# Complexity:
# O(N) time | where N represent the number of homes
# O(1) space
class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0, 0
for n in nums:
rob1, rob2 = rob2, max(rob1 + n, rob2)
return rob2
| class Solution:
def rob(self, nums: List[int]) -> int:
(rob1, rob2) = (0, 0)
for n in nums:
(rob1, rob2) = (rob2, max(rob1 + n, rob2))
return rob2 |
# %% [6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)
class Solution:
def convert(self, s: str, numRows: int) -> str:
lst = [[] for _ in range(numRows)]
for cc in use(s, numRows):
for i, c in enumerate(cc):
lst[i].append(c)
return "".join("".join(i) for i in lst)
def use(s, numRows):
p, n = 0, len(s)
while p < n:
yield [s[p + i] if p + i < n else "" for i in range(numRows)]
p += numRows
for i in range(1, numRows - 1):
if p < n:
yield [""] * (numRows - i - 1) + [s[p]] + [""] * i
p += 1
| class Solution:
def convert(self, s: str, numRows: int) -> str:
lst = [[] for _ in range(numRows)]
for cc in use(s, numRows):
for (i, c) in enumerate(cc):
lst[i].append(c)
return ''.join((''.join(i) for i in lst))
def use(s, numRows):
(p, n) = (0, len(s))
while p < n:
yield [s[p + i] if p + i < n else '' for i in range(numRows)]
p += numRows
for i in range(1, numRows - 1):
if p < n:
yield ([''] * (numRows - i - 1) + [s[p]] + [''] * i)
p += 1 |
"""
Response to
https://www.reddit.com/r/Python/comments/fwq1f3/procedurally_generated_object_attribute/
"""
class Products(object):
"""Sale unit object for GoodPaws' products.
"""
def __init__(self):
self.df = get_sheets(scopes, sheet_id, range_name, creds_path)
self.df = self.df.set_index('order_id')
dct_sku_dtype = {sku:'int64' for sku in lst_sku}
self.df = self.df.astype(dct_sku_dtype)
##Walee
walee = [
't001_walee_S', 't001_walee_M', 't001_walee_L', 't001_walee_XL', 't001_walee_XXL'
]
blues = [
't001_walee_S', 't001_walee_M', 't001_walee_L', 't001_walee_XL' , 't001_walee_XXL'
]
inventory = {
'walee': walee,
'blues' : blues
}
def total(self, inventory_index):
"""Total of a particular item.
Arguments:
inventory_index - a key into the inventory index (e.g. 'walee' or 'blues' for now.
Sample usage:
self.walee_total = self.total('walee')
self.blues_total = self.total('blues')
"""
sum = 0
for key in self.inventory[inventory_index]:
sum += np.sum(self.df.loc[:, key].values)
return sum
| """
Response to
https://www.reddit.com/r/Python/comments/fwq1f3/procedurally_generated_object_attribute/
"""
class Products(object):
"""Sale unit object for GoodPaws' products.
"""
def __init__(self):
self.df = get_sheets(scopes, sheet_id, range_name, creds_path)
self.df = self.df.set_index('order_id')
dct_sku_dtype = {sku: 'int64' for sku in lst_sku}
self.df = self.df.astype(dct_sku_dtype)
walee = ['t001_walee_S', 't001_walee_M', 't001_walee_L', 't001_walee_XL', 't001_walee_XXL']
blues = ['t001_walee_S', 't001_walee_M', 't001_walee_L', 't001_walee_XL', 't001_walee_XXL']
inventory = {'walee': walee, 'blues': blues}
def total(self, inventory_index):
"""Total of a particular item.
Arguments:
inventory_index - a key into the inventory index (e.g. 'walee' or 'blues' for now.
Sample usage:
self.walee_total = self.total('walee')
self.blues_total = self.total('blues')
"""
sum = 0
for key in self.inventory[inventory_index]:
sum += np.sum(self.df.loc[:, key].values)
return sum |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
def get_tensor_shape(tensor):
shape = []
for dim in tensor.type.tensor_type.shape.dim:
shape.append(dim.dim_value)
if len(shape) == 4:
shape = [shape[0], shape[2], shape[3], shape[1]]
return shape
| def get_tensor_shape(tensor):
shape = []
for dim in tensor.type.tensor_type.shape.dim:
shape.append(dim.dim_value)
if len(shape) == 4:
shape = [shape[0], shape[2], shape[3], shape[1]]
return shape |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "/app/home/skins/default/style.css")
| def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, '/app/home/skins/default/style.css') |
class PluginNotInitialisableException(BaseException):
pass
class PluginNotActivatableException(BaseException):
pass
class PluginNotDeactivatableException(BaseException):
pass
class PluginAttributeMissingException(BaseException):
pass
class PluginRegistrationException(BaseException):
pass
| class Pluginnotinitialisableexception(BaseException):
pass
class Pluginnotactivatableexception(BaseException):
pass
class Pluginnotdeactivatableexception(BaseException):
pass
class Pluginattributemissingexception(BaseException):
pass
class Pluginregistrationexception(BaseException):
pass |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv".split(';') if "/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv" != "" else []
PROJECT_CATKIN_DEPENDS = "cv_bridge;roscpp;rospy;sensor_msgs;std_msgs;std_srvs;nav_msgs;geometry_msgs;visualization_msgs;image_transport;tf;tf_conversions;tf2_ros;eigen_conversions;laser_geometry;pcl_conversions;pcl_ros;nodelet;dynamic_reconfigure;message_filters;class_loader;rosgraph_msgs;stereo_msgs;move_base_msgs;image_geometry;costmap_2d;rviz".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1".split(';') if "-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1" != "" else []
PROJECT_NAME = "rtabmap_ros"
PROJECT_SPACE_DIR = "/home/xtark/ros_ws/install"
PROJECT_VERSION = "0.19.3"
| catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv'.split(';') if '/home/xtark/ros_ws/install/include;/home/xtark/ros_ws/devel/lib/rtabmap-0.19/../../include/rtabmap-0.19;/opt/ros/kinetic/include/opencv-3.3.1-dev;/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv' != '' else []
project_catkin_depends = 'cv_bridge;roscpp;rospy;sensor_msgs;std_msgs;std_srvs;nav_msgs;geometry_msgs;visualization_msgs;image_transport;tf;tf_conversions;tf2_ros;eigen_conversions;laser_geometry;pcl_conversions;pcl_ros;nodelet;dynamic_reconfigure;message_filters;class_loader;rosgraph_msgs;stereo_msgs;move_base_msgs;image_geometry;costmap_2d;rviz'.replace(';', ' ')
pkg_config_libraries_with_prefix = '-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1'.split(';') if '-lrtabmap_ros;/home/xtark/ros_ws/devel/lib/librtabmap_core.so;/home/xtark/ros_ws/devel/lib/librtabmap_utilite.so;/home/xtark/ros_ws/devel/lib/librtabmap_gui.so;/usr/lib/arm-linux-gnueabihf/libz.so;/usr/local/lib/libg2o_core.so;/usr/local/lib/libg2o_types_slam2d.so;/usr/local/lib/libg2o_types_slam3d.so;/usr/local/lib/libg2o_types_sba.so;/usr/local/lib/libg2o_stuff.so;/usr/local/lib/libg2o_solver_csparse.so;/usr/local/lib/libg2o_csparse_extension.so;/usr/lib/arm-linux-gnueabihf/libcxsparse.so;/usr/local/lib/libg2o_solver_cholmod.so;/usr/lib/arm-linux-gnueabihf/libcholmod.so;/usr/lib/libOpenNI2.so;/opt/ros/kinetic/lib/liboctomap.so;/opt/ros/kinetic/lib/liboctomath.so;/opt/ros/kinetic/lib/libopencv_calib3d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_core3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dnn3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_features2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_flann3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_highgui3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgcodecs3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_imgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ml3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_objdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_photo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_shape3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stitching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_superres3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_video3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videoio3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_videostab3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_viz3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_aruco3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bgsegm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_bioinspired3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ccalib3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_cvv3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_datasets3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_dpm3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_face3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_fuzzy3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_hdf3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_img_hash3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_line_descriptor3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_optflow3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_phase_unwrapping3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_plot3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_reg3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_rgbd3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_saliency3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_stereo3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_structured_light3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_surface_matching3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_text3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_tracking3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xfeatures2d3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_ximgproc3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xobjdetect3.so.3.3.1;/opt/ros/kinetic/lib/libopencv_xphoto3.so.3.3.1' != '' else []
project_name = 'rtabmap_ros'
project_space_dir = '/home/xtark/ros_ws/install'
project_version = '0.19.3' |
"""Trait Browser App.
This app handles displaying, searching, and browsing through information on
source traits and harmonized traits.
"""
default_app_config = 'trait_browser.apps.TraitBrowserConfig'
| """Trait Browser App.
This app handles displaying, searching, and browsing through information on
source traits and harmonized traits.
"""
default_app_config = 'trait_browser.apps.TraitBrowserConfig' |
# ------------------------------------
# CODE BOOLA 2015 PYTHON WORKSHOP
# Mike Wu, Jonathan Chang, Kevin Tan
# Puzzle Challenges Number 7
# ------------------------------------
# INSTRUCTIONS:
# Using only 1 line, write a function
# to reverse a list. The function is
# passed a list as an argument.
# EXAMPLE:
# reverse_lst([1, 2, 3]) => [3, 2, 1]
# reverse_lst([]) => []
# reverse_lst([1]) => [1]
# reverse_lst([1, 1, 1, 2, 1, 1]) => [1, 1, 2, 1, 1, 1]
# HINT:
# lists have a reverse function!
# If lst is a list, then lst.reverse() should
# do the trick! After calling lst.reverse()
# [you don't need to set it to a variable],
# you can just return lst!
def reverse_lst(lst):
pass # 1 line
return lst # Don't remove this! You want to return the lst.
| def reverse_lst(lst):
pass
return lst |
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Top-level presubmit script for appengine/components/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gclient.
"""
def CommonChecks(input_api, output_api):
files_to_skip = list(input_api.DEFAULT_FILES_TO_SKIP) + [
r'.*_pb2\.py$',
]
disabled_warnings = [
# Pylint fails to recognize lazy module loading in components.auth.config,
# no local disables work, so had to kill it globally.
'cyclic-import',
'relative-import',
]
return input_api.canned_checks.RunPylint(
input_api,
output_api,
files_to_skip=files_to_skip,
disabled_warnings=disabled_warnings,
pylintrc=input_api.os_path.join(input_api.PresubmitLocalPath(), '../../',
'pylintrc'))
# pylint: disable=unused-argument
def CheckChangeOnUpload(input_api, output_api):
return []
def CheckChangeOnCommit(input_api, output_api):
return CommonChecks(input_api, output_api)
| """Top-level presubmit script for appengine/components/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gclient.
"""
def common_checks(input_api, output_api):
files_to_skip = list(input_api.DEFAULT_FILES_TO_SKIP) + ['.*_pb2\\.py$']
disabled_warnings = ['cyclic-import', 'relative-import']
return input_api.canned_checks.RunPylint(input_api, output_api, files_to_skip=files_to_skip, disabled_warnings=disabled_warnings, pylintrc=input_api.os_path.join(input_api.PresubmitLocalPath(), '../../', 'pylintrc'))
def check_change_on_upload(input_api, output_api):
return []
def check_change_on_commit(input_api, output_api):
return common_checks(input_api, output_api) |
__all__ = ['UserScript']
class UserScript:
def __init__(self, id=None, activations=None):
self.functions = []
self._function_by_name = {}
self.id = id
self.activations = [] if activations is None else activations
def __len__(self):
return len(self.functions)
def __getitem__(self, index):
return self.functions[index]
def register(self, func):
self.functions.append(func)
self._function_by_name[func.__name__] = func
def exec(self, index=None, name=None, *args, **kwargs):
if index is not None:
return self.functions[index](*args, **kwargs)
elif name is not None:
return self._function_by_name[name](*args, **kwargs)
raise ValueError("index and name are both None")
| __all__ = ['UserScript']
class Userscript:
def __init__(self, id=None, activations=None):
self.functions = []
self._function_by_name = {}
self.id = id
self.activations = [] if activations is None else activations
def __len__(self):
return len(self.functions)
def __getitem__(self, index):
return self.functions[index]
def register(self, func):
self.functions.append(func)
self._function_by_name[func.__name__] = func
def exec(self, index=None, name=None, *args, **kwargs):
if index is not None:
return self.functions[index](*args, **kwargs)
elif name is not None:
return self._function_by_name[name](*args, **kwargs)
raise value_error('index and name are both None') |
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n=len(nums);
c=[0]*n
ans=list()
for i in range(n):
c[nums[i]-1]+=1
for i in range(n):
if(c[i]==2):
ans.append(i+1)
return ans;
| class Solution:
def find_duplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
c = [0] * n
ans = list()
for i in range(n):
c[nums[i] - 1] += 1
for i in range(n):
if c[i] == 2:
ans.append(i + 1)
return ans |
def is_isogram(s):
if isinstance(s, str):
s = [i for i in s.lower() if i.isalpha()]
return len(s) == len(set(s))
else:
raise TypeError("This doesn't look like a string.") | def is_isogram(s):
if isinstance(s, str):
s = [i for i in s.lower() if i.isalpha()]
return len(s) == len(set(s))
else:
raise type_error("This doesn't look like a string.") |
def zero_initializer(n):
assert isinstance(n, int) and n > 0
return [0] * n
def zeros_initializer(n, n_args):
if n_args == 1:
return zero_initializer(n)
return map(zero_initializer, [n] * n_args) | def zero_initializer(n):
assert isinstance(n, int) and n > 0
return [0] * n
def zeros_initializer(n, n_args):
if n_args == 1:
return zero_initializer(n)
return map(zero_initializer, [n] * n_args) |
## Gerador de tabuada.
canGenerateTabuada = False
#print("Tabuada de: ")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <= 10
while not canGenerateTabuada:
print("Digite um valor de 1 a 10.")
vInput = int(input("Tabuada de: "))
canGenerateTabuada = vInput >= 1 and vInput <= 10
pass
## Gerando tabuada
for i in range(10):
print(str(vInput) + " x " + str((i+1)) + " = " + str(vInput*(i+1)))
pass
| can_generate_tabuada = False
v_input = int(input('Tabuada de: '))
can_generate_tabuada = vInput >= 1 and vInput <= 10
while not canGenerateTabuada:
print('Digite um valor de 1 a 10.')
v_input = int(input('Tabuada de: '))
can_generate_tabuada = vInput >= 1 and vInput <= 10
pass
for i in range(10):
print(str(vInput) + ' x ' + str(i + 1) + ' = ' + str(vInput * (i + 1)))
pass |
# Space: O(n)
# Time: O(n!)
class Solution:
def combine(self, n: int, k: int):
if k > n: return []
data = [i for i in range(1, n + 1)] # list all numbers
status = [False for _ in range(len(data))] # identify if current item has been used or not
def dfs(data, index, temp_res, res, k):
if len(temp_res) == k:
res.append(temp_res[:])
return
for i in range(index, len(data)):
if status[i]: continue # if current number has been used, then pass to next one
status[i] = True
temp_res.append(data[i])
dfs(data, i, temp_res, res, k)
temp_res.pop()
status[i] = False
return res
return dfs(data, 0, [], [], k)
| class Solution:
def combine(self, n: int, k: int):
if k > n:
return []
data = [i for i in range(1, n + 1)]
status = [False for _ in range(len(data))]
def dfs(data, index, temp_res, res, k):
if len(temp_res) == k:
res.append(temp_res[:])
return
for i in range(index, len(data)):
if status[i]:
continue
status[i] = True
temp_res.append(data[i])
dfs(data, i, temp_res, res, k)
temp_res.pop()
status[i] = False
return res
return dfs(data, 0, [], [], k) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Approach 1
# O(N) - Space
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
hashmap = set()
node = head
while node:
if node is None:
return None
elif node in hashmap:
return node
else:
hashmap.add(node)
node = node.next
def detect(head):
if head is None:
return
hashmap = set()
curr = head
while curr:
if curr in hashmap:
return curr
hashmap.add(curr)
return None
def detect(head):
if head is None:
return
slow = head
fast = head
flag = None
while fast and fast.next :
slow = slow.next
fast = fast.next.next
if slow == fast:
flag = fast
break
if flag:
return
iter1 = head
iter2 = flag
while iter1 and iter2:
if iter1 is iter2:
return iter1
iter1 = iter1.next
iter2 = iter2.next
# Approach 2
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
def helper(head):
if head is None or head.next is None:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return slow
fast = helper(head)
if fast is None:
return None
slow = head
while fast is not slow:
fast = fast.next
slow = slow.next
return slow
| class Solution:
def detect_cycle(self, head: ListNode) -> ListNode:
hashmap = set()
node = head
while node:
if node is None:
return None
elif node in hashmap:
return node
else:
hashmap.add(node)
node = node.next
def detect(head):
if head is None:
return
hashmap = set()
curr = head
while curr:
if curr in hashmap:
return curr
hashmap.add(curr)
return None
def detect(head):
if head is None:
return
slow = head
fast = head
flag = None
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
flag = fast
break
if flag:
return
iter1 = head
iter2 = flag
while iter1 and iter2:
if iter1 is iter2:
return iter1
iter1 = iter1.next
iter2 = iter2.next
class Solution:
def detect_cycle(self, head: ListNode) -> ListNode:
def helper(head):
if head is None or head.next is None:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return slow
fast = helper(head)
if fast is None:
return None
slow = head
while fast is not slow:
fast = fast.next
slow = slow.next
return slow |
"""
# Zdoom Textures Writer (zdtw)
"""
__version__ = "1.0"
__author__ = "GianptDev"
__date__ = '14-2-2022' # Revisioned.
# will not include default properties in PatchData and TextureData, output will become smaller.
compact_mode = True
# ----------------------------------------
class PatchData():
"""
Patch information for a patch element.
Is used inside TextureData, but it can work indipendently.
"""
# ----------------------------------------
# List of style types.
STYLE_TYPE = [
"add",
"copy",
"copyalpha",
"copynewalpha",
"modulate",
"overlay",
"reversesubtract",
"subtract",
"translucent",
]
# all possible rotates, i really whish the engine could use an actual rotation.
ROTATE_TYPE = [
0,
90,
180,
270,
]
# blend mode definition in Textures is bullshit, just use one of these in blend_mode
BLEND_NONE = 0
BLEND_COLOR = 1
BLEND_TINT = 2
BLEND_TRANSLATION = 3
# ----------------------------------------
# all the properties of a single patch.
# to change the blend to use, set blend_mode to one of the BLEND_ values.
def __init__(self, path = "", positionX = 0, positionY = 0,
flipX = False, flipY = False, use_offsets = False,
style = "copy", rotate = 0, alpha = 1.0,
blend_mode = BLEND_NONE, blend = (255,255,255), tint = 255, translation = ""
) -> None:
self.path = str(path)
self.positionX = int(positionX)
self.positionY = int(positionY)
self.flipX = bool(flipX)
self.flipY = bool(flipY)
self.use_offsets = bool(use_offsets)
self.style = str(style)
self.rotate = int(rotate)
self.alpha = float(alpha)
self.blend_mode = int(blend_mode)
self.blend = blend # r,g,b
self.tint = int(tint)
self.translation = str(translation)
def __repr__(self) -> str:
return "PatchData[ \"" + str(self.path) + "\" ]"
# ----------------------------------------
# write the patch block and return it as a string, on problems it will print some messages but will continue whit execution.
# newline -> specifcy a string to use for new lines.
# tab -> specify a string to use as tabulation.
def write(self, newline = "\n", tab = "\t") -> str:
result = ""
props = ""
# ----------------------------------------
if (not self.style.lower() in self.STYLE_TYPE):
print(
"Inside the patch \" " + str(self.path) + " \":\n" +
" - The style \" " + str(self.style) + " \" is unknow.\n" +
" Possible values are: " + str(self.STYLE_TYPE)
)
return ""
if (not int(self.rotate) in self.ROTATE_TYPE):
print(
"Inside the patch \" " + str(self.path) + " \":\n" +
" - The rotate \" " + str(self.rotate) + " \" is unknow.\n" +
" Possible values are: " + str(self.ROTATE_TYPE)
)
return ""
if ((self.blend_mode < self.BLEND_NONE) or (self.blend_mode > self.BLEND_TRANSLATION)):
print(
"Inside the patch \" " + str(self.path) + " \":\n" +
" - The blend mode \" " + str(self.blend_mode) + " \" is unknow, please see BLEND_ values."
)
# ----------------------------------------
# start of patch definition
result += "patch \"" + str(self.path) + "\", " + str(int(self.positionX)) + ", " + str(int(self.positionY))
# flags
if (self.use_offsets == True):
props += tab + "UseOffsets" + newline
if (self.flipX == True):
props += tab + "flipX" + newline
if (self.flipY == True):
props += tab + "flipY" + newline
# properties
if ((compact_mode == False) or (compact_mode == True) and (self.style != "copy")):
props += tab + "style " + str(self.style) + newline
if ((compact_mode == False) or (compact_mode == True) and (self.rotate != 0)):
props += tab + "rotate " + str(self.rotate) + newline
if ((compact_mode == False) or (compact_mode == True) and (self.alpha != 1.0)):
props += tab + "alpha " + str(self.alpha) + newline
# color blend and tint work the same way.
if ((self.blend_mode == self.BLEND_COLOR) or (self.blend_mode == self.BLEND_TINT)):
props += tab + "blend "
# check if is a iterable type
if ((type(self.blend) is tuple) or (type(self.blend) is list)):
if (len(self.blend) < 3):
print(
"Inside the patch \" " + str(self.path) + " \":\n" +
" - The blend property require at least 3 (r,g,b) values."
)
# if is a iterable type add all his value (even if only 3 are required...)
for b in self.blend:
props += str(b) + ", "
props = props[:-2] # remove last ", "
# if is a string it can be used as a hex color, nothing will check if is valid.
elif (type(self.blend) is str):
# add the quotes and the # if missing (slade automatically add it but gzdoom does not required it, so i'm not sure....)
props += "\"" + ("#" if (self.blend[0] != "#") else "") + str(self.blend).upper() + "\""
# add the tint argoument
if (self.blend_mode == self.BLEND_TINT):
props += ", " + str(self.tint)
props += newline
# color translation is just a string tk add
elif (self.blend_mode == self.BLEND_TRANSLATION):
props += tab + "blend \"" + str(self.translation) + "\"" + newline
# add property shit only if property do actually exist.
if (props != ""):
result += newline + "{" + newline + props + "}" + newline
# ----------------------------------------
return result
# ----------------------------------------
# to do
#def read(self,data) -> bool:
#return False
# ----------------------------------------
# ----------------------------------------
class TextureData():
"""
This class contain all the information about a texture definition.
The result of write can be directly used as valid textures data.
"""
# ----------------------------------------
# list of know textures types.
TEXTURE_TYPE = [
"sprite",
"texture",
"flat",
"graphic",
"walltexture",
]
# ----------------------------------------
def __init__(self, name = "", type = "texture", sizeX = 64, sizeY = 128,
optional = False, world_panning = False, no_decals = False, null_texture = False,
offsetX = 0, offsetY = 0, scaleX = 1.0, scaleY = 1.0
) -> None:
self.name = str(name)
self.type = str(type)
self.sizeX = int(sizeX)
self.sizeY = int(sizeY)
self.offsetX = int(offsetX)
self.offsetY = int(offsetY)
self.scaleX = float(scaleX)
self.scaleY = float(scaleY)
self.optional = bool(optional)
self.world_panning = bool(world_panning)
self.no_decals = bool(no_decals)
self.null_texture = bool(null_texture)
self.patches = [] # This is the list of all patches inside this texture block
def __repr__(self) -> str:
return "<TextureData[ \"" + str(self.name) + "\" ]>"
# ----------------------------------------
# add a patch in the list of patches, but only if is a valid PatchData
def add_patch(self, patch) -> None:
if (not type(patch) is PatchData):
print(
"Inside the texture \" " + str(self.name) + " \":\n" +
" - Non-PatchData cannot be added, it may result in errors"
)
return
self.patches.append(patch)
# return all patches that uses the specific path name.
def get_patches(self, path) -> list:
patches = self.patches
result = []
for p in patches:
if (p.path == path):
result.append(p)
return result
# ----------------------------------------
# write the texture block and return it as a string, the result can be directly used for a textures file.
# newline -> specify a string to use for new lines.
# tab -> specify a string to use as tabulation.
def write(self, newline = "\n", tab = "\t") -> str:
result = ""
# ----------------------------------------
if (not self.type.lower() in self.TEXTURE_TYPE):
print(
"Inside the texture \" " + str(self.name) + " \":\n" +
" - The type \" " + str(type) + " \" is unknow.\n" +
" Possible values are: " + str(self.TEXTURE_TYPE)
)
return ""
if (len(self.patches) <= 0):
print(
"Inside the texture \" " + str(self.name) + " \":\n" +
" - No patch are used, the texture will be empty."
)
# ----------------------------------------
# set the texture type
result += self.type
# add the optional flag first
if (self.optional == True):
result += " optional"
# start of texture definition
result += " \"" + str(self.name) + "\", " + str(int(self.sizeX)) + ", " + str(int(self.sizeY)) + newline + "{" + newline
# flags
if (self.world_panning == True):
result += tab + "WorldPanning" + newline
if (self.no_decals == True):
result += tab + "NoDecals" + newline
if (self.null_texture == True):
result += tab + "NullTexture" + newline
# properties
if ((compact_mode == False) or (compact_mode == True) and ((self.offsetX != 0) or (self.offsetY != 0))):
result += tab + "offset " + str(int(self.offsetX)) + ", " + str(int(self.offsetY)) + newline
if ((compact_mode == False) or (compact_mode == True) and (self.scaleX != 1.0)):
result += tab + "Xscale " + str(float(self.scaleX)) + newline
if ((compact_mode == False) or (compact_mode == True) and (self.scaleY != 1.0)):
result += tab + "Yscale " + str(float(self.scaleY)) + newline
# add each patch to the result and make sure to tabulate.
for p in self.patches:
b = p.write(newline,tab)
# fix extra newline
if (b[-1] == newline):
b = b[:-1]
# do not execute work if the string is empty.
if (b == ""):
continue
else:
result += tab + b.replace(newline, newline + tab) + newline
# end of patch definition
result += "}" + newline
return result
# ----------------------------------------
# ----------------------------------------
# write a list of TextureData into a single string as a valid textures lump, does not write any file.
# invalid data is ignored and will show a message.
def write_textures(blocks, newline = "\n", tab = "\t") -> str:
result = ""
invalid_count = 0 # count invalid data
clone_found = False # true if a texture is defined twince or more
clone_count = {} # count every cloned definition
# ----------------------------------------
# loop to every data in the input
for b in blocks:
# check if data is valid
if (not type(b) is TextureData):
invalid_count += 1
continue
# check if a clone exist
if (b.name in clone_count):
clone_found = True
clone_count[b.name] += 1
else:
clone_count[b.name] = 1
# just write the block and merge whit the result
result += b.write(newline,tab) + newline
# ----------------------------------------
# display the amount of invalid data
if (invalid_count > 0):
print(
"While writing the lump of size " + str(len(blocks)) + ":\n" +
" - The input contain " + str(invalid_count) + " invalid data,\n" +
" maybe non-TextureData or None are inside."
)
# display the amount of clones
if (clone_found == True):
print(
"While writing the lump of size " + str(len(blocks)) + ":\n" +
" - Some textures are defined more than once:"
)
# display each clone by the name and amount of clones
for c in clone_count:
if (clone_count[c] <= 1):
continue
print(
" - - \"" + str(c) + "\" is defined " + str(clone_count[c]) + " times."
)
# ----------------------------------------
return result
# parse an actual textures definition into TextureData and PatchData instances, will not load a file.
# the function work, but does not handle all errors yet, will receive changes in future versions.
# load_textures, does nothing.
# load_patches, if enabled will load patches data, if disabled patches are not loaded (resulting in empty textures).
def read_textures(parse, endline = "\n", tab = "\t", load_textures = True, load_patches = True) -> list:
result = []
# ----------------------------------------
# parse from string become an array.
parse = parse.split(endline)
# remove garbage
for d in range(len(parse)):
parse[d] = parse[d].replace(tab,"")
parse[d] = parse[d].replace(",","")
# clear useless stuff
for d in range(len(parse)):
if (d >= len(parse)):
break
if (parse[d] == ""):
del parse[d]
elif (parse[d] == "}"):
parse[d] = None
elif (parse[d] == "{"):
del parse[d]
# start to instance stuff
current_patch = None
current_texture = None
for d in range(len(parse)):
info = parse[d]
if (info == None):
if (current_patch != None):
current_patch = None
continue
if (current_texture != None):
current_texture = None
continue
# error to add
print("what the? } used twince?")
return []
# this is all the info when need to read the textures lump!
info = info.split(" ")
# stuff to load a texture
if (info[0] in TextureData.TEXTURE_TYPE):
if (current_texture != None):
print("what the? texture defined twince?")
return []
if (len(info) < 4):
print("what the? not enough texture informations?")
return []
is_optional = False
if (info[1].lower() == "optional"):
is_optional = True
del info[1]
# remove quotes if they exist.
if (info[1][0] == "\""):
info[1] = info[1][1:]
if (info[1][-1] == "\""):
info[1] = info[1][:-1]
current_texture = TextureData()
current_texture.type = info[0]
current_texture.name = info[1]
current_texture.sizeX = float(info[2])
current_texture.sizeY = float(info[3])
current_texture.optional = is_optional
result.append(current_texture)
# stuff to load a patch
if ((load_patches == True) and (info[0].lower() == "patch")):
if (current_texture == None):
print("what the? patch connected to nothing?")
return []
if (current_patch != None):
print("what the? patch defined twince?")
return []
if (len(info) < 4):
print("what the? not enough patch informations?")
return []
# remove quotes if they exist.
if (info[1][0] == "\""):
info[1] = info[1][1:]
if (info[1][-1] == "\""):
info[1] = info[1][:-1]
current_patch = PatchData()
current_patch.type = info[0]
current_patch.path = info[1]
current_patch.positionX = float(info[2])
current_patch.positionY = float(info[3])
current_texture.add_patch(current_patch)
if (current_patch != None):
p = info[0].lower()
# properties
if (len(info) >= 2):
if (p == "style"):
current_patch.style = info[1]
elif (p == "rotate"):
current_patch.rotate = int(info[1])
elif (p == "alpha"):
current_patch.alpha = float(info[1])
elif (p == "blend"):
# todo: blend mode is detected like shit
if (len(info) >= 4):
current_patch.blend = (int(info[1]),int(info[2]),int(info[3]))
if (len(info) >= 5):
current_patch.tint = int(info[4])
current_patch.blend_mode = current_patch.BLEND_TINT
else:
current_patch.blend_mode = current_patch.BLEND_COLOR
elif (len(info) >= 2):
current_patch.blend = info[1]
current_patch.translation = info[1] # yeah...
if (len(info) >= 3):
current_patch.tint = int(info[2])
current_patch.blend_mode = current_patch.BLEND_TINT
else:
current_patch.blend_mode = current_patch.BLEND_COLOR
else:
print("what the? wrong blend data?")
# flags
else:
if (p == "flipx"):
current_patch.flipX = True
elif (p == "flipy"):
current_patch.flipY = True
elif (p == "useoffsets"):
current_patch.use_offsets = True
if (current_texture != None):
p = info[0].lower()
# properties
if (len(info) >= 2):
if (p == "offset"):
current_texture.offsetX = int(info[1])
current_texture.offsetY = int(info[2])
elif (p == "xscale"):
current_texture.scaleX = float(info[1])
elif (p == "yscale"):
current_texture.scaleY = float(info[1])
# flags
else:
if (p == "worldpanning"):
current_texture.world_panning = True
elif (p == "nodecals"):
current_texture.no_decals = True
elif (p == "nulltexture"):
current_texture.null_texture = True
# ----------------------------------------
# return a beautiful amount of classes!
return result
# ----------------------------------------
# Will convert a string into a valid sprite name, will add the frame character and angle by using a simple number.
# index is the range between A and Z, a greater number will wrap around and override the name.
# angle is the rotate of the sprite, 0 is no rotate and 1 to 8 are all rotate keys.
def to_sprite_name(name, index = 0, angle = 0) -> None:
result = ""
# get only 4 characters for the name, it will be used to wrap around.
wrap = [ord(name[0]) - 65,ord(name[1]) - 65,ord(name[2]) - 65,ord(name[3]) - 65]
base = 25 # from A to Z
# convert to base 26
while(True):
# if the index is already under the limit, then no more shit is required.
if (index >= base):
index -= base
# increase the next character every time the number is greater than the limit.
for i in range(len(wrap)):
i = len(wrap) - (i + 1)
if (wrap[i] >= base):
wrap[i] = 0
else:
wrap[i] += 1
break
else:
break
# build the new name.
name = ""
for i in wrap:
name += chr(65 + i)
frame = chr(65 + index)
# add the frame string to the name.
result += name + frame
# add the rotate index.
if (angle == 0):
result += "0"
elif (angle == 1):
result += "1"
elif (angle == 2):
result += frame + "8"
elif (angle == 3):
result += frame + "7"
elif (angle == 4):
result += frame + "6"
elif (angle == 5):
result += "5"
elif (angle == 6):
result += frame + "4"
elif (angle == 7):
result += frame + "3"
elif (angle == 8):
result += frame + "2"
return result
# ----------------------------------------
# Exampes
if __name__ == '__main__':
# load test
#ims = read_textures(open("test.txt","r").read())
#print(write_textures(ims))
#input()
print("Zdoom Textures Parser examples:\n")
empty = TextureData(type = "sprite",sizeX = 32, sizeY = 16)
empty.name = to_sprite_name("PIST",0)
wall = TextureData("WALLBRICK",type = "walltexture", optional = True, scaleY = 1.2)
p = PatchData("textures/brick.png")
wall.add_patch(p)
more_patches = TextureData("WALLSTONE","walltexture",sizeX = 64, sizeY = 64)
for i in [
PatchData("textures/stone1.png", flipX = True, rotate = 90),
PatchData("textures/stone2.png",positionX = 32, blend_mode = PatchData.BLEND_TINT, blend = "ff0000"),
]: more_patches.add_patch(i)
print("Empty texture example:")
print(empty.write())
print("Texture whit a single patch:")
print(wall.write())
print("Texture whit more patches:")
print(more_patches.write())
# spam test
#for i in range(26 ** 4):
# c = to_sprite_name("AAAA",i)
# print(c)
# write test
#print(write_textures([empty]))
#open("test.txt","w").write(write_textures([more_patches,wall]))
| """
# Zdoom Textures Writer (zdtw)
"""
__version__ = '1.0'
__author__ = 'GianptDev'
__date__ = '14-2-2022'
compact_mode = True
class Patchdata:
"""
Patch information for a patch element.
Is used inside TextureData, but it can work indipendently.
"""
style_type = ['add', 'copy', 'copyalpha', 'copynewalpha', 'modulate', 'overlay', 'reversesubtract', 'subtract', 'translucent']
rotate_type = [0, 90, 180, 270]
blend_none = 0
blend_color = 1
blend_tint = 2
blend_translation = 3
def __init__(self, path='', positionX=0, positionY=0, flipX=False, flipY=False, use_offsets=False, style='copy', rotate=0, alpha=1.0, blend_mode=BLEND_NONE, blend=(255, 255, 255), tint=255, translation='') -> None:
self.path = str(path)
self.positionX = int(positionX)
self.positionY = int(positionY)
self.flipX = bool(flipX)
self.flipY = bool(flipY)
self.use_offsets = bool(use_offsets)
self.style = str(style)
self.rotate = int(rotate)
self.alpha = float(alpha)
self.blend_mode = int(blend_mode)
self.blend = blend
self.tint = int(tint)
self.translation = str(translation)
def __repr__(self) -> str:
return 'PatchData[ "' + str(self.path) + '" ]'
def write(self, newline='\n', tab='\t') -> str:
result = ''
props = ''
if not self.style.lower() in self.STYLE_TYPE:
print('Inside the patch " ' + str(self.path) + ' ":\n' + ' - The style " ' + str(self.style) + ' " is unknow.\n' + ' Possible values are: ' + str(self.STYLE_TYPE))
return ''
if not int(self.rotate) in self.ROTATE_TYPE:
print('Inside the patch " ' + str(self.path) + ' ":\n' + ' - The rotate " ' + str(self.rotate) + ' " is unknow.\n' + ' Possible values are: ' + str(self.ROTATE_TYPE))
return ''
if self.blend_mode < self.BLEND_NONE or self.blend_mode > self.BLEND_TRANSLATION:
print('Inside the patch " ' + str(self.path) + ' ":\n' + ' - The blend mode " ' + str(self.blend_mode) + ' " is unknow, please see BLEND_ values.')
result += 'patch "' + str(self.path) + '", ' + str(int(self.positionX)) + ', ' + str(int(self.positionY))
if self.use_offsets == True:
props += tab + 'UseOffsets' + newline
if self.flipX == True:
props += tab + 'flipX' + newline
if self.flipY == True:
props += tab + 'flipY' + newline
if compact_mode == False or (compact_mode == True and self.style != 'copy'):
props += tab + 'style ' + str(self.style) + newline
if compact_mode == False or (compact_mode == True and self.rotate != 0):
props += tab + 'rotate ' + str(self.rotate) + newline
if compact_mode == False or (compact_mode == True and self.alpha != 1.0):
props += tab + 'alpha ' + str(self.alpha) + newline
if self.blend_mode == self.BLEND_COLOR or self.blend_mode == self.BLEND_TINT:
props += tab + 'blend '
if type(self.blend) is tuple or type(self.blend) is list:
if len(self.blend) < 3:
print('Inside the patch " ' + str(self.path) + ' ":\n' + ' - The blend property require at least 3 (r,g,b) values.')
for b in self.blend:
props += str(b) + ', '
props = props[:-2]
elif type(self.blend) is str:
props += '"' + ('#' if self.blend[0] != '#' else '') + str(self.blend).upper() + '"'
if self.blend_mode == self.BLEND_TINT:
props += ', ' + str(self.tint)
props += newline
elif self.blend_mode == self.BLEND_TRANSLATION:
props += tab + 'blend "' + str(self.translation) + '"' + newline
if props != '':
result += newline + '{' + newline + props + '}' + newline
return result
class Texturedata:
"""
This class contain all the information about a texture definition.
The result of write can be directly used as valid textures data.
"""
texture_type = ['sprite', 'texture', 'flat', 'graphic', 'walltexture']
def __init__(self, name='', type='texture', sizeX=64, sizeY=128, optional=False, world_panning=False, no_decals=False, null_texture=False, offsetX=0, offsetY=0, scaleX=1.0, scaleY=1.0) -> None:
self.name = str(name)
self.type = str(type)
self.sizeX = int(sizeX)
self.sizeY = int(sizeY)
self.offsetX = int(offsetX)
self.offsetY = int(offsetY)
self.scaleX = float(scaleX)
self.scaleY = float(scaleY)
self.optional = bool(optional)
self.world_panning = bool(world_panning)
self.no_decals = bool(no_decals)
self.null_texture = bool(null_texture)
self.patches = []
def __repr__(self) -> str:
return '<TextureData[ "' + str(self.name) + '" ]>'
def add_patch(self, patch) -> None:
if not type(patch) is PatchData:
print('Inside the texture " ' + str(self.name) + ' ":\n' + ' - Non-PatchData cannot be added, it may result in errors')
return
self.patches.append(patch)
def get_patches(self, path) -> list:
patches = self.patches
result = []
for p in patches:
if p.path == path:
result.append(p)
return result
def write(self, newline='\n', tab='\t') -> str:
result = ''
if not self.type.lower() in self.TEXTURE_TYPE:
print('Inside the texture " ' + str(self.name) + ' ":\n' + ' - The type " ' + str(type) + ' " is unknow.\n' + ' Possible values are: ' + str(self.TEXTURE_TYPE))
return ''
if len(self.patches) <= 0:
print('Inside the texture " ' + str(self.name) + ' ":\n' + ' - No patch are used, the texture will be empty.')
result += self.type
if self.optional == True:
result += ' optional'
result += ' "' + str(self.name) + '", ' + str(int(self.sizeX)) + ', ' + str(int(self.sizeY)) + newline + '{' + newline
if self.world_panning == True:
result += tab + 'WorldPanning' + newline
if self.no_decals == True:
result += tab + 'NoDecals' + newline
if self.null_texture == True:
result += tab + 'NullTexture' + newline
if compact_mode == False or (compact_mode == True and (self.offsetX != 0 or self.offsetY != 0)):
result += tab + 'offset ' + str(int(self.offsetX)) + ', ' + str(int(self.offsetY)) + newline
if compact_mode == False or (compact_mode == True and self.scaleX != 1.0):
result += tab + 'Xscale ' + str(float(self.scaleX)) + newline
if compact_mode == False or (compact_mode == True and self.scaleY != 1.0):
result += tab + 'Yscale ' + str(float(self.scaleY)) + newline
for p in self.patches:
b = p.write(newline, tab)
if b[-1] == newline:
b = b[:-1]
if b == '':
continue
else:
result += tab + b.replace(newline, newline + tab) + newline
result += '}' + newline
return result
def write_textures(blocks, newline='\n', tab='\t') -> str:
result = ''
invalid_count = 0
clone_found = False
clone_count = {}
for b in blocks:
if not type(b) is TextureData:
invalid_count += 1
continue
if b.name in clone_count:
clone_found = True
clone_count[b.name] += 1
else:
clone_count[b.name] = 1
result += b.write(newline, tab) + newline
if invalid_count > 0:
print('While writing the lump of size ' + str(len(blocks)) + ':\n' + ' - The input contain ' + str(invalid_count) + ' invalid data,\n' + ' maybe non-TextureData or None are inside.')
if clone_found == True:
print('While writing the lump of size ' + str(len(blocks)) + ':\n' + ' - Some textures are defined more than once:')
for c in clone_count:
if clone_count[c] <= 1:
continue
print(' - - "' + str(c) + '" is defined ' + str(clone_count[c]) + ' times.')
return result
def read_textures(parse, endline='\n', tab='\t', load_textures=True, load_patches=True) -> list:
result = []
parse = parse.split(endline)
for d in range(len(parse)):
parse[d] = parse[d].replace(tab, '')
parse[d] = parse[d].replace(',', '')
for d in range(len(parse)):
if d >= len(parse):
break
if parse[d] == '':
del parse[d]
elif parse[d] == '}':
parse[d] = None
elif parse[d] == '{':
del parse[d]
current_patch = None
current_texture = None
for d in range(len(parse)):
info = parse[d]
if info == None:
if current_patch != None:
current_patch = None
continue
if current_texture != None:
current_texture = None
continue
print('what the? } used twince?')
return []
info = info.split(' ')
if info[0] in TextureData.TEXTURE_TYPE:
if current_texture != None:
print('what the? texture defined twince?')
return []
if len(info) < 4:
print('what the? not enough texture informations?')
return []
is_optional = False
if info[1].lower() == 'optional':
is_optional = True
del info[1]
if info[1][0] == '"':
info[1] = info[1][1:]
if info[1][-1] == '"':
info[1] = info[1][:-1]
current_texture = texture_data()
current_texture.type = info[0]
current_texture.name = info[1]
current_texture.sizeX = float(info[2])
current_texture.sizeY = float(info[3])
current_texture.optional = is_optional
result.append(current_texture)
if load_patches == True and info[0].lower() == 'patch':
if current_texture == None:
print('what the? patch connected to nothing?')
return []
if current_patch != None:
print('what the? patch defined twince?')
return []
if len(info) < 4:
print('what the? not enough patch informations?')
return []
if info[1][0] == '"':
info[1] = info[1][1:]
if info[1][-1] == '"':
info[1] = info[1][:-1]
current_patch = patch_data()
current_patch.type = info[0]
current_patch.path = info[1]
current_patch.positionX = float(info[2])
current_patch.positionY = float(info[3])
current_texture.add_patch(current_patch)
if current_patch != None:
p = info[0].lower()
if len(info) >= 2:
if p == 'style':
current_patch.style = info[1]
elif p == 'rotate':
current_patch.rotate = int(info[1])
elif p == 'alpha':
current_patch.alpha = float(info[1])
elif p == 'blend':
if len(info) >= 4:
current_patch.blend = (int(info[1]), int(info[2]), int(info[3]))
if len(info) >= 5:
current_patch.tint = int(info[4])
current_patch.blend_mode = current_patch.BLEND_TINT
else:
current_patch.blend_mode = current_patch.BLEND_COLOR
elif len(info) >= 2:
current_patch.blend = info[1]
current_patch.translation = info[1]
if len(info) >= 3:
current_patch.tint = int(info[2])
current_patch.blend_mode = current_patch.BLEND_TINT
else:
current_patch.blend_mode = current_patch.BLEND_COLOR
else:
print('what the? wrong blend data?')
elif p == 'flipx':
current_patch.flipX = True
elif p == 'flipy':
current_patch.flipY = True
elif p == 'useoffsets':
current_patch.use_offsets = True
if current_texture != None:
p = info[0].lower()
if len(info) >= 2:
if p == 'offset':
current_texture.offsetX = int(info[1])
current_texture.offsetY = int(info[2])
elif p == 'xscale':
current_texture.scaleX = float(info[1])
elif p == 'yscale':
current_texture.scaleY = float(info[1])
elif p == 'worldpanning':
current_texture.world_panning = True
elif p == 'nodecals':
current_texture.no_decals = True
elif p == 'nulltexture':
current_texture.null_texture = True
return result
def to_sprite_name(name, index=0, angle=0) -> None:
result = ''
wrap = [ord(name[0]) - 65, ord(name[1]) - 65, ord(name[2]) - 65, ord(name[3]) - 65]
base = 25
while True:
if index >= base:
index -= base
for i in range(len(wrap)):
i = len(wrap) - (i + 1)
if wrap[i] >= base:
wrap[i] = 0
else:
wrap[i] += 1
break
else:
break
name = ''
for i in wrap:
name += chr(65 + i)
frame = chr(65 + index)
result += name + frame
if angle == 0:
result += '0'
elif angle == 1:
result += '1'
elif angle == 2:
result += frame + '8'
elif angle == 3:
result += frame + '7'
elif angle == 4:
result += frame + '6'
elif angle == 5:
result += '5'
elif angle == 6:
result += frame + '4'
elif angle == 7:
result += frame + '3'
elif angle == 8:
result += frame + '2'
return result
if __name__ == '__main__':
print('Zdoom Textures Parser examples:\n')
empty = texture_data(type='sprite', sizeX=32, sizeY=16)
empty.name = to_sprite_name('PIST', 0)
wall = texture_data('WALLBRICK', type='walltexture', optional=True, scaleY=1.2)
p = patch_data('textures/brick.png')
wall.add_patch(p)
more_patches = texture_data('WALLSTONE', 'walltexture', sizeX=64, sizeY=64)
for i in [patch_data('textures/stone1.png', flipX=True, rotate=90), patch_data('textures/stone2.png', positionX=32, blend_mode=PatchData.BLEND_TINT, blend='ff0000')]:
more_patches.add_patch(i)
print('Empty texture example:')
print(empty.write())
print('Texture whit a single patch:')
print(wall.write())
print('Texture whit more patches:')
print(more_patches.write()) |
#!/Users/philip/opt/anaconda3/bin/python
a = [ "aa", "bb", "cc" ]
print ( "".join(a) )
| a = ['aa', 'bb', 'cc']
print(''.join(a)) |
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
total_a = sum(A)
total_b = sum(B)
set_b = set(B)
for candy in A:
swap_item = candy + (total_b - total_a) / 2
if swap_item in set_b:
return [candy, candy + (total_b - total_a) / 2] | class Solution:
def fair_candy_swap(self, A: List[int], B: List[int]) -> List[int]:
total_a = sum(A)
total_b = sum(B)
set_b = set(B)
for candy in A:
swap_item = candy + (total_b - total_a) / 2
if swap_item in set_b:
return [candy, candy + (total_b - total_a) / 2] |
# Shortest Unsorted Continuous Subarray
"""
Find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return length of the shortest subarray.
Example 1: nums = [2,6,4,8,10,9,15]
o/p:- 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Example 2: nums = [1,2,3,4]
o/p:- 0
"""
def findUnsortedSubarray(nums):
res=[]
ans=[]
final=[]
for i in nums:
res.append(i)
res.sort()
for i in range(0,len(nums)):
if nums[i]!=res[i]:
ans.append(i)
if len(ans)==0:
return 0
else:
for i in range(ans[0],ans[len(ans)-1]+1):
final.append(nums[i])
return len(final)
nums=[]
n=int(input("Enter the no. of elements: "))
print("Enter the elements of the array one by one: ")
for i in range(0,n):
ele=int(input())
nums.append(ele)
answer=findUnsortedSubarray(nums)
print("The length of the shortest subarray:",answer) | """
Find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
Return length of the shortest subarray.
Example 1: nums = [2,6,4,8,10,9,15]
o/p:- 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Example 2: nums = [1,2,3,4]
o/p:- 0
"""
def find_unsorted_subarray(nums):
res = []
ans = []
final = []
for i in nums:
res.append(i)
res.sort()
for i in range(0, len(nums)):
if nums[i] != res[i]:
ans.append(i)
if len(ans) == 0:
return 0
else:
for i in range(ans[0], ans[len(ans) - 1] + 1):
final.append(nums[i])
return len(final)
nums = []
n = int(input('Enter the no. of elements: '))
print('Enter the elements of the array one by one: ')
for i in range(0, n):
ele = int(input())
nums.append(ele)
answer = find_unsorted_subarray(nums)
print('The length of the shortest subarray:', answer) |
class ARMAModel():
def __init__(self, gamma=0.15, beta=0.8):
self.gamma_param = gamma
self.beta_param = beta
def predict(self, x):
x_simplified = x[0, 0, :] # convert to a simple array, ignoring batch size
return (self.beta_param * x_simplified[-1]) + \
(self.gamma_param * x_simplified[-2]) + \
((1 - (self.gamma_param + self.beta_param)) * x_simplified[-3])
| class Armamodel:
def __init__(self, gamma=0.15, beta=0.8):
self.gamma_param = gamma
self.beta_param = beta
def predict(self, x):
x_simplified = x[0, 0, :]
return self.beta_param * x_simplified[-1] + self.gamma_param * x_simplified[-2] + (1 - (self.gamma_param + self.beta_param)) * x_simplified[-3] |
"""Debug flag."""
ON: bool = False
| """Debug flag."""
on: bool = False |
class InterpretationParser:
def __init__(self, socketio):
self.interpreter = None
self.entity_intent_map = {'item_attribute_query': {'attribute': None, 'entity': None},
'batch_restriction_query': {'attribute': None, 'class': None},
'batch_restriction_query_numerical': {'class': None, 'attribute': None,
'comparison': None, 'numerical_value': None},
'batch_restriction_query_numerical_and_attribute': {'attribute': [],
'class': None, 'comparison': None,
'numerical_value': None}
}
self.socketio = socketio
def parse_question_interpretation(self, question):
result = self.interpreter.parse(question)
# get the key components and their types out
# get the intent of the question
intent = result['intent']['name']
entities = result['entities']
result = self.fill_in_components(intent, entities)
return result
def fill_in_components(self, intent, entities):
obj = self.entity_intent_map[intent]
for entity in entities:
entity_type = entity['entity']
term = entity['value'].lower()
slot = obj[entity_type]
if type(slot) is list:
obj[entity_type].append(term)
# more than one term should present ...
else:
obj[entity_type] = term
return {'type': intent, 'entities': obj}
| class Interpretationparser:
def __init__(self, socketio):
self.interpreter = None
self.entity_intent_map = {'item_attribute_query': {'attribute': None, 'entity': None}, 'batch_restriction_query': {'attribute': None, 'class': None}, 'batch_restriction_query_numerical': {'class': None, 'attribute': None, 'comparison': None, 'numerical_value': None}, 'batch_restriction_query_numerical_and_attribute': {'attribute': [], 'class': None, 'comparison': None, 'numerical_value': None}}
self.socketio = socketio
def parse_question_interpretation(self, question):
result = self.interpreter.parse(question)
intent = result['intent']['name']
entities = result['entities']
result = self.fill_in_components(intent, entities)
return result
def fill_in_components(self, intent, entities):
obj = self.entity_intent_map[intent]
for entity in entities:
entity_type = entity['entity']
term = entity['value'].lower()
slot = obj[entity_type]
if type(slot) is list:
obj[entity_type].append(term)
else:
obj[entity_type] = term
return {'type': intent, 'entities': obj} |
list_of_users=[] # it stores the list of usernames in form of strings
def fun(l1):
global list_of_users
list_of_users=l1
def fun2():
return list_of_users | list_of_users = []
def fun(l1):
global list_of_users
list_of_users = l1
def fun2():
return list_of_users |
# Scrapy settings for gettaiex project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'gettaiex'
BOT_VERSION = '1.0'
SPIDER_MODULES = ['gettaiex.spiders']
NEWSPIDER_MODULE = 'gettaiex.spiders'
USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION)
| bot_name = 'gettaiex'
bot_version = '1.0'
spider_modules = ['gettaiex.spiders']
newspider_module = 'gettaiex.spiders'
user_agent = '%s/%s' % (BOT_NAME, BOT_VERSION) |
penctutions = ".,;?()[]{}&_-@%<>:!~1234567890/*+$#^/"
newt = "" #text without penctutions
List2 = []
text = str("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.")
for char in text:
if char not in penctutions:
newt += char
for char in newt:
y = ord(char)
x = 128 - y
List2.append(x)
print(List2[::-1])
| penctutions = '.,;?()[]{}&_-@%<>:!~1234567890/*+$#^/'
newt = ''
list2 = []
text = str('Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of de Finibus Bonorum et Malorum (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, Lorem ipsum dolor sit amet.., comes from a line in section 1.10.32.The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.')
for char in text:
if char not in penctutions:
newt += char
for char in newt:
y = ord(char)
x = 128 - y
List2.append(x)
print(List2[::-1]) |
"""
Demonstration of defining functions.
"""
def sayhello():
"""
Prints "hello".
"""
print("hello")
# Call the function
sayhello()
def double(value):
"""
Return twice the input value
"""
return value * 2
# Call the function and assign the result to a variable
result = double(6)
print(result)
def product(value1, value2, value3):
"""
Returns the product of the three input values.
"""
prod = value1 * value2
prod = prod * value3
return prod
# Call the function and assign the result to a variable
result = product(7, 13.3, -1.2)
print(result)
"""
Demonstration of parameters and variables within functions.
"""
def fahrenheit_to_celsius(fahrenheit):
"""
Return celsius temperature that corresponds to fahrenheit
temperature input.
"""
offset = 32
multiplier = 5 / 9
celsius = (fahrenheit - offset) * multiplier
print("inside function:", fahrenheit, offset, multiplier, celsius)
return celsius
temperature = 95
converted = fahrenheit_to_celsius(temperature)
print("Fahrenheit temp:", temperature)
print("Celsius temp:", converted)
# Variables defined inside a function are local to that function
fahrenheit = 27
offset = 2
multiplier = 19
celsius = 77
print("before:", fahrenheit, offset, multiplier, celsius)
newtemp = fahrenheit_to_celsius(32)
print("after:", fahrenheit, offset, multiplier, celsius)
print("result:", newtemp)
| """
Demonstration of defining functions.
"""
def sayhello():
"""
Prints "hello".
"""
print('hello')
sayhello()
def double(value):
"""
Return twice the input value
"""
return value * 2
result = double(6)
print(result)
def product(value1, value2, value3):
"""
Returns the product of the three input values.
"""
prod = value1 * value2
prod = prod * value3
return prod
result = product(7, 13.3, -1.2)
print(result)
'\nDemonstration of parameters and variables within functions.\n'
def fahrenheit_to_celsius(fahrenheit):
"""
Return celsius temperature that corresponds to fahrenheit
temperature input.
"""
offset = 32
multiplier = 5 / 9
celsius = (fahrenheit - offset) * multiplier
print('inside function:', fahrenheit, offset, multiplier, celsius)
return celsius
temperature = 95
converted = fahrenheit_to_celsius(temperature)
print('Fahrenheit temp:', temperature)
print('Celsius temp:', converted)
fahrenheit = 27
offset = 2
multiplier = 19
celsius = 77
print('before:', fahrenheit, offset, multiplier, celsius)
newtemp = fahrenheit_to_celsius(32)
print('after:', fahrenheit, offset, multiplier, celsius)
print('result:', newtemp) |
_base_ = './rr_yolov3_d53_416_coco.py'
# model settings
model = dict(
type='SingleStageDetector',
pretrained=None,
backbone=dict(type='RRTinyYolov4Backbone'),
neck=None,
bbox_head=dict(
type='RRTinyYolov4Head',
num_classes=80,
in_channels=[512, 256],
out_channels=[256, 128],
anchor_generator=dict(
type='YOLOAnchorGenerator',
base_sizes=[[(81, 82), (135, 169), (344, 319)],
[(23, 27), (37, 58), (81, 82)]],
strides=[32, 16]),
bbox_coder=dict(type='YOLOBBoxCoder'),
featmap_strides=[32, 16],
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0,
reduction='sum'),
loss_conf=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0,
reduction='sum'),
loss_xy=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=2.0,
reduction='sum'),
loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum')))
| _base_ = './rr_yolov3_d53_416_coco.py'
model = dict(type='SingleStageDetector', pretrained=None, backbone=dict(type='RRTinyYolov4Backbone'), neck=None, bbox_head=dict(type='RRTinyYolov4Head', num_classes=80, in_channels=[512, 256], out_channels=[256, 128], anchor_generator=dict(type='YOLOAnchorGenerator', base_sizes=[[(81, 82), (135, 169), (344, 319)], [(23, 27), (37, 58), (81, 82)]], strides=[32, 16]), bbox_coder=dict(type='YOLOBBoxCoder'), featmap_strides=[32, 16], loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0, reduction='sum'), loss_conf=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0, reduction='sum'), loss_xy=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=2.0, reduction='sum'), loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum'))) |
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for each_letter in secretWord:
if each_letter not in lettersGuessed:
return False
return True
print(isWordGuessed('apple', ['e', 'a', 'l', 'i', 'k', 'p', 'r', 's']))
| def is_word_guessed(secretWord, lettersGuessed):
"""
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
"""
for each_letter in secretWord:
if each_letter not in lettersGuessed:
return False
return True
print(is_word_guessed('apple', ['e', 'a', 'l', 'i', 'k', 'p', 'r', 's'])) |
def extractNadenadeshitai(item):
"""
Nadenadeshitai
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title'].startswith('Command Chapter '):
return buildReleaseMessageWithType(item, 'Command Sousa Skill de, Isekai no Subete wo Kage kara Shihaishitemita', vol, chp, frag=frag, postfix=postfix)
return False
| def extract_nadenadeshitai(item):
"""
Nadenadeshitai
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title'].startswith('Command Chapter '):
return build_release_message_with_type(item, 'Command Sousa Skill de, Isekai no Subete wo Kage kara Shihaishitemita', vol, chp, frag=frag, postfix=postfix)
return False |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
if root is not None:
output.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return output
if __name__ == "__main__":
solution = Solution()
node = TreeNode(2)
node.left = TreeNode(1)
node.right = TreeNode(3)
node.right.left = TreeNode(4)
print(solution.levelOrder(node))
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
(stack, output) = ([root], [])
while stack:
root = stack.pop()
if root is not None:
output.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return output
if __name__ == '__main__':
solution = solution()
node = tree_node(2)
node.left = tree_node(1)
node.right = tree_node(3)
node.right.left = tree_node(4)
print(solution.levelOrder(node)) |
#!/usr/bin/env python3
'''
This is a
multiline
comment
'''
print("This is some dummy code") # Hi # This shouldn't count as another comment '''neither should this'''
| """
This is a
multiline
comment
"""
print('This is some dummy code') |
"""
FastAPI uses data models (pydantic) to
validate data types
For each resource (data), describe how it
should look and behave at various stage
""" | """
FastAPI uses data models (pydantic) to
validate data types
For each resource (data), describe how it
should look and behave at various stage
""" |
def sock_merchant(n, ar):
stock = set()
pairs = 0
for socks in ar:
if socks in stock:
stock.remove(socks)
pairs += 1
else:
stock.add(socks)
return pairs
n = int(input("Number of socks: "))
ar = list(
map(int, input("Different socks (spaces in between): ").rstrip().split()))
print("sock_merchant():", sock_merchant(n, ar))
"""
Number of socks: 10
Different socks (spaces in between): 1 2 2 2 1 2 2 2 1 2
sock_merchant(): 4
""" | def sock_merchant(n, ar):
stock = set()
pairs = 0
for socks in ar:
if socks in stock:
stock.remove(socks)
pairs += 1
else:
stock.add(socks)
return pairs
n = int(input('Number of socks: '))
ar = list(map(int, input('Different socks (spaces in between): ').rstrip().split()))
print('sock_merchant():', sock_merchant(n, ar))
'\nNumber of socks: 10\nDifferent socks (spaces in between): 1 2 2 2 1 2 2 2 1 2\nsock_merchant(): 4\n' |
class Solution:
def halveArray(self, nums: List[int]) -> int:
halfSum = sum(nums) / 2
ans = 0
runningSum = 0.0
maxHeap = [-num for num in nums]
heapq.heapify(maxHeap)
while runningSum < halfSum:
maxValue = -heapq.heappop(maxHeap) / 2
runningSum += maxValue
heapq.heappush(maxHeap, -maxValue)
ans += 1
return ans
| class Solution:
def halve_array(self, nums: List[int]) -> int:
half_sum = sum(nums) / 2
ans = 0
running_sum = 0.0
max_heap = [-num for num in nums]
heapq.heapify(maxHeap)
while runningSum < halfSum:
max_value = -heapq.heappop(maxHeap) / 2
running_sum += maxValue
heapq.heappush(maxHeap, -maxValue)
ans += 1
return ans |
# TODO BenM/assessor_of_assessor/pick this up later; it isn't required for the
# initial working solution
class TestPyxnatSession:
def __init__(self, project, subject, session, scans, assessors):
self.scans_ = scans
self.assessors_ = assessors
self.project = project
self.subject = subject
self.session = session
def scans(self):
return self.scans_
def assessors(self):
return self.assessors_
class TestAttrs:
def __init__(self, properties):
pass
class TestPyxnatScan:
def __init__(self, project, subject, session, scanjson):
self.scanjson = scanjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/scans/{}'
self._uri = uristr.format(project,
subject,
session,
self.scanjson['label'])
def id(self):
return self.scanjson['id']
def label(self):
return self.scanjson['label']
class TestPyxnatAssessor:
def __init__(self, project, subject, session, asrjson):
self.asrjson = asrjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/assessors/{}'
self._uri = uristr.format(project,
subject,
session,
self.asrjson['label'])
def id(self):
return self.asrjson['id']
def label(self):
return self.asrjson['label']
def inputs(self):
return self.asrjson['xsitype'] + '/' + self.asrjson['inputs']
| class Testpyxnatsession:
def __init__(self, project, subject, session, scans, assessors):
self.scans_ = scans
self.assessors_ = assessors
self.project = project
self.subject = subject
self.session = session
def scans(self):
return self.scans_
def assessors(self):
return self.assessors_
class Testattrs:
def __init__(self, properties):
pass
class Testpyxnatscan:
def __init__(self, project, subject, session, scanjson):
self.scanjson = scanjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/scans/{}'
self._uri = uristr.format(project, subject, session, self.scanjson['label'])
def id(self):
return self.scanjson['id']
def label(self):
return self.scanjson['label']
class Testpyxnatassessor:
def __init__(self, project, subject, session, asrjson):
self.asrjson = asrjson
self.project = project
self.subject = subject
self.session = session
uristr = '/data/project/{}/subjects/{}/experiments/{}/assessors/{}'
self._uri = uristr.format(project, subject, session, self.asrjson['label'])
def id(self):
return self.asrjson['id']
def label(self):
return self.asrjson['label']
def inputs(self):
return self.asrjson['xsitype'] + '/' + self.asrjson['inputs'] |
def Main():
"""
:return:
"""
a = 1
c = 3
a += c
b = 10
b -= a
d = 2
b *= d
b /= c
b %= 3
f = b + 20
# f |= 34 # this doesn't curretly work
return f # expect 21
| def main():
"""
:return:
"""
a = 1
c = 3
a += c
b = 10
b -= a
d = 2
b *= d
b /= c
b %= 3
f = b + 20
return f |
def operation(first,second,operator):
if(operator == 1):
return first + second
if(operator == 2):
return first - second
if(operator == 3):
return first / second
if(operator == 4):
return first * second
return "invalid selection or input"
print("Welcome to calculator.py, please enter 2 values to perform an operation")
firstValue = float(input("What is the first value? \n"))
secondValue = float(input("What is the second value? \n"))
print("Available operations")
print("1. add - add two numbers")
print("2. sub - subtract two numbers")
print("3. div - divide two numbers")
print("4. mul - multiply two numbers")
operator = int(input("What operation would you like to perform? \n"))
print(operation(firstValue,secondValue,operator))
| def operation(first, second, operator):
if operator == 1:
return first + second
if operator == 2:
return first - second
if operator == 3:
return first / second
if operator == 4:
return first * second
return 'invalid selection or input'
print('Welcome to calculator.py, please enter 2 values to perform an operation')
first_value = float(input('What is the first value? \n'))
second_value = float(input('What is the second value? \n'))
print('Available operations')
print('1. add - add two numbers')
print('2. sub - subtract two numbers')
print('3. div - divide two numbers')
print('4. mul - multiply two numbers')
operator = int(input('What operation would you like to perform? \n'))
print(operation(firstValue, secondValue, operator)) |
class NoDataForTrigger(ValueError):
"""An error that's raised when a trigger is passed
a data point that cannot be handled due to an incompatible
value being stored"""
pass
class IncompatibleTriggerError(NoDataForTrigger):
"""An error that's raised when a trigger is passed
a data point that cannot be handled due to an incompatible
value being stored"""
pass
| class Nodatafortrigger(ValueError):
"""An error that's raised when a trigger is passed
a data point that cannot be handled due to an incompatible
value being stored"""
pass
class Incompatibletriggererror(NoDataForTrigger):
"""An error that's raised when a trigger is passed
a data point that cannot be handled due to an incompatible
value being stored"""
pass |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyYarl(PythonPackage):
"""The module provides handy URL class for URL parsing and changing."""
homepage = "https://github.com/aio-libs/yarl"
url = "https://github.com/aio-libs/yarl/archive/v1.4.2.tar.gz"
version('1.7.2', sha256='19b94c68e8eda5731f87d79e3c34967a11e69695965113c4724d2491f76ad461')
version('1.4.2', sha256='a400eb3f54f7596eeaba8100a8fa3d72135195423c52808dc54a43c6b100b192')
depends_on('python@3.5:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools@40:', type='build', when='@1.7.2:')
depends_on('py-cython', type='build')
depends_on('py-multidict@4.0:', type=('build', 'run'))
depends_on('py-idna@2.0:', type=('build', 'run'))
depends_on('py-typing-extensions@3.7.4:', type=('build', 'run'), when='@1.7.2: ^python@:3.7')
@run_before('build')
def fix_cython(self):
if self.spec.satisfies('@1.7.2:'):
pyxfile = 'yarl/_quoting_c'
else:
pyxfile = 'yarl/_quoting'
cython = self.spec['py-cython'].command
cython('-3',
'-o',
pyxfile + '.c',
pyxfile + '.pyx',
'-Iyarl')
| class Pyyarl(PythonPackage):
"""The module provides handy URL class for URL parsing and changing."""
homepage = 'https://github.com/aio-libs/yarl'
url = 'https://github.com/aio-libs/yarl/archive/v1.4.2.tar.gz'
version('1.7.2', sha256='19b94c68e8eda5731f87d79e3c34967a11e69695965113c4724d2491f76ad461')
version('1.4.2', sha256='a400eb3f54f7596eeaba8100a8fa3d72135195423c52808dc54a43c6b100b192')
depends_on('python@3.5:', type=('build', 'run'))
depends_on('py-setuptools', type='build')
depends_on('py-setuptools@40:', type='build', when='@1.7.2:')
depends_on('py-cython', type='build')
depends_on('py-multidict@4.0:', type=('build', 'run'))
depends_on('py-idna@2.0:', type=('build', 'run'))
depends_on('py-typing-extensions@3.7.4:', type=('build', 'run'), when='@1.7.2: ^python@:3.7')
@run_before('build')
def fix_cython(self):
if self.spec.satisfies('@1.7.2:'):
pyxfile = 'yarl/_quoting_c'
else:
pyxfile = 'yarl/_quoting'
cython = self.spec['py-cython'].command
cython('-3', '-o', pyxfile + '.c', pyxfile + '.pyx', '-Iyarl') |
mod, maxn, cur, ans, r = 998244353, 1000005, 10, 0, 0
dp, x, a = [0] * maxn, [0] * maxn, [0] * 12,
x[1] = 1
dp[0] = 1
for i in range(2 , maxn):
x[i] = mod - (mod // i) * x[mod % i] % mod
n, k = map(int, input().split())
n = n // 2
p = [0] * k
for u in map(int, input().split()):
cur = min(cur, u)
p[r] = u
r += 1
for i in range(k):
a[p[i] - cur] = 1
for i in range(n * 10 + 1):
sm, j = 0, 0
while j < min(10, i + 1):
sm += dp[i-j] * (j+1) * a[j+1] * n % mod
j += 1
j = 1
while j < min(10, i + 1):
sm -= dp[i-j+1] * (i-j+1) * a[j]
j += 1
ans = (ans + dp[i] * dp[i]) % mod
dp[i+1] = sm * x[i+1] % mod
print(ans % mod)
| (mod, maxn, cur, ans, r) = (998244353, 1000005, 10, 0, 0)
(dp, x, a) = ([0] * maxn, [0] * maxn, [0] * 12)
x[1] = 1
dp[0] = 1
for i in range(2, maxn):
x[i] = mod - mod // i * x[mod % i] % mod
(n, k) = map(int, input().split())
n = n // 2
p = [0] * k
for u in map(int, input().split()):
cur = min(cur, u)
p[r] = u
r += 1
for i in range(k):
a[p[i] - cur] = 1
for i in range(n * 10 + 1):
(sm, j) = (0, 0)
while j < min(10, i + 1):
sm += dp[i - j] * (j + 1) * a[j + 1] * n % mod
j += 1
j = 1
while j < min(10, i + 1):
sm -= dp[i - j + 1] * (i - j + 1) * a[j]
j += 1
ans = (ans + dp[i] * dp[i]) % mod
dp[i + 1] = sm * x[i + 1] % mod
print(ans % mod) |
def nomina(salario, horasNormales, horasExtra):
if horasNormales+horasExtra>=36 and horasNormales+horasExtra<=43:
salario=salario+horasExtra*1.25
elif horasNormales+horasExtra>=44:
salario=salario+horasExtra*1.5
else:
salario=salario
return print(salario)
nomina(1500,35,0)
| def nomina(salario, horasNormales, horasExtra):
if horasNormales + horasExtra >= 36 and horasNormales + horasExtra <= 43:
salario = salario + horasExtra * 1.25
elif horasNormales + horasExtra >= 44:
salario = salario + horasExtra * 1.5
else:
salario = salario
return print(salario)
nomina(1500, 35, 0) |
"""
map
"""
def multiply(value, times=1):
return value * times
a = list(map(multiply, [1, 2, 3]))
print(a)
print()
a = list(map(multiply, [1, 2, 3], [1, 2, 3]))
print(a)
| """
map
"""
def multiply(value, times=1):
return value * times
a = list(map(multiply, [1, 2, 3]))
print(a)
print()
a = list(map(multiply, [1, 2, 3], [1, 2, 3]))
print(a) |
print('The choice coin voting session has started!!!!!')
print('------------------------------------------------')
print ('should we continue with the proposal method')
nominee_1 = 'yes'
nominee_2 = 'no'
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1,2,3,4,5,6,7,8,9,10]
num_of_voter = len(votes_id)
while True:
voter = int(input('enter your voter id no:'))
if votes_id ==[]:
print('voting session over')
if nom_1_votes >nom_2_votes:
percent = (nom_1_votes/num_of_voter)*100
print(nominee_1, 'has won', 'with', percent, '% votes')
break
if nom_2_votes > nom_1_votes:
percent = (nom_2_votes/num_of_voter)*100
print(nominee_2, 'has won', 'with', percent, '% votes')
break
else:
if voter in votes_id:
print('you are a voter')
votes_id.remove(voter)
vote = int(input('enter your vote 1 for yes, 2 for no: '))
if vote==1:
nom_1_votes+=1
print('thank you for voting')
elif vote == 2:
nom_2_votes+=1
print('thanks for voting')
else:
print('you are not a voter here or you have already voted')
| print('The choice coin voting session has started!!!!!')
print('------------------------------------------------')
print('should we continue with the proposal method')
nominee_1 = 'yes'
nominee_2 = 'no'
nom_1_votes = 0
nom_2_votes = 0
votes_id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_of_voter = len(votes_id)
while True:
voter = int(input('enter your voter id no:'))
if votes_id == []:
print('voting session over')
if nom_1_votes > nom_2_votes:
percent = nom_1_votes / num_of_voter * 100
print(nominee_1, 'has won', 'with', percent, '% votes')
break
if nom_2_votes > nom_1_votes:
percent = nom_2_votes / num_of_voter * 100
print(nominee_2, 'has won', 'with', percent, '% votes')
break
elif voter in votes_id:
print('you are a voter')
votes_id.remove(voter)
vote = int(input('enter your vote 1 for yes, 2 for no: '))
if vote == 1:
nom_1_votes += 1
print('thank you for voting')
elif vote == 2:
nom_2_votes += 1
print('thanks for voting')
else:
print('you are not a voter here or you have already voted') |
''' The complete Intcode computer
N. B. Someone wrote an intcode computer in intcode
https://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/
'''
fin = open('input_13.txt')
temp = fin.readline().split(',')
fin.close()
program_template = [int(x) for x in temp]
# program_template = [109, 1, 204, -1, 1001, 100,
# 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
# program_template = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
# program_template = [104, 1125899906842624, 99]
# memory extension
program_template += [0] * 2000
def pexec(p, pc, in_queue, out_queue, rbase):
def g_o(pc, opnum): # get operand
modes = p[pc] // 100
m = [0, 0, 0, 0]
m[1] = modes % 10
modes = modes // 10
m[2] = modes % 10
modes = modes // 10
m[3] = modes % 10
if (opnum == 3): # target address for write operations
if m[3] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if (p[pc] % 100 == 3): # target address for input write
if m[1] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if m[opnum] == 0: # positional, immediate, relative target value
return p[p[pc + opnum]]
elif m[opnum] == 1:
return p[pc + opnum]
elif m[opnum] == 2:
return p[p[pc + opnum] + rbase]
else:
return None
while True:
# decode instruction
opcode = p[pc] % 100
if opcode == 99: # terminate
return 'END', pc, rbase
elif opcode == 1: # add
p[g_o(pc, 3)] = g_o(pc, 1) + g_o(pc, 2)
pc += 4
elif opcode == 2: # multiply
p[g_o(pc, 3)] = g_o(pc, 1) * g_o(pc, 2)
pc += 4
elif opcode == 3: # input
# inp = int(input('Input at location ' + str(pc) + ' : '))
if in_queue == []:
return 'WAIT', pc, rbase
inp = in_queue.pop(0)
p[g_o(pc, 1)] = inp
pc += 2
elif opcode == 4: # print
# print(g_o(pc, 1))
out_queue.append(g_o(pc, 1))
pc += 2
elif opcode == 5: # jump-if-true
if g_o(pc, 1) != 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 6: # jump-if-false
if g_o(pc, 1) == 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 7: # less than
if g_o(pc, 1) < g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 8: # equal
if g_o(pc, 1) == g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 9: # change relative base
rbase += g_o(pc, 1)
pc += 2
else: # unknown opcode
return 'ERROR', pc, rbase
pA = program_template[:]
qAin = []
qAout = []
pcA = 0
stateA = 'WAIT'
rbaseA = 0
while True:
if stateA == 'WAIT':
stateA, pcA, rbaseA = pexec(pA, pcA, qAin, qAout, rbaseA)
if stateA == 'END':
break
print(qAout[::3], qAout[1::3], qAout[2::3], qAout[2::3].count(2))
| """ The complete Intcode computer
N. B. Someone wrote an intcode computer in intcode
https://www.reddit.com/r/adventofcode/comments/e7wml1/2019_intcode_computer_in_intcode/
"""
fin = open('input_13.txt')
temp = fin.readline().split(',')
fin.close()
program_template = [int(x) for x in temp]
program_template += [0] * 2000
def pexec(p, pc, in_queue, out_queue, rbase):
def g_o(pc, opnum):
modes = p[pc] // 100
m = [0, 0, 0, 0]
m[1] = modes % 10
modes = modes // 10
m[2] = modes % 10
modes = modes // 10
m[3] = modes % 10
if opnum == 3:
if m[3] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if p[pc] % 100 == 3:
if m[1] == 0:
return p[pc + opnum]
else:
return p[pc + opnum] + rbase
if m[opnum] == 0:
return p[p[pc + opnum]]
elif m[opnum] == 1:
return p[pc + opnum]
elif m[opnum] == 2:
return p[p[pc + opnum] + rbase]
else:
return None
while True:
opcode = p[pc] % 100
if opcode == 99:
return ('END', pc, rbase)
elif opcode == 1:
p[g_o(pc, 3)] = g_o(pc, 1) + g_o(pc, 2)
pc += 4
elif opcode == 2:
p[g_o(pc, 3)] = g_o(pc, 1) * g_o(pc, 2)
pc += 4
elif opcode == 3:
if in_queue == []:
return ('WAIT', pc, rbase)
inp = in_queue.pop(0)
p[g_o(pc, 1)] = inp
pc += 2
elif opcode == 4:
out_queue.append(g_o(pc, 1))
pc += 2
elif opcode == 5:
if g_o(pc, 1) != 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 6:
if g_o(pc, 1) == 0:
pc = g_o(pc, 2)
else:
pc += 3
elif opcode == 7:
if g_o(pc, 1) < g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 8:
if g_o(pc, 1) == g_o(pc, 2):
p[g_o(pc, 3)] = 1
else:
p[g_o(pc, 3)] = 0
pc += 4
elif opcode == 9:
rbase += g_o(pc, 1)
pc += 2
else:
return ('ERROR', pc, rbase)
p_a = program_template[:]
q_ain = []
q_aout = []
pc_a = 0
state_a = 'WAIT'
rbase_a = 0
while True:
if stateA == 'WAIT':
(state_a, pc_a, rbase_a) = pexec(pA, pcA, qAin, qAout, rbaseA)
if stateA == 'END':
break
print(qAout[::3], qAout[1::3], qAout[2::3], qAout[2::3].count(2)) |
# Original Solution
def additionWithoutCarrying(param1, param2):
smaller = min(param1,param2)
larger = max(param1,param2)
small_list = list(str(smaller))
large_list = list(str(larger))
output = []
print(param1,param2)
print(small_list,large_list)
index_2= 0
for index,i in enumerate(large_list):
if index >= (len(large_list) - len(small_list)):
print('index1:',index)
print('index_two',index_2)
print('larger_num',i)
print('smaller_num',small_list[index_2])
number = int(i)+int(small_list[index_2])
if number > 9:
digit = list(str(number))[-1]
output.append(digit)
else:
output.append(str(number))
index_2+=1
else:
print('index1:',index)
print(i)
output.append(i)
return int("".join(output))
# Much cleaner solution (from reading the solutions)
# the reason that this works is because you stay in numeric space
# you are composing the number numerically not logically.
# I was composing the number logically, and so I was working in
# "string" space, and going back and forth. Here
# you don't have to translate back and forth.
def additionWithoutCarrying(param1, param2):
output = 0
tenPower = 1
while param1 or param2:
output += tenPower * ((param1+param2)%10)
param1 //= 10
param2 //= 10
tenPower *= 10
return output | def addition_without_carrying(param1, param2):
smaller = min(param1, param2)
larger = max(param1, param2)
small_list = list(str(smaller))
large_list = list(str(larger))
output = []
print(param1, param2)
print(small_list, large_list)
index_2 = 0
for (index, i) in enumerate(large_list):
if index >= len(large_list) - len(small_list):
print('index1:', index)
print('index_two', index_2)
print('larger_num', i)
print('smaller_num', small_list[index_2])
number = int(i) + int(small_list[index_2])
if number > 9:
digit = list(str(number))[-1]
output.append(digit)
else:
output.append(str(number))
index_2 += 1
else:
print('index1:', index)
print(i)
output.append(i)
return int(''.join(output))
def addition_without_carrying(param1, param2):
output = 0
ten_power = 1
while param1 or param2:
output += tenPower * ((param1 + param2) % 10)
param1 //= 10
param2 //= 10
ten_power *= 10
return output |
def soma (x,y):
return x+y
def subtrai (x,y):
return x-y
def mult():
pass
| def soma(x, y):
return x + y
def subtrai(x, y):
return x - y
def mult():
pass |
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Common code for reuse across java_* rules
"""
load(":common/rule_util.bzl", "create_composite_dep")
load(":common/java/android_lint.bzl", "ANDROID_LINT_ACTION")
load(":common/java/compile_action.bzl", "COMPILE_ACTION")
coverage_common = _builtins.toplevel.coverage_common
def _filter_srcs(srcs, ext):
return [f for f in srcs if f.extension == ext]
def _base_common_impl(
ctx,
extra_resources,
output_prefix,
enable_compile_jar_action = True,
extra_runtime_jars = [],
coverage_config = None):
srcs = ctx.files.srcs
source_files = _filter_srcs(srcs, "java")
source_jars = _filter_srcs(srcs, "srcjar")
java_info, default_info, compilation_info = COMPILE_ACTION.call(
ctx,
extra_resources,
source_files,
source_jars,
output_prefix,
enable_compile_jar_action,
extra_runtime_jars,
extra_deps = [coverage_config.runner] if coverage_config else [],
)
output_groups = dict(
compilation_outputs = compilation_info.outputs,
_source_jars = java_info.transitive_source_jars,
_direct_source_jars = java_info.source_jars,
)
lint_output = ANDROID_LINT_ACTION.call(ctx, java_info, source_files, source_jars, compilation_info)
if lint_output:
output_groups["_validation"] = [lint_output]
instrumented_files_info = coverage_common.instrumented_files_info(
ctx,
source_attributes = ["srcs"],
dependency_attributes = ["deps", "data", "resources", "resource_jars", "exports", "runtime_deps", "jars"],
coverage_support_files = coverage_config.support_files if coverage_config else depset(),
coverage_environment = coverage_config.env if coverage_config else {},
)
return struct(
java_info = java_info,
default_info = default_info,
instrumented_files_info = instrumented_files_info,
output_groups = output_groups,
extra_providers = [],
)
JAVA_COMMON_DEP = create_composite_dep(
_base_common_impl,
COMPILE_ACTION,
ANDROID_LINT_ACTION,
)
| """
Common code for reuse across java_* rules
"""
load(':common/rule_util.bzl', 'create_composite_dep')
load(':common/java/android_lint.bzl', 'ANDROID_LINT_ACTION')
load(':common/java/compile_action.bzl', 'COMPILE_ACTION')
coverage_common = _builtins.toplevel.coverage_common
def _filter_srcs(srcs, ext):
return [f for f in srcs if f.extension == ext]
def _base_common_impl(ctx, extra_resources, output_prefix, enable_compile_jar_action=True, extra_runtime_jars=[], coverage_config=None):
srcs = ctx.files.srcs
source_files = _filter_srcs(srcs, 'java')
source_jars = _filter_srcs(srcs, 'srcjar')
(java_info, default_info, compilation_info) = COMPILE_ACTION.call(ctx, extra_resources, source_files, source_jars, output_prefix, enable_compile_jar_action, extra_runtime_jars, extra_deps=[coverage_config.runner] if coverage_config else [])
output_groups = dict(compilation_outputs=compilation_info.outputs, _source_jars=java_info.transitive_source_jars, _direct_source_jars=java_info.source_jars)
lint_output = ANDROID_LINT_ACTION.call(ctx, java_info, source_files, source_jars, compilation_info)
if lint_output:
output_groups['_validation'] = [lint_output]
instrumented_files_info = coverage_common.instrumented_files_info(ctx, source_attributes=['srcs'], dependency_attributes=['deps', 'data', 'resources', 'resource_jars', 'exports', 'runtime_deps', 'jars'], coverage_support_files=coverage_config.support_files if coverage_config else depset(), coverage_environment=coverage_config.env if coverage_config else {})
return struct(java_info=java_info, default_info=default_info, instrumented_files_info=instrumented_files_info, output_groups=output_groups, extra_providers=[])
java_common_dep = create_composite_dep(_base_common_impl, COMPILE_ACTION, ANDROID_LINT_ACTION) |
if __name__ == '__main__':
N = int(input())
Output = [];
for i in range(0,N):
ip = input().split();
if ip[0] == "print":
print(Output)
elif ip[0] == "insert":
Output.insert(int(ip[1]),int(ip[2]))
elif ip[0] == "remove":
Output.remove(int(ip[1]))
elif ip[0] == "pop":
Output.pop();
elif ip[0] == "append":
Output.append(int(ip[1]))
elif ip[0] == "sort":
Output.sort();
else:
Output.reverse();
| if __name__ == '__main__':
n = int(input())
output = []
for i in range(0, N):
ip = input().split()
if ip[0] == 'print':
print(Output)
elif ip[0] == 'insert':
Output.insert(int(ip[1]), int(ip[2]))
elif ip[0] == 'remove':
Output.remove(int(ip[1]))
elif ip[0] == 'pop':
Output.pop()
elif ip[0] == 'append':
Output.append(int(ip[1]))
elif ip[0] == 'sort':
Output.sort()
else:
Output.reverse() |
def capacity(K, weights):
if sum(weights) < K:
return None
weights = sorted(weights, reverse=True)
def solve(K, i):
print("Solve({0}, {1})".format(K, i))
if K == 0:
return []
while i < len(weights) and weights[i]> K:
i += 1
if i == len(weights):
return None
subK = K - weights[i]
subI = i + 1
subsolution = solve(subK, subI)
if subsolution is not None:
subsolution.append(weights[i])
return subsolution
subsolution = solve(K, subI)
if subsolution is not None:
return subsolution
return None
return solve(K, 0)
print(capacity(20000, [x**2 for x in range(100)]))
| def capacity(K, weights):
if sum(weights) < K:
return None
weights = sorted(weights, reverse=True)
def solve(K, i):
print('Solve({0}, {1})'.format(K, i))
if K == 0:
return []
while i < len(weights) and weights[i] > K:
i += 1
if i == len(weights):
return None
sub_k = K - weights[i]
sub_i = i + 1
subsolution = solve(subK, subI)
if subsolution is not None:
subsolution.append(weights[i])
return subsolution
subsolution = solve(K, subI)
if subsolution is not None:
return subsolution
return None
return solve(K, 0)
print(capacity(20000, [x ** 2 for x in range(100)])) |
def main():
n = int(input())
for case in range(1, n + 1):
d = int(input())
guys = [int(s) for s in input().split(" ")]
# print(d, guys)
guys = sorted(guys, reverse=True)
# print(d, guys)
print("Case #{}: {}".format(case, cal_move(d, guys)))
def cal_move(d, guys, moved=0):
"""special move for single 9."""
# print(d, guys, moved)
unmove = guys[0]
if unmove == 9 and d == 1:
return 5
if unmove == 9 and d > 1 and guys[1] <= 3:
return 5
if unmove == 9 and d > 1 and guys[1] <= 6 and (d == 2 or (d > 2 and guys[2] <= 3)):
# special case of 9, 6, 2, min_move = 6 (333 6 2, 333 33 2)
# and special case of 9 6.
move_guys = guys
del move_guys[0]
move_guys.append(3)
move_guys.append(3)
move_guys.append(3)
move_guys = sorted(move_guys, reverse=True)
move_n = cal_move(d+1, move_guys.copy(), moved+1)
if move_n < unmove:
return move_n + 2
else:
return unmove + 1
elif unmove <= 2:
return unmove
else:
move_guys = guys
del move_guys[0]
if unmove % 2 == 0:
move_guys.append(int(unmove / 2))
move_guys.append(int(unmove / 2))
else:
move_guys.append(int((unmove+1) / 2))
move_guys.append(int((unmove-1) / 2))
# special 9 here
move_guys = sorted(move_guys, reverse=True)
"""
print(move_guys)
print(cal_move(d+1, move_guys, moved+1))
print(move_guys)
print("before add.")
print(move_guys)
print(cal_move(d+1, move_guys, moved+1))
"""
move_n = cal_move(d+1, move_guys.copy(), moved+1)
if move_n < unmove:
return move_n + 1
else:
return unmove
def test_iter(i):
if i == 1:
return i
else:
return test_iter(i-1) * i
main()
| def main():
n = int(input())
for case in range(1, n + 1):
d = int(input())
guys = [int(s) for s in input().split(' ')]
guys = sorted(guys, reverse=True)
print('Case #{}: {}'.format(case, cal_move(d, guys)))
def cal_move(d, guys, moved=0):
"""special move for single 9."""
unmove = guys[0]
if unmove == 9 and d == 1:
return 5
if unmove == 9 and d > 1 and (guys[1] <= 3):
return 5
if unmove == 9 and d > 1 and (guys[1] <= 6) and (d == 2 or (d > 2 and guys[2] <= 3)):
move_guys = guys
del move_guys[0]
move_guys.append(3)
move_guys.append(3)
move_guys.append(3)
move_guys = sorted(move_guys, reverse=True)
move_n = cal_move(d + 1, move_guys.copy(), moved + 1)
if move_n < unmove:
return move_n + 2
else:
return unmove + 1
elif unmove <= 2:
return unmove
else:
move_guys = guys
del move_guys[0]
if unmove % 2 == 0:
move_guys.append(int(unmove / 2))
move_guys.append(int(unmove / 2))
else:
move_guys.append(int((unmove + 1) / 2))
move_guys.append(int((unmove - 1) / 2))
move_guys = sorted(move_guys, reverse=True)
'\n print(move_guys)\n print(cal_move(d+1, move_guys, moved+1))\n print(move_guys)\n print("before add.")\n print(move_guys)\n print(cal_move(d+1, move_guys, moved+1))\n '
move_n = cal_move(d + 1, move_guys.copy(), moved + 1)
if move_n < unmove:
return move_n + 1
else:
return unmove
def test_iter(i):
if i == 1:
return i
else:
return test_iter(i - 1) * i
main() |
flatmates = [
{
'name': "Fred",
'telegram_id': "930376906"
},
{
'name': "Kata",
'telegram_id': "1524429277"
},
{
'name': "Daniel",
'telegram_id': "1145198247"
},
{
'name': "Ricky",
'telegram_id': "930376906"
},
{
'name': "Ankit",
'telegram_id': "1519503399"
},
{
'name': "Csaba",
'telegram_id': "5044038381"
},
{
'name': "Lisa",
'telegram_id': "2087012195"
},
{
'name': "Raminta",
'telegram_id': "930376906"
}
]
| flatmates = [{'name': 'Fred', 'telegram_id': '930376906'}, {'name': 'Kata', 'telegram_id': '1524429277'}, {'name': 'Daniel', 'telegram_id': '1145198247'}, {'name': 'Ricky', 'telegram_id': '930376906'}, {'name': 'Ankit', 'telegram_id': '1519503399'}, {'name': 'Csaba', 'telegram_id': '5044038381'}, {'name': 'Lisa', 'telegram_id': '2087012195'}, {'name': 'Raminta', 'telegram_id': '930376906'}] |
#!/usr/bin/python
"""Programa que implementa el algoritmo de ordenamiento por insercion."""
def InsertionSort(lista):
"""Algoritmo de ordenamiento por insercion."""
for j in range(1, len(lista)):
key = lista[j]
# Inserta lista[j] en la secuecia ordenada lista[0.. j]
i = j - 1
while i >= 0 and lista[i] > key:
lista[i + 1] = lista[i]
i -= 1
lista[i + 1] = key
lista = [5, 3, 2, 1, 6, 7, 10, 0, 4, 8, 9]
print(lista)
InsertionSort(lista)
print(lista)
| """Programa que implementa el algoritmo de ordenamiento por insercion."""
def insertion_sort(lista):
"""Algoritmo de ordenamiento por insercion."""
for j in range(1, len(lista)):
key = lista[j]
i = j - 1
while i >= 0 and lista[i] > key:
lista[i + 1] = lista[i]
i -= 1
lista[i + 1] = key
lista = [5, 3, 2, 1, 6, 7, 10, 0, 4, 8, 9]
print(lista)
insertion_sort(lista)
print(lista) |
# callback handlers: reloaded each time triggered
def message1(): # change me
print('BIMRI') # or could build a dialog...
def message2(self):
print('Nil!') # change me
self.method1() # access the 'Hello' instance...
| def message1():
print('BIMRI')
def message2(self):
print('Nil!')
self.method1() |
class Solution:
def largestNumber(self, num):
num_str = map(str, num)
num_str.sort(cmp=lambda str1, str2: -1 if str1 + str2 > str2 + str1 else 1)
if len(num_str) >= 2 and num_str[0] == num_str[1] == "0":
return "0"
return "".join(num_str)
| class Solution:
def largest_number(self, num):
num_str = map(str, num)
num_str.sort(cmp=lambda str1, str2: -1 if str1 + str2 > str2 + str1 else 1)
if len(num_str) >= 2 and num_str[0] == num_str[1] == '0':
return '0'
return ''.join(num_str) |
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
emails = dict()
for line in handle:
words = line.split()
if not line.startswith('From') or len(words) < 3:
continue
email = words[1]
emails[email] = emails.get(email, 0) + 1
max = 0
max_email = None
for email, count in emails.items():
if count > max:
max = count
max_email = email
print(max_email, max)
| name = input('Enter file:')
if len(name) < 1:
name = 'mbox-short.txt'
handle = open(name)
emails = dict()
for line in handle:
words = line.split()
if not line.startswith('From') or len(words) < 3:
continue
email = words[1]
emails[email] = emails.get(email, 0) + 1
max = 0
max_email = None
for (email, count) in emails.items():
if count > max:
max = count
max_email = email
print(max_email, max) |
# -*- coding: utf-8 -*-
# @Time : 2021/8/25 4:25
# @Author : pixb
# @Email : tpxsky@163.com
# @File : main_model.py.py
# @Software: PyCharm
# @Description:
class main_model(object):
pass
| class Main_Model(object):
pass |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 17:32:32 2020
@author: abhi0
"""
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
count=0
i=0
s=sorted(s)
while i<len(g): #greed factor for childrens
for j in range(len(s)): #size of cookies
if s[j]>=g[i]: #if the size is larger than greed factor,children is satisfied
count+=1 #increment the counter
s.pop(j) #Remove the cookie
break #go to the next children
i+=1
return count | """
Created on Mon Jun 22 17:32:32 2020
@author: abhi0
"""
class Solution:
def find_content_children(self, g: List[int], s: List[int]) -> int:
count = 0
i = 0
s = sorted(s)
while i < len(g):
for j in range(len(s)):
if s[j] >= g[i]:
count += 1
s.pop(j)
break
i += 1
return count |
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Index'),URL('default','index')==URL(),URL('default','index'),[]),
(T('Book'),URL('default','book_manage')==URL(),URL('default','book_manage'),[]),
(T('Chapter'),URL('default','chapter_manage')==URL(),URL('default','chapter_manage'),[]),
(T('Character'),URL('default','character_manage')==URL(),URL('default','character_manage'),[]),
(T('Character Reference'),URL('default','character_reference_manage')==URL(),URL('default','character_reference_manage'),[]),
(T('Question'),URL('default','question_manage')==URL(),URL('default','question_manage'),[]),
] | response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [(t('Index'), url('default', 'index') == url(), url('default', 'index'), []), (t('Book'), url('default', 'book_manage') == url(), url('default', 'book_manage'), []), (t('Chapter'), url('default', 'chapter_manage') == url(), url('default', 'chapter_manage'), []), (t('Character'), url('default', 'character_manage') == url(), url('default', 'character_manage'), []), (t('Character Reference'), url('default', 'character_reference_manage') == url(), url('default', 'character_reference_manage'), []), (t('Question'), url('default', 'question_manage') == url(), url('default', 'question_manage'), [])] |
DEFAULT_GEASE_FILE_NAME = ".gease"
DEFAULT_RELEASE_MESSAGE = "A new release via gease."
NOT_ENOUGH_ARGS = "Not enough arguments"
KEY_GEASE_USER = "user"
KEY_GEASE_TOKEN = "personal_access_token"
MESSAGE_FMT_RELEASED = "Release is created at: %s"
| default_gease_file_name = '.gease'
default_release_message = 'A new release via gease.'
not_enough_args = 'Not enough arguments'
key_gease_user = 'user'
key_gease_token = 'personal_access_token'
message_fmt_released = 'Release is created at: %s' |
def paint_calc(height,width,cover):
number_of_cans = round((height * width) / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
height = int(input("Height of Wall :\n"))
width = int(input("Width of wall : \n"))
coverage = 5
paint_calc(height=height,width=width,cover=coverage)
| def paint_calc(height, width, cover):
number_of_cans = round(height * width / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
height = int(input('Height of Wall :\n'))
width = int(input('Width of wall : \n'))
coverage = 5
paint_calc(height=height, width=width, cover=coverage) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.