content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
__version__ = '1.0.0'
__author__ = 'Steven Huang'
__all__ = ["file", "basic", "geo_math", "geo_transformation"]
| __version__ = '1.0.0'
__author__ = 'Steven Huang'
__all__ = ['file', 'basic', 'geo_math', 'geo_transformation'] |
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.
#
# @COPYRIGHT_end
"""@package src.common.hardware
Cluster configuration
You can specify here what hardware will be emulated on this cluster and all
supported disk types/formats. Some variables have python-dictionary format.
Each element is sub-dictionary: <id>: {'param_name': 'param_value', ...}.
Usually required parameters are name and enabled. If any attitional are re-
quired, it is written in comment.
"""
## Network devices available for Virtual Machines. Add own if necessary
# (virtualizator has to support it!)
network_devices = {
'rtl8139': 0,
'virtio': 1,
'ne2k_pci': 2,
'e1000': 3
}
## Emulated video devices for Virtual Machines. Add own if necessary
# (virtualizator has to support it!)
video_devices = {
'cirrus': 0,
'vga': 1
}
## Disk controllers for virtual machines.
disk_controllers = {
'scsi': 0,
'virtio': 1,
'ide': 2,
'sata': 3,
'usb': 4
}
live_attach_disk_controllers = ['virtio', 'usb']
# Disk filesystems (must be supported by ResourceManager for this CM!)
# Required parameters:
# - name
# - command - formatting program. %%s will be replaced with formatting filename
# - enabled
disk_filesystems = {
'raw': 0,
'fat32': 2,
'ext4': 5,
'reiserfs': 6,
'xfs': 7,
'ntfs': 8
}
disk_format_commands = {
'raw': '',
'ntfs-full': '/sbin/mkfs.ntfs -F',
'fat32': '/sbin/mkfs.vfat',
'ext2': '/sbin/mkfs.ext2 -F',
'ext3': '/sbin/mkfs.ext3 -F',
'ext4': '/sbin/mkfs.ext4 -F',
'reiserfs': '/sbin/mkfs.reiserfs -f -q',
'xfs': '/sbin/mkfs.xfs -f',
'ntfs': '/sbin/mkfs.ntfs -Q -F',
}
video_devices_reversed = dict((v, k) for k, v in video_devices.iteritems())
disk_controllers_reversed = dict((v, k) for k, v in disk_controllers.iteritems())
network_devices_reversed = dict((v, k) for k, v in network_devices.iteritems())
disk_filesystems_reversed = dict((v, k) for k, v in disk_filesystems.iteritems()) | """@package src.common.hardware
Cluster configuration
You can specify here what hardware will be emulated on this cluster and all
supported disk types/formats. Some variables have python-dictionary format.
Each element is sub-dictionary: <id>: {'param_name': 'param_value', ...}.
Usually required parameters are name and enabled. If any attitional are re-
quired, it is written in comment.
"""
network_devices = {'rtl8139': 0, 'virtio': 1, 'ne2k_pci': 2, 'e1000': 3}
video_devices = {'cirrus': 0, 'vga': 1}
disk_controllers = {'scsi': 0, 'virtio': 1, 'ide': 2, 'sata': 3, 'usb': 4}
live_attach_disk_controllers = ['virtio', 'usb']
disk_filesystems = {'raw': 0, 'fat32': 2, 'ext4': 5, 'reiserfs': 6, 'xfs': 7, 'ntfs': 8}
disk_format_commands = {'raw': '', 'ntfs-full': '/sbin/mkfs.ntfs -F', 'fat32': '/sbin/mkfs.vfat', 'ext2': '/sbin/mkfs.ext2 -F', 'ext3': '/sbin/mkfs.ext3 -F', 'ext4': '/sbin/mkfs.ext4 -F', 'reiserfs': '/sbin/mkfs.reiserfs -f -q', 'xfs': '/sbin/mkfs.xfs -f', 'ntfs': '/sbin/mkfs.ntfs -Q -F'}
video_devices_reversed = dict(((v, k) for (k, v) in video_devices.iteritems()))
disk_controllers_reversed = dict(((v, k) for (k, v) in disk_controllers.iteritems()))
network_devices_reversed = dict(((v, k) for (k, v) in network_devices.iteritems()))
disk_filesystems_reversed = dict(((v, k) for (k, v) in disk_filesystems.iteritems())) |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
n = int(input())
for i in range(1, n+1):
if i % 2 == 0:
print('{}^2 = {}'.format(i, i**2))
| n = int(input())
for i in range(1, n + 1):
if i % 2 == 0:
print('{}^2 = {}'.format(i, i ** 2)) |
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
class Node:
def __init__(self):
self.visits = 0
self.children = {}
def traverse(name, node, output):
if not node:
return
output.append(str(node.visits) + " " + name)
for child_name, child in node.children.items():
if name:
traverse(child_name + '.' + name, child, output)
else:
traverse(child_name, child, output)
root = Node()
for entry in cpdomains:
visits, domains = entry.split()
node = root
for path in reversed(domains.split('.')):
if path not in node.children:
node.children[path] = Node()
node.children[path].visits += int(visits)
node = node.children[path]
output = []
traverse("", root, output)
return output[1:]
| class Solution:
def subdomain_visits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
class Node:
def __init__(self):
self.visits = 0
self.children = {}
def traverse(name, node, output):
if not node:
return
output.append(str(node.visits) + ' ' + name)
for (child_name, child) in node.children.items():
if name:
traverse(child_name + '.' + name, child, output)
else:
traverse(child_name, child, output)
root = node()
for entry in cpdomains:
(visits, domains) = entry.split()
node = root
for path in reversed(domains.split('.')):
if path not in node.children:
node.children[path] = node()
node.children[path].visits += int(visits)
node = node.children[path]
output = []
traverse('', root, output)
return output[1:] |
# Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
num = int(input("Input an integer : "))
n1 = int( "%s" % num )
n2 = int( "%s%s" % (num,num) )
n3 = int( "%s%s%s" % (num,num,num) )
print (n1+n2+n3)
| num = int(input('Input an integer : '))
n1 = int('%s' % num)
n2 = int('%s%s' % (num, num))
n3 = int('%s%s%s' % (num, num, num))
print(n1 + n2 + n3) |
'''
example of models and GPU distribution sampler.
To run models demo, you need to download data files 'mnist_gray.mat'&'TREC.pkl' and put it under pydpm.example.data
data url: https://1drv.ms/u/s!AlkDawhaUUBWtHRWuNESEdOsDz7V?e=LQlGLW
'''
| """
example of models and GPU distribution sampler.
To run models demo, you need to download data files 'mnist_gray.mat'&'TREC.pkl' and put it under pydpm.example.data
data url: https://1drv.ms/u/s!AlkDawhaUUBWtHRWuNESEdOsDz7V?e=LQlGLW
""" |
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total_sum = sum(nums)
sum_so_far = 0
for i in range(len(nums)):
if sum_so_far * 2 + nums[i] == total_sum:
return i
else:
sum_so_far += nums[i]
return -1
| class Solution(object):
def pivot_index(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total_sum = sum(nums)
sum_so_far = 0
for i in range(len(nums)):
if sum_so_far * 2 + nums[i] == total_sum:
return i
else:
sum_so_far += nums[i]
return -1 |
class DefaultConfig(object):
DEBUG = False
TESTING = False
class TestConfig(DefaultConfig):
TESTING = True
class DebugConfig(DefaultConfig):
DEBUG = True
| class Defaultconfig(object):
debug = False
testing = False
class Testconfig(DefaultConfig):
testing = True
class Debugconfig(DefaultConfig):
debug = True |
def mac2ipv6(mac):
# only accept MACs separated by a colon
parts = mac.split(":")
# modify parts to match IPv6 value
parts.insert(3, "ff")
parts.insert(4, "fe")
parts[0] = "%x" % (int(parts[0], 16) ^ 2)
# format output
ipv6Parts = []
for i in range(0, len(parts), 2):
ipv6Parts.append("".join(parts[i:i+2]))
ipv6 = "fe80::%s/64" % (":".join(ipv6Parts))
return ipv6
def ipv62mac(ipv6):
# remove subnet info if given
subnetIndex = ipv6.find("/")
if subnetIndex != -1:
ipv6 = ipv6[:subnetIndex]
ipv6Parts = ipv6.split(":")
macParts = []
for ipv6Part in ipv6Parts[-4:]:
while len(ipv6Part) < 4:
ipv6Part = "0" + ipv6Part
macParts.append(ipv6Part[:2])
macParts.append(ipv6Part[-2:])
# modify parts to match MAC value
macParts[0] = "%02x" % (int(macParts[0], 16) ^ 2)
del macParts[4]
del macParts[3]
return ":".join(macParts)
# print(mac2ipv6('80:4a:14:69:b1:5d'))
print(ipv62mac('fe80::417:2066:cc4f:eff9'))
# 1e:4c:54:a4:5a:77
# 80:4a:14:69:b1:5d | def mac2ipv6(mac):
parts = mac.split(':')
parts.insert(3, 'ff')
parts.insert(4, 'fe')
parts[0] = '%x' % (int(parts[0], 16) ^ 2)
ipv6_parts = []
for i in range(0, len(parts), 2):
ipv6Parts.append(''.join(parts[i:i + 2]))
ipv6 = 'fe80::%s/64' % ':'.join(ipv6Parts)
return ipv6
def ipv62mac(ipv6):
subnet_index = ipv6.find('/')
if subnetIndex != -1:
ipv6 = ipv6[:subnetIndex]
ipv6_parts = ipv6.split(':')
mac_parts = []
for ipv6_part in ipv6Parts[-4:]:
while len(ipv6Part) < 4:
ipv6_part = '0' + ipv6Part
macParts.append(ipv6Part[:2])
macParts.append(ipv6Part[-2:])
macParts[0] = '%02x' % (int(macParts[0], 16) ^ 2)
del macParts[4]
del macParts[3]
return ':'.join(macParts)
print(ipv62mac('fe80::417:2066:cc4f:eff9')) |
name = "sample_module"
"""sample_module - Sample control test module demonstrating required functions
"""
def match(request):
"""match(request) - Match conditions in order for module to be run
"""
if request.method == "PUT":
return True
return False
def run(request):
"""run(request) - Execute module and return a string
"""
return 'sample module complete'
| name = 'sample_module'
'sample_module - Sample control test module demonstrating required functions\n'
def match(request):
"""match(request) - Match conditions in order for module to be run
"""
if request.method == 'PUT':
return True
return False
def run(request):
"""run(request) - Execute module and return a string
"""
return 'sample module complete' |
class Error(Exception):
pass
class WrappedError(Error):
BASE_MESSAGE = 'WrappedError'
def __init__(self, *args, origin_error=None, **kwargs):
self._origin_error = origin_error
if self._origin_error:
message = self.BASE_MESSAGE + ': ' + str(self._origin_error)
else:
message = self.BASE_MESSAGE
super().__init__(message, *args, **kwargs)
class ConnectError(WrappedError):
'''
errors when connect to database
'''
BASE_MESSAGE = 'ConnectError'
class UnexpectedError(WrappedError):
'''
uncategorized errors
'''
BASE_MESSAGE = 'UnexpectedError'
class OperationFailure(WrappedError):
'''
errors like timeout, mysql gone away, retriable
'''
BASE_MESSAGE = 'OperationFailure'
class ProgrammingError(WrappedError):
BASE_MESSAGE = 'ProgrammingError'
class DuplicateKeyError(Error):
pass
| class Error(Exception):
pass
class Wrappederror(Error):
base_message = 'WrappedError'
def __init__(self, *args, origin_error=None, **kwargs):
self._origin_error = origin_error
if self._origin_error:
message = self.BASE_MESSAGE + ': ' + str(self._origin_error)
else:
message = self.BASE_MESSAGE
super().__init__(message, *args, **kwargs)
class Connecterror(WrappedError):
"""
errors when connect to database
"""
base_message = 'ConnectError'
class Unexpectederror(WrappedError):
"""
uncategorized errors
"""
base_message = 'UnexpectedError'
class Operationfailure(WrappedError):
"""
errors like timeout, mysql gone away, retriable
"""
base_message = 'OperationFailure'
class Programmingerror(WrappedError):
base_message = 'ProgrammingError'
class Duplicatekeyerror(Error):
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 09:12:46 2019
@author: Brandon
"""
class nhcOutlooks():
def __init__(self, name, year, advisory_num):
self.name = name
self.yr = int(year)
self.adv_n = str(advisory_num)
self._check_inputs()
def _import_hurricane_info():
# return hurrs[self.yr]
# for now, assume year is 2019.
return {
"Andrea" : ["al01", "Atlantic"],
"Barry" : ["al02", "Atlantic"],
"Three" : ["al03", "Atlantic"],
"Chantal" : ["al04", "Atlantic"],
"Dorian" : ["al05", "Atlantic"],
"Erin" : ["al06", "Atlantic"],
"Fernand" : ["al07", "Atlantic"],
"Gabrielle" : ["al08", "Atlantic"],
"Humberto" : ["al09", "Atlantic"],
"Jerry" : ["al10", "Atlantic"],
"Imelda" : ["al11", "Atlantic"],
"Karen" : ["al12", "Atlantic"],
"Lorenzo" : ["al13", "Atlantic"],
"Alvin" : ["ep01", "East Pacific"],
"Barbara" : ["ep02", "East Pacific"],
"Cosme" : ["ep03", "East Pacific"],
"Four-e" : ["ep04", "East Pacific"],
"Dalila" : ["ep05", "East Pacific"],
"Erick" : ["ep06", "East Pacific"],
"Flossie" : ["ep07", "East Pacific"],
"Gil" : ["ep08", "East Pacific"],
"Henriette" : ["ep09", "East Pacific"],
"Ivo" : ["ep10", "East Pacific"],
"Juliette" : ["ep11", "East Pacific"],
"Akoni" : ["ep12", "East Pacific"],
"Kiko" : ["ep13", "East Pacific"],
"Mario" : ["ep14", "East Pacific"],
"Lorena" : ["ep15", "East Pacific"],
"Narda" : ["ep16", "East Pacific"]
}
# import the hurricane info; for now, hardcoded
def _check_inputs(self):
# checks to see if parameters are correct
if not 2008 <= self.yr <= 2019:
raise ValueError("Year must be between 2008 and current year")
if self.name not in self._import_hurricane_info():
raise ValueError("Cyclone name not in the specified year. Double check spelling and year.")
| """
Created on Wed Aug 28 09:12:46 2019
@author: Brandon
"""
class Nhcoutlooks:
def __init__(self, name, year, advisory_num):
self.name = name
self.yr = int(year)
self.adv_n = str(advisory_num)
self._check_inputs()
def _import_hurricane_info():
return {'Andrea': ['al01', 'Atlantic'], 'Barry': ['al02', 'Atlantic'], 'Three': ['al03', 'Atlantic'], 'Chantal': ['al04', 'Atlantic'], 'Dorian': ['al05', 'Atlantic'], 'Erin': ['al06', 'Atlantic'], 'Fernand': ['al07', 'Atlantic'], 'Gabrielle': ['al08', 'Atlantic'], 'Humberto': ['al09', 'Atlantic'], 'Jerry': ['al10', 'Atlantic'], 'Imelda': ['al11', 'Atlantic'], 'Karen': ['al12', 'Atlantic'], 'Lorenzo': ['al13', 'Atlantic'], 'Alvin': ['ep01', 'East Pacific'], 'Barbara': ['ep02', 'East Pacific'], 'Cosme': ['ep03', 'East Pacific'], 'Four-e': ['ep04', 'East Pacific'], 'Dalila': ['ep05', 'East Pacific'], 'Erick': ['ep06', 'East Pacific'], 'Flossie': ['ep07', 'East Pacific'], 'Gil': ['ep08', 'East Pacific'], 'Henriette': ['ep09', 'East Pacific'], 'Ivo': ['ep10', 'East Pacific'], 'Juliette': ['ep11', 'East Pacific'], 'Akoni': ['ep12', 'East Pacific'], 'Kiko': ['ep13', 'East Pacific'], 'Mario': ['ep14', 'East Pacific'], 'Lorena': ['ep15', 'East Pacific'], 'Narda': ['ep16', 'East Pacific']}
def _check_inputs(self):
if not 2008 <= self.yr <= 2019:
raise value_error('Year must be between 2008 and current year')
if self.name not in self._import_hurricane_info():
raise value_error('Cyclone name not in the specified year. Double check spelling and year.') |
def convert_iso_to_json(dateString):
tempDateObject = dateString.split("-")
return {
"year": tempDateObject[0],
"month": tempDateObject[1],
"day": tempDateObject[2]
}
def convert_json_to_iso(json):
return "{0}-{1}-{2}".format(int(json['year']), int(json['month']), int(json['day'])) | def convert_iso_to_json(dateString):
temp_date_object = dateString.split('-')
return {'year': tempDateObject[0], 'month': tempDateObject[1], 'day': tempDateObject[2]}
def convert_json_to_iso(json):
return '{0}-{1}-{2}'.format(int(json['year']), int(json['month']), int(json['day'])) |
#
# PySNMP MIB module WWP-LEOS-USER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-USER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:38:33 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter32, Counter64, iso, ModuleIdentity, Bits, TimeTicks, IpAddress, MibIdentifier, Integer32, Unsigned32, Gauge32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Counter64", "iso", "ModuleIdentity", "Bits", "TimeTicks", "IpAddress", "MibIdentifier", "Integer32", "Unsigned32", "Gauge32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity")
TextualConvention, TruthValue, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "RowStatus", "DisplayString")
wwpModulesLeos, = mibBuilder.importSymbols("WWP-SMI", "wwpModulesLeos")
wwpLeosUserMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39))
wwpLeosUserMIB.setRevisions(('2012-07-11 00:00', '2012-06-27 00:00', '2011-07-06 00:00', '2007-03-01 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: wwpLeosUserMIB.setRevisionsDescriptions(('Changed the definitions of the wwpLeosUserPrivLevel values to match those used internally and at the CLI.', 'Corrected string lengths.', ' Added a new object wwpLeosUserAuthProviderScope.', 'Initial creation.',))
if mibBuilder.loadTexts: wwpLeosUserMIB.setLastUpdated('201207110000Z')
if mibBuilder.loadTexts: wwpLeosUserMIB.setOrganization('Ciena, Inc')
if mibBuilder.loadTexts: wwpLeosUserMIB.setContactInfo(' Mib Meister 115 North Sullivan Road Spokane Valley, WA 99037 USA Phone: +1 509 242 9000 Email: support@ciena.com')
if mibBuilder.loadTexts: wwpLeosUserMIB.setDescription('This MIB module defines the generic managed objects for User Information on WWP devices.')
wwpLeosUserMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1))
wwpLeosUser = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1))
wwpLeosUserMIBNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 2))
wwpLeosUserMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 2, 0))
wwpLeosUserMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3))
wwpLeosUserMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3, 1))
wwpLeosUserMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3, 2))
wwpLeosUserAuthProviderTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1), )
if mibBuilder.loadTexts: wwpLeosUserAuthProviderTable.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderTable.setDescription('Table of UserAuth Providers.')
wwpLeosUserAuthProviderEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1), ).setIndexNames((0, "WWP-LEOS-USER-MIB", "wwpLeosUserAuthProviderPriority"))
if mibBuilder.loadTexts: wwpLeosUserAuthProviderEntry.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderEntry.setDescription('An entry for each User Authorization Provider.')
wwpLeosUserAuthProviderPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)))
if mibBuilder.loadTexts: wwpLeosUserAuthProviderPriority.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderPriority.setDescription('The priority of this user authentication provider.')
wwpLeosUserAuthProviderType = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("local", 2), ("radius", 3), ("tacacs", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderType.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderType.setDescription("The type/method of this user authentication provider. At least one entry must be a provider other than 'none' and any given provider may not be used twice. When a provider is changed to 'none', lower priority providers will have their priority increased to close the gap.")
wwpLeosUserAuthProviderCalled = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 3), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderCalled.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderCalled.setDescription('The number of calls to this user authentication provider. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwpLeosUserAuthProviderSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 4), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderSuccess.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderSuccess.setDescription('The number of times this user authentication provider returned a Success response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwpLeosUserAuthProviderFailure = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderFailure.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderFailure.setDescription('The number of times this user authentication provider returned a Failure response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwpLeosUserAuthProviderSkipped = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 6), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderSkipped.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderSkipped.setDescription('The number of times this user authentication provider returned a Skip Me response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwpLeosUserAuthProviderScope = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("serial", 1), ("remote", 2), ("all", 3))).clone('all')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserAuthProviderScope.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserAuthProviderScope.setDescription('The scope to be used for each authentication method.')
wwpLeosUserWhoTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2), )
if mibBuilder.loadTexts: wwpLeosUserWhoTable.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoTable.setDescription('Table of logged in users.')
wwpLeosUserWhoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1), ).setIndexNames((0, "WWP-LEOS-USER-MIB", "wwpLeosUserWhoPid"))
if mibBuilder.loadTexts: wwpLeosUserWhoEntry.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoEntry.setDescription('An entry for each logged in user.')
wwpLeosUserWhoPid = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 1), Unsigned32())
if mibBuilder.loadTexts: wwpLeosUserWhoPid.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoPid.setDescription('The pid of the users shell process.')
wwpLeosUserWhoUser = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wwpLeosUserWhoUser.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoUser.setDescription('The username used during login authentication.')
wwpLeosUserWhoTerminal = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wwpLeosUserWhoTerminal.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoTerminal.setDescription('The terminal the user logged in from.')
wwpLeosUserWhoIdleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wwpLeosUserWhoIdleTime.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoIdleTime.setDescription('The users idle time in minutes. This counter is reset to zero when ever the shell process detects input from the user.')
wwpLeosUserWhoStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wwpLeosUserWhoStatus.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserWhoStatus.setDescription("Status of the users shell process. To kill a users shell, set this object to 'Destroy'.")
wwpLeosUserTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3), )
if mibBuilder.loadTexts: wwpLeosUserTable.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserTable.setDescription('Table of locally configured users.')
wwpLeosUserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1), ).setIndexNames((0, "WWP-LEOS-USER-MIB", "wwpLeosUserUid"))
if mibBuilder.loadTexts: wwpLeosUserEntry.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserEntry.setDescription('An entry for each user in the local password file.')
wwpLeosUserUid = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 1), Unsigned32())
if mibBuilder.loadTexts: wwpLeosUserUid.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserUid.setDescription('The numeric userid of the user. These numbers are generated by the device in order to making indexing the table easy, but they are not tied to specific user names during a reboot. When a new user is created, the userid must be an unused value.')
wwpLeosUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: wwpLeosUserName.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserName.setDescription('The name of the user.')
wwpLeosUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 34))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: wwpLeosUserPassword.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserPassword.setDescription('The users password in encrypted form. When setting this object you must set wwpLeosUserIsEncrypted at the same time in order to specify whether the password you are setting needs to be encrypted by the device or whether you have already encrypted it.')
wwpLeosUserPrivLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("limited", 1), ("admin", 2), ("super", 3), ("diag", 4)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: wwpLeosUserPrivLevel.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserPrivLevel.setDescription('The privilege level of the user.')
wwpLeosUserIsDefault = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wwpLeosUserIsDefault.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserIsDefault.setDescription('When this is set to True, the user is one of the default users created in the device at boot time.')
wwpLeosUserIsEncrypted = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 6), TruthValue()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: wwpLeosUserIsEncrypted.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserIsEncrypted.setDescription('This will always be True on a Get as the password is always stored locally on the device in encrypted form. During a Set, it is False if you are sending wwpLeosUserPassword in the clear so the device can encrypt it, or True if wwpLeosUserPassword is already in encrypted MD5 form.')
wwpLeosUserIsModified = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 7), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wwpLeosUserIsModified.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserIsModified.setDescription('When this is set to True, the user is one of the default users created in the device, but one or more properties of the user account has been altered from the default values.')
wwpLeosUserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: wwpLeosUserStatus.setStatus('current')
if mibBuilder.loadTexts: wwpLeosUserStatus.setDescription('Use CreateAndGo to create a new user, Destroy to remove a user.')
mibBuilder.exportSymbols("WWP-LEOS-USER-MIB", wwpLeosUserWhoEntry=wwpLeosUserWhoEntry, wwpLeosUserPrivLevel=wwpLeosUserPrivLevel, wwpLeosUserMIBCompliances=wwpLeosUserMIBCompliances, wwpLeosUserTable=wwpLeosUserTable, wwpLeosUserIsModified=wwpLeosUserIsModified, wwpLeosUserAuthProviderEntry=wwpLeosUserAuthProviderEntry, wwpLeosUserMIBGroups=wwpLeosUserMIBGroups, wwpLeosUserMIBConformance=wwpLeosUserMIBConformance, wwpLeosUserMIBObjects=wwpLeosUserMIBObjects, wwpLeosUserWhoPid=wwpLeosUserWhoPid, wwpLeosUserUid=wwpLeosUserUid, wwpLeosUserStatus=wwpLeosUserStatus, wwpLeosUserWhoUser=wwpLeosUserWhoUser, wwpLeosUserAuthProviderTable=wwpLeosUserAuthProviderTable, wwpLeosUserMIB=wwpLeosUserMIB, wwpLeosUserName=wwpLeosUserName, wwpLeosUserAuthProviderSuccess=wwpLeosUserAuthProviderSuccess, wwpLeosUserAuthProviderCalled=wwpLeosUserAuthProviderCalled, wwpLeosUserAuthProviderPriority=wwpLeosUserAuthProviderPriority, wwpLeosUserIsDefault=wwpLeosUserIsDefault, wwpLeosUser=wwpLeosUser, wwpLeosUserWhoIdleTime=wwpLeosUserWhoIdleTime, wwpLeosUserPassword=wwpLeosUserPassword, wwpLeosUserWhoTerminal=wwpLeosUserWhoTerminal, wwpLeosUserMIBNotifications=wwpLeosUserMIBNotifications, wwpLeosUserWhoStatus=wwpLeosUserWhoStatus, wwpLeosUserAuthProviderScope=wwpLeosUserAuthProviderScope, wwpLeosUserEntry=wwpLeosUserEntry, wwpLeosUserAuthProviderFailure=wwpLeosUserAuthProviderFailure, wwpLeosUserAuthProviderType=wwpLeosUserAuthProviderType, wwpLeosUserAuthProviderSkipped=wwpLeosUserAuthProviderSkipped, PYSNMP_MODULE_ID=wwpLeosUserMIB, wwpLeosUserIsEncrypted=wwpLeosUserIsEncrypted, wwpLeosUserMIBNotificationPrefix=wwpLeosUserMIBNotificationPrefix, wwpLeosUserWhoTable=wwpLeosUserWhoTable)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter32, counter64, iso, module_identity, bits, time_ticks, ip_address, mib_identifier, integer32, unsigned32, gauge32, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Counter64', 'iso', 'ModuleIdentity', 'Bits', 'TimeTicks', 'IpAddress', 'MibIdentifier', 'Integer32', 'Unsigned32', 'Gauge32', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity')
(textual_convention, truth_value, row_status, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'TruthValue', 'RowStatus', 'DisplayString')
(wwp_modules_leos,) = mibBuilder.importSymbols('WWP-SMI', 'wwpModulesLeos')
wwp_leos_user_mib = module_identity((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39))
wwpLeosUserMIB.setRevisions(('2012-07-11 00:00', '2012-06-27 00:00', '2011-07-06 00:00', '2007-03-01 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
wwpLeosUserMIB.setRevisionsDescriptions(('Changed the definitions of the wwpLeosUserPrivLevel values to match those used internally and at the CLI.', 'Corrected string lengths.', ' Added a new object wwpLeosUserAuthProviderScope.', 'Initial creation.'))
if mibBuilder.loadTexts:
wwpLeosUserMIB.setLastUpdated('201207110000Z')
if mibBuilder.loadTexts:
wwpLeosUserMIB.setOrganization('Ciena, Inc')
if mibBuilder.loadTexts:
wwpLeosUserMIB.setContactInfo(' Mib Meister 115 North Sullivan Road Spokane Valley, WA 99037 USA Phone: +1 509 242 9000 Email: support@ciena.com')
if mibBuilder.loadTexts:
wwpLeosUserMIB.setDescription('This MIB module defines the generic managed objects for User Information on WWP devices.')
wwp_leos_user_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1))
wwp_leos_user = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1))
wwp_leos_user_mib_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 2))
wwp_leos_user_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 2, 0))
wwp_leos_user_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3))
wwp_leos_user_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3, 1))
wwp_leos_user_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 3, 2))
wwp_leos_user_auth_provider_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1))
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderTable.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderTable.setDescription('Table of UserAuth Providers.')
wwp_leos_user_auth_provider_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1)).setIndexNames((0, 'WWP-LEOS-USER-MIB', 'wwpLeosUserAuthProviderPriority'))
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderEntry.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderEntry.setDescription('An entry for each User Authorization Provider.')
wwp_leos_user_auth_provider_priority = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2)))
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderPriority.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderPriority.setDescription('The priority of this user authentication provider.')
wwp_leos_user_auth_provider_type = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('local', 2), ('radius', 3), ('tacacs', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderType.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderType.setDescription("The type/method of this user authentication provider. At least one entry must be a provider other than 'none' and any given provider may not be used twice. When a provider is changed to 'none', lower priority providers will have their priority increased to close the gap.")
wwp_leos_user_auth_provider_called = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 3), unsigned32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderCalled.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderCalled.setDescription('The number of calls to this user authentication provider. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwp_leos_user_auth_provider_success = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 4), unsigned32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderSuccess.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderSuccess.setDescription('The number of times this user authentication provider returned a Success response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwp_leos_user_auth_provider_failure = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 5), unsigned32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderFailure.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderFailure.setDescription('The number of times this user authentication provider returned a Failure response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwp_leos_user_auth_provider_skipped = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 6), unsigned32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderSkipped.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderSkipped.setDescription('The number of times this user authentication provider returned a Skip Me response. The counter is cleared automatically when AuthProviderType is changed or may be cleared manually.')
wwp_leos_user_auth_provider_scope = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('none', 0), ('serial', 1), ('remote', 2), ('all', 3))).clone('all')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderScope.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserAuthProviderScope.setDescription('The scope to be used for each authentication method.')
wwp_leos_user_who_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2))
if mibBuilder.loadTexts:
wwpLeosUserWhoTable.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoTable.setDescription('Table of logged in users.')
wwp_leos_user_who_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1)).setIndexNames((0, 'WWP-LEOS-USER-MIB', 'wwpLeosUserWhoPid'))
if mibBuilder.loadTexts:
wwpLeosUserWhoEntry.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoEntry.setDescription('An entry for each logged in user.')
wwp_leos_user_who_pid = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 1), unsigned32())
if mibBuilder.loadTexts:
wwpLeosUserWhoPid.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoPid.setDescription('The pid of the users shell process.')
wwp_leos_user_who_user = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
wwpLeosUserWhoUser.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoUser.setDescription('The username used during login authentication.')
wwp_leos_user_who_terminal = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
wwpLeosUserWhoTerminal.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoTerminal.setDescription('The terminal the user logged in from.')
wwp_leos_user_who_idle_time = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
wwpLeosUserWhoIdleTime.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoIdleTime.setDescription('The users idle time in minutes. This counter is reset to zero when ever the shell process detects input from the user.')
wwp_leos_user_who_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 2, 1, 5), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wwpLeosUserWhoStatus.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserWhoStatus.setDescription("Status of the users shell process. To kill a users shell, set this object to 'Destroy'.")
wwp_leos_user_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3))
if mibBuilder.loadTexts:
wwpLeosUserTable.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserTable.setDescription('Table of locally configured users.')
wwp_leos_user_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1)).setIndexNames((0, 'WWP-LEOS-USER-MIB', 'wwpLeosUserUid'))
if mibBuilder.loadTexts:
wwpLeosUserEntry.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserEntry.setDescription('An entry for each user in the local password file.')
wwp_leos_user_uid = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 1), unsigned32())
if mibBuilder.loadTexts:
wwpLeosUserUid.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserUid.setDescription('The numeric userid of the user. These numbers are generated by the device in order to making indexing the table easy, but they are not tied to specific user names during a reboot. When a new user is created, the userid must be an unused value.')
wwp_leos_user_name = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
wwpLeosUserName.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserName.setDescription('The name of the user.')
wwp_leos_user_password = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 34))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
wwpLeosUserPassword.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserPassword.setDescription('The users password in encrypted form. When setting this object you must set wwpLeosUserIsEncrypted at the same time in order to specify whether the password you are setting needs to be encrypted by the device or whether you have already encrypted it.')
wwp_leos_user_priv_level = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4))).clone(namedValues=named_values(('none', 0), ('limited', 1), ('admin', 2), ('super', 3), ('diag', 4)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
wwpLeosUserPrivLevel.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserPrivLevel.setDescription('The privilege level of the user.')
wwp_leos_user_is_default = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
wwpLeosUserIsDefault.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserIsDefault.setDescription('When this is set to True, the user is one of the default users created in the device at boot time.')
wwp_leos_user_is_encrypted = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 6), truth_value()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
wwpLeosUserIsEncrypted.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserIsEncrypted.setDescription('This will always be True on a Get as the password is always stored locally on the device in encrypted form. During a Set, it is False if you are sending wwpLeosUserPassword in the clear so the device can encrypt it, or True if wwpLeosUserPassword is already in encrypted MD5 form.')
wwp_leos_user_is_modified = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 7), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
wwpLeosUserIsModified.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserIsModified.setDescription('When this is set to True, the user is one of the default users created in the device, but one or more properties of the user account has been altered from the default values.')
wwp_leos_user_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 60, 39, 1, 1, 3, 1, 8), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
wwpLeosUserStatus.setStatus('current')
if mibBuilder.loadTexts:
wwpLeosUserStatus.setDescription('Use CreateAndGo to create a new user, Destroy to remove a user.')
mibBuilder.exportSymbols('WWP-LEOS-USER-MIB', wwpLeosUserWhoEntry=wwpLeosUserWhoEntry, wwpLeosUserPrivLevel=wwpLeosUserPrivLevel, wwpLeosUserMIBCompliances=wwpLeosUserMIBCompliances, wwpLeosUserTable=wwpLeosUserTable, wwpLeosUserIsModified=wwpLeosUserIsModified, wwpLeosUserAuthProviderEntry=wwpLeosUserAuthProviderEntry, wwpLeosUserMIBGroups=wwpLeosUserMIBGroups, wwpLeosUserMIBConformance=wwpLeosUserMIBConformance, wwpLeosUserMIBObjects=wwpLeosUserMIBObjects, wwpLeosUserWhoPid=wwpLeosUserWhoPid, wwpLeosUserUid=wwpLeosUserUid, wwpLeosUserStatus=wwpLeosUserStatus, wwpLeosUserWhoUser=wwpLeosUserWhoUser, wwpLeosUserAuthProviderTable=wwpLeosUserAuthProviderTable, wwpLeosUserMIB=wwpLeosUserMIB, wwpLeosUserName=wwpLeosUserName, wwpLeosUserAuthProviderSuccess=wwpLeosUserAuthProviderSuccess, wwpLeosUserAuthProviderCalled=wwpLeosUserAuthProviderCalled, wwpLeosUserAuthProviderPriority=wwpLeosUserAuthProviderPriority, wwpLeosUserIsDefault=wwpLeosUserIsDefault, wwpLeosUser=wwpLeosUser, wwpLeosUserWhoIdleTime=wwpLeosUserWhoIdleTime, wwpLeosUserPassword=wwpLeosUserPassword, wwpLeosUserWhoTerminal=wwpLeosUserWhoTerminal, wwpLeosUserMIBNotifications=wwpLeosUserMIBNotifications, wwpLeosUserWhoStatus=wwpLeosUserWhoStatus, wwpLeosUserAuthProviderScope=wwpLeosUserAuthProviderScope, wwpLeosUserEntry=wwpLeosUserEntry, wwpLeosUserAuthProviderFailure=wwpLeosUserAuthProviderFailure, wwpLeosUserAuthProviderType=wwpLeosUserAuthProviderType, wwpLeosUserAuthProviderSkipped=wwpLeosUserAuthProviderSkipped, PYSNMP_MODULE_ID=wwpLeosUserMIB, wwpLeosUserIsEncrypted=wwpLeosUserIsEncrypted, wwpLeosUserMIBNotificationPrefix=wwpLeosUserMIBNotificationPrefix, wwpLeosUserWhoTable=wwpLeosUserWhoTable) |
REGISTERED_PLATFORMS = {}
def register_class(cls):
REGISTERED_PLATFORMS[cls.BASENAME] = cls
return cls
| registered_platforms = {}
def register_class(cls):
REGISTERED_PLATFORMS[cls.BASENAME] = cls
return cls |
# sito eratostenesa
def sito(num):
x = 2
tab = [False, False] + [True for i in range(x, num+1)]
while x * x <= num:
if tab[x]:
for i in range(x*x, num+1, x):
tab[i] = False
x += 1
else:
x += 1
return tab
if __name__ == '__main__':
num = int(input('podaj liczbe: '))
tab = sito(num)
for x in range(len(tab)):
print(x, tab[x])
| def sito(num):
x = 2
tab = [False, False] + [True for i in range(x, num + 1)]
while x * x <= num:
if tab[x]:
for i in range(x * x, num + 1, x):
tab[i] = False
x += 1
else:
x += 1
return tab
if __name__ == '__main__':
num = int(input('podaj liczbe: '))
tab = sito(num)
for x in range(len(tab)):
print(x, tab[x]) |
# Copyright 2017 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.
load(
"@bazel_tools//tools/build_defs/repo:git.bzl",
"git_repository",
)
load(
"@bazel_gazelle//internal:go_repository.bzl",
_go_repository = "go_repository",
)
load(
"@bazel_gazelle//internal:go_repository_cache.bzl",
"go_repository_cache",
)
load(
"@bazel_gazelle//internal:go_repository_tools.bzl",
"go_repository_tools",
)
load(
"@bazel_gazelle//internal:go_repository_config.bzl",
"go_repository_config",
)
# Re-export go_repository . Users should get it from this file.
go_repository = _go_repository
def gazelle_dependencies(
go_sdk = "",
go_repository_default_config = "@//:WORKSPACE",
go_env = {}):
_maybe(
git_repository,
name = "bazel_skylib",
commit = "df3c9e2735f02a7fe8cd80db4db00fec8e13d25f", # `master` as of 2021-08-19
remote = "https://github.com/bazelbuild/bazel-skylib",
)
if go_sdk:
go_repository_cache(
name = "bazel_gazelle_go_repository_cache",
go_sdk_name = go_sdk,
go_env = go_env,
)
else:
go_sdk_info = {}
for name, r in native.existing_rules().items():
# match internal rule names but don't reference them directly.
# New rules may be added in the future, and they might be
# renamed (_go_download_sdk => go_download_sdk).
if name != "go_sdk" and ("go_" not in r["kind"] or "_sdk" not in r["kind"]):
continue
if r.get("goos", "") and r.get("goarch", ""):
platform = r["goos"] + "_" + r["goarch"]
else:
platform = "host"
go_sdk_info[name] = platform
go_repository_cache(
name = "bazel_gazelle_go_repository_cache",
go_sdk_info = go_sdk_info,
go_env = go_env,
)
go_repository_tools(
name = "bazel_gazelle_go_repository_tools",
go_cache = "@bazel_gazelle_go_repository_cache//:go.env",
)
go_repository_config(
name = "bazel_gazelle_go_repository_config",
config = go_repository_default_config,
)
_maybe(
go_repository,
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-20190523083050-ea95bdfd59fc",
)
_maybe(
go_repository,
name = "com_github_bazelbuild_buildtools",
importpath = "github.com/bazelbuild/buildtools",
sum = "h1:VMFMISXa1RypQNG0j4KVCbsUcrxFudkY/IvWzEJCyO8=",
version = "v0.0.0-20211007154642-8dd79e56e98e",
build_naming_convention = "go_default_library",
)
_maybe(
go_repository,
name = "com_github_bazelbuild_rules_go",
importpath = "github.com/bazelbuild/rules_go",
sum = "h1:SfxjyO/V68rVnzOHop92fB0gv/Aa75KNLAN0PMqXbIw=",
version = "v0.29.0",
)
_maybe(
go_repository,
name = "com_github_bmatcuk_doublestar",
importpath = "github.com/bmatcuk/doublestar",
sum = "h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=",
version = "v1.3.4",
)
_maybe(
go_repository,
name = "com_github_burntsushi_toml",
importpath = "github.com/BurntSushi/toml",
sum = "h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=",
version = "v0.3.1",
)
_maybe(
go_repository,
name = "com_github_census_instrumentation_opencensus_proto",
importpath = "github.com/census-instrumentation/opencensus-proto",
sum = "h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk=",
version = "v0.2.1",
)
_maybe(
go_repository,
name = "com_github_chzyer_logex",
importpath = "github.com/chzyer/logex",
sum = "h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=",
version = "v1.1.10",
)
_maybe(
go_repository,
name = "com_github_chzyer_readline",
importpath = "github.com/chzyer/readline",
sum = "h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=",
version = "v0.0.0-20180603132655-2972be24d48e",
)
_maybe(
go_repository,
name = "com_github_chzyer_test",
importpath = "github.com/chzyer/test",
sum = "h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=",
version = "v0.0.0-20180213035817-a1ea475d72b1",
)
_maybe(
go_repository,
name = "com_github_client9_misspell",
importpath = "github.com/client9/misspell",
sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=",
version = "v0.3.4",
)
_maybe(
go_repository,
name = "com_github_davecgh_go_spew",
importpath = "github.com/davecgh/go-spew",
sum = "h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=",
version = "v1.1.1",
)
_maybe(
go_repository,
name = "com_github_envoyproxy_go_control_plane",
importpath = "github.com/envoyproxy/go-control-plane",
sum = "h1:4cmBvAEBNJaGARUEs3/suWRyfyBfhf7I60WBZq+bv2w=",
version = "v0.9.1-0.20191026205805-5f8ba28d4473",
)
_maybe(
go_repository,
name = "com_github_envoyproxy_protoc_gen_validate",
importpath = "github.com/envoyproxy/protoc-gen-validate",
sum = "h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=",
version = "v0.1.0",
)
_maybe(
go_repository,
name = "com_github_fsnotify_fsnotify",
importpath = "github.com/fsnotify/fsnotify",
sum = "h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=",
version = "v1.5.1",
)
_maybe(
go_repository,
name = "com_github_golang_glog",
importpath = "github.com/golang/glog",
sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=",
version = "v0.0.0-20160126235308-23def4e6c14b",
)
_maybe(
go_repository,
name = "com_github_golang_mock",
importpath = "github.com/golang/mock",
sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=",
version = "v1.1.1",
)
_maybe(
go_repository,
name = "com_github_golang_protobuf",
importpath = "github.com/golang/protobuf",
sum = "h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=",
version = "v1.4.3",
)
_maybe(
go_repository,
name = "com_github_google_go_cmp",
importpath = "github.com/google/go-cmp",
sum = "h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=",
version = "v0.5.6",
)
_maybe(
go_repository,
name = "com_github_pelletier_go_toml",
importpath = "github.com/pelletier/go-toml",
sum = "h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM=",
version = "v1.9.4",
)
_maybe(
go_repository,
name = "com_github_pmezard_go_difflib",
importpath = "github.com/pmezard/go-difflib",
sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=",
version = "v1.0.0",
)
_maybe(
go_repository,
name = "com_github_prometheus_client_model",
importpath = "github.com/prometheus/client_model",
sum = "h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=",
version = "v0.0.0-20190812154241-14fe0d1b01d4",
)
_maybe(
go_repository,
name = "com_github_yuin_goldmark",
importpath = "github.com/yuin/goldmark",
sum = "h1:OtISOGfH6sOWa1/qXqqAiOIAO6Z5J3AEAE18WAq6BiQ=",
version = "v1.4.0",
)
_maybe(
go_repository,
name = "com_google_cloud_go",
importpath = "cloud.google.com/go",
sum = "h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ=",
version = "v0.26.0",
)
_maybe(
go_repository,
name = "in_gopkg_check_v1",
importpath = "gopkg.in/check.v1",
sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=",
version = "v0.0.0-20161208181325-20d25e280405",
)
_maybe(
go_repository,
name = "in_gopkg_yaml_v2",
importpath = "gopkg.in/yaml.v2",
sum = "h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=",
version = "v2.2.2",
)
_maybe(
go_repository,
name = "net_starlark_go",
importpath = "go.starlark.net",
sum = "h1:xwwDQW5We85NaTk2APgoN9202w/l0DVGp+GZMfsrh7s=",
version = "v0.0.0-20210223155950-e043a3d3c984",
)
_maybe(
go_repository,
name = "org_golang_google_appengine",
importpath = "google.golang.org/appengine",
sum = "h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=",
version = "v1.4.0",
)
_maybe(
go_repository,
name = "org_golang_google_genproto",
importpath = "google.golang.org/genproto",
sum = "h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=",
version = "v0.0.0-20200526211855-cb27e3aa2013",
)
_maybe(
go_repository,
name = "org_golang_google_grpc",
importpath = "google.golang.org/grpc",
sum = "h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg=",
version = "v1.27.0",
)
_maybe(
go_repository,
name = "org_golang_google_protobuf",
importpath = "google.golang.org/protobuf",
sum = "h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=",
version = "v1.25.0",
)
_maybe(
go_repository,
name = "org_golang_x_crypto",
importpath = "golang.org/x/crypto",
sum = "h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=",
version = "v0.0.0-20191011191535-87dc89f01550",
)
_maybe(
go_repository,
name = "org_golang_x_exp",
importpath = "golang.org/x/exp",
sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=",
version = "v0.0.0-20190121172915-509febef88a4",
)
_maybe(
go_repository,
name = "org_golang_x_lint",
importpath = "golang.org/x/lint",
sum = "h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=",
version = "v0.0.0-20190313153728-d0100b6bd8b3",
)
_maybe(
go_repository,
name = "org_golang_x_mod",
importpath = "golang.org/x/mod",
sum = "h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=",
version = "v0.5.1",
)
_maybe(
go_repository,
name = "org_golang_x_net",
importpath = "golang.org/x/net",
sum = "h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI=",
version = "v0.0.0-20210805182204-aaa1db679c0d",
)
_maybe(
go_repository,
name = "org_golang_x_oauth2",
importpath = "golang.org/x/oauth2",
sum = "h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=",
version = "v0.0.0-20180821212333-d2e6202438be",
)
_maybe(
go_repository,
name = "org_golang_x_sync",
importpath = "golang.org/x/sync",
sum = "h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=",
version = "v0.0.0-20210220032951-036812b2e83c",
)
_maybe(
go_repository,
name = "org_golang_x_sys",
importpath = "golang.org/x/sys",
sum = "h1:oN6lz7iLW/YC7un8pq+9bOLyXrprv2+DKfkJY+2LJJw=",
version = "v0.0.0-20211007075335-d3039528d8ac",
)
_maybe(
go_repository,
name = "org_golang_x_text",
importpath = "golang.org/x/text",
sum = "h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=",
version = "v0.3.6",
)
_maybe(
go_repository,
name = "org_golang_x_tools",
importpath = "golang.org/x/tools",
sum = "h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=",
version = "v0.1.7",
)
_maybe(
go_repository,
name = "org_golang_x_xerrors",
importpath = "golang.org/x/xerrors",
sum = "h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=",
version = "v0.0.0-20200804184101-5ec99f83aff1",
)
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name = name, **kwargs)
| load('@bazel_tools//tools/build_defs/repo:git.bzl', 'git_repository')
load('@bazel_gazelle//internal:go_repository.bzl', _go_repository='go_repository')
load('@bazel_gazelle//internal:go_repository_cache.bzl', 'go_repository_cache')
load('@bazel_gazelle//internal:go_repository_tools.bzl', 'go_repository_tools')
load('@bazel_gazelle//internal:go_repository_config.bzl', 'go_repository_config')
go_repository = _go_repository
def gazelle_dependencies(go_sdk='', go_repository_default_config='@//:WORKSPACE', go_env={}):
_maybe(git_repository, name='bazel_skylib', commit='df3c9e2735f02a7fe8cd80db4db00fec8e13d25f', remote='https://github.com/bazelbuild/bazel-skylib')
if go_sdk:
go_repository_cache(name='bazel_gazelle_go_repository_cache', go_sdk_name=go_sdk, go_env=go_env)
else:
go_sdk_info = {}
for (name, r) in native.existing_rules().items():
if name != 'go_sdk' and ('go_' not in r['kind'] or '_sdk' not in r['kind']):
continue
if r.get('goos', '') and r.get('goarch', ''):
platform = r['goos'] + '_' + r['goarch']
else:
platform = 'host'
go_sdk_info[name] = platform
go_repository_cache(name='bazel_gazelle_go_repository_cache', go_sdk_info=go_sdk_info, go_env=go_env)
go_repository_tools(name='bazel_gazelle_go_repository_tools', go_cache='@bazel_gazelle_go_repository_cache//:go.env')
go_repository_config(name='bazel_gazelle_go_repository_config', config=go_repository_default_config)
_maybe(go_repository, name='co_honnef_go_tools', importpath='honnef.co/go/tools', sum='h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=', version='v0.0.0-20190523083050-ea95bdfd59fc')
_maybe(go_repository, name='com_github_bazelbuild_buildtools', importpath='github.com/bazelbuild/buildtools', sum='h1:VMFMISXa1RypQNG0j4KVCbsUcrxFudkY/IvWzEJCyO8=', version='v0.0.0-20211007154642-8dd79e56e98e', build_naming_convention='go_default_library')
_maybe(go_repository, name='com_github_bazelbuild_rules_go', importpath='github.com/bazelbuild/rules_go', sum='h1:SfxjyO/V68rVnzOHop92fB0gv/Aa75KNLAN0PMqXbIw=', version='v0.29.0')
_maybe(go_repository, name='com_github_bmatcuk_doublestar', importpath='github.com/bmatcuk/doublestar', sum='h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=', version='v1.3.4')
_maybe(go_repository, name='com_github_burntsushi_toml', importpath='github.com/BurntSushi/toml', sum='h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=', version='v0.3.1')
_maybe(go_repository, name='com_github_census_instrumentation_opencensus_proto', importpath='github.com/census-instrumentation/opencensus-proto', sum='h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk=', version='v0.2.1')
_maybe(go_repository, name='com_github_chzyer_logex', importpath='github.com/chzyer/logex', sum='h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=', version='v1.1.10')
_maybe(go_repository, name='com_github_chzyer_readline', importpath='github.com/chzyer/readline', sum='h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8=', version='v0.0.0-20180603132655-2972be24d48e')
_maybe(go_repository, name='com_github_chzyer_test', importpath='github.com/chzyer/test', sum='h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=', version='v0.0.0-20180213035817-a1ea475d72b1')
_maybe(go_repository, name='com_github_client9_misspell', importpath='github.com/client9/misspell', sum='h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=', version='v0.3.4')
_maybe(go_repository, name='com_github_davecgh_go_spew', importpath='github.com/davecgh/go-spew', sum='h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=', version='v1.1.1')
_maybe(go_repository, name='com_github_envoyproxy_go_control_plane', importpath='github.com/envoyproxy/go-control-plane', sum='h1:4cmBvAEBNJaGARUEs3/suWRyfyBfhf7I60WBZq+bv2w=', version='v0.9.1-0.20191026205805-5f8ba28d4473')
_maybe(go_repository, name='com_github_envoyproxy_protoc_gen_validate', importpath='github.com/envoyproxy/protoc-gen-validate', sum='h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=', version='v0.1.0')
_maybe(go_repository, name='com_github_fsnotify_fsnotify', importpath='github.com/fsnotify/fsnotify', sum='h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=', version='v1.5.1')
_maybe(go_repository, name='com_github_golang_glog', importpath='github.com/golang/glog', sum='h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=', version='v0.0.0-20160126235308-23def4e6c14b')
_maybe(go_repository, name='com_github_golang_mock', importpath='github.com/golang/mock', sum='h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=', version='v1.1.1')
_maybe(go_repository, name='com_github_golang_protobuf', importpath='github.com/golang/protobuf', sum='h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=', version='v1.4.3')
_maybe(go_repository, name='com_github_google_go_cmp', importpath='github.com/google/go-cmp', sum='h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=', version='v0.5.6')
_maybe(go_repository, name='com_github_pelletier_go_toml', importpath='github.com/pelletier/go-toml', sum='h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM=', version='v1.9.4')
_maybe(go_repository, name='com_github_pmezard_go_difflib', importpath='github.com/pmezard/go-difflib', sum='h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=', version='v1.0.0')
_maybe(go_repository, name='com_github_prometheus_client_model', importpath='github.com/prometheus/client_model', sum='h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=', version='v0.0.0-20190812154241-14fe0d1b01d4')
_maybe(go_repository, name='com_github_yuin_goldmark', importpath='github.com/yuin/goldmark', sum='h1:OtISOGfH6sOWa1/qXqqAiOIAO6Z5J3AEAE18WAq6BiQ=', version='v1.4.0')
_maybe(go_repository, name='com_google_cloud_go', importpath='cloud.google.com/go', sum='h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ=', version='v0.26.0')
_maybe(go_repository, name='in_gopkg_check_v1', importpath='gopkg.in/check.v1', sum='h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=', version='v0.0.0-20161208181325-20d25e280405')
_maybe(go_repository, name='in_gopkg_yaml_v2', importpath='gopkg.in/yaml.v2', sum='h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=', version='v2.2.2')
_maybe(go_repository, name='net_starlark_go', importpath='go.starlark.net', sum='h1:xwwDQW5We85NaTk2APgoN9202w/l0DVGp+GZMfsrh7s=', version='v0.0.0-20210223155950-e043a3d3c984')
_maybe(go_repository, name='org_golang_google_appengine', importpath='google.golang.org/appengine', sum='h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=', version='v1.4.0')
_maybe(go_repository, name='org_golang_google_genproto', importpath='google.golang.org/genproto', sum='h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=', version='v0.0.0-20200526211855-cb27e3aa2013')
_maybe(go_repository, name='org_golang_google_grpc', importpath='google.golang.org/grpc', sum='h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg=', version='v1.27.0')
_maybe(go_repository, name='org_golang_google_protobuf', importpath='google.golang.org/protobuf', sum='h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=', version='v1.25.0')
_maybe(go_repository, name='org_golang_x_crypto', importpath='golang.org/x/crypto', sum='h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=', version='v0.0.0-20191011191535-87dc89f01550')
_maybe(go_repository, name='org_golang_x_exp', importpath='golang.org/x/exp', sum='h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=', version='v0.0.0-20190121172915-509febef88a4')
_maybe(go_repository, name='org_golang_x_lint', importpath='golang.org/x/lint', sum='h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=', version='v0.0.0-20190313153728-d0100b6bd8b3')
_maybe(go_repository, name='org_golang_x_mod', importpath='golang.org/x/mod', sum='h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=', version='v0.5.1')
_maybe(go_repository, name='org_golang_x_net', importpath='golang.org/x/net', sum='h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI=', version='v0.0.0-20210805182204-aaa1db679c0d')
_maybe(go_repository, name='org_golang_x_oauth2', importpath='golang.org/x/oauth2', sum='h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=', version='v0.0.0-20180821212333-d2e6202438be')
_maybe(go_repository, name='org_golang_x_sync', importpath='golang.org/x/sync', sum='h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=', version='v0.0.0-20210220032951-036812b2e83c')
_maybe(go_repository, name='org_golang_x_sys', importpath='golang.org/x/sys', sum='h1:oN6lz7iLW/YC7un8pq+9bOLyXrprv2+DKfkJY+2LJJw=', version='v0.0.0-20211007075335-d3039528d8ac')
_maybe(go_repository, name='org_golang_x_text', importpath='golang.org/x/text', sum='h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=', version='v0.3.6')
_maybe(go_repository, name='org_golang_x_tools', importpath='golang.org/x/tools', sum='h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=', version='v0.1.7')
_maybe(go_repository, name='org_golang_x_xerrors', importpath='golang.org/x/xerrors', sum='h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=', version='v0.0.0-20200804184101-5ec99f83aff1')
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name=name, **kwargs) |
def user_information_helper(data) -> dict:
return {
"id": str(data["_id"]),
"name": data["timePredict"],
"email": data["email"],
"phoneNumber": data["phoneNumber"],
"weight": data["weight"],
"createAt": str(data["createAt"]),
"updateAt": str(data["updateAt"]),
}
def user_helper(data) -> dict:
return {
"id": str(data["_id"]),
"username": data["username"],
"password": data["password"],
"hashed_password": data["password"],
"role": data["role"],
"createAt": str(data["createAt"]),
"updateAt": str(data["updateAt"]),
}
| def user_information_helper(data) -> dict:
return {'id': str(data['_id']), 'name': data['timePredict'], 'email': data['email'], 'phoneNumber': data['phoneNumber'], 'weight': data['weight'], 'createAt': str(data['createAt']), 'updateAt': str(data['updateAt'])}
def user_helper(data) -> dict:
return {'id': str(data['_id']), 'username': data['username'], 'password': data['password'], 'hashed_password': data['password'], 'role': data['role'], 'createAt': str(data['createAt']), 'updateAt': str(data['updateAt'])} |
def odd_and_even_sums(numbers):
even_sum = 0
odd_sum = 0
for digit in numbers:
if int(digit) % 2 == 0:
even_sum += int(digit)
else:
odd_sum += int(digit)
return f"Odd sum = {odd_sum}, Even sum = {even_sum}"
numbers = input()
answer = odd_and_even_sums(numbers)
print(answer) | def odd_and_even_sums(numbers):
even_sum = 0
odd_sum = 0
for digit in numbers:
if int(digit) % 2 == 0:
even_sum += int(digit)
else:
odd_sum += int(digit)
return f'Odd sum = {odd_sum}, Even sum = {even_sum}'
numbers = input()
answer = odd_and_even_sums(numbers)
print(answer) |
def selection(x):
n = len(x)
for i in range(0, n-1):
for j in range(i+1, n):
if x[i]>x[j]:
x[i], x[j] = x[j], x[i]
print('''{} - {} - {}'''.format(i, j, x))
return x
x = [2, 7, 8, 1, 3, 6]
print(selection(x)) | def selection(x):
n = len(x)
for i in range(0, n - 1):
for j in range(i + 1, n):
if x[i] > x[j]:
(x[i], x[j]) = (x[j], x[i])
print('{} - {} - {}'.format(i, j, x))
return x
x = [2, 7, 8, 1, 3, 6]
print(selection(x)) |
"""
spider.supervised_learning sub-package
__init__.py
@author: zeyu sun
Supervised Learning primitives
difines the model index
"""
__all__ = [
"OWLRegression",
]
| """
spider.supervised_learning sub-package
__init__.py
@author: zeyu sun
Supervised Learning primitives
difines the model index
"""
__all__ = ['OWLRegression'] |
class Solution:
def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
ans = 0
def isUnival(root: Optional[TreeNode], val: int) -> bool:
nonlocal ans
if not root:
return True
if isUnival(root.left, root.val) & isUnival(root.right, root.val):
ans += 1
return root.val == val
return False
isUnival(root, math.inf)
return ans
| class Solution:
def count_unival_subtrees(self, root: Optional[TreeNode]) -> int:
ans = 0
def is_unival(root: Optional[TreeNode], val: int) -> bool:
nonlocal ans
if not root:
return True
if is_unival(root.left, root.val) & is_unival(root.right, root.val):
ans += 1
return root.val == val
return False
is_unival(root, math.inf)
return ans |
def subsitute_object(file, obj) -> str:
"""Subsitute fields of dictionatry into a copy of a file.
This function will seek out all the keys in the form of {key}
within the file, then it will subsitute the value into them.
Returns a string, does not create nor edit files
"""
template_file = open(file)
template = template_file.read()
template_file.close()
for field in obj.keys():
if template.find('{' + field + '}') == -1:
continue
# Strings are immutable
template = template.replace('{' + field + '}', obj[field])
return template | def subsitute_object(file, obj) -> str:
"""Subsitute fields of dictionatry into a copy of a file.
This function will seek out all the keys in the form of {key}
within the file, then it will subsitute the value into them.
Returns a string, does not create nor edit files
"""
template_file = open(file)
template = template_file.read()
template_file.close()
for field in obj.keys():
if template.find('{' + field + '}') == -1:
continue
template = template.replace('{' + field + '}', obj[field])
return template |
POSITION_IMAGE_LEFT = 'image-left'
POSITION_IMAGE_RIGHT = 'image-right'
POSITION_CHOICES = (
(POSITION_IMAGE_LEFT, 'Image Left'),
(POSITION_IMAGE_RIGHT, 'Image Right'),
)
| position_image_left = 'image-left'
position_image_right = 'image-right'
position_choices = ((POSITION_IMAGE_LEFT, 'Image Left'), (POSITION_IMAGE_RIGHT, 'Image Right')) |
def setup():
size(1000, 500)
smooth()
strokeWeight(30)
stroke(100)
def draw():
background(0)
line(frameCount, 300,100 + frameCount,400)
line(100 + frameCount, 300, frameCount, 400)
| def setup():
size(1000, 500)
smooth()
stroke_weight(30)
stroke(100)
def draw():
background(0)
line(frameCount, 300, 100 + frameCount, 400)
line(100 + frameCount, 300, frameCount, 400) |
# -*- encoding=utf-8 -*-
# Copyright 2016 David Cary; licensed under the Apache License, Version 2.0
"""
Unit tests
"""
| """
Unit tests
""" |
class Customer:
def __init__(self, name, age, phone_no):
self.name = name
self.age = age
self.phone_no = phone_no
def purchase(self, payment):
if payment.type == "card":
print("Paying by card")
elif payment.type == "e-wallet":
print("Paying by wallet")
else:
print("Paying by cash")
class Payment:
def __init__(self, type):
self.type = type
payment1 = Payment("card")
c = Customer("Jack", 23, 1234)
c.purchase(payment1)
| class Customer:
def __init__(self, name, age, phone_no):
self.name = name
self.age = age
self.phone_no = phone_no
def purchase(self, payment):
if payment.type == 'card':
print('Paying by card')
elif payment.type == 'e-wallet':
print('Paying by wallet')
else:
print('Paying by cash')
class Payment:
def __init__(self, type):
self.type = type
payment1 = payment('card')
c = customer('Jack', 23, 1234)
c.purchase(payment1) |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Event beans for Pelix.
:author: Thomas Calmant
:copyright: Copyright 2020, Thomas Calmant
:license: Apache License 2.0
:version: 1.0.1
..
Copyright 2020 Thomas Calmant
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.
"""
# Module version
__version_info__ = (1, 0, 1)
__version__ = ".".join(str(x) for x in __version_info__)
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
class BundleEvent(object):
"""
Represents a bundle event
"""
__slots__ = ("__bundle", "__kind")
INSTALLED = 1
"""The bundle has been installed."""
STARTED = 2
"""The bundle has been started."""
STARTING = 128
"""The bundle is about to be activated."""
STOPPED = 4
"""
The bundle has been stopped. All of its services have been unregistered.
"""
STOPPING = 256
"""The bundle is about to deactivated."""
STOPPING_PRECLEAN = 512
"""
The bundle has been deactivated, but some of its services may still remain.
"""
UNINSTALLED = 16
"""The bundle has been uninstalled."""
UPDATED = 8
"""The bundle has been updated. (called after STARTED) """
UPDATE_BEGIN = 32
""" The bundle will be updated (called before STOPPING) """
UPDATE_FAILED = 64
""" The bundle update has failed. The bundle might be in RESOLVED state """
def __init__(self, kind, bundle):
"""
Sets up the event
"""
self.__kind = kind
self.__bundle = bundle
def __str__(self):
"""
String representation
"""
return "BundleEvent({0}, {1})".format(self.__kind, self.__bundle)
def get_bundle(self):
"""
Retrieves the modified bundle
"""
return self.__bundle
def get_kind(self):
"""
Retrieves the kind of event
"""
return self.__kind
# ------------------------------------------------------------------------------
class ServiceEvent(object):
"""
Represents a service event
"""
__slots__ = ("__kind", "__reference", "__previous_properties")
REGISTERED = 1
""" This service has been registered """
MODIFIED = 2
""" The properties of a registered service have been modified """
UNREGISTERING = 4
""" This service is in the process of being unregistered """
MODIFIED_ENDMATCH = 8
"""
The properties of a registered service have been modified and the new
properties no longer match the listener's filter
"""
def __init__(self, kind, reference, previous_properties=None):
"""
Sets up the event
:param kind: Kind of event
:param reference: Reference to the modified service
:param previous_properties: Previous service properties (for MODIFIED
and MODIFIED_ENDMATCH events)
"""
self.__kind = kind
self.__reference = reference
if previous_properties is not None and not isinstance(
previous_properties, dict
):
# Accept None or dict() only
previous_properties = {}
self.__previous_properties = previous_properties
def __str__(self):
"""
String representation
"""
return "ServiceEvent({0}, {1})".format(self.__kind, self.__reference)
def get_previous_properties(self):
"""
Returns the previous values of the service properties, meaningless if
the the event is not MODIFIED nor MODIFIED_ENDMATCH.
:return: The previous properties of the service
"""
return self.__previous_properties
def get_service_reference(self):
"""
Returns the reference to the service associated to this event
:return: A ServiceReference object
"""
return self.__reference
def get_kind(self):
"""
Returns the kind of service event (see the constants)
:return: the kind of service event
"""
return self.__kind
| """
Event beans for Pelix.
:author: Thomas Calmant
:copyright: Copyright 2020, Thomas Calmant
:license: Apache License 2.0
:version: 1.0.1
..
Copyright 2020 Thomas Calmant
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.
"""
__version_info__ = (1, 0, 1)
__version__ = '.'.join((str(x) for x in __version_info__))
__docformat__ = 'restructuredtext en'
class Bundleevent(object):
"""
Represents a bundle event
"""
__slots__ = ('__bundle', '__kind')
installed = 1
'The bundle has been installed.'
started = 2
'The bundle has been started.'
starting = 128
'The bundle is about to be activated.'
stopped = 4
'\n The bundle has been stopped. All of its services have been unregistered.\n '
stopping = 256
'The bundle is about to deactivated.'
stopping_preclean = 512
'\n The bundle has been deactivated, but some of its services may still remain.\n '
uninstalled = 16
'The bundle has been uninstalled.'
updated = 8
'The bundle has been updated. (called after STARTED) '
update_begin = 32
' The bundle will be updated (called before STOPPING) '
update_failed = 64
' The bundle update has failed. The bundle might be in RESOLVED state '
def __init__(self, kind, bundle):
"""
Sets up the event
"""
self.__kind = kind
self.__bundle = bundle
def __str__(self):
"""
String representation
"""
return 'BundleEvent({0}, {1})'.format(self.__kind, self.__bundle)
def get_bundle(self):
"""
Retrieves the modified bundle
"""
return self.__bundle
def get_kind(self):
"""
Retrieves the kind of event
"""
return self.__kind
class Serviceevent(object):
"""
Represents a service event
"""
__slots__ = ('__kind', '__reference', '__previous_properties')
registered = 1
' This service has been registered '
modified = 2
' The properties of a registered service have been modified '
unregistering = 4
' This service is in the process of being unregistered '
modified_endmatch = 8
"\n The properties of a registered service have been modified and the new\n properties no longer match the listener's filter\n "
def __init__(self, kind, reference, previous_properties=None):
"""
Sets up the event
:param kind: Kind of event
:param reference: Reference to the modified service
:param previous_properties: Previous service properties (for MODIFIED
and MODIFIED_ENDMATCH events)
"""
self.__kind = kind
self.__reference = reference
if previous_properties is not None and (not isinstance(previous_properties, dict)):
previous_properties = {}
self.__previous_properties = previous_properties
def __str__(self):
"""
String representation
"""
return 'ServiceEvent({0}, {1})'.format(self.__kind, self.__reference)
def get_previous_properties(self):
"""
Returns the previous values of the service properties, meaningless if
the the event is not MODIFIED nor MODIFIED_ENDMATCH.
:return: The previous properties of the service
"""
return self.__previous_properties
def get_service_reference(self):
"""
Returns the reference to the service associated to this event
:return: A ServiceReference object
"""
return self.__reference
def get_kind(self):
"""
Returns the kind of service event (see the constants)
:return: the kind of service event
"""
return self.__kind |
'''
YTV.su Playlist Downloader Plugin configuration file
'''
# Channels url
url = 'http://ytv.su/tv/channels'
| """
YTV.su Playlist Downloader Plugin configuration file
"""
url = 'http://ytv.su/tv/channels' |
""" constant values for the pygaro module """
ENDPOINT_RFID = "rest/chargebox/rfid"
DEFAULT_PORT = 2222
# api methods currently supported
METHOD_GET = "GET"
METHOD_POST = "POST"
METHOD_DELETE = "DELETE"
# status code
HTTP_OK = 200
| """ constant values for the pygaro module """
endpoint_rfid = 'rest/chargebox/rfid'
default_port = 2222
method_get = 'GET'
method_post = 'POST'
method_delete = 'DELETE'
http_ok = 200 |
add2 = addN(2)
add2
add2(7)
9
| add2 = add_n(2)
add2
add2(7)
9 |
#!/usr/bin/env python
def times(x, y):
return x * y
z = times(2, 3)
print("2 times 3 is " + str(z));
| def times(x, y):
return x * y
z = times(2, 3)
print('2 times 3 is ' + str(z)) |
# Copyright 2020 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.
"""Actions for supporting exported symbols in link actions."""
load(
"@build_bazel_rules_apple//apple/internal:linking_support.bzl",
"linking_support",
)
def _exported_symbols_lists_impl(ctx):
return [
linking_support.exported_symbols_list_objc_provider(ctx.files.lists),
]
exported_symbols_lists = rule(
implementation = _exported_symbols_lists_impl,
attrs = {
"lists": attr.label_list(
allow_empty = False,
allow_files = True,
mandatory = True,
doc = "The list of files that contain exported symbols.",
),
},
fragments = ["apple", "objc"],
)
| """Actions for supporting exported symbols in link actions."""
load('@build_bazel_rules_apple//apple/internal:linking_support.bzl', 'linking_support')
def _exported_symbols_lists_impl(ctx):
return [linking_support.exported_symbols_list_objc_provider(ctx.files.lists)]
exported_symbols_lists = rule(implementation=_exported_symbols_lists_impl, attrs={'lists': attr.label_list(allow_empty=False, allow_files=True, mandatory=True, doc='The list of files that contain exported symbols.')}, fragments=['apple', 'objc']) |
# Scrapy settings for chuansong project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = "chuansong"
SPIDER_MODULES = ['chuansong.spiders']
NEWSPIDER_MODULE = 'chuansong.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = [u'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0']
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'chuansong.middlewares.MyCustomSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'chuansong.middlewares.MyCustomDownloaderMiddleware': 543,
#}
#DOWNLOADER_MIDDLEWARES = {
# 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware':None,
# 'chuansong.middlewares.useragent_middleware.RotateUserAgentMiddleware':400,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'chuansong.pipelines.JsonWriterPipeline': 0,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# DEPTH_LIMIT = 2
IMAGES_URLS_FIELD = 'image_urls'
IMAGES_RESULT_FIELD = 'images'
IMAGES_STORE = "images"
COUNT_DATA = True
# mongo pipeline settings
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'scrapy'
MONGODB_DOCNAME = 'chuansong'
# elasticsearch pipeline settings
ELASTICSEARCH_SERVER = 'http://127.0.0.1'
ELASTICSEARCH_PORT = 9200
ELASTICSEARCH_INDEX = 'scrapy'
ELASTICSEARCH_TYPE = 'items'
ELASTICSEARCH_UNIQ_KEY = 'url'
| bot_name = 'chuansong'
spider_modules = ['chuansong.spiders']
newspider_module = 'chuansong.spiders'
user_agent = [u'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0']
download_delay = 3
item_pipelines = {'chuansong.pipelines.JsonWriterPipeline': 0}
images_urls_field = 'image_urls'
images_result_field = 'images'
images_store = 'images'
count_data = True
mongodb_host = '127.0.0.1'
mongodb_port = 27017
mongodb_dbname = 'scrapy'
mongodb_docname = 'chuansong'
elasticsearch_server = 'http://127.0.0.1'
elasticsearch_port = 9200
elasticsearch_index = 'scrapy'
elasticsearch_type = 'items'
elasticsearch_uniq_key = 'url' |
a={}
def fib(n):
if n==0:
return 0
if n==1:
return 1
if n in a:
return a[n]
else:
ans=fib(n-1)+fib(n-2)
d[n]=ans
return ans
print(fib(int(input('Enter n : ')))) | a = {}
def fib(n):
if n == 0:
return 0
if n == 1:
return 1
if n in a:
return a[n]
else:
ans = fib(n - 1) + fib(n - 2)
d[n] = ans
return ans
print(fib(int(input('Enter n : ')))) |
# This is a placeholder version of this file; in an actual installation, it
# is generated from scratch by the installer. The constants defined here
# are exposed by constants.py
DEFAULT_DATABASE_HOST = None # XXX
DEFAULT_PROXYCACHE_HOST = None # XXX
MASTER_MANAGER_HOST = None # XXX - used to define BUNDLES_SRC_HOST for worker_manager below
DEVPAYMENTS_API_KEY = None
| default_database_host = None
default_proxycache_host = None
master_manager_host = None
devpayments_api_key = None |
class Solution:
def maxChunksToSorted(self, arr: [int]) -> int:
stack = []
for num in arr:
if stack and num < stack[-1]:
head = stack.pop()
while stack and num < stack[-1]: stack.pop()
stack.append(head)
else: stack.append(num)
return len(stack)
s = Solution()
print(s.maxChunksToSorted([1,1,2,1,1,3,4,5,3,6]))
| class Solution:
def max_chunks_to_sorted(self, arr: [int]) -> int:
stack = []
for num in arr:
if stack and num < stack[-1]:
head = stack.pop()
while stack and num < stack[-1]:
stack.pop()
stack.append(head)
else:
stack.append(num)
return len(stack)
s = solution()
print(s.maxChunksToSorted([1, 1, 2, 1, 1, 3, 4, 5, 3, 6])) |
""" Asked by: Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
"""
| """ Asked by: Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
""" |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class DescribeDevicePageVo(object):
def __init__(self, uuid=None, instanceId=None, deviceId=None, displayName=None, deviceType=None, deviceState=None, omId=None, deviceFilePath=None, omName=None, createTime=None, userPin=None, parentUuid=None, parentName=None, lastConnectTime=None):
"""
:param uuid: (Optional)
:param instanceId: (Optional)
:param deviceId: (Optional)
:param displayName: (Optional)
:param deviceType: (Optional)
:param deviceState: (Optional)
:param omId: (Optional)
:param deviceFilePath: (Optional)
:param omName: (Optional)
:param createTime: (Optional)
:param userPin: (Optional)
:param parentUuid: (Optional)
:param parentName: (Optional)
:param lastConnectTime: (Optional)
"""
self.uuid = uuid
self.instanceId = instanceId
self.deviceId = deviceId
self.displayName = displayName
self.deviceType = deviceType
self.deviceState = deviceState
self.omId = omId
self.deviceFilePath = deviceFilePath
self.omName = omName
self.createTime = createTime
self.userPin = userPin
self.parentUuid = parentUuid
self.parentName = parentName
self.lastConnectTime = lastConnectTime
| class Describedevicepagevo(object):
def __init__(self, uuid=None, instanceId=None, deviceId=None, displayName=None, deviceType=None, deviceState=None, omId=None, deviceFilePath=None, omName=None, createTime=None, userPin=None, parentUuid=None, parentName=None, lastConnectTime=None):
"""
:param uuid: (Optional)
:param instanceId: (Optional)
:param deviceId: (Optional)
:param displayName: (Optional)
:param deviceType: (Optional)
:param deviceState: (Optional)
:param omId: (Optional)
:param deviceFilePath: (Optional)
:param omName: (Optional)
:param createTime: (Optional)
:param userPin: (Optional)
:param parentUuid: (Optional)
:param parentName: (Optional)
:param lastConnectTime: (Optional)
"""
self.uuid = uuid
self.instanceId = instanceId
self.deviceId = deviceId
self.displayName = displayName
self.deviceType = deviceType
self.deviceState = deviceState
self.omId = omId
self.deviceFilePath = deviceFilePath
self.omName = omName
self.createTime = createTime
self.userPin = userPin
self.parentUuid = parentUuid
self.parentName = parentName
self.lastConnectTime = lastConnectTime |
def insertion_sort(arr):
"""Performs an Insertion Sort on the array arr."""
for i in range(1, len(arr)):
key = arr[i]
j = i-1
# 2 5
while key < arr[j] and j >= 0:
# swap(key, j, arr)
# 6 5
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
def swap(i, j, arr):
arr[i], arr[j] = arr[j], arr[i]
if __name__ == '__main__':
print('### Insertion Sort ###')
answer = insertion_sort([5, 2, 3, 1, 6])
print(answer) | def insertion_sort(arr):
"""Performs an Insertion Sort on the array arr."""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while key < arr[j] and j >= 0:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def swap(i, j, arr):
(arr[i], arr[j]) = (arr[j], arr[i])
if __name__ == '__main__':
print('### Insertion Sort ###')
answer = insertion_sort([5, 2, 3, 1, 6])
print(answer) |
def water_depth_press(wd: "h_l", rho_water, g=9.81) -> "p_e":
p_e = rho_water * g * abs(wd)
return p_e
| def water_depth_press(wd: 'h_l', rho_water, g=9.81) -> 'p_e':
p_e = rho_water * g * abs(wd)
return p_e |
def aumentar(au=0, taxa=0, show=False):
au = au + ((au * taxa) / 100)
if show == True:
au = moeda(au)
return au
def diminuir(di=0, taxa=0, show=False):
di = di - ((di * taxa) / 100)
if show == True:
di = moeda(di)
return di
def dobro(do=0, show=False):
do *= 2
if show == True:
do = moeda(do)
return do
def metade(me=0, show=False):
me /= 2
if show == True:
me = moeda(me)
return me
def moeda(preco=0, moeda= 'R$'):
formatado = f'{preco:.2f}{moeda}'.replace('.', ',')
return formatado
| def aumentar(au=0, taxa=0, show=False):
au = au + au * taxa / 100
if show == True:
au = moeda(au)
return au
def diminuir(di=0, taxa=0, show=False):
di = di - di * taxa / 100
if show == True:
di = moeda(di)
return di
def dobro(do=0, show=False):
do *= 2
if show == True:
do = moeda(do)
return do
def metade(me=0, show=False):
me /= 2
if show == True:
me = moeda(me)
return me
def moeda(preco=0, moeda='R$'):
formatado = f'{preco:.2f}{moeda}'.replace('.', ',')
return formatado |
"""
Sponge Knowledge Base
Test - KB from an archive file
"""
class Action2FromArchive(Action):
def onCall(self, arg):
return arg.lower()
| """
Sponge Knowledge Base
Test - KB from an archive file
"""
class Action2Fromarchive(Action):
def on_call(self, arg):
return arg.lower() |
class Card(object):
def __init__(self):
self.fields = []
for i in range (0, 5):
self.fields.append([])
for j in range(0, 5):
self.fields[i].append(Field())
class Field(object):
def __init__(self):
self.number = -1
self.marked = False
def check_for_bingo(card):
for i in range(0, 5):
bingo = True
for j in range(0, 5):
bingo &= card.fields[i][j].marked
if bingo:
return True
for j in range(0, 5):
bingo = True
for i in range(0, 5):
bingo &= card.fields[i][j].marked
if bingo:
return True
cards = []
calls = []
cards = []
with open('input.txt', 'r+') as file:
lines = file.readlines()
calls = list(map(lambda i: int(i), str.split(lines[0], ",")))
c = 2
while c < len(lines):
card = Card()
for i in range(0, 5):
for j in range(0, 5):
card.fields[i][j].number = int(lines[c+i][0+j*3:3+j*3])
cards.append(card)
c += 6
for call in calls:
for card in cards:
for row in card.fields:
for field in row:
if field.number == call:
field.marked = True
if check_for_bingo(card):
s = 0
for row in card.fields:
for field in row:
if not field.marked:
s += field.number
print(s * call)
quit() | class Card(object):
def __init__(self):
self.fields = []
for i in range(0, 5):
self.fields.append([])
for j in range(0, 5):
self.fields[i].append(field())
class Field(object):
def __init__(self):
self.number = -1
self.marked = False
def check_for_bingo(card):
for i in range(0, 5):
bingo = True
for j in range(0, 5):
bingo &= card.fields[i][j].marked
if bingo:
return True
for j in range(0, 5):
bingo = True
for i in range(0, 5):
bingo &= card.fields[i][j].marked
if bingo:
return True
cards = []
calls = []
cards = []
with open('input.txt', 'r+') as file:
lines = file.readlines()
calls = list(map(lambda i: int(i), str.split(lines[0], ',')))
c = 2
while c < len(lines):
card = card()
for i in range(0, 5):
for j in range(0, 5):
card.fields[i][j].number = int(lines[c + i][0 + j * 3:3 + j * 3])
cards.append(card)
c += 6
for call in calls:
for card in cards:
for row in card.fields:
for field in row:
if field.number == call:
field.marked = True
if check_for_bingo(card):
s = 0
for row in card.fields:
for field in row:
if not field.marked:
s += field.number
print(s * call)
quit() |
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) - sum(cost) < 0: return -1
tank = start = total = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
total += tank
tank = 0
return start if tank + total >= 0 else -1
| class Solution:
def can_complete_circuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) - sum(cost) < 0:
return -1
tank = start = total = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
total += tank
tank = 0
return start if tank + total >= 0 else -1 |
# -*- coding: utf-8 -*-
'''
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
'''
name = 'VirtualPrivateZone' # custom resource name
sdk = 'vra' # imported SDK at common directory
inputs = {
'create': {
'VraManager': 'constant'
},
'read': {
},
'update': {
'VraManager': 'constant'
},
'delete': {
'VraManager': 'constant'
}
}
properties = {
'name': {
'type': 'string',
'title': 'Name',
'description': 'Name of virtual private zone'
},
'computes': {
'type': 'array',
'title': 'Computes',
'items': {
'type': 'string'
},
'description': 'Compute name list of placement hosts, clusters or resource pools'
},
'networks': {
'type': 'array',
'title': 'Networks',
'items': {
'type': 'string'
},
'description': 'Network id list'
},
'storage': {
'type': 'string',
'title': 'Storage',
'description': 'Datastore name to deploy',
},
'folder': {
'type': 'string',
'title': 'Folder',
'default': '',
'description': 'Folder name to deploy',
},
'placementPolicy': {
'type': 'string',
'title': 'Placement Policy',
'default': 'default',
'enum': ['default', 'binpack', 'spread'],
'description': 'Placement policy with "default", "binpack" or "spread"'
},
'loadBalancers': {
'type': 'array',
'title': 'Load Balancer',
'default': [],
'items': {
'type': 'string'
},
'description': 'Load balancer id list'
},
'edgeCluster': {
'type': 'string',
'title': 'Edge Cluster',
'default': '',
'description': 'Edge cluster name to use deployment',
},
'storageType': {
'type': 'string',
'title': 'Storage Type',
'default': 'thin',
'enum': ['thin', 'thick', 'eagerZeroedThick'],
'description': 'Storage type with "thin", "thick" or "eagerZeroedThick"'
},
} | """
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
"""
name = 'VirtualPrivateZone'
sdk = 'vra'
inputs = {'create': {'VraManager': 'constant'}, 'read': {}, 'update': {'VraManager': 'constant'}, 'delete': {'VraManager': 'constant'}}
properties = {'name': {'type': 'string', 'title': 'Name', 'description': 'Name of virtual private zone'}, 'computes': {'type': 'array', 'title': 'Computes', 'items': {'type': 'string'}, 'description': 'Compute name list of placement hosts, clusters or resource pools'}, 'networks': {'type': 'array', 'title': 'Networks', 'items': {'type': 'string'}, 'description': 'Network id list'}, 'storage': {'type': 'string', 'title': 'Storage', 'description': 'Datastore name to deploy'}, 'folder': {'type': 'string', 'title': 'Folder', 'default': '', 'description': 'Folder name to deploy'}, 'placementPolicy': {'type': 'string', 'title': 'Placement Policy', 'default': 'default', 'enum': ['default', 'binpack', 'spread'], 'description': 'Placement policy with "default", "binpack" or "spread"'}, 'loadBalancers': {'type': 'array', 'title': 'Load Balancer', 'default': [], 'items': {'type': 'string'}, 'description': 'Load balancer id list'}, 'edgeCluster': {'type': 'string', 'title': 'Edge Cluster', 'default': '', 'description': 'Edge cluster name to use deployment'}, 'storageType': {'type': 'string', 'title': 'Storage Type', 'default': 'thin', 'enum': ['thin', 'thick', 'eagerZeroedThick'], 'description': 'Storage type with "thin", "thick" or "eagerZeroedThick"'}} |
def to_dict_tools(target):
data = dict()
attribute = dir(target)
if 'public_info' in attribute:
public_info = getattr(target, 'public_info')
attribute = dir(target)
for item in attribute:
item = str(item)
if not item.startswith('_') and item in public_info:
data[item] = str(getattr(target, item))
return data
| def to_dict_tools(target):
data = dict()
attribute = dir(target)
if 'public_info' in attribute:
public_info = getattr(target, 'public_info')
attribute = dir(target)
for item in attribute:
item = str(item)
if not item.startswith('_') and item in public_info:
data[item] = str(getattr(target, item))
return data |
class Person:
population: int = 0
def __new__(cls):
cls.population += 1
print(f'DBG: new Person created, {cls.population=}')
return object.__new__(cls)
def __repr__(self) -> str:
return f'{self.__class__.__name__} {id(self)=} {self.population=}'
def main():
people = [
Person()
for _ in range(5)
]
print(people[0], people[-1], sep='\n')
if __name__ == '__main__':
main()
| class Person:
population: int = 0
def __new__(cls):
cls.population += 1
print(f'DBG: new Person created, cls.population={cls.population!r}')
return object.__new__(cls)
def __repr__(self) -> str:
return f'{self.__class__.__name__} id(self)={id(self)!r} self.population={self.population!r}'
def main():
people = [person() for _ in range(5)]
print(people[0], people[-1], sep='\n')
if __name__ == '__main__':
main() |
root = 'data/eval_det'
train = dict(
type='IcdarDataset',
ann_file=f'{root}/instances_training.json',
img_prefix=f'{root}/imgs',
pipeline=None)
test = dict(
type='IcdarDataset',
img_prefix=f'{root}/imgs',
ann_file=f'{root}/instances_test.json',
pipeline=None,
test_mode=True)
train_list = [train]
test_list = [test]
| root = 'data/eval_det'
train = dict(type='IcdarDataset', ann_file=f'{root}/instances_training.json', img_prefix=f'{root}/imgs', pipeline=None)
test = dict(type='IcdarDataset', img_prefix=f'{root}/imgs', ann_file=f'{root}/instances_test.json', pipeline=None, test_mode=True)
train_list = [train]
test_list = [test] |
P = ("Rafael","Beto","Carlos")
for k in range(int(input())):
x, y = tuple(map(int,input().split()))
players = (9*x*x + y*y, 2*x*x + 25*y*y, -100*x + y*y*y)
winner = players.index(max(players))
print("{0} ganhou".format(P[winner]))
| p = ('Rafael', 'Beto', 'Carlos')
for k in range(int(input())):
(x, y) = tuple(map(int, input().split()))
players = (9 * x * x + y * y, 2 * x * x + 25 * y * y, -100 * x + y * y * y)
winner = players.index(max(players))
print('{0} ganhou'.format(P[winner])) |
"""
Author: Huaze Shen
Date: 2019-07-09
"""
def remove_duplicates(nums):
if nums is None or len(nums) == 0:
return 0
length = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
continue
length += 1
nums[length - 1] = nums[i]
return length
if __name__ == '__main__':
nums_ = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
length_ = remove_duplicates(nums_)
print(nums_[:length_])
| """
Author: Huaze Shen
Date: 2019-07-09
"""
def remove_duplicates(nums):
if nums is None or len(nums) == 0:
return 0
length = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
continue
length += 1
nums[length - 1] = nums[i]
return length
if __name__ == '__main__':
nums_ = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
length_ = remove_duplicates(nums_)
print(nums_[:length_]) |
test = { 'name': 'q3_1_2',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> type(event_result) in set([np.ndarray])\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> # Your list should have 5 elements.;\n>>> len(event_result) == 5\nTrue', 'hidden': False, 'locked': False},
{ 'code': '>>> # Every element of your list should be a string.;\n>>> [type(i) in set([np.str_, str]) for i in event_result]\n[True, True, True, True, True]',
'hidden': False,
'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
| test = {'name': 'q3_1_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> type(event_result) in set([np.ndarray])\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Your list should have 5 elements.;\n>>> len(event_result) == 5\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Every element of your list should be a string.;\n>>> [type(i) in set([np.str_, str]) for i in event_result]\n[True, True, True, True, True]', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
class Fencepost():
vertices = [(0.25,0,0),
(0.25,0.75,0),
(1,0.75,0),
(1,0,0),
(0.25,0,1.75),
(0.25,0.75,1.75),
(1,0.75,1.75),
(1,0,1.75), #7
# Back post
(0,0.75,0.575),
(0,1.05,0.575),
(1.25,1.05,0.575),
(1.25,0.75,0.575),
(0,0.75,1.175),
(0,1.05,1.175),
(1.25,1.05,1.175),
(1.25,0.75,1.175) #15
]
faces = [(0,1,2,3),
(0,4,5,1),
(1,5,6,2),
(2,6,7,3),
(3,7,4,0),
(4,5,6,7),
# Back post
(8,9,10,11),
(8,12,13,9),
(9,13,14,10),
(10,14,15,11),
(11,15,12,8),
(12,13,14,15),
]
def load():
return Fencepost() | class Fencepost:
vertices = [(0.25, 0, 0), (0.25, 0.75, 0), (1, 0.75, 0), (1, 0, 0), (0.25, 0, 1.75), (0.25, 0.75, 1.75), (1, 0.75, 1.75), (1, 0, 1.75), (0, 0.75, 0.575), (0, 1.05, 0.575), (1.25, 1.05, 0.575), (1.25, 0.75, 0.575), (0, 0.75, 1.175), (0, 1.05, 1.175), (1.25, 1.05, 1.175), (1.25, 0.75, 1.175)]
faces = [(0, 1, 2, 3), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0), (4, 5, 6, 7), (8, 9, 10, 11), (8, 12, 13, 9), (9, 13, 14, 10), (10, 14, 15, 11), (11, 15, 12, 8), (12, 13, 14, 15)]
def load():
return fencepost() |
################ modules for HSPICE sim ######################
##############################################################
######### varmap definition ####################
##############################################################
### This class is to make combinations of given variables ####
### mostly used for testbench generation #################
### EX: varmap1=HSPICE_varmap.varmap(4) %%num of var=4 #######
### varmap1.get_var('vdd',1.5,1.8,0.2) %%vdd=1.5:0.2:1.8##
### varmap1.get_var('abc', ........ %%do this for 4 var ##
### varmap1.cal_nbigcy() %%end of var input###
### varmap1.combinate %%returns variable comb 1 by 1 ####
##############################################################
class varmap:
#def __init__(self,num_var):
# self.n_smlcycle=1
# self.last=0
# self.smlcy=1
# self.bigcy=0
# self.vv=0
# self.vf=1
# self.size=num_var
# self.map=[None]*self.size
# self.comblist=[None]*self.size
# self.nvar=0
def __init__(self):
self.n_smlcycle=1
self.last=0
self.smlcy=1
self.bigcy=0
self.vv=0
self.vf=1
#self.map=[None]
#self.comblist=[None]
self.nvar=0
def get_var(self,name,start,end,step):
if self.nvar==0:
self.map=[None]
self.comblist=[None]
else:
self.map.append(None)
self.comblist.append(None)
self.map[self.nvar]=list([name])
self.comblist[self.nvar]=list([name])
self.nswp=(end-start)//step+1
for i in range(1,self.nswp+1):
self.map[self.nvar].append(start+step*(i-1))
self.nvar+=1
def cal_nbigcy(self):
self.bias=[1]*(len(self.map))
for j in range(1,len(self.map)+1):
self.n_smlcycle=self.n_smlcycle*(len(self.map[j-1])-1)
self.n_smlcycle=self.n_smlcycle*len(self.map)
def increm(self,inc): #increment bias
self.bias[inc]+=1
if self.bias[inc]>len(self.map[inc])-1:
self.bias[inc]%len(self.map[inc])-1
def check_end(self,vf): #When this is called, it's already last stage of self.map[vf]
self.bias[vf]=1
# if vf==0 and self.bias[0]==len(self.map[0])-1:
# return 0
if self.bias[vf-1]==len(self.map[vf-1])-1: #if previous column is last element
self.check_end(vf-1)
else:
self.bias[vf-1]+=1
return 1
def combinate(self):
# print self.map[self.vv][self.bias[self.vv]]
self.smlcy+=1
if self.vv==len(self.map)-1: #last variable
self.bigcy+=1
for vprint in range(0,len(self.map)):
self.comblist[vprint].append(self.map[vprint][self.bias[vprint]])
#print self.map[vprint][self.bias[vprint]]
if self.bias[self.vv]==len(self.map[self.vv])-1: #last element
if self.smlcy<self.n_smlcycle:
self.check_end(self.vv)
self.vv=(self.vv+1)%len(self.map)
self.combinate()
else:
pass
else:
self.bias[self.vv]+=1
self.vv=(self.vv+1)%len(self.map)
self.combinate()
else:
self.vv=(self.vv+1)%len(self.map)
self.combinate()
##############################################################
######### netmap ########################
##############################################################
### This class is used for replacing lines ################
### detects @@ for line and @ for nets #######################
##############################################################
#-------- EXAMPLE ---------------------------------------#
### netmap1=netmap(2) %input num_var #########################
### netmap1.get_var('ab','NN',1,4,1) %flag MUST be 2 char ####
## netmap2.get_var('bc','DD',2,5,1) %length of var must match#
# !!caution: do get_var in order, except for lateral prints ##
### which is using @W => varibales here, do get_var at last ##
### for line in r_file.readlines():###########################
### netmap1.printline(line,w_file) #######################
##############################################################
class netmap:
#def __init__(self,num_var):
# self.size=num_var
# self.map=[None]*self.size
# self.flag=[None]*self.size
# self.name=[None]*self.size
# self.nnet=[None]*self.size
# self.nn=0
# self.pvar=1
# self.cnta=0
# self.line_nvar=0 # index of last variable for this line
# self.nxtl_var=0 # index of variable of next line
# self.ci_at=100
def __init__(self):
self.nn=0
self.pvar=1
self.cnta=0
self.line_nvar=0 # index of last variable for this line
self.nxtl_var=0 # index of variable of next line
self.ci_at=-5
def get_net(self,flag,netname,start,end,step): #if start==None: want to repeat without incrementation(usually for tab) (end)x(step) is the num of repetition
if self.nn==0:
self.map=[None]
self.flag=[None]
self.name=[None]
self.nnet=[None]
else:
self.map.append(None)
self.name.append(None)
self.flag.append(None)
self.nnet.append(None)
if netname==None:
self.name[self.nn]=0
else:
self.name[self.nn]=1
self.map[self.nn]=list([netname])
self.flag[self.nn]=(flag)
if start!=None and start!='d2o':
self.nnet[self.nn]=int((end-start+step/10)//step+1)
if self.name[self.nn]==1:
for i in range(1,self.nnet[self.nn]+1):
self.map[self.nn].append('')
else:
for i in range(1,self.nnet[self.nn]+1):
self.map[self.nn].append(start+step*(i-1))
elif start=='d2o':
for i in range(0,end):
if step-i>0:
self.map[self.nn].append(1)
else:
self.map[self.nn].append(0)
i+=1
else:
self.map[self.nn]=list([netname])
for i in range(1,step+1):
self.map[self.nn].append(end)
# self.map[self.nn]=[None]*step
# for i in range(1,self.nnet[self.nn]+1):
# self.map[self.nn][i]=None
self.nn+=1
#print self.map
def add_val(self,flag,netname,start,end,step):
varidx=self.flag.index(flag)
if start!=None:
nval=int((end-start+step/10)//step+1)
for i in range(1,nval+1):
self.map[varidx].append(start+step*(i-1))
else:
for i in range(1,step+1):
self.map[varidx].append(end)
def printline(self,line,wrfile):
if line[0:2]=='@@':
#print('self.ci_at=%d'%(self.ci_at))
self.nline=line[3:len(line)]
self.clist=list(self.nline) #character list
#print(self.clist,self.nxtl_var)
for iv in range (1,len(self.map[self.nxtl_var])):
for ci in range(0,len(self.clist)):
if (ci==self.ci_at+1 or ci==self.ci_at+2) and ci!=len(self.clist)-1:
pass
elif self.clist[ci]=='@':
#print self.cnta
self.cnta+=1
self.line_nvar+=1
varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2])
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
# print(self.map[varidx])
if type(self.map[varidx][self.pvar])==float:
wrfile.write('%e'%(self.map[varidx][self.pvar])) #modify here!!!!
elif type(self.map[varidx][self.pvar])==int:
wrfile.write('%d'%(self.map[varidx][self.pvar]))
self.ci_at=ci
elif ci==len(self.clist)-1: #end of the line
if self.pvar==len(self.map[self.nxtl_var+self.line_nvar-1])-1: #last element
self.pvar=1
self.nxtl_var=self.nxtl_var+self.line_nvar
self.line_nvar=0
self.cnta=0
self.ci_at=-6
#print('printed all var for this line, %d'%(ci))
else:
self.pvar+=1
#self.line_nvar=self.cnta
self.line_nvar=0
#print ('line_nvar= %d'%(self.line_nvar))
self.cnta=0
wrfile.write(self.clist[ci])
else:
wrfile.write(self.clist[ci])
elif line[0:2]=='@W':
#print('found word line')
self.nline=line[3:len(line)]
self.clist=list(self.nline)
for ci in range(0,len(self.clist)):
if (ci==self.ci_at+1 or ci==self.ci_at+2):
pass
elif self.clist[ci]=='@':
varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2])
for iv in range(1,len(self.map[varidx])):
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
wrfile.write('%d '%(self.map[varidx][iv]))
print ('n is %d, varidx=%d, iv=%d'%(self.map[varidx][iv],varidx,iv))
self.ci_at=ci
else:
wrfile.write(self.clist[ci])
self.ci_at=-5
else:
wrfile.write(line)
##############################################################
######### resmap ########################
##############################################################
### This class is used to deal with results ################
### detects @@ for line and @ for nets #######################
##############################################################
#-------- EXAMPLE ---------------------------------------#
### netmap1=netmap(2) %input num_var #########################
### netmap1.get_var('ab','NN',1,4,1) %flag MUST be 2 char ####
## netmap2.get_var('bc','DD',2,5,1) %length of var must match#
### for line in r_file.readlines():###########################
### netmap1.printline(line,w_file) #######################
###### self.tb[x][y][env[]]###############################
##############################################################
class resmap:
def __init__(self,num_tb,num_words,index): #num_words includes index
self.tb=[None]*num_tb
self.tbi=[None]*num_tb
self.vl=[None]*num_tb
self.vlinit=[None]*num_tb
self.svar=[None]*num_tb
self.index=index
self.nenv=0
self.num_words=num_words
self.vr=[None]*(num_words+index) #one set of variables per plot
self.vidx=[None]*(num_words+index)
self.env=[None]*(num_words+index)
# self.vl=[None]*(num_words+index) #one set of variables per plot
for itb in range(0,len(self.tb)):
# self.tb[itb].vr=[None]*(num_words+index)
self.tbi[itb]=0 #index for counting vars within tb
self.vl[itb]=[None]*(num_words+index)
self.vlinit[itb]=[0]*(num_words+index)
def get_var(self,ntb,var):
self.vr[self.tbi[ntb]]=(var)
# self.vl[ntb][self.tbi[ntb]]=list([None])
self.tbi[ntb]+=1
if self.tbi[ntb]==len(self.vr): #????????
self.tbi[ntb]=0
def add(self,ntb,value):
if self.vlinit[ntb][self.tbi[ntb]]==0: #initialization
self.vl[ntb][self.tbi[ntb]]=[value]
self.vlinit[ntb][self.tbi[ntb]]+=1
else:
self.vl[ntb][self.tbi[ntb]].append(value)
self.tbi[ntb]=(self.tbi[ntb]+1)%len(self.vr)
def plot_env(self,ntb,start,step,xvar,xval): #setting plot environment: if ntb=='all': x axis is in terms of testbench
if ntb=='all':
self.nenv+=1
self.xaxis=[None]*len(self.tb)
for i in range(0,len(self.tb)):
self.xaxis[i]=start+i*step
self.vidx[self.nenv]=self.vr.index(xvar)
#print self.vl[0][self.vidx[self.nenv]]
print('', self.vl[0][self.vidx[self.nenv]])
self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)]
else:
self.nenv+=1
self.xaxis=[None] #one output
self.xaxis=[start]
self.vidx[self.nenv]=self.vr.index(xvar)
self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)]
def rst_env(self):
self.vidx[self.nenv]=None
self.env[self.nenv]=0
self.nenv=0
#print self.vl[0][self.vidx[self.nenv]]
def plot_y(self,yvar):
self.yidx=self.vr.index(yvar)
print ('yidx=%d'%(self.yidx))
#print self.vl[0][self.yidx][self.env[self.nenv][0]]
print('', self.vl[0][self.yidx][self.env[self.nenv][0]])
self.yaxis=[None]*len(self.xaxis)
for xx in range(0,len(self.xaxis)):
self.yaxis[xx]=self.vl[xx][self.yidx][self.env[self.nenv][0]]
#plt.plot(self.xaxis,self.yaxis)
#plt.ylabel(self.vr[self.yidx])
def sort(self,var):
varidx=self.vr.index(var)
for k in range(len(self.vl)): #all testbenches
self.svar[k]={} #define dict
for i in range(len(self.vl[0][0])): #all values
self.svar[k][self.vl[k][varidx][i]]=[]
for j in range(len(self.vr)): #all variables
if j!=varidx:
self.svar[k][self.vl[k][varidx][i]].append(self.vl[k][j][i])
# if k==0:
# print self.svar[k]
| class Varmap:
def __init__(self):
self.n_smlcycle = 1
self.last = 0
self.smlcy = 1
self.bigcy = 0
self.vv = 0
self.vf = 1
self.nvar = 0
def get_var(self, name, start, end, step):
if self.nvar == 0:
self.map = [None]
self.comblist = [None]
else:
self.map.append(None)
self.comblist.append(None)
self.map[self.nvar] = list([name])
self.comblist[self.nvar] = list([name])
self.nswp = (end - start) // step + 1
for i in range(1, self.nswp + 1):
self.map[self.nvar].append(start + step * (i - 1))
self.nvar += 1
def cal_nbigcy(self):
self.bias = [1] * len(self.map)
for j in range(1, len(self.map) + 1):
self.n_smlcycle = self.n_smlcycle * (len(self.map[j - 1]) - 1)
self.n_smlcycle = self.n_smlcycle * len(self.map)
def increm(self, inc):
self.bias[inc] += 1
if self.bias[inc] > len(self.map[inc]) - 1:
self.bias[inc] % len(self.map[inc]) - 1
def check_end(self, vf):
self.bias[vf] = 1
if self.bias[vf - 1] == len(self.map[vf - 1]) - 1:
self.check_end(vf - 1)
else:
self.bias[vf - 1] += 1
return 1
def combinate(self):
self.smlcy += 1
if self.vv == len(self.map) - 1:
self.bigcy += 1
for vprint in range(0, len(self.map)):
self.comblist[vprint].append(self.map[vprint][self.bias[vprint]])
if self.bias[self.vv] == len(self.map[self.vv]) - 1:
if self.smlcy < self.n_smlcycle:
self.check_end(self.vv)
self.vv = (self.vv + 1) % len(self.map)
self.combinate()
else:
pass
else:
self.bias[self.vv] += 1
self.vv = (self.vv + 1) % len(self.map)
self.combinate()
else:
self.vv = (self.vv + 1) % len(self.map)
self.combinate()
class Netmap:
def __init__(self):
self.nn = 0
self.pvar = 1
self.cnta = 0
self.line_nvar = 0
self.nxtl_var = 0
self.ci_at = -5
def get_net(self, flag, netname, start, end, step):
if self.nn == 0:
self.map = [None]
self.flag = [None]
self.name = [None]
self.nnet = [None]
else:
self.map.append(None)
self.name.append(None)
self.flag.append(None)
self.nnet.append(None)
if netname == None:
self.name[self.nn] = 0
else:
self.name[self.nn] = 1
self.map[self.nn] = list([netname])
self.flag[self.nn] = flag
if start != None and start != 'd2o':
self.nnet[self.nn] = int((end - start + step / 10) // step + 1)
if self.name[self.nn] == 1:
for i in range(1, self.nnet[self.nn] + 1):
self.map[self.nn].append('')
else:
for i in range(1, self.nnet[self.nn] + 1):
self.map[self.nn].append(start + step * (i - 1))
elif start == 'd2o':
for i in range(0, end):
if step - i > 0:
self.map[self.nn].append(1)
else:
self.map[self.nn].append(0)
i += 1
else:
self.map[self.nn] = list([netname])
for i in range(1, step + 1):
self.map[self.nn].append(end)
self.nn += 1
def add_val(self, flag, netname, start, end, step):
varidx = self.flag.index(flag)
if start != None:
nval = int((end - start + step / 10) // step + 1)
for i in range(1, nval + 1):
self.map[varidx].append(start + step * (i - 1))
else:
for i in range(1, step + 1):
self.map[varidx].append(end)
def printline(self, line, wrfile):
if line[0:2] == '@@':
self.nline = line[3:len(line)]
self.clist = list(self.nline)
for iv in range(1, len(self.map[self.nxtl_var])):
for ci in range(0, len(self.clist)):
if (ci == self.ci_at + 1 or ci == self.ci_at + 2) and ci != len(self.clist) - 1:
pass
elif self.clist[ci] == '@':
self.cnta += 1
self.line_nvar += 1
varidx = self.flag.index(self.clist[ci + 1] + self.clist[ci + 2])
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
if type(self.map[varidx][self.pvar]) == float:
wrfile.write('%e' % self.map[varidx][self.pvar])
elif type(self.map[varidx][self.pvar]) == int:
wrfile.write('%d' % self.map[varidx][self.pvar])
self.ci_at = ci
elif ci == len(self.clist) - 1:
if self.pvar == len(self.map[self.nxtl_var + self.line_nvar - 1]) - 1:
self.pvar = 1
self.nxtl_var = self.nxtl_var + self.line_nvar
self.line_nvar = 0
self.cnta = 0
self.ci_at = -6
else:
self.pvar += 1
self.line_nvar = 0
self.cnta = 0
wrfile.write(self.clist[ci])
else:
wrfile.write(self.clist[ci])
elif line[0:2] == '@W':
self.nline = line[3:len(line)]
self.clist = list(self.nline)
for ci in range(0, len(self.clist)):
if ci == self.ci_at + 1 or ci == self.ci_at + 2:
pass
elif self.clist[ci] == '@':
varidx = self.flag.index(self.clist[ci + 1] + self.clist[ci + 2])
for iv in range(1, len(self.map[varidx])):
if self.name[varidx]:
wrfile.write(self.map[varidx][0])
wrfile.write('%d\t' % self.map[varidx][iv])
print('n is %d, varidx=%d, iv=%d' % (self.map[varidx][iv], varidx, iv))
self.ci_at = ci
else:
wrfile.write(self.clist[ci])
self.ci_at = -5
else:
wrfile.write(line)
class Resmap:
def __init__(self, num_tb, num_words, index):
self.tb = [None] * num_tb
self.tbi = [None] * num_tb
self.vl = [None] * num_tb
self.vlinit = [None] * num_tb
self.svar = [None] * num_tb
self.index = index
self.nenv = 0
self.num_words = num_words
self.vr = [None] * (num_words + index)
self.vidx = [None] * (num_words + index)
self.env = [None] * (num_words + index)
for itb in range(0, len(self.tb)):
self.tbi[itb] = 0
self.vl[itb] = [None] * (num_words + index)
self.vlinit[itb] = [0] * (num_words + index)
def get_var(self, ntb, var):
self.vr[self.tbi[ntb]] = var
self.tbi[ntb] += 1
if self.tbi[ntb] == len(self.vr):
self.tbi[ntb] = 0
def add(self, ntb, value):
if self.vlinit[ntb][self.tbi[ntb]] == 0:
self.vl[ntb][self.tbi[ntb]] = [value]
self.vlinit[ntb][self.tbi[ntb]] += 1
else:
self.vl[ntb][self.tbi[ntb]].append(value)
self.tbi[ntb] = (self.tbi[ntb] + 1) % len(self.vr)
def plot_env(self, ntb, start, step, xvar, xval):
if ntb == 'all':
self.nenv += 1
self.xaxis = [None] * len(self.tb)
for i in range(0, len(self.tb)):
self.xaxis[i] = start + i * step
self.vidx[self.nenv] = self.vr.index(xvar)
print('', self.vl[0][self.vidx[self.nenv]])
self.env[self.nenv] = [i for (i, x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x == '%s' % xval]
else:
self.nenv += 1
self.xaxis = [None]
self.xaxis = [start]
self.vidx[self.nenv] = self.vr.index(xvar)
self.env[self.nenv] = [i for (i, x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x == '%s' % xval]
def rst_env(self):
self.vidx[self.nenv] = None
self.env[self.nenv] = 0
self.nenv = 0
def plot_y(self, yvar):
self.yidx = self.vr.index(yvar)
print('yidx=%d' % self.yidx)
print('', self.vl[0][self.yidx][self.env[self.nenv][0]])
self.yaxis = [None] * len(self.xaxis)
for xx in range(0, len(self.xaxis)):
self.yaxis[xx] = self.vl[xx][self.yidx][self.env[self.nenv][0]]
def sort(self, var):
varidx = self.vr.index(var)
for k in range(len(self.vl)):
self.svar[k] = {}
for i in range(len(self.vl[0][0])):
self.svar[k][self.vl[k][varidx][i]] = []
for j in range(len(self.vr)):
if j != varidx:
self.svar[k][self.vl[k][varidx][i]].append(self.vl[k][j][i]) |
def line_br_int(win, p1, p2):
if p1 == p2:
win.image.setPixel(p1[0], p1[1], win.pen.color().rgb())
return
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
sx = sign(dx)
sy = sign(dy)
dx = abs(dx)
dy = abs(dy)
x = p1[0]
y = p1[1]
change = False
if dy > dx:
temp = dx
dx = dy
dy = temp
change = True
e = 2 * dy - dx
i = 1
while i <= dx:
win.image.setPixel(x, y, win.pen.color().rgb())
if e >= 0:
if change == 0:
y += sy
else:
x += sx
e -= 2 * dx
if e < 0:
if change == 0:
x += sx
else:
y += sy
e += (2 * dy)
i += 1
| def line_br_int(win, p1, p2):
if p1 == p2:
win.image.setPixel(p1[0], p1[1], win.pen.color().rgb())
return
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
sx = sign(dx)
sy = sign(dy)
dx = abs(dx)
dy = abs(dy)
x = p1[0]
y = p1[1]
change = False
if dy > dx:
temp = dx
dx = dy
dy = temp
change = True
e = 2 * dy - dx
i = 1
while i <= dx:
win.image.setPixel(x, y, win.pen.color().rgb())
if e >= 0:
if change == 0:
y += sy
else:
x += sx
e -= 2 * dx
if e < 0:
if change == 0:
x += sx
else:
y += sy
e += 2 * dy
i += 1 |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ADSBVehicle.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ActuatorControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Altitude.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/AttitudeTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/BatteryStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CamIMUStamp.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CommandCode.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CompanionProcessStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OnboardComputerStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/DebugValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfoItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatusItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/EstimatorStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ExtendedState.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/FileEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GlobalPositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRAW.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRTK.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilActuatorControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilGPS.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilSensor.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilStateQuaternion.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HomePosition.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LandingTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogData.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ManualControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Mavlink.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/MountControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OpticalFlowRad.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OverrideRCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Param.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ParamValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PlayTuneV2.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCOut.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTCM.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RadioStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTKBaseline.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/State.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/StatusText.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Thrust.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/TimesyncStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Trajectory.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VFR_HUD.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VehicleInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Vibration.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Waypoint.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointList.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointReached.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WheelOdomStamped.msg"
services_str = "/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandBool.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandHome.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandInt.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandLong.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTOL.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerControl.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandVtolTransition.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileChecksum.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileClose.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileMakeDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileOpen.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRead.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemove.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemoveDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRename.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileTruncate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileWrite.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestData.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestEnd.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MountConfigure.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MessageInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamSet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMavFrame.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMode.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/StreamRate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/VehicleInfoGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointClear.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointSetCurrent.srv"
pkg_name = "mavros_msgs"
dependencies_str = "geographic_msgs;geometry_msgs;sensor_msgs;std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "mavros_msgs;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg;geographic_msgs;/opt/ros/melodic/share/geographic_msgs/cmake/../msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg;sensor_msgs;/opt/ros/melodic/share/sensor_msgs/cmake/../msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg;uuid_msgs;/opt/ros/melodic/share/uuid_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python2"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| messages_str = '/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ADSBVehicle.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ActuatorControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Altitude.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/AttitudeTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/BatteryStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CamIMUStamp.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CommandCode.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/CompanionProcessStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OnboardComputerStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/DebugValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCInfoItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ESCStatusItem.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/EstimatorStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ExtendedState.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/FileEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GlobalPositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRAW.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/GPSRTK.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilActuatorControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilControls.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilGPS.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilSensor.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HilStateQuaternion.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/HomePosition.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LandingTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogData.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/LogEntry.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ManualControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Mavlink.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/MountControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OpticalFlowRad.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/OverrideRCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Param.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ParamValue.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PlayTuneV2.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/PositionTarget.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCIn.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RCOut.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTCM.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RadioStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/RTKBaseline.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/State.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/StatusText.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Thrust.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/TimesyncStatus.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Trajectory.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VFR_HUD.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/VehicleInfo.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Vibration.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Waypoint.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointList.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WaypointReached.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/WheelOdomStamped.msg'
services_str = '/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandBool.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandHome.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandInt.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandLong.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTOL.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerControl.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandTriggerInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/CommandVtolTransition.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileChecksum.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileClose.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileMakeDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileOpen.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRead.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemove.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRemoveDir.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileRename.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileTruncate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/FileWrite.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestData.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestEnd.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/LogRequestList.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MountConfigure.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/MessageInterval.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/ParamSet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMavFrame.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/SetMode.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/StreamRate.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/VehicleInfoGet.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointClear.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPull.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointPush.srv;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/srv/WaypointSetCurrent.srv'
pkg_name = 'mavros_msgs'
dependencies_str = 'geographic_msgs;geometry_msgs;sensor_msgs;std_msgs'
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = 'mavros_msgs;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg;geographic_msgs;/opt/ros/melodic/share/geographic_msgs/cmake/../msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg;sensor_msgs;/opt/ros/melodic/share/sensor_msgs/cmake/../msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg;uuid_msgs;/opt/ros/melodic/share/uuid_msgs/cmake/../msg'
python_executable = '/usr/bin/python2'
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = '/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py' |
# *-* coding: utf-8 *-*
class Customer:
def __init__(self, firstname=None, lastname=None, address1=None, postcode=None, city=None, phone=None, email=None,
password=None, confirmed_password=None):
self.firstname = firstname
self.lastname = lastname
self.address1 = address1
self.postcode = postcode
self.city = city
self.phone = phone
self.email = email
self.password = password
self.confirmed_password = confirmed_password
| class Customer:
def __init__(self, firstname=None, lastname=None, address1=None, postcode=None, city=None, phone=None, email=None, password=None, confirmed_password=None):
self.firstname = firstname
self.lastname = lastname
self.address1 = address1
self.postcode = postcode
self.city = city
self.phone = phone
self.email = email
self.password = password
self.confirmed_password = confirmed_password |
class Solution(object):
def longestValidParentheses(self, s):
if len(s) == 0:
return 0
stack = [-1]
result = 0
for idx, ch in enumerate(s):
if ch == "(":
stack.append(idx)
else:
stack.pop()
if len(stack) == 0:
stack.append(idx)
else:
length = idx-stack[-1]
result = max(result, length)
return result
def longestParentheses(string):
if len(string) == 0:
return 0
stk = []
longestLength = 0
for i, ch in enumerate(string):
if ch == '(':
stk.append(i)
elif ch == ')':
if stk:
open_i = stk.pop()
length = i-open_i + 1
if length > longestLength:
longestLength = length
return longestLength
| class Solution(object):
def longest_valid_parentheses(self, s):
if len(s) == 0:
return 0
stack = [-1]
result = 0
for (idx, ch) in enumerate(s):
if ch == '(':
stack.append(idx)
else:
stack.pop()
if len(stack) == 0:
stack.append(idx)
else:
length = idx - stack[-1]
result = max(result, length)
return result
def longest_parentheses(string):
if len(string) == 0:
return 0
stk = []
longest_length = 0
for (i, ch) in enumerate(string):
if ch == '(':
stk.append(i)
elif ch == ')':
if stk:
open_i = stk.pop()
length = i - open_i + 1
if length > longestLength:
longest_length = length
return longestLength |
# You are at the zoo, and the meerkats look strange.
# You will receive 3 strings: (tail, body, head).
# Your task is to re-arrange the elements in a list
# so that the animal looks normal again: (head, body, tail).
tail = input()
body = input()
head = input()
lst = [head,body,tail]
print(lst) | tail = input()
body = input()
head = input()
lst = [head, body, tail]
print(lst) |
tiles = [
# highway=steps, with route regional (Coastal Trail, Marin, II)
# https://www.openstreetmap.org/way/24655593
# https://www.openstreetmap.org/relation/2260059
[12, 653, 1582],
# highway=steps, no route, but has name, and designation (Levant St Stairway, SF)
# https://www.openstreetmap.org/way/38060491
[13, 1309, 3166]
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'roads',
{'highway': 'steps'})
# way 25292070 highway=steps, no route, but has name (Esmeralda, Bernal, SF)
assert_no_matching_feature(
13, 1310, 3167, 'roads',
{'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'})
# way 25292070 highway=steps, no route, but has name (Esmeralda, Bernal, SF)
assert_has_feature(
14, 2620, 6334, 'roads',
{'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'})
| tiles = [[12, 653, 1582], [13, 1309, 3166]]
for (z, x, y) in tiles:
assert_has_feature(z, x, y, 'roads', {'highway': 'steps'})
assert_no_matching_feature(13, 1310, 3167, 'roads', {'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'})
assert_has_feature(14, 2620, 6334, 'roads', {'kind': 'path', 'highway': 'steps', 'name': 'Esmeralda Ave.'}) |
# Time: O(h * p^2), p is the number of patterns
# Space: O(p^2)
# bitmask, backtracking, dp
class Solution(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask^(1<<width))
return
for x in bricks:
backtracking(height, width, bricks, total+x, mask|(1<<(total+x)), lookup, patterns)
patterns, lookup = [], set()
backtracking(height, width, bricks, 0, 0, lookup, patterns)
adj = [[j for j, r2 in enumerate(patterns) if not (r1 & r2)] for r1 in patterns]
dp = [[1]*len(patterns), [0]*len(patterns)]
for i in xrange(height-1):
dp[(i+1)%2] = [sum(dp[i%2][k] for k in adj[j]) % MOD for j in xrange(len(patterns))]
return sum(dp[(height-1)%2]) % MOD
# Time: O(p^3 * logh), p is the number of patterns, p may be up to 512
# Space: O(p^3)
# bitmask, backtracking, matrix exponentiation
class Solution_TLE(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask^(1<<width))
return
for x in bricks:
backtracking(height, width, bricks, total+x, mask|(1<<(total+x)), lookup, patterns)
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD for col in ZB] for row in A]
def matrix_expo(A, K):
result = [[int(i == j) for j in xrange(len(A))] for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result
patterns, lookup = [], set()
backtracking(height, width, bricks, 0, 0, lookup, patterns)
return reduce(lambda x,y: (x+y)%MOD,
matrix_mult([[1]*len(patterns)],
matrix_expo([[int((mask1 & mask2) == 0)
for mask2 in patterns]
for mask1 in patterns], height-1))[0],
0) # Time: O(p^3 * logh), Space: O(p^2)
| class Solution(object):
def build_wall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
mod = 10 ** 9 + 7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask ^ 1 << width)
return
for x in bricks:
backtracking(height, width, bricks, total + x, mask | 1 << total + x, lookup, patterns)
(patterns, lookup) = ([], set())
backtracking(height, width, bricks, 0, 0, lookup, patterns)
adj = [[j for (j, r2) in enumerate(patterns) if not r1 & r2] for r1 in patterns]
dp = [[1] * len(patterns), [0] * len(patterns)]
for i in xrange(height - 1):
dp[(i + 1) % 2] = [sum((dp[i % 2][k] for k in adj[j])) % MOD for j in xrange(len(patterns))]
return sum(dp[(height - 1) % 2]) % MOD
class Solution_Tle(object):
def build_wall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
mod = 10 ** 9 + 7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in lookup:
return
lookup.add(mask)
if total >= width:
if total == width:
patterns.append(mask ^ 1 << width)
return
for x in bricks:
backtracking(height, width, bricks, total + x, mask | 1 << total + x, lookup, patterns)
def matrix_mult(A, B):
zb = zip(*B)
return [[sum((a * b % MOD for (a, b) in itertools.izip(row, col))) % MOD for col in ZB] for row in A]
def matrix_expo(A, K):
result = [[int(i == j) for j in xrange(len(A))] for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
a = matrix_mult(A, A)
k /= 2
return result
(patterns, lookup) = ([], set())
backtracking(height, width, bricks, 0, 0, lookup, patterns)
return reduce(lambda x, y: (x + y) % MOD, matrix_mult([[1] * len(patterns)], matrix_expo([[int(mask1 & mask2 == 0) for mask2 in patterns] for mask1 in patterns], height - 1))[0], 0) |
# Copyright 2018 BlueCat Networks. All rights reserved.
# -*- coding: utf-8 -*-
type = 'api'
sub_pages = [
{
'name' : 'ipam_page',
'title' : u'Cisco_DNA_IPAM_Interface',
'endpoint' : 'ipam/ipam_endpoint',
'description' : u'Gateway workflow to be IPAM interface to integrate with Cisco DNA Centre'
},
]
| type = 'api'
sub_pages = [{'name': 'ipam_page', 'title': u'Cisco_DNA_IPAM_Interface', 'endpoint': 'ipam/ipam_endpoint', 'description': u'Gateway workflow to be IPAM interface to integrate with Cisco DNA Centre'}] |
n=int(input())
alpha_code = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
NEW_INPUT = 9
NUMERIC = 1
ALPHA = 2
BYTE_CODE = 4
KANJI = 8
TERMINATION = 0
while n:
code = int(input(), 16)
state = NEW_INPUT
ans = ''
p = 38*4
ret_size = 0
while p>0:
if state == TERMINATION:
break
elif state == NEW_INPUT:
p-=4
state = code//(2**p)
code%=2**p
elif state == NUMERIC:
p-=10
size = code//(2**p)
code%=2**p
while size:
if size == 1:
p-=4
data = code//(2**p)
code%=2**p
ret_size+=1
size-=1
ans+='%01d'%data
elif size == 2:
p-=7
data = code//(2**p)
code%=2**p
ret_size+=2
size-=2
ans+='%02d'%data
else:
p-=10
data = code//(2**p)
code%=2**p
ret_size+=3
size-=3
ans+='%03d'%data
state = NEW_INPUT
elif state == ALPHA:
p-=9
size = code//(2**p)
code%=2**p
while size:
if size==1:
p-=6
data = code//(2**p)
code%=2**p
ret_size+=1
size-=1
ans+=alpha_code[data]
else:
p-=11
data = code//(2**p)
code%=2**p
ret_size+=2
size-=2
data1 = alpha_code[data//45]
data2 = alpha_code[data%45]
ans+= data1+data2
state = NEW_INPUT
elif state == BYTE_CODE:
p-=8
size = code//(2**p)
code%=2**p
while size:
p-=8
size-=1
data = code//(2**p)
code%=2**p
ret_size+=1
if data>=0x20 and data<=0x7e:
ans+=chr(data)
else:
ans+='\\'+'%02X'%(data)
state = NEW_INPUT
elif state == KANJI:
p-=8
size = code//(2**p)
code%=2**p
while size:
p-=13
size-=1
data = code//(2**p)
code%=2**p
ret_size+=1
ans+='#'+'%04X'%(data)
state = NEW_INPUT
print(ret_size, ans)
n-=1 | n = int(input())
alpha_code = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
new_input = 9
numeric = 1
alpha = 2
byte_code = 4
kanji = 8
termination = 0
while n:
code = int(input(), 16)
state = NEW_INPUT
ans = ''
p = 38 * 4
ret_size = 0
while p > 0:
if state == TERMINATION:
break
elif state == NEW_INPUT:
p -= 4
state = code // 2 ** p
code %= 2 ** p
elif state == NUMERIC:
p -= 10
size = code // 2 ** p
code %= 2 ** p
while size:
if size == 1:
p -= 4
data = code // 2 ** p
code %= 2 ** p
ret_size += 1
size -= 1
ans += '%01d' % data
elif size == 2:
p -= 7
data = code // 2 ** p
code %= 2 ** p
ret_size += 2
size -= 2
ans += '%02d' % data
else:
p -= 10
data = code // 2 ** p
code %= 2 ** p
ret_size += 3
size -= 3
ans += '%03d' % data
state = NEW_INPUT
elif state == ALPHA:
p -= 9
size = code // 2 ** p
code %= 2 ** p
while size:
if size == 1:
p -= 6
data = code // 2 ** p
code %= 2 ** p
ret_size += 1
size -= 1
ans += alpha_code[data]
else:
p -= 11
data = code // 2 ** p
code %= 2 ** p
ret_size += 2
size -= 2
data1 = alpha_code[data // 45]
data2 = alpha_code[data % 45]
ans += data1 + data2
state = NEW_INPUT
elif state == BYTE_CODE:
p -= 8
size = code // 2 ** p
code %= 2 ** p
while size:
p -= 8
size -= 1
data = code // 2 ** p
code %= 2 ** p
ret_size += 1
if data >= 32 and data <= 126:
ans += chr(data)
else:
ans += '\\' + '%02X' % data
state = NEW_INPUT
elif state == KANJI:
p -= 8
size = code // 2 ** p
code %= 2 ** p
while size:
p -= 13
size -= 1
data = code // 2 ** p
code %= 2 ** p
ret_size += 1
ans += '#' + '%04X' % data
state = NEW_INPUT
print(ret_size, ans)
n -= 1 |
# Read two rectangles, discern wheter rect1 is inside rect2
class Rectangle:
def __init__(self, *tokens):
self.left, self.top, self.width, self.height = list(map(float, tokens))
def is_inside(self, other_rect):
if type(other_rect) is not Rectangle:
raise TypeError('other_rect is not a Point object.')
inside_horiz = self.left >= other_rect.left and self.width <= other_rect.width
inside_verti = self.top <= other_rect.top and self.height <= other_rect.height
fully_inside = inside_horiz and inside_verti
result = 'Inside' if fully_inside else 'Not inside'
return(result)
rectangle_list = []
for i in range(2):
user_input = input().split()
user_input = map(int, user_input)
cur_rect = Rectangle(*user_input)
rectangle_list.append(cur_rect)
print(rectangle_list[0].is_inside(rectangle_list[1]))
| class Rectangle:
def __init__(self, *tokens):
(self.left, self.top, self.width, self.height) = list(map(float, tokens))
def is_inside(self, other_rect):
if type(other_rect) is not Rectangle:
raise type_error('other_rect is not a Point object.')
inside_horiz = self.left >= other_rect.left and self.width <= other_rect.width
inside_verti = self.top <= other_rect.top and self.height <= other_rect.height
fully_inside = inside_horiz and inside_verti
result = 'Inside' if fully_inside else 'Not inside'
return result
rectangle_list = []
for i in range(2):
user_input = input().split()
user_input = map(int, user_input)
cur_rect = rectangle(*user_input)
rectangle_list.append(cur_rect)
print(rectangle_list[0].is_inside(rectangle_list[1])) |
#!/usr/bin/python
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'item to purchase.')
print('These items are:', end=' ')
for item in shoplist:
print(item, end = ' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist) | shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'item to purchase.')
print('These items are:', end=' ')
for item in shoplist:
print(item, end=' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist) |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
tmp = list(nums[:len(nums) - k])
del nums[:len(nums) - k]
nums.extend(tmp) | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
tmp = list(nums[:len(nums) - k])
del nums[:len(nums) - k]
nums.extend(tmp) |
"""
entrada
suelto=>int=>su
ventas departamento 1=>int=>dep1
ventas departamento 2=>int=>dep2
ventas departamento 3=>int=>dep3
salida
sueldo total al final del mes 3 departamentos=>int=> total3dep
"""
su=int(input("ingrese sueldo "))
dep1=int(input("ingrese ventas echas "))
dep2=int(input("ingrese ventas echas "))
dep3=int(input("ingrese ventas echas "))
ventotal=(dep1+dep2+dep3)
print("venta total: "+str(ventotal))
ex33=(ventotal*33)/100
if(dep1>ex33):
dep1=su+su*.20/100
else:
dep1=su
print("los vendedores del departamento 1 recibiran: "+str(dep1))
if(dep2>ex33):
dep2=su+su*.20/100
else:
dep2=su
print("los vendedores del departamento 2 recibiran: "+str(dep2))
if(dep3>ex33):
dep3=su+su*.20/100
else:
dep3=su
print("los vendedores del departamento 3 recibiran: "+str(dep3))
| """
entrada
suelto=>int=>su
ventas departamento 1=>int=>dep1
ventas departamento 2=>int=>dep2
ventas departamento 3=>int=>dep3
salida
sueldo total al final del mes 3 departamentos=>int=> total3dep
"""
su = int(input('ingrese sueldo '))
dep1 = int(input('ingrese ventas echas '))
dep2 = int(input('ingrese ventas echas '))
dep3 = int(input('ingrese ventas echas '))
ventotal = dep1 + dep2 + dep3
print('venta total: ' + str(ventotal))
ex33 = ventotal * 33 / 100
if dep1 > ex33:
dep1 = su + su * 0.2 / 100
else:
dep1 = su
print('los vendedores del departamento 1 recibiran: ' + str(dep1))
if dep2 > ex33:
dep2 = su + su * 0.2 / 100
else:
dep2 = su
print('los vendedores del departamento 2 recibiran: ' + str(dep2))
if dep3 > ex33:
dep3 = su + su * 0.2 / 100
else:
dep3 = su
print('los vendedores del departamento 3 recibiran: ' + str(dep3)) |
"""This module implements the abstract classes/interfaces of all variable pipeline components."""
class AbstractDataLoader:
"""The AbstractDataLoader defines the interface for any kind of IMU data loader."""
def __init__(self, raw_base_path, dataset, subject, run):
"""
Initialization of an AbstractDataLoader
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.data = {}
self.load(raw_base_path, dataset, subject, run)
def load(self, raw_base_path, dataset, subject, run):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store them as a dictionary of IMU objects into self.data
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded data.
Returns:
dict[str, IMU]: IMU data from all sensors
"""
return self.data
class AbstractTrajectoryEstimator:
""" The AbstractTrajectoryEstimator defines the interface for each trajectory estimation algorithm."""
def __init__(self, imus):
"""
Initialization of an AbstractTrajectoryEstimator
Args:
imus dict[str, IMU]: Dictionary of IMU objects for each sensor location
"""
self.imus = imus
def estimate(self, interim_base_path, dataset, subject_num, run_num):
"""
This method is expected to be implemented by each trajectory estimation algorithm.
Args:
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject_num (int): Subject index
run_num (int): Run index
Returns:
dict[str, DataFrame]: DataFrames containing trajectory information for each foot
"""
pass
class AbstractEventDetector:
"""
The AbstractEventDetector defines the interface for any kind of event detection algorithm.
"""
def __init__(self, imus):
"""
Initialization of an AbstractEventDetector.
Args:
imus (dict[str, IMU]): Dictionary of IMU objects for each sensor location.
"""
self.imus = imus
def detect(self):
"""
This method is expected to be implemented by each event detection algorithm.
Returns:
(dict[str, dict]): dictionaries containing gait event information for each foot.
"""
pass
class AbstractReferenceLoader:
"""
The AbstractReferenceLoader defines the interface for any kind of reference data loader.
"""
def __init__(
self, name, raw_base_path, interim_base_path, dataset, subject, run, overwrite
):
"""
Initialization of an AbstractReferenceLoader.
Args:
mame (str): Identifier used to create caching files
raw_base_path (str): Base folder for every dataset
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.name = name
self.raw_base_path = raw_base_path
self.interim_base_path = interim_base_path
self.dataset = dataset
self.subject = subject
self.run = run
self.overwrite = overwrite
self.data = {"left": {}, "right": {}}
self.load()
def load(self):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store reference data for the left and right foot in self.data
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded reference data.
Returns:
dict[str, DataFrame]: DataFrames with gait parameters for the left and right foot
"""
return self.data
| """This module implements the abstract classes/interfaces of all variable pipeline components."""
class Abstractdataloader:
"""The AbstractDataLoader defines the interface for any kind of IMU data loader."""
def __init__(self, raw_base_path, dataset, subject, run):
"""
Initialization of an AbstractDataLoader
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.data = {}
self.load(raw_base_path, dataset, subject, run)
def load(self, raw_base_path, dataset, subject, run):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store them as a dictionary of IMU objects into self.data
Args:
raw_base_path (str): Base folder for every dataset
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded data.
Returns:
dict[str, IMU]: IMU data from all sensors
"""
return self.data
class Abstracttrajectoryestimator:
""" The AbstractTrajectoryEstimator defines the interface for each trajectory estimation algorithm."""
def __init__(self, imus):
"""
Initialization of an AbstractTrajectoryEstimator
Args:
imus dict[str, IMU]: Dictionary of IMU objects for each sensor location
"""
self.imus = imus
def estimate(self, interim_base_path, dataset, subject_num, run_num):
"""
This method is expected to be implemented by each trajectory estimation algorithm.
Args:
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject_num (int): Subject index
run_num (int): Run index
Returns:
dict[str, DataFrame]: DataFrames containing trajectory information for each foot
"""
pass
class Abstracteventdetector:
"""
The AbstractEventDetector defines the interface for any kind of event detection algorithm.
"""
def __init__(self, imus):
"""
Initialization of an AbstractEventDetector.
Args:
imus (dict[str, IMU]): Dictionary of IMU objects for each sensor location.
"""
self.imus = imus
def detect(self):
"""
This method is expected to be implemented by each event detection algorithm.
Returns:
(dict[str, dict]): dictionaries containing gait event information for each foot.
"""
pass
class Abstractreferenceloader:
"""
The AbstractReferenceLoader defines the interface for any kind of reference data loader.
"""
def __init__(self, name, raw_base_path, interim_base_path, dataset, subject, run, overwrite):
"""
Initialization of an AbstractReferenceLoader.
Args:
mame (str): Identifier used to create caching files
raw_base_path (str): Base folder for every dataset
interim_base_path (str): Base folder where interim data can be stored
dataset (str): Folder containing the dataset
subject (str): Subject identifier
run (str): Run identifier
"""
self.name = name
self.raw_base_path = raw_base_path
self.interim_base_path = interim_base_path
self.dataset = dataset
self.subject = subject
self.run = run
self.overwrite = overwrite
self.data = {'left': {}, 'right': {}}
self.load()
def load(self):
"""
This method is called at instantiation and needs to be implemented by the derived class.
It is expected to find the actual data files based on the given parameters
and store reference data for the left and right foot in self.data
Returns:
None
"""
pass
def get_data(self):
"""
Get the loaded reference data.
Returns:
dict[str, DataFrame]: DataFrames with gait parameters for the left and right foot
"""
return self.data |
graph={
'A':['B','C'],
'B':['A'],
'C':['D','E','F','S'],
'D':['C'],
'E':['C','H'],
'F':['C','G'],
'G':['F','G'],
'H':['E','G'],
'S':['A','C','G']
}
visited=[]
def dfs(graph,node):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph,n)
dfs(graph,'A')
print(visited)
| graph = {'A': ['B', 'C'], 'B': ['A'], 'C': ['D', 'E', 'F', 'S'], 'D': ['C'], 'E': ['C', 'H'], 'F': ['C', 'G'], 'G': ['F', 'G'], 'H': ['E', 'G'], 'S': ['A', 'C', 'G']}
visited = []
def dfs(graph, node):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph, n)
dfs(graph, 'A')
print(visited) |
'''
Lec 7
while loop
'''
i=5
while i >=0 :
try:
print(1/(i-3))
except:
pass
i = i - 1
| """
Lec 7
while loop
"""
i = 5
while i >= 0:
try:
print(1 / (i - 3))
except:
pass
i = i - 1 |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Test.Summary = 'Testing ATS TCP handshake timeout'
# Skipping this in the normal CI because it requires privilege.
# Comment out to run in your privileged environment
Test.SkipIf(Condition.true("Test requires privilege"))
ts = Test.MakeATSProcess("ts")
Test.ContinueOnFail = True
Test.GetTcpPort("blocked_upstream_port")
Test.GetTcpPort("upstream_port")
server4 = Test.MakeOriginServer("server4")
ts.Disk.records_config.update({
'proxy.config.url_remap.remap_required': 1,
'proxy.config.http.connect_attempts_timeout': 2,
'proxy.config.http.connect_attempts_max_retries': 0,
'proxy.config.http.transaction_no_activity_timeout_out': 5,
'proxy.config.diags.debug.enabled': 0,
'proxy.config.diags.debug.tags': 'http',
})
ts.Disk.remap_config.AddLine('map /blocked http://10.1.1.1:{0}'.format(Test.Variables.blocked_upstream_port))
ts.Disk.remap_config.AddLine('map /not-blocked http://10.1.1.1:{0}'.format(Test.Variables.upstream_port))
ts.Disk.logging_yaml.AddLines(
'''
logging:
formats:
- name: testformat
format: '%<pssc> %<cquc> %<pscert> %<cscert>'
logs:
- mode: ascii
format: testformat
filename: squid
'''.split("\n")
)
# Set up the network name space. Requires privilege
tr = Test.AddTestRun("tr-ns-setup")
tr.Processes.Default.StartBefore(ts)
tr.Processes.Default.TimeOut = 2
tr.Setup.Copy('setupnetns.sh')
tr.Processes.Default.Command = 'echo start; sudo sh -x ./setupnetns.sh {0} {1}'.format(
Test.Variables.blocked_upstream_port, Test.Variables.upstream_port)
# Request to the port that is blocked in the network ns. The SYN should never be responded to
# and the connect timeout should trigger with a 50x return. If the SYN handshake occurs, the
# no activity timeout would trigger, but not before the test timeout expires
tr = Test.AddTestRun("tr-blocking")
tr.Processes.Default.Command = 'curl -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression(
"HTTP/1.1 502 internal error - server connection terminated", "Connect failed")
tr = Test.AddTestRun("tr-blocking-post")
tr.Processes.Default.Command = 'curl -d "stuff" -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression(
"HTTP/1.1 502 internal error - server connection terminated", "Connect failed")
# Should not catch the connect timeout. Even though the first bytes are not sent until after the 2 second connect timeout
# But before the no-activity timeout
tr = Test.AddTestRun("tr-delayed")
tr.Setup.Copy('delay-server.sh')
tr.Setup.Copy('case1.sh')
tr.Processes.Default.Command = 'sh ./case1.sh {0} {1}'.format(ts.Variables.port, ts.Variables.upstream_port)
tr.Processes.Default.TimeOut = 7
tr.Processes.Default.Streams.All = Testers.ContainsExpression("HTTP/1.1 200", "Connect succeeded")
# cleanup the network namespace and virtual network
tr = Test.AddTestRun("tr-cleanup")
tr.Processes.Default.Command = 'sudo ip netns del testserver; sudo ip link del veth0 type veth peer name veth1'
tr.Processes.Default.TimeOut = 4
tr = Test.AddTestRun("Wait for the access log to write out")
tr.Processes.Default.StartBefore(server4, ready=When.FileExists(ts.Disk.squid_log))
tr.StillRunningAfter = ts
tr.Processes.Default.Command = 'echo "log file exists"'
tr.Processes.Default.ReturnCode = 0
| """
"""
Test.Summary = 'Testing ATS TCP handshake timeout'
Test.SkipIf(Condition.true('Test requires privilege'))
ts = Test.MakeATSProcess('ts')
Test.ContinueOnFail = True
Test.GetTcpPort('blocked_upstream_port')
Test.GetTcpPort('upstream_port')
server4 = Test.MakeOriginServer('server4')
ts.Disk.records_config.update({'proxy.config.url_remap.remap_required': 1, 'proxy.config.http.connect_attempts_timeout': 2, 'proxy.config.http.connect_attempts_max_retries': 0, 'proxy.config.http.transaction_no_activity_timeout_out': 5, 'proxy.config.diags.debug.enabled': 0, 'proxy.config.diags.debug.tags': 'http'})
ts.Disk.remap_config.AddLine('map /blocked http://10.1.1.1:{0}'.format(Test.Variables.blocked_upstream_port))
ts.Disk.remap_config.AddLine('map /not-blocked http://10.1.1.1:{0}'.format(Test.Variables.upstream_port))
ts.Disk.logging_yaml.AddLines("\nlogging:\n formats:\n - name: testformat\n format: '%<pssc> %<cquc> %<pscert> %<cscert>'\n logs:\n - mode: ascii\n format: testformat\n filename: squid\n".split('\n'))
tr = Test.AddTestRun('tr-ns-setup')
tr.Processes.Default.StartBefore(ts)
tr.Processes.Default.TimeOut = 2
tr.Setup.Copy('setupnetns.sh')
tr.Processes.Default.Command = 'echo start; sudo sh -x ./setupnetns.sh {0} {1}'.format(Test.Variables.blocked_upstream_port, Test.Variables.upstream_port)
tr = Test.AddTestRun('tr-blocking')
tr.Processes.Default.Command = 'curl -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression('HTTP/1.1 502 internal error - server connection terminated', 'Connect failed')
tr = Test.AddTestRun('tr-blocking-post')
tr.Processes.Default.Command = 'curl -d "stuff" -i http://127.0.0.1:{0}/blocked {0}'.format(ts.Variables.port)
tr.Processes.Default.TimeOut = 4
tr.Processes.Default.Streams.All = Testers.ContainsExpression('HTTP/1.1 502 internal error - server connection terminated', 'Connect failed')
tr = Test.AddTestRun('tr-delayed')
tr.Setup.Copy('delay-server.sh')
tr.Setup.Copy('case1.sh')
tr.Processes.Default.Command = 'sh ./case1.sh {0} {1}'.format(ts.Variables.port, ts.Variables.upstream_port)
tr.Processes.Default.TimeOut = 7
tr.Processes.Default.Streams.All = Testers.ContainsExpression('HTTP/1.1 200', 'Connect succeeded')
tr = Test.AddTestRun('tr-cleanup')
tr.Processes.Default.Command = 'sudo ip netns del testserver; sudo ip link del veth0 type veth peer name veth1'
tr.Processes.Default.TimeOut = 4
tr = Test.AddTestRun('Wait for the access log to write out')
tr.Processes.Default.StartBefore(server4, ready=When.FileExists(ts.Disk.squid_log))
tr.StillRunningAfter = ts
tr.Processes.Default.Command = 'echo "log file exists"'
tr.Processes.Default.ReturnCode = 0 |
# udacity solution, normaly I would have ordered it, and the traverse it being O(nlogn + N).
# like this is O(2N)
def longest_consecutive_subsequence(input_list):
# Create a dictionary.
# Each element of the input_list would become a "key", and
# the corresponding index in the input_list would become the "value"
element_dict = dict()
# Traverse through the input_list, and populate the dictionary
# Time complexity = O(n)
for index, element in enumerate(input_list):
element_dict[element] = index
# Represents the length of longest subsequence
max_length = -1
# Represents the index of smallest element in the longest subsequence
starts_at = -1
# Traverse again - Time complexity = O(n)
for index, element in enumerate(input_list):
current_starts = index
element_dict[element] = -1 # Mark as visited
current_count = 1 # length of the current subsequence
'''CHECK ONE ELEMENT FORWARD'''
current = element + 1 # `current` is the expected number
# check if the expected number is available (as a key) in the dictionary,
# and it has not been visited yet (i.e., value > 0)
# Time complexity: Constant time for checking a key and retrieving the value = O(1)
while current in element_dict and element_dict[current] > 0:
current_count += 1 # increment the length of subsequence
element_dict[current] = -1 # Mark as visited
current = current + 1
'''CHECK ONE ELEMENT BACKWARD'''
# Time complexity: Constant time for checking a key and retrieving the value = O(1)
current = element - 1 # `current` is the expected number
while current in element_dict and element_dict[current] > 0:
current_starts = element_dict[
current] # index of smallest element in the current subsequence
current_count += 1 # increment the length of subsequence
element_dict[current] = -1
current = current - 1
'''If length of current subsequence >= max length of previously visited subsequence'''
if current_count >= max_length:
if current_count == max_length and current_starts > starts_at:
continue
starts_at = current_starts # index of smallest element in the current (longest so far) subsequence
max_length = current_count # store the length of current (longest so far) subsequence
start_element = input_list[starts_at] # smallest element in the longest subsequence
# return a NEW list starting from `start_element` to `(start_element + max_length)`
return [element for element in range(start_element, start_element + max_length)]
def test_function(test_case):
output = longest_consecutive_subsequence(test_case[0])
if output == test_case[1]:
print("Pass")
else:
print("Fail")
test_case_1 = [[5, 4, 7, 10, 1, 3, 55, 2], [1, 2, 3, 4, 5]]
test_function(test_case_1)
test_case_2 = [[2, 12, 9, 16, 10, 5, 3, 20, 25, 11, 1, 8, 6 ], [8, 9, 10, 11, 12]]
test_function(test_case_2)
test_case_3 = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
test_function(test_case_3) | def longest_consecutive_subsequence(input_list):
element_dict = dict()
for (index, element) in enumerate(input_list):
element_dict[element] = index
max_length = -1
starts_at = -1
for (index, element) in enumerate(input_list):
current_starts = index
element_dict[element] = -1
current_count = 1
'CHECK ONE ELEMENT FORWARD'
current = element + 1
while current in element_dict and element_dict[current] > 0:
current_count += 1
element_dict[current] = -1
current = current + 1
'CHECK ONE ELEMENT BACKWARD'
current = element - 1
while current in element_dict and element_dict[current] > 0:
current_starts = element_dict[current]
current_count += 1
element_dict[current] = -1
current = current - 1
'If length of current subsequence >= max length of previously visited subsequence'
if current_count >= max_length:
if current_count == max_length and current_starts > starts_at:
continue
starts_at = current_starts
max_length = current_count
start_element = input_list[starts_at]
return [element for element in range(start_element, start_element + max_length)]
def test_function(test_case):
output = longest_consecutive_subsequence(test_case[0])
if output == test_case[1]:
print('Pass')
else:
print('Fail')
test_case_1 = [[5, 4, 7, 10, 1, 3, 55, 2], [1, 2, 3, 4, 5]]
test_function(test_case_1)
test_case_2 = [[2, 12, 9, 16, 10, 5, 3, 20, 25, 11, 1, 8, 6], [8, 9, 10, 11, 12]]
test_function(test_case_2)
test_case_3 = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
test_function(test_case_3) |
# Problem Code: HDIVISR
def highest_divisor(n):
for i in range(10, 0, -1):
if not n % i:
return i
n = int(input())
print(highest_divisor(n))
| def highest_divisor(n):
for i in range(10, 0, -1):
if not n % i:
return i
n = int(input())
print(highest_divisor(n)) |
_settings = None
def set_settings(settings):
global _settings
_settings = settings
def get_settings():
global _settings
return _settings | _settings = None
def set_settings(settings):
global _settings
_settings = settings
def get_settings():
global _settings
return _settings |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-basic-statistics/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
N = int(input())
NUMBER = list(map(int, input().split()))
# Mean
SUM = 0
for i in NUMBER:
SUM = SUM + i
print(float(SUM / N))
# Median
NUMBER = sorted(NUMBER)
if N % 2 == 0:
A = NUMBER[N//2]
B = NUMBER[N//2 - 1]
print((A+B)/2)
else:
print(NUMBER[N//2])
# Mode
MAX_1 = 0
NUMBER = sorted(NUMBER)
for i in NUMBER:
COUNTER = 0
INDEX = NUMBER.index(i)
for j in range(INDEX, len(NUMBER)):
if i == NUMBER[j]:
COUNTER = COUNTER + 1
if COUNTER > MAX_1:
MAX_1 = COUNTER
if MAX_1 == 1:
MODE = NUMBER[0]
else:
MODE = i
print(MODE)
| n = int(input())
number = list(map(int, input().split()))
sum = 0
for i in NUMBER:
sum = SUM + i
print(float(SUM / N))
number = sorted(NUMBER)
if N % 2 == 0:
a = NUMBER[N // 2]
b = NUMBER[N // 2 - 1]
print((A + B) / 2)
else:
print(NUMBER[N // 2])
max_1 = 0
number = sorted(NUMBER)
for i in NUMBER:
counter = 0
index = NUMBER.index(i)
for j in range(INDEX, len(NUMBER)):
if i == NUMBER[j]:
counter = COUNTER + 1
if COUNTER > MAX_1:
max_1 = COUNTER
if MAX_1 == 1:
mode = NUMBER[0]
else:
mode = i
print(MODE) |
# Module 3 Assignment
# Jordan Phillips
myfile = open("question.txt", "r+")
myquestion = myfile.read()
myresponse = input(myquestion)
myfile.write(myresponse)
myfile.close()
| myfile = open('question.txt', 'r+')
myquestion = myfile.read()
myresponse = input(myquestion)
myfile.write(myresponse)
myfile.close() |
favorite_fruits = ['banana', 'orange', 'lemon']
listed_fruits = ['apple', 'banana', 'orange', 'grappe', 'blackberry', 'lemon']
for favorite_fruit in favorite_fruits:
for listed_fruit in listed_fruits:
if listed_fruit == favorite_fruit:
print ("You really like " + listed_fruit)
print ('\n')
for listed_fruit in listed_fruits:
check = False
for favorite_fruit in favorite_fruits:
if favorite_fruit == listed_fruit:
check = True
print ("You reallly like " + listed_fruit)
if check == False:
print ("You really don't like " + listed_fruit)
print ('\n')
for listed_fruit in listed_fruits:
if listed_fruit in favorite_fruits:
print ("You really like " + listed_fruit)
else :
print ("You really don't like " + listed_fruit)
| favorite_fruits = ['banana', 'orange', 'lemon']
listed_fruits = ['apple', 'banana', 'orange', 'grappe', 'blackberry', 'lemon']
for favorite_fruit in favorite_fruits:
for listed_fruit in listed_fruits:
if listed_fruit == favorite_fruit:
print('You really like ' + listed_fruit)
print('\n')
for listed_fruit in listed_fruits:
check = False
for favorite_fruit in favorite_fruits:
if favorite_fruit == listed_fruit:
check = True
print('You reallly like ' + listed_fruit)
if check == False:
print("You really don't like " + listed_fruit)
print('\n')
for listed_fruit in listed_fruits:
if listed_fruit in favorite_fruits:
print('You really like ' + listed_fruit)
else:
print("You really don't like " + listed_fruit) |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 08:47:55 2018
@author: conta
"""
costprice=input()
costprice=int(costprice)
sellprice=input()
sellprice=int(sellprice)
if(costprice<sellprice):
print("Profit")
if(costprice==sellprice):
print("Neither")
if(costprice>sellprice):
print("Loss") | """
Created on Sat Aug 11 08:47:55 2018
@author: conta
"""
costprice = input()
costprice = int(costprice)
sellprice = input()
sellprice = int(sellprice)
if costprice < sellprice:
print('Profit')
if costprice == sellprice:
print('Neither')
if costprice > sellprice:
print('Loss') |
numbers = list(map(int, input().split()))
expected = [2, 2, 2, 1.5, 1, 0]
ans = 0
for n, e in zip(numbers, expected):
ans += e * n
print(ans)
| numbers = list(map(int, input().split()))
expected = [2, 2, 2, 1.5, 1, 0]
ans = 0
for (n, e) in zip(numbers, expected):
ans += e * n
print(ans) |
"""
Wave Gradient
by Ira Greenberg.
Generate a gradient along a sin() wave.
"""
amplitude = 30
fillGap = 2.5
def setup():
size(640, 360)
background(200)
noLoop()
def draw():
frequency = 0
for i in range(-75, height + 75):
# Reset angle to 0, so waves stack properly
angle = 0
# Increasing frequency causes more gaps
frequency += .002
for j in range(0, width + 75):
py = i + sin(radians(angle)) * amplitude
angle += frequency
c = color(abs(py - i) * 255 / amplitude, 255 - abs(py - i)
* 255 / amplitude, j * (255.0 / (width + 50)))
# Hack to fill gaps. Raise value of fillGap if you increase
# frequency
for filler in range(0, int(fillGap)):
set(int(j - filler), int(py) - filler, c)
set(int(j), int(py), c)
set(int(j + filler), int(py) + filler, c)
| """
Wave Gradient
by Ira Greenberg.
Generate a gradient along a sin() wave.
"""
amplitude = 30
fill_gap = 2.5
def setup():
size(640, 360)
background(200)
no_loop()
def draw():
frequency = 0
for i in range(-75, height + 75):
angle = 0
frequency += 0.002
for j in range(0, width + 75):
py = i + sin(radians(angle)) * amplitude
angle += frequency
c = color(abs(py - i) * 255 / amplitude, 255 - abs(py - i) * 255 / amplitude, j * (255.0 / (width + 50)))
for filler in range(0, int(fillGap)):
set(int(j - filler), int(py) - filler, c)
set(int(j), int(py), c)
set(int(j + filler), int(py) + filler, c) |
class Student:
def __init__(self):
self.name=input('Enter name')
self.age=int(input('Enter age'))
def display(self):
print(self.name,self.age)
s=Student()
s.display()
| class Student:
def __init__(self):
self.name = input('Enter name')
self.age = int(input('Enter age'))
def display(self):
print(self.name, self.age)
s = student()
s.display() |
i4 = Int32Scalar("b4", 2)
i5 = Int32Scalar("b5", 2)
i6 = Int32Scalar("b6", 2)
i7 = Int32Scalar("b7", 0)
i2 = Input("op2", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}") # input 0
i3 = Output("op3", "TENSOR_QUANT8_ASYMM", "{1, 1, 1, 1}") # output 0
i0 = Parameter("op0", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}", [1, 1, 1, 1]) # parameters
i1 = Parameter("op1", "TENSOR_INT32", "{1}", [0]) # parameters
model = Model()
model = model.Conv(i2, i0, i1, i4, i5, i6, i7).To(i3)
| i4 = int32_scalar('b4', 2)
i5 = int32_scalar('b5', 2)
i6 = int32_scalar('b6', 2)
i7 = int32_scalar('b7', 0)
i2 = input('op2', 'TENSOR_QUANT8_ASYMM', '{1, 2, 2, 1}')
i3 = output('op3', 'TENSOR_QUANT8_ASYMM', '{1, 1, 1, 1}')
i0 = parameter('op0', 'TENSOR_QUANT8_ASYMM', '{1, 2, 2, 1}', [1, 1, 1, 1])
i1 = parameter('op1', 'TENSOR_INT32', '{1}', [0])
model = model()
model = model.Conv(i2, i0, i1, i4, i5, i6, i7).To(i3) |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2021 plun1331
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
class APIKey(object):
r"""Represents an API Key.
:param key_data: The raw key data from the API.
:type key_data: dict
:param cached: The raw key data from the API.
:type cached: bool
:param hypixel: The raw key data from the API.
:type hypixel: PyPixel.Hypixel.Hypixel"""
def __init__(self, key_data: dict, cached, hypixel):
self.cached = cached
self._hypixel = hypixel
self.key = key_data['key']
self.owner = key_data['owner']
self.ratelimit = key_data['limit']
self.request_past_minute = key_data['queriesInPastMin']
self.total_requests = key_data['totalQueries']
async def get_owner(self):
r"""|coro|
Gets the owner pf the key as a Player object.
:return: The key's owner.
:rtype: PyPixel.Player.Player"""
return await self._hypixel.get_player(self.owner)
| """
MIT License
Copyright (c) 2021 plun1331
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
class Apikey(object):
"""Represents an API Key.
:param key_data: The raw key data from the API.
:type key_data: dict
:param cached: The raw key data from the API.
:type cached: bool
:param hypixel: The raw key data from the API.
:type hypixel: PyPixel.Hypixel.Hypixel"""
def __init__(self, key_data: dict, cached, hypixel):
self.cached = cached
self._hypixel = hypixel
self.key = key_data['key']
self.owner = key_data['owner']
self.ratelimit = key_data['limit']
self.request_past_minute = key_data['queriesInPastMin']
self.total_requests = key_data['totalQueries']
async def get_owner(self):
"""|coro|
Gets the owner pf the key as a Player object.
:return: The key's owner.
:rtype: PyPixel.Player.Player"""
return await self._hypixel.get_player(self.owner) |
# ----------------------------------------------------------------
# SUNDIALS Copyright Start
# Copyright (c) 2002-2022, Lawrence Livermore National Security
# and Southern Methodist University.
# All rights reserved.
#
# See the top-level LICENSE and NOTICE files for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# SUNDIALS Copyright End
# ----------------------------------------------------------------
sundials_version = 'v6.1.1'
arkode_version = 'v5.1.1'
cvode_version = 'v6.1.1'
cvodes_version = 'v6.1.1'
ida_version = 'v6.1.1'
idas_version = 'v5.1.1'
kinsol_version = 'v6.1.1'
| sundials_version = 'v6.1.1'
arkode_version = 'v5.1.1'
cvode_version = 'v6.1.1'
cvodes_version = 'v6.1.1'
ida_version = 'v6.1.1'
idas_version = 'v5.1.1'
kinsol_version = 'v6.1.1' |
# Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2))
# Space: O(m + n + k^2)
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def get_max_digits(nums, start, end, max_digits):
max_digits[end] = max_digit(nums, end)
for i in reversed(range(start, end)):
max_digits[i] = delete_digit(max_digits[i + 1])
def max_digit(nums, k):
drop = len(nums) - k
res = []
for num in nums:
while drop and res and res[-1] < num:
res.pop()
drop -= 1
res.append(num)
return res[:k]
def delete_digit(nums):
res = list(nums)
for i in range(len(res)):
if i == len(res) - 1 or res[i] < res[i + 1]:
res = res[:i] + res[i+1:]
break
return res
def merge(a, b):
return [max(a, b).pop(0) for _ in range(len(a)+len(b))]
m, n = len(nums1), len(nums2)
max_digits1, max_digits2 = [[] for _ in range(k + 1)], [[] for _ in range(k + 1)]
get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1)
get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2)
return max(merge(max_digits1[i], max_digits2[k-i]) \
for i in range(max(0, k - n), min(k, m) + 1))
| class Solution(object):
def max_number(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def get_max_digits(nums, start, end, max_digits):
max_digits[end] = max_digit(nums, end)
for i in reversed(range(start, end)):
max_digits[i] = delete_digit(max_digits[i + 1])
def max_digit(nums, k):
drop = len(nums) - k
res = []
for num in nums:
while drop and res and (res[-1] < num):
res.pop()
drop -= 1
res.append(num)
return res[:k]
def delete_digit(nums):
res = list(nums)
for i in range(len(res)):
if i == len(res) - 1 or res[i] < res[i + 1]:
res = res[:i] + res[i + 1:]
break
return res
def merge(a, b):
return [max(a, b).pop(0) for _ in range(len(a) + len(b))]
(m, n) = (len(nums1), len(nums2))
(max_digits1, max_digits2) = ([[] for _ in range(k + 1)], [[] for _ in range(k + 1)])
get_max_digits(nums1, max(0, k - n), min(k, m), max_digits1)
get_max_digits(nums2, max(0, k - m), min(k, n), max_digits2)
return max((merge(max_digits1[i], max_digits2[k - i]) for i in range(max(0, k - n), min(k, m) + 1))) |
# Captain's Quarters (106030800)
blackViking = 3300110
sm.spawnMob(blackViking) | black_viking = 3300110
sm.spawnMob(blackViking) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-06
Last_modify: 2016-03-06
******************************************
'''
'''
Given a binary tree,
return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next
level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
q1 = [root]
q2 = []
levels = []
while q1:
level = []
while q1:
cur = q1.pop()
level.append(cur.val)
if cur.left:
q2.append(cur.left)
if cur.right:
q2.append(cur.right)
levels.append(level)
level = []
while q2:
cur = q2.pop()
level.append(cur.val)
if cur.right:
q1.append(cur.right)
if cur.left:
q1.append(cur.left)
if level:
levels.append(level)
return levels
| """
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-06
Last_modify: 2016-03-06
******************************************
"""
"\nGiven a binary tree,\nreturn the zigzag level order traversal of its nodes' values.\n(ie, from left to right, then right to left for the next\nlevel and alternate between).\n\nFor example:\nGiven binary tree {3,9,20,#,#,15,7},\n 3\n / 9 20\n / 15 7\nreturn its zigzag level order traversal as:\n[\n [3],\n [20,9],\n [15,7]\n]\n"
class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzag_level_order(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
q1 = [root]
q2 = []
levels = []
while q1:
level = []
while q1:
cur = q1.pop()
level.append(cur.val)
if cur.left:
q2.append(cur.left)
if cur.right:
q2.append(cur.right)
levels.append(level)
level = []
while q2:
cur = q2.pop()
level.append(cur.val)
if cur.right:
q1.append(cur.right)
if cur.left:
q1.append(cur.left)
if level:
levels.append(level)
return levels |
"""
Cadaster system in Chicago as of 2014
based on https://nationalmap.gov/small_scale/a_plss.html
"""
'''
Survery Township
The Public Land Survey System (PLSS) forms the foundation of
Cook County's cadastral system for identifying and locating
land records. Tax parcels are identified using township and
section notation, in a modified format. This PLSS feature data
set is intended to correspond to tax pages in the Cook County
Assessor's Tax Map book (current as of tax year 2000 for 66%
of the County and as of tax year 2001 for the remaining 33%
of the County), and should not be used for measurement or
surveyor purposes. In addition, the parcel attributes PINA
(area/township) and PINSA (subarea/section) do not necessarily
correspond to the PLSS township and section polygon in which
a given parcel resides. The PLSS data is modeled as a single
composite network coverage that encompasses townships (area),
sections (subarea), quarter sections, and half quarter section.
'''
# Survey Township https://datacatalog.cookcountyil.gov/resource/iz5k-qtpu.json
'''
PLSS Line
The County's system of tax maps is based on the Illinois
Public Land Survey System (PLSS). In the PLSS, each township
is divided into 36 sections, and each section into four
quarter-sections. A quarter-section is further divided into
two tax map sheets, often called "pages". Each tax map
(1/4 mile by 1/2 mile) represents the east or west half of
one quarter-section, and typically there are eight tax maps
per section.
'''
# PLSS Line https://datacatalog.cookcountyil.gov/resource/yvw8-g53g.json
'''
Section
The PLSS data is modeled as a single composite network
coverage that encompasses townships (area), sections (subarea),
quarter sections, and half quarter section. If an indigenous
people's reserve was present on the tax map, it was digitized
to create subpolygons of the half-quarter section, and those
polygons were attributed with the name of the reserve. Within
this PLSS data set, a half-quarter section is the smallest
polygon unit, except in cases where an Indigenous People's
Reserve line is present.
'''
# Section https://datacatalog.cookcountyil.gov/resource/xhzu-6w77.json
'''
Unincorporated Zoning by Parcel
This is a Cook County Feature class of Unincorporated Zoning
District Boundaries by parcel. This data is provided by the
Cook County Dept. Of Building and Zoning and is maintained by
the Cook County Zoning Board of Appeals.
Only unincorporated district boundaries are available, please
contact specific municipalities for questions regarding
incorporated municipal zoning districts.
'''
# https://datacatalog.cookcountyil.gov/resource/yski-9fq7.json
'''
Unincorporated Zoning districts
This is a Cook County Feature class of Unincorporated Zoning
District Boundaries (Aggregate). This data is provided by the
Cook County Dept. Of Building and Zoning and is maintained by
the Cook County Zoning Board of Appeals.
Only unincorporated district boundaries are available, please
contact specific municipalities for questions regarding
incorporated municipal zoning districts.
'''
# https://datacatalog.cookcountyil.gov/resource/jwue-cxuq.json
'''
Community Areas
'''
# https://data.cityofchicago.org/resource/igwz-8jzy.json
'''
Wards 2015
'''
# https://data.cityofchicago.org/resource/k9yb-bpqx.json
# requests and
# https://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3
# api_url = '{}orgs/{}/repos'.format(api_url_base, username) | """
Cadaster system in Chicago as of 2014
based on https://nationalmap.gov/small_scale/a_plss.html
"""
"\nSurvery Township\nThe Public Land Survey System (PLSS) forms the foundation of \nCook County's cadastral system for identifying and locating \nland records. Tax parcels are identified using township and \nsection notation, in a modified format. This PLSS feature data \nset is intended to correspond to tax pages in the Cook County \nAssessor's Tax Map book (current as of tax year 2000 for 66% \nof the County and as of tax year 2001 for the remaining 33% \nof the County), and should not be used for measurement or \nsurveyor purposes. In addition, the parcel attributes PINA \n(area/township) and PINSA (subarea/section) do not necessarily \ncorrespond to the PLSS township and section polygon in which \na given parcel resides. The PLSS data is modeled as a single \ncomposite network coverage that encompasses townships (area), \nsections (subarea), quarter sections, and half quarter section.\n"
'\nPLSS Line\nThe County\'s system of tax maps is based on the Illinois\nPublic Land Survey System (PLSS). In the PLSS, each township\nis divided into 36 sections, and each section into four\nquarter-sections. A quarter-section is further divided into\ntwo tax map sheets, often called "pages". Each tax map\n(1/4 mile by 1/2 mile) represents the east or west half of\none quarter-section, and typically there are eight tax maps\nper section.\n'
"\nSection\nThe PLSS data is modeled as a single composite network \ncoverage that encompasses townships (area), sections (subarea), \nquarter sections, and half quarter section. If an indigenous \npeople's reserve was present on the tax map, it was digitized \nto create subpolygons of the half-quarter section, and those \npolygons were attributed with the name of the reserve. Within \nthis PLSS data set, a half-quarter section is the smallest \npolygon unit, except in cases where an Indigenous People's \nReserve line is present.\n"
'\nUnincorporated Zoning by Parcel\nThis is a Cook County Feature class of Unincorporated Zoning \nDistrict Boundaries by parcel. This data is provided by the \nCook County Dept. Of Building and Zoning and is maintained by \nthe Cook County Zoning Board of Appeals. \nOnly unincorporated district boundaries are available, please \ncontact specific municipalities for questions regarding \nincorporated municipal zoning districts.\n'
'\nUnincorporated Zoning districts\nThis is a Cook County Feature class of Unincorporated Zoning \nDistrict Boundaries (Aggregate). This data is provided by the \nCook County Dept. Of Building and Zoning and is maintained by \nthe Cook County Zoning Board of Appeals. \nOnly unincorporated district boundaries are available, please \ncontact specific municipalities for questions regarding \nincorporated municipal zoning districts.\n'
'\nCommunity Areas\n'
'\nWards 2015\n' |
# zadanie 1
# Wygeneruj liczby podzielne przez 4 i zapisz je do pliku.
plik = open('zadanie_1.txt', 'w')
for i in range(0, 1000, 1):
plik.write(str(i*4)+'\n')
plik.close() | plik = open('zadanie_1.txt', 'w')
for i in range(0, 1000, 1):
plik.write(str(i * 4) + '\n')
plik.close() |
# File: forescoutcounteract_consts.py
#
# Copyright (c) 2018-2022 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
#
# Define your constants here
FS_DEX_HOST_ENDPOINT = '/fsapi/niCore/Hosts'
FS_DEX_LIST_ENDPOINT = '/fsapi/niCore/Lists'
FS_DEX_TEST_CONNECTIVITY = \
"""<?xml version="1.0" encoding="UTF-8"?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="update">
<OPTIONS CREATE_NEW_HOST="true"/>
<HOST_KEY NAME="ip" VALUE="{host_key_value}"/>
<PROPERTIES></PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_UPDATE_SIMPLE_PROPERTY = \
"""<?xml version='1.0' encoding='utf-8'?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="update">
<OPTIONS CREATE_NEW_HOST="{create_host}"/>
<HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>
<PROPERTIES>
<PROPERTY NAME="{property_name}">
<VALUE>{property_value}</VALUE>
</PROPERTY>
</PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_DELETE_SIMPLE_PROPERTY = \
"""<?xml version='1.0' encoding='utf-8'?>
<FSAPI TYPE="request" API_VERSION="1.0">
<TRANSACTION TYPE="delete">
<HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>
<PROPERTIES>
<PROPERTY NAME="{property_name}" />
</PROPERTIES>
</TRANSACTION>
</FSAPI>"""
FS_DEX_UPDATE_LIST_PROPERTY = \
"""<?xml version="1.0" encoding="UTF-8"?>
<FSAPI TYPE="request" API_VERSION="2.0">
<TRANSACTION TYPE="{transaction_type}">
<LISTS>
{list_body}
</LISTS>
</TRANSACTION>
</FSAPI>"""
FS_WEB_LOGIN = '/api/login'
FS_WEB_HOSTS = '/api/hosts'
FS_WEB_HOSTFIELDS = '/api/hostfields'
FS_WEB_POLICIES = '/api/policies'
# Error message constants
FS_ERR_CODE_MSG = "Error code unavailable"
FS_ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
FS_PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
# validate integer
ERR_VALID_INT_MSG = "Please provide a valid integer value in the {}"
ERR_NON_NEG_INT_MSG = "Please provide a valid non-negative integer value in the {}"
ERR_POSITIVE_INTEGER_MSG = "Please provide a valid non-zero positive integer value in the {}"
HOST_ID_INT_PARAM = "'host_id' action parameter"
# Timeout
FS_DEFAULT_TIMEOUT = 30
| fs_dex_host_endpoint = '/fsapi/niCore/Hosts'
fs_dex_list_endpoint = '/fsapi/niCore/Lists'
fs_dex_test_connectivity = '<?xml version="1.0" encoding="UTF-8"?>\n <FSAPI TYPE="request" API_VERSION="1.0">\n <TRANSACTION TYPE="update">\n <OPTIONS CREATE_NEW_HOST="true"/>\n <HOST_KEY NAME="ip" VALUE="{host_key_value}"/>\n <PROPERTIES></PROPERTIES>\n </TRANSACTION>\n </FSAPI>'
fs_dex_update_simple_property = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n <FSAPI TYPE="request" API_VERSION="1.0">\n <TRANSACTION TYPE="update">\n <OPTIONS CREATE_NEW_HOST="{create_host}"/>\n <HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>\n <PROPERTIES>\n <PROPERTY NAME="{property_name}">\n <VALUE>{property_value}</VALUE>\n </PROPERTY>\n </PROPERTIES>\n </TRANSACTION>\n </FSAPI>'
fs_dex_delete_simple_property = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n <FSAPI TYPE="request" API_VERSION="1.0">\n <TRANSACTION TYPE="delete">\n <HOST_KEY NAME="{host_key_name}" VALUE="{host_key_value}"/>\n <PROPERTIES>\n <PROPERTY NAME="{property_name}" />\n </PROPERTIES>\n </TRANSACTION>\n </FSAPI>'
fs_dex_update_list_property = '<?xml version="1.0" encoding="UTF-8"?>\n <FSAPI TYPE="request" API_VERSION="2.0">\n <TRANSACTION TYPE="{transaction_type}">\n <LISTS>\n {list_body}\n </LISTS>\n </TRANSACTION>\n </FSAPI>'
fs_web_login = '/api/login'
fs_web_hosts = '/api/hosts'
fs_web_hostfields = '/api/hostfields'
fs_web_policies = '/api/policies'
fs_err_code_msg = 'Error code unavailable'
fs_err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
fs_parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters'
err_valid_int_msg = 'Please provide a valid integer value in the {}'
err_non_neg_int_msg = 'Please provide a valid non-negative integer value in the {}'
err_positive_integer_msg = 'Please provide a valid non-zero positive integer value in the {}'
host_id_int_param = "'host_id' action parameter"
fs_default_timeout = 30 |
def find_secret_message(paragraph):
unique = set()
result = []
for word in (a.strip('.,:!?').lower() for a in paragraph.split()):
if word in unique and word not in result:
result.append(word)
unique.add(word)
return ' '.join(result)
| def find_secret_message(paragraph):
unique = set()
result = []
for word in (a.strip('.,:!?').lower() for a in paragraph.split()):
if word in unique and word not in result:
result.append(word)
unique.add(word)
return ' '.join(result) |
class EntityNotFoundException(Exception):
pass
class SessionExpiredException(Exception):
pass
| class Entitynotfoundexception(Exception):
pass
class Sessionexpiredexception(Exception):
pass |
def main():
NAME = input("What is your name?: ")
print("Hello "+ str(NAME) + "!")
if __name__ == '__main__':
main() | def main():
name = input('What is your name?: ')
print('Hello ' + str(NAME) + '!')
if __name__ == '__main__':
main() |
#ipaddress validation
def ip_val(ipadd):
l=ipadd.split(".")
if len(l)!=4:
return False
for i in l:
if int(i) not in range(256):
return False
return True
print(ip_val("192.168.0.1"))
print(ip_val("192.168.0.1.1"))
print(ip_val("192.168.258.1"))
| def ip_val(ipadd):
l = ipadd.split('.')
if len(l) != 4:
return False
for i in l:
if int(i) not in range(256):
return False
return True
print(ip_val('192.168.0.1'))
print(ip_val('192.168.0.1.1'))
print(ip_val('192.168.258.1')) |
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
digits = [str(i) for i in digits]
s = str(int(''.join(digits))+1)
ans = [int(i) for i in s]
return ans
| class Solution:
def xxx(self, digits: List[int]) -> List[int]:
digits = [str(i) for i in digits]
s = str(int(''.join(digits)) + 1)
ans = [int(i) for i in s]
return ans |
X,Y,x,y=map(int,input().split())
while 1:
d=""
if y>Y:d+="N";y-=1
if y<Y:d+="S";y+=1
if x>X:d+="W";x-=1
if x<X:d+="E";x+=1
print(d)
| (x, y, x, y) = map(int, input().split())
while 1:
d = ''
if y > Y:
d += 'N'
y -= 1
if y < Y:
d += 'S'
y += 1
if x > X:
d += 'W'
x -= 1
if x < X:
d += 'E'
x += 1
print(d) |
with open("Input.txt", "r") as fp:
lines = fp.readlines()
# remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in lines]
# clockwise
# N
# W E
# S
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
cur_direction = 0 # East
pos_x, pos_y = (0, 0)
for line in lines:
instr, val = line[:1], int(line[1:])
print(f"{instr}, {val}")
if instr == 'F':
pos_x += directions[cur_direction][0] * val
pos_y += directions[cur_direction][1] * val
if instr == 'E':
pos_x += val
if instr == 'S':
pos_y -= val
if instr == 'W':
pos_x -= val
if instr == 'N':
pos_y += val
if instr == 'R':
if val == 90:
cur_direction = (cur_direction + 1) % 4
elif val == 180:
cur_direction = (cur_direction + 2) % 4
elif val == 270:
cur_direction = (cur_direction + 3) % 4
else:
print(f"UNKNOSN R {val}")
raise Exception
if instr == 'L':
if val == 90:
cur_direction = (cur_direction - 1 + 4) % 4
elif val == 180:
cur_direction = (cur_direction - 2 + 4) % 4
elif val == 270:
cur_direction = (cur_direction - 3 + 4) % 4
else:
print(f"UNKNOSN R {val}")
raise Exception
print(f"pos= {pos_x}, {pos_y}")
print(f"solution1 = {abs(pos_x) + abs(pos_y)}") # 2847
| with open('Input.txt', 'r') as fp:
lines = fp.readlines()
lines = [x.strip() for x in lines]
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
cur_direction = 0
(pos_x, pos_y) = (0, 0)
for line in lines:
(instr, val) = (line[:1], int(line[1:]))
print(f'{instr}, {val}')
if instr == 'F':
pos_x += directions[cur_direction][0] * val
pos_y += directions[cur_direction][1] * val
if instr == 'E':
pos_x += val
if instr == 'S':
pos_y -= val
if instr == 'W':
pos_x -= val
if instr == 'N':
pos_y += val
if instr == 'R':
if val == 90:
cur_direction = (cur_direction + 1) % 4
elif val == 180:
cur_direction = (cur_direction + 2) % 4
elif val == 270:
cur_direction = (cur_direction + 3) % 4
else:
print(f'UNKNOSN R {val}')
raise Exception
if instr == 'L':
if val == 90:
cur_direction = (cur_direction - 1 + 4) % 4
elif val == 180:
cur_direction = (cur_direction - 2 + 4) % 4
elif val == 270:
cur_direction = (cur_direction - 3 + 4) % 4
else:
print(f'UNKNOSN R {val}')
raise Exception
print(f'pos= {pos_x}, {pos_y}')
print(f'solution1 = {abs(pos_x) + abs(pos_y)}') |
# You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other
# items. We want to create the text that should be displayed next to such an item.
#
# Implement a function likes :: [String] -> String, which must take in input array, containing the names of people
# who like an item. It must return the display text as shown in the examples:
#
# likes([]) # must be "no one likes this"
# likes(["Peter"]) # must be "Peter likes this"
# likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this"
# likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this"
# likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this"
# For 4 or more names, the number in and 2 others simply increases.
def likes(names):
if not names:
return "no one likes this"
elif len(names) == 1:
return names[0] + " likes this"
elif len(names) == 2:
return names[0] + " and " + names[1] + " like this"
elif len(names) == 3:
return names[0] + ", " + names[1] + " and " + names[2] + " like this"
else:
return names[0] + ", " + names[1] + " and " + str(len(names)-2) + " others like this"
| def likes(names):
if not names:
return 'no one likes this'
elif len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return names[0] + ' and ' + names[1] + ' like this'
elif len(names) == 3:
return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'
else:
return names[0] + ', ' + names[1] + ' and ' + str(len(names) - 2) + ' others like this' |
"""
Probably will roll a wxPython front end because web frameworks
hurt my soul, while Qt-esque front ends are only extraordinarily
annoying and repetitive nightmares written in some semblance of
python.
"""
| """
Probably will roll a wxPython front end because web frameworks
hurt my soul, while Qt-esque front ends are only extraordinarily
annoying and repetitive nightmares written in some semblance of
python.
""" |
class Solution:
def isValid(self, s: str) -> bool:
ans = list()
for x in s:
if x in ['(', '{', '[']:
ans.append(x)
elif x == ')':
if len(ans) < 1:
return False
if ans[-1] == '(':
ans.pop(-1)
else:
return False
elif x == ']':
if len(ans) < 1:
return False
if ans[-1] == '[':
ans.pop(-1)
else:
return False
elif x == '}':
if len(ans) < 1:
return False
if ans[-1] == '{':
ans.pop(-1)
else:
return False
if len(ans) > 0:
return False
return True
| class Solution:
def is_valid(self, s: str) -> bool:
ans = list()
for x in s:
if x in ['(', '{', '[']:
ans.append(x)
elif x == ')':
if len(ans) < 1:
return False
if ans[-1] == '(':
ans.pop(-1)
else:
return False
elif x == ']':
if len(ans) < 1:
return False
if ans[-1] == '[':
ans.pop(-1)
else:
return False
elif x == '}':
if len(ans) < 1:
return False
if ans[-1] == '{':
ans.pop(-1)
else:
return False
if len(ans) > 0:
return False
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.