content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""Scale a group of active objects up/down as required"""
class ScalingGroup:
"""Scale collection of objects up/down to meet criteria"""
def __init__(self, object_pool):
self.object_pool = object_pool
self.instances = []
def scale_to(self, number):
"""Adjust number of instances to... | """Scale a group of active objects up/down as required"""
class Scalinggroup:
"""Scale collection of objects up/down to meet criteria"""
def __init__(self, object_pool):
self.object_pool = object_pool
self.instances = []
def scale_to(self, number):
"""Adjust number of instances to... |
num_acc=int(input())
accounts={}
for i in range(num_acc):
p,b = input().split()
accounts[p] = int(b)
#print (accounts)
num_t=int(input())
trans=[]
for i in range(num_t):
pf,pt,c,t = input().split()
trans.append((int(t),pf,pt,int(c)))
trans = sorted(trans)
for i in trans:
accounts[i[1]]-=i[3]
accounts[i[2]]+=i[3]... | num_acc = int(input())
accounts = {}
for i in range(num_acc):
(p, b) = input().split()
accounts[p] = int(b)
num_t = int(input())
trans = []
for i in range(num_t):
(pf, pt, c, t) = input().split()
trans.append((int(t), pf, pt, int(c)))
trans = sorted(trans)
for i in trans:
accounts[i[1]] -= i[3]
... |
count = 1
def show_title(msg):
global count
print('\n')
print('#' * 30)
print(count, '.', msg)
print('#' * 30)
count += 1
| count = 1
def show_title(msg):
global count
print('\n')
print('#' * 30)
print(count, '.', msg)
print('#' * 30)
count += 1 |
# result = 5/3
# if result:
data = ['asdf', '123', 'Aa']
names = ['asdf', '123', 'Aa']
# builtin functions that operate on sequences
# zip
# max
# min
# sum
sum([1, 2, 3])
# generator expressions
print(sum(len(x) for x in data))
# all
# any
print(all(len(x) > 2 for x in data))
print(any(len(... | data = ['asdf', '123', 'Aa']
names = ['asdf', '123', 'Aa']
sum([1, 2, 3])
print(sum((len(x) for x in data)))
print(all((len(x) > 2 for x in data)))
print(any((len(x) > 2 for x in data)))
for x in reversed(data):
pass
get_len = lambda x: len(x)
def get_length(x):
return len(x)
def get_second_item(x):
retur... |
__copyright__ = "2015 Cisco Systems, Inc."
# Define your areas here. you can add or remove area in areas_container
areas_container = [
{
"areaId": "area1",
"areaName": "Area Name 1",
"dimension": {
"length": 100,
"offsetX": 0,
"offsetY": 0,
"u... | __copyright__ = '2015 Cisco Systems, Inc.'
areas_container = [{'areaId': 'area1', 'areaName': 'Area Name 1', 'dimension': {'length': 100, 'offsetX': 0, 'offsetY': 0, 'unit': 'FEET', 'width': 100}, 'floorRefId': '723402329507758200'}, {'areaId': 'area2', 'areaName': 'Area Name 2', 'dimension': {'length': 500, 'offsetX':... |
# apis_v1/documentation_source/voter_guide_possibility_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_guide_possibility_retrieve_doc_template_values(url_root):
"""
Show documentation about voterGuidePossibilityRetrieve
"""
required_query_parameter_list = [
... | def voter_guide_possibility_retrieve_doc_template_values(url_root):
"""
Show documentation about voterGuidePossibilityRetrieve
"""
required_query_parameter_list = [{'name': 'voter_device_id', 'value': 'string', 'description': 'An 88 character unique identifier linked to a voter record on the server'}, {... |
Errors = {
400: "BAD_REQUEST_BODY",
401: "UNAUTHORIZED",
403: "ACCESS_DENIED",
404: "NotFoundError",
406: "NotAcceptableError",
409: "ConflictError",
415: "UnsupportedMediaTypeError",
422: "UnprocessableEntityError",
429: "TooManyRequestsError",
... | errors = {400: 'BAD_REQUEST_BODY', 401: 'UNAUTHORIZED', 403: 'ACCESS_DENIED', 404: 'NotFoundError', 406: 'NotAcceptableError', 409: 'ConflictError', 415: 'UnsupportedMediaTypeError', 422: 'UnprocessableEntityError', 429: 'TooManyRequestsError', 500: 'API_CONFIGURATION_ERROR', 502: 'BadGatewayError', 503: 'ServiceUnavai... |
response = {"username": "username", "password": "pass"}
db = list()
def add_user(user_obj):
password = response.get("password")
if len(password) < 5:
return "Password is shorter than 5 characters."
else:
db.append(user_obj)
return "User has been added."
print(add_user(response))
... | response = {'username': 'username', 'password': 'pass'}
db = list()
def add_user(user_obj):
password = response.get('password')
if len(password) < 5:
return 'Password is shorter than 5 characters.'
else:
db.append(user_obj)
return 'User has been added.'
print(add_user(response))
pri... |
#errorcodes.py
#version 2.0.6
errorList = ["no error",
"error code 1",
"mrBayes.py: Could not open quartets file",
"mrBayes.py: Could not interpret quartets file",
"mrBayes.py: Could not open translate file",
"mrBayes.py: Could not interpret translate fi... | error_list = ['no error', 'error code 1', 'mrBayes.py: Could not open quartets file', 'mrBayes.py: Could not interpret quartets file', 'mrBayes.py: Could not open translate file', 'mrBayes.py: Could not interpret translate file', 'mrBayes.py: Could not interpret condor job name', 'mrBayes.py: Could not find tarfile', '... |
size_matrix = int(input())
matrix = []
pls = []
for i in range(size_matrix):
matrix.append([x for x in input()])
for row in range(size_matrix):
for col in range(size_matrix):
if matrix[row][col] == 'B':
pls.append((row, col))
count_food = 0
for row in range(size_matrix):
for col in r... | size_matrix = int(input())
matrix = []
pls = []
for i in range(size_matrix):
matrix.append([x for x in input()])
for row in range(size_matrix):
for col in range(size_matrix):
if matrix[row][col] == 'B':
pls.append((row, col))
count_food = 0
for row in range(size_matrix):
for col in range... |
"""createwxdb configuration information.
"""
#: MongoDb URI where fisb_location DB is located.
MONGO_URI = 'mongodb://localhost:27017/'
| """createwxdb configuration information.
"""
mongo_uri = 'mongodb://localhost:27017/' |
+ utility('transmissionMgmt',50)
+ requiresFunction('transmissionMgmt','transmissionF')
+ utility('transmissionF',100)
+ requiresFunction('transmissionF','opcF')
+ implements('opcF','opc',0)
+ consumesData('transmissionMgmt','engineerWorkstation','statusRestData',False,0,True,1,True,0.5)
#Allocation/Deployments
+isTyp... | +utility('transmissionMgmt', 50)
+requires_function('transmissionMgmt', 'transmissionF')
+utility('transmissionF', 100)
+requires_function('transmissionF', 'opcF')
+implements('opcF', 'opc', 0)
+consumes_data('transmissionMgmt', 'engineerWorkstation', 'statusRestData', False, 0, True, 1, True, 0.5)
+is_type('opc', 'ser... |
class AsyncSerialPy3Mixin:
async def read_exactly(self, n):
data = bytearray()
while len(data) < n:
remaining = n - len(data)
data += await self.read(remaining)
return data
async def write_exactly(self, data):
while data:
res = await self.writ... | class Asyncserialpy3Mixin:
async def read_exactly(self, n):
data = bytearray()
while len(data) < n:
remaining = n - len(data)
data += await self.read(remaining)
return data
async def write_exactly(self, data):
while data:
res = await self.wri... |
def test_clear_group(app):
while 0 != app.group.count_groups():
app.group.delete_first_group()
else:
print("Group list is already empty")
| def test_clear_group(app):
while 0 != app.group.count_groups():
app.group.delete_first_group()
else:
print('Group list is already empty') |
def attritems(class_):
def _getitem(self, key):
return getattr(self, key)
setattr(class_, '__getitem__', _getitem)
if getattr(class_, '__setitem__', None):
delattr(class_, '__setitem__')
if getattr(class_, '__delitem__', None):
delattr(class_, '__delitem__')
return class_... | def attritems(class_):
def _getitem(self, key):
return getattr(self, key)
setattr(class_, '__getitem__', _getitem)
if getattr(class_, '__setitem__', None):
delattr(class_, '__setitem__')
if getattr(class_, '__delitem__', None):
delattr(class_, '__delitem__')
return class_
@... |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root: return []
result, q = [], [root]
while q:
node = ... | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
(result, q) = ([], [root])
while q:
... |
BINGO_BOARD_LENGTH = 5
class BingoField:
def __init__(self, number):
self.number = number
self.marked = False
class BingoBoard:
def __init__(self, numbers: list):
self.board = [[], [], [], [], []]
self.already_won = False
for row_idx, _ in enumerate(numbers):
... | bingo_board_length = 5
class Bingofield:
def __init__(self, number):
self.number = number
self.marked = False
class Bingoboard:
def __init__(self, numbers: list):
self.board = [[], [], [], [], []]
self.already_won = False
for (row_idx, _) in enumerate(numbers):
... |
x=input('first number?')
y=input('second number?')
outcome=int(x)*int(y)
print (outcome)
| x = input('first number?')
y = input('second number?')
outcome = int(x) * int(y)
print(outcome) |
# -*- coding: utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ... | """
ui_utils.py
Some UI utility functions
"""
class Gui:
@classmethod
def draw_icon_button(cls, enabled, layout, iconName, operator, frame=True):
col = layout.column()
col.enabled = enabled
bt = col.operator(operator, text='', icon=iconName, emboss=frame)
@clas... |
def validate_extension(filename: str) -> bool:
"""
Validate file extension
:param filename: file name as string
:return: True if extension is allowed
"""
allowed_extensions = {'png', 'jpg', 'jpeg'}
return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions | def validate_extension(filename: str) -> bool:
"""
Validate file extension
:param filename: file name as string
:return: True if extension is allowed
"""
allowed_extensions = {'png', 'jpg', 'jpeg'}
return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions |
'''
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Appends the i... | """
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Appends the i... |
# Challenge 9 : Write a function named same_values() that takes two lists of numbers of equal size as parameters.
# The function should return a list of the indices where the values were equal in lst1 and lst2.
# Date : Sun 07 Jun 2020 09:28:38 AM IST
def same_values(lst1, lst2):
newList = []
... | def same_values(lst1, lst2):
new_list = []
for i in range(len(lst1)):
if lst1[i] == lst2[i]:
newList.append(i)
return newList
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5])) |
def info(a):
a = raw_input("type your height here: ")
return a
| def info(a):
a = raw_input('type your height here: ')
return a |
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
elif num < 0:
num += 2**32
hex_chars, res = '0123456789abcdef', ''
while num:
res = hex_chars[num % 16] + res
... | class Solution(object):
def to_hex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
elif num < 0:
num += 2 ** 32
(hex_chars, res) = ('0123456789abcdef', '')
while num:
res = hex_chars[num % 16]... |
def strategy(history, memory):
if memory is None:
memory = (0, 0)
defections = memory[0]
count = memory[1]
choice = 1
if count > 0:
if count < defections:
choice = 0
count += 1
elif count == defections:
count += 1
elif count > defections:
count = 0
elif history.shape[1] >= 1 an... | def strategy(history, memory):
if memory is None:
memory = (0, 0)
defections = memory[0]
count = memory[1]
choice = 1
if count > 0:
if count < defections:
choice = 0
count += 1
elif count == defections:
count += 1
elif count > defec... |
def get_2(digits, one, seven, four):
for digit in digits:
if len(digit - one - seven - four) == 2:
return digit
assert False, f"2 cannot be calculated from {digits=} using {one=}, {seven=} and {four=}"
def get_3(digits, two):
for digit in digits:
if len(digit - two) == 1:
... | def get_2(digits, one, seven, four):
for digit in digits:
if len(digit - one - seven - four) == 2:
return digit
assert False, f'2 cannot be calculated from digits={digits!r} using one={one!r}, seven={seven!r} and four={four!r}'
def get_3(digits, two):
for digit in digits:
if len... |
# Firstly, get the flatfile from the user.
def getFile():
file_path = input("Input the path to the flat file: ")
try:
keypath = open(file_path, "r")
return keypath
except:
print("No file found there.")
# Secondly, iterate through the file and update a state dictionary containing str... | def get_file():
file_path = input('Input the path to the flat file: ')
try:
keypath = open(file_path, 'r')
return keypath
except:
print('No file found there.')
def analyze_file(file):
state_dict = {'string_state': '', 'grid_state': [0, 0]}
nav_grid = [['A', 'B', 'C', 'D', 'E... |
def linear_service_fee(principal, fee=0.0):
"""Calculate service fee proportional to the principal.
If :math:`S` is the principal and :math:`g` is the fee aliquot, then the
fee is given by :math:`gS`.
"""
return float(principal * fee)
| def linear_service_fee(principal, fee=0.0):
"""Calculate service fee proportional to the principal.
If :math:`S` is the principal and :math:`g` is the fee aliquot, then the
fee is given by :math:`gS`.
"""
return float(principal * fee) |
#!/usr/bin/env python
""" generated source for module Event """
# package: org.ggp.base.util.observer
class Event(object):
""" generated source for class Event """
| """ generated source for module Event """
class Event(object):
""" generated source for class Event """ |
#
# @lc app=leetcode id=83 lang=python3
#
# [83] Remove Duplicates from Sorted List
#
# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
#
# algorithms
# Easy (41.95%)
# Likes: 774
# Dislikes: 82
# Total Accepted: 333.1K
# Total Submissions: 779.9K
# Testcase Example: '[... | class Solution:
def delete_duplicates(self, head: ListNode) -> ListNode:
if not head:
return head
(p, q) = (head, head.next)
while q:
if p.val == q.val:
p.next = q.next
q = q.next
else:
p = p.next
re... |
def high_and_low(numbers):
numbers = list((max(map(int,numbers.split())),min(map(int,numbers.split()))))
return ' '.join(map(str,numbers))
def high_and_lowB(numbers):
nn = [int(s) for s in numbers.split(" ")]
return "%i %i" % (max(nn),min(nn)) | def high_and_low(numbers):
numbers = list((max(map(int, numbers.split())), min(map(int, numbers.split()))))
return ' '.join(map(str, numbers))
def high_and_low_b(numbers):
nn = [int(s) for s in numbers.split(' ')]
return '%i %i' % (max(nn), min(nn)) |
"""
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Exam... | """
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Exam... |
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
... | grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']]
def grid_output(grid):
... |
#
TYPES = [('int', 'INT'),
('varchar', 'VARCHAR'),
('boolean', 'BOOLEAN'),
('json', 'JSON'),
('timestamp', 'TIMESTAMP'),
('enum', 'ENUM')]
class UnknownType(Exception):
pass
class NotImplementeD(Exception):
pass
class SQLTypes(object):
__slots__ = ['_type',... | types = [('int', 'INT'), ('varchar', 'VARCHAR'), ('boolean', 'BOOLEAN'), ('json', 'JSON'), ('timestamp', 'TIMESTAMP'), ('enum', 'ENUM')]
class Unknowntype(Exception):
pass
class Notimplemented(Exception):
pass
class Sqltypes(object):
__slots__ = ['_type', '_init']
def __new__(cls, *args, **kwargs):
... |
t = int(input())
for i in range(t):
b,c=map(int,input().split())
ans = (2*b-c-1)//2
print(2*ans)
| t = int(input())
for i in range(t):
(b, c) = map(int, input().split())
ans = (2 * b - c - 1) // 2
print(2 * ans) |
def moveZeroes(nums):
lastNonZero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[lastNonZero], nums[i] = nums[i], nums[lastNonZero]
lastNonZero += 1
nums = [0, 1, 0, 3, 12]
moveZeroes(nums)
print(nums) # [1, 3, 12, 0, 0]
nums = [4, 2, 4, 0, 0, 3, 0, 5, 1, 0]
moveZeroes(nu... | def move_zeroes(nums):
last_non_zero = 0
for i in range(len(nums)):
if nums[i] != 0:
(nums[lastNonZero], nums[i]) = (nums[i], nums[lastNonZero])
last_non_zero += 1
nums = [0, 1, 0, 3, 12]
move_zeroes(nums)
print(nums)
nums = [4, 2, 4, 0, 0, 3, 0, 5, 1, 0]
move_zeroes(nums)
print(... |
def move(n, a, b, c):
if n == 1:
print(str(a) + " " + str(c))
else:
move(n - 1, a, c, b)
print(str(a) + " " + str(c))
move(n - 1, b, a, c)
def Num11729():
n = int(input())
print(2 ** n -1)
move(n, 1, 2, 3)
Num11729()
| def move(n, a, b, c):
if n == 1:
print(str(a) + ' ' + str(c))
else:
move(n - 1, a, c, b)
print(str(a) + ' ' + str(c))
move(n - 1, b, a, c)
def num11729():
n = int(input())
print(2 ** n - 1)
move(n, 1, 2, 3)
num11729() |
def get_synset(path='../data/imagenet_synset_words.txt'):
with open(path, 'r') as f:
# Strip off the first word (until space, maxsplit=1), then synset is remainder
return [ line.strip().split(' ', 1)[1] for line in f]
| def get_synset(path='../data/imagenet_synset_words.txt'):
with open(path, 'r') as f:
return [line.strip().split(' ', 1)[1] for line in f] |
"""
Cloudless Package Information
"""
__title__ = 'cloudless'
__description__ = 'The cloudless infrastructure project.'
__url__ = 'https://github.com/sverch/cloudless'
__version__ = '0.0.5'
__author__ = 'Shaun Verch'
__author_email__ = 'shaun@getcloudless.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2018 ... | """
Cloudless Package Information
"""
__title__ = 'cloudless'
__description__ = 'The cloudless infrastructure project.'
__url__ = 'https://github.com/sverch/cloudless'
__version__ = '0.0.5'
__author__ = 'Shaun Verch'
__author_email__ = 'shaun@getcloudless.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2018 ... |
"""
[2015-12-16] Challenge #245 [Intermediate] Ggggggg gggg Ggggg-ggggg!
https://www.reddit.com/r/dailyprogrammer/comments/3x3hqa/20151216_challenge_245_intermediate_ggggggg_gggg/
We have discovered a new species of aliens! They look like
[this](https://www.redditstatic.com/about/assets/reddit-alien.png) and are tryi... | """
[2015-12-16] Challenge #245 [Intermediate] Ggggggg gggg Ggggg-ggggg!
https://www.reddit.com/r/dailyprogrammer/comments/3x3hqa/20151216_challenge_245_intermediate_ggggggg_gggg/
We have discovered a new species of aliens! They look like
[this](https://www.redditstatic.com/about/assets/reddit-alien.png) and are tryi... |
class Deque:
def __init__(self):
self.deque =[]
def addFront(self,element):
self.deque.append(element)
print("After adding from front the deque value is : ", self.deque)
def addRear(self,element):
self.deque.insert(0,element)
print("After adding from end t... | class Deque:
def __init__(self):
self.deque = []
def add_front(self, element):
self.deque.append(element)
print('After adding from front the deque value is : ', self.deque)
def add_rear(self, element):
self.deque.insert(0, element)
print('After adding from end the ... |
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
class Metric(object):
"""
Metric object contains:
- the metric sub prefix,
- metrics mapping (response JSON key to metric name and metric type)
- tags mapping (response JS... | class Metric(object):
"""
Metric object contains:
- the metric sub prefix,
- metrics mapping (response JSON key to metric name and metric type)
- tags mapping (response JSON key to tag name)
- field_to_name (response JSON key to metric name)
"""
def __init__(self, prefix... |
things = [
'An old Box',
'Ancient Knife',
'Oppenheimer Blue Diamond',
'1962 Ferrari 250 GTO Berlinetta',
'Hindoostan Antique Map 1826',
'Rare 19th C. Mughal Indian ZANGHAL Axe with Strong',
'1850 $5 Baldwin Gold Half Eagle UNCIRCULATED',
'Chevrolet Corvette 1963'
]
| things = ['An old Box', 'Ancient Knife', 'Oppenheimer Blue Diamond', '1962 Ferrari 250 GTO Berlinetta', 'Hindoostan Antique Map 1826', 'Rare 19th C. Mughal Indian ZANGHAL Axe with Strong', '1850 $5 Baldwin Gold Half Eagle UNCIRCULATED', 'Chevrolet Corvette 1963'] |
x,y=0,0
for i in range(5):
b=input("").split()
for j in range(5):
if(b[j]=='1'):
x=i+1
y=j+1
x=x-3;
y=y-3;
if(x<0):
x=-x
if(y<0):
y=-y
print(x+y)
a=[[],[],[]]
b=len(a[1])//2
a[b][b],a[i][j]=a[i][j],a[b][b]
a=tan(3.33) | (x, y) = (0, 0)
for i in range(5):
b = input('').split()
for j in range(5):
if b[j] == '1':
x = i + 1
y = j + 1
x = x - 3
y = y - 3
if x < 0:
x = -x
if y < 0:
y = -y
print(x + y)
a = [[], [], []]
b = len(a[1]) // 2
(a[b][b], a[i][j]) = (a[i][j], a[b][b])
a = tan(3.33) |
class Salary:
def __init__(self, pay):
self._pay = pay
def get_total(self):
return (self._pay * 12) // 4.9545
class SalarySenior:
def __init__(self, pay):
self._pay = pay
def get_total(self):
return (self._pay * 24) // 4.9545
class Employee:
def __init__(self, p... | class Salary:
def __init__(self, pay):
self._pay = pay
def get_total(self):
return self._pay * 12 // 4.9545
class Salarysenior:
def __init__(self, pay):
self._pay = pay
def get_total(self):
return self._pay * 24 // 4.9545
class Employee:
def __init__(self, pay,... |
changes = {'.': 0, ',': 1, '+': 2, '-': 3, '>':4, '<': 5, '[': 6, ']': 7}
def convert(code):
current = 0
x = ""
for i in code:
dest = changes.get(i)
if dest is None:
continue
diff = (dest - current) % 8
x += "+" * diff + "!"
current = dest
print(cu... | changes = {'.': 0, ',': 1, '+': 2, '-': 3, '>': 4, '<': 5, '[': 6, ']': 7}
def convert(code):
current = 0
x = ''
for i in code:
dest = changes.get(i)
if dest is None:
continue
diff = (dest - current) % 8
x += '+' * diff + '!'
current = dest
print(... |
{'application':{'type':'Application',
'name':'webgrabber',
'backgrounds': [
{'type':'Background',
'name':'bgGrabber',
'title':'webgrabber PythonCard Application',
'size':(540, 172),
'statusBar':1,
'menubar': {'type':'MenuBar',
'menus': [
... | {'application': {'type': 'Application', 'name': 'webgrabber', 'backgrounds': [{'type': 'Background', 'name': 'bgGrabber', 'title': 'webgrabber PythonCard Application', 'size': (540, 172), 'statusBar': 1, 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': '... |
# ------------------------------------------------------------------------------------
# Tutorial: The replace method replaces a specified string with another specified string.
# ------------------------------------------------------------------------------------
# Example 1.
# Replace all occurences of "dog" with "ca... | dog_txt = "I always wanted a dog! My dog is awsome :) My dog's name is Taco"
cat_txt = dog_txt.replace('dog', 'cat')
print('\nExample 1. - Replace all occurences of "dog" with "cat"')
print(f'Old String: {dog_txt}')
print(f'New String: {cat_txt}')
dog_txt = "I always wanted a dog! My dog is awsome :) My dog's name is T... |
is_day = False
lights_on = not is_day
print("Daytime?")
print(is_day)
print("Lights on?")
print(lights_on) | is_day = False
lights_on = not is_day
print('Daytime?')
print(is_day)
print('Lights on?')
print(lights_on) |
def insertionSort(arr):
output = arr[:]
#go through each element
for index in range(1, len(output)):
#grab current element
current = output[index]
#get last index of sorted output
j = index
#shift up all sorted elements that are greater than current one
whi... | def insertion_sort(arr):
output = arr[:]
for index in range(1, len(output)):
current = output[index]
j = index
while j > 0 and output[j - 1] > current:
output[j] = output[j - 1]
j = j - 1
output[j] = current
return output |
"""Namespace of all tag system in tvm
Each operator can be tagged by a tag, which indicate its type.
Generic categories
- tag.ELEMWISE="elemwise":
Elementwise operator, for example :code:`out[i, j] = input[i, j]`
- tag.BROADCAST="broadcast":
Broadcasting operator, can always map output axis to the input in or... | """Namespace of all tag system in tvm
Each operator can be tagged by a tag, which indicate its type.
Generic categories
- tag.ELEMWISE="elemwise":
Elementwise operator, for example :code:`out[i, j] = input[i, j]`
- tag.BROADCAST="broadcast":
Broadcasting operator, can always map output axis to the input in or... |
SCHEMA_URL = "https://raw.githubusercontent.com/vz-risk/veris/master/verisc-merged.json"
VARIETY_AMT_ENUMS = ['asset.assets', 'attribute.confidentiality.data', 'impact.loss']
VARIETY_AMT = ['variety', 'amount']
ASSETMAP = {'S ' : 'Server', 'N ' : 'Network', 'U ' : 'User Dev', 'M ' : 'Media',
'P ' : 'Person'... | schema_url = 'https://raw.githubusercontent.com/vz-risk/veris/master/verisc-merged.json'
variety_amt_enums = ['asset.assets', 'attribute.confidentiality.data', 'impact.loss']
variety_amt = ['variety', 'amount']
assetmap = {'S ': 'Server', 'N ': 'Network', 'U ': 'User Dev', 'M ': 'Media', 'P ': 'Person', 'T ': 'Kiosk/Te... |
N = int(input())
ans = min(9, N) + max(0, min(999, N) - 99) + max(0, min(99999, N) - 9999)
print(ans)
| n = int(input())
ans = min(9, N) + max(0, min(999, N) - 99) + max(0, min(99999, N) - 9999)
print(ans) |
__author__ = 'vlosing'
class BaseClassifier(object):
"""
Base class for classifier.
"""
def __init__(self):
pass
def fit(self, samples, labels, epochs):
raise NotImplementedError()
def partial_fit(self, samples, labels, classes):
raise NotImplementedError()
def alt... | __author__ = 'vlosing'
class Baseclassifier(object):
"""
Base class for classifier.
"""
def __init__(self):
pass
def fit(self, samples, labels, epochs):
raise not_implemented_error()
def partial_fit(self, samples, labels, classes):
raise not_implemented_error()
d... |
'''
done
'''
def Jumlah(a, b):
return a + b
print(Jumlah(2, 8)) | """
done
"""
def jumlah(a, b):
return a + b
print(jumlah(2, 8)) |
greetings = ["hello", "world", "Jenn"]
for greeting in greetings:
print(f"{greeting}, World")
def add_number(x, y):
return x + y
add_number(1, 2)
things_to_do = ["pickup meds", "shower", "change bandage", "python", "brush Baby and pack dogs", "Whole Foods", "Jocelyn"] | greetings = ['hello', 'world', 'Jenn']
for greeting in greetings:
print(f'{greeting}, World')
def add_number(x, y):
return x + y
add_number(1, 2)
things_to_do = ['pickup meds', 'shower', 'change bandage', 'python', 'brush Baby and pack dogs', 'Whole Foods', 'Jocelyn'] |
class Solution:
#Function to convert a binary tree into its mirror tree.
def mirror(self,root):
# Code here
if(root == None):
return
else:
self.mirror(root.left)
self.mirror(root.right)
root.left, root.right = root.right, root.... | class Solution:
def mirror(self, root):
if root == None:
return
else:
self.mirror(root.left)
self.mirror(root.right)
(root.left, root.right) = (root.right, root.left) |
class InvalidTableIdException(Exception):
"""
Indicate that the table id was not 0xFC as required
"""
pass
class ReservedBitsException(Exception):
"""
Indicate that bits reserved by the specification were not set to 1 as required
"""
pass
class SectionParsingErrorException(Exception)... | class Invalidtableidexception(Exception):
"""
Indicate that the table id was not 0xFC as required
"""
pass
class Reservedbitsexception(Exception):
"""
Indicate that bits reserved by the specification were not set to 1 as required
"""
pass
class Sectionparsingerrorexception(Exception):
... |
## robot_servant.py
## This code implements a search space model for a robot
## that can move around a house and pick up and put down
## objects.
## The function calls provided for a general search algorithm are:
## robot_print_problem_info()
## robot_initial_state
## robot_possible_actions(state)
## robot_successor... | print('Loading robot_servant.py')
robot_goal = 'undefined'
def robot_initialise_1():
global permanent_facts, initial_state, ROBOT_GOAL
permanent_facts = robot_permanent_facts_1
initial_state = robot_initial_state_1
robot_goal = robot_goal_1
robot_permanent_facts_1 = [('connected', 'kitchen', 'garage', ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# Invenio-Files-Transformer is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Invenio module for transforming and/or processing files."""
# TODO: This is an example file. Remov... | """Invenio module for transforming and/or processing files."""
files_transformer_default_value = 'foobar'
'Default value for the application.'
files_transformer_base_template = 'invenio_files_transformer/base.html'
'Default base template for the demo page.' |
# [Root Abyss] The World Girl
MYSTERIOUS_GIRL = 1064001 # npc Id
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext("If you're really the World Tree, can't you just like... magic yourself outta here?")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("No! Those bad people did this to me!")
... | mysterious_girl = 1064001
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext("If you're really the World Tree, can't you just like... magic yourself outta here?")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext('No! Those bad people did this to me!')
sm.setPlayerAsSpeaker()
sm.sendNext('Oh, ... |
#!usr/bin/python
# -*- coding:utf8 -*-
class MyException(Exception):
pass
try:
raise MyException('my exception')
# exception MyException as e:
except Exception as e:
print(e) | class Myexception(Exception):
pass
try:
raise my_exception('my exception')
except Exception as e:
print(e) |
# Author: Kay Hartmann <kg.hartma@gmail.com>
def weight_filler(m):
classname = m.__class__.__name__
if classname.find('MultiConv') != -1:
for conv in m.convs:
conv.weight.data.normal_(0.0, 1.)
if conv.bias is not None:
conv.bias.data.fill_(0.)
elif classname... | def weight_filler(m):
classname = m.__class__.__name__
if classname.find('MultiConv') != -1:
for conv in m.convs:
conv.weight.data.normal_(0.0, 1.0)
if conv.bias is not None:
conv.bias.data.fill_(0.0)
elif classname.find('Conv') != -1 or classname.find('Linear... |
# Copyright (c) 2021 Arm Limited.
#
# SPDX-License-Identifier: MIT
#
# 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, cop... | _tflite_typecode2_aclname = {0: 'fp32', 1: 'fp16', 2: 'integer', 3: 'qasymm8', 6: 'integer', 7: 'qsymm16', 9: 'qasymm8_signed'}
_tflite_typecode2_name = {0: 'Float32', 1: 'Float16', 2: 'Int32', 3: 'Uint8', 4: 'Int64', 5: 'String', 6: 'Bool', 7: 'Int16', 8: 'Complex64', 9: 'Int8'}
_tflite_to_acl = {'ADD': 'Add', 'AVERAG... |
class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
"""DP.
Running time: O(N*N).
"""
mines = set(tuple(mine) for mine in mines)
counts = [[0] * N for i in range(N)]
res = 0
for i in range(N):
... | class Solution:
def order_of_largest_plus_sign(self, N: int, mines: List[List[int]]) -> int:
"""DP.
Running time: O(N*N).
"""
mines = set((tuple(mine) for mine in mines))
counts = [[0] * N for i in range(N)]
res = 0
for i in range(N):
c = 0
... |
class Figura():
def __init__(self, figura):
self.__figura = figura
def area(self):
return self.__figura.area()
def perimetro(self):
return self.__figura.perimetro()
| class Figura:
def __init__(self, figura):
self.__figura = figura
def area(self):
return self.__figura.area()
def perimetro(self):
return self.__figura.perimetro() |
###
### NOTICE: this file did not exit in the original Dimorphite_DL release.
### The is newly created based on "sites_substructures.smarts" file
### - made a readable Python module from it. Andrey Frolov, 2020-09-15
### - added last column with acid-base classification. Andrey Frolov, 2020-09-11
### - added TATA sub... | data_txt = '\nTATA CC(=O)N1CN(CN(C1)C(C)=O)C(C)=O NaN NaN NaN base\n\n*Azide\t[N+0:1]=[N+:2]=[N+0:3]-[H]\t2\t4.65\t0.07071067811865513 acid\nNitro\t[C,c,N,n,O,o:1]-[NX3:2](=[O:3])-[O:4]-[H]\t3\t-1000.0\t0 acid\nAmidineGuanidine1\t[N:1]-[C:2](-[N:3])=[NX2:4]-[H:5]\t3\t12.025333333333334\t1.594104615076916... |
"""
Modification of existing parameters in this file is NOT encouraged.
"""
Sct_Cen = {'B-begin': 0, 'B-end': 430, 'R-kink': 4.91, 'B-kink': 67,
'psi-before': -12.5, 'psi-between': -15,
'psi-after': -11.7, 'l-tangency': 145, 'w-kink': 0.23}
Norma = {'B-begin': 30, 'B-end': 481, 'R-kink': 4.46, '... | """
Modification of existing parameters in this file is NOT encouraged.
"""
sct__cen = {'B-begin': 0, 'B-end': 430, 'R-kink': 4.91, 'B-kink': 67, 'psi-before': -12.5, 'psi-between': -15, 'psi-after': -11.7, 'l-tangency': 145, 'w-kink': 0.23}
norma = {'B-begin': 30, 'B-end': 481, 'R-kink': 4.46, 'B-kink': 72, 'psi-befor... |
n=int(input("enter a number"))
if(n%5==0 or n%7==0):
print("divisible by 5 or 7")
else:
print("not divisible")
| n = int(input('enter a number'))
if n % 5 == 0 or n % 7 == 0:
print('divisible by 5 or 7')
else:
print('not divisible') |
#
# PySNMP MIB module HM2-DHCPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DHCPS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:18:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
#
# PySNMP MIB module HUAWEI-UNIMNG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-UNIMNG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:49:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
"""A wrapper class for optimizer"""
class TransformerOptimizer(object):
"""A simple wrapper class for learning rate scheduling"""
def __init__(self, optimizer, k, d_model, warmup_steps=4000, step_num=0):
self.optimizer = optimizer
self.k = k
self.init_lr = d_model ** (-0.5)
se... | """A wrapper class for optimizer"""
class Transformeroptimizer(object):
"""A simple wrapper class for learning rate scheduling"""
def __init__(self, optimizer, k, d_model, warmup_steps=4000, step_num=0):
self.optimizer = optimizer
self.k = k
self.init_lr = d_model ** (-0.5)
sel... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self, head=None):
self.head = head
self.length = 1
def append(self, element):
"""
Adds the `element` at the end of the Link... | class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class Doublylinkedlist:
def __init__(self, head=None):
self.head = head
self.length = 1
def append(self, element):
"""
Adds the `element` at the end of the Lin... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CombineMethodEnum(object):
"""Implementation of the 'CombineMethod' enum.
Specifies how to combine the children of this node.
The combining strategy for child devices. Some of these strategies imply
constraint on the number of child devices... | class Combinemethodenum(object):
"""Implementation of the 'CombineMethod' enum.
Specifies how to combine the children of this node.
The combining strategy for child devices. Some of these strategies imply
constraint on the number of child devices. e.g. RAID5 will have 5
children.
'LINEAR' indic... |
'''
NAME
Program that calculates the percentage of a list of amino acids.
VERSION
[1.0]
AUTHOR
Rodrigo Daniel Hernandez Barrera <<rodrigoh@lcg.unam.mx>>
DESCRIPTION
This program takes a sequence of amino acids from a protein and a list of amino acids, looks for these in the
sequen... | """
NAME
Program that calculates the percentage of a list of amino acids.
VERSION
[1.0]
AUTHOR
Rodrigo Daniel Hernandez Barrera <<rodrigoh@lcg.unam.mx>>
DESCRIPTION
This program takes a sequence of amino acids from a protein and a list of amino acids, looks for these in the
sequen... |
#Gary Cunningham. 27/03/19
#My program intends to convert the string inputted by removing every second word on the output.
#Adaptation from python tutorials, class content and w3schools.com interactive tutorials.
#Attempted this solution alongside the inputs from the learnings of previous solutions in this problem set.... | n = input('Please enter a sentence: ')
secondstring = n.split()
for words in secondstring:
print(' '.join(secondstring[::2]))
break |
distance = int(input('Inform the distance: '))
if distance <= 200:
price = distance * 0.5
else:
price = distance * 0.45
print('Your trip cost \033[1;33;44mR$ {:.2f}\033[m.'.format(price))
| distance = int(input('Inform the distance: '))
if distance <= 200:
price = distance * 0.5
else:
price = distance * 0.45
print('Your trip cost \x1b[1;33;44mR$ {:.2f}\x1b[m.'.format(price)) |
#!/usr/bin/env python
imagedir = parent + "/oiio-images"
command += oiiotool (imagedir+"/grid.tif --scanline -o grid.iff")
command += diff_command (imagedir+"/grid.tif", "grid.iff")
| imagedir = parent + '/oiio-images'
command += oiiotool(imagedir + '/grid.tif --scanline -o grid.iff')
command += diff_command(imagedir + '/grid.tif', 'grid.iff') |
"""Helper functions."""
# Given a number, finds the next number that meets
# criteria 4 (digits never decrease).
#
# Returns that number and whether or not the new
# number meets criteria 3 (two adjacent digits are the same)
def part1_inc(n):
digits = list(str(n + 1))
will_succeed = False
for i in range(1, len(... | """Helper functions."""
def part1_inc(n):
digits = list(str(n + 1))
will_succeed = False
for i in range(1, len(digits)):
if digits[i] <= digits[i - 1]:
will_succeed = True
if digits[i] < digits[i - 1]:
for j in range(i, len(digits)):
digits[j] = digit... |
class Sang:
def __init__(self, tittel, artist):
self._tittel = tittel
self._artist = artist
def spill(self):
print('\t Spiller av', self._tittel, 'av', self._artist)
def sjekkArtist(self, navn):
liste = navn.split()
for i in liste:
if i in self._artist:
... | class Sang:
def __init__(self, tittel, artist):
self._tittel = tittel
self._artist = artist
def spill(self):
print('\t Spiller av', self._tittel, 'av', self._artist)
def sjekk_artist(self, navn):
liste = navn.split()
for i in liste:
if i in self._artist... |
"""
hopeit.engine CLI (Command Line Interface) module
provides implementation for the following CLI commands:
* **openapi** (hopeit_openapi): creation, diff and update openapi.json spec files
* **server** (hopeit_server): tool for running a server instance
"""
| """
hopeit.engine CLI (Command Line Interface) module
provides implementation for the following CLI commands:
* **openapi** (hopeit_openapi): creation, diff and update openapi.json spec files
* **server** (hopeit_server): tool for running a server instance
""" |
def searchInsert(nums, target):
if target in nums:
return nums.index(target)
elif target <= nums[0]:
return 0
elif target >= nums[-1]:
return len(nums)
else:
for idx, val in enumerate(nums):
if target < val:
nums.index(idx, target)
... | def search_insert(nums, target):
if target in nums:
return nums.index(target)
elif target <= nums[0]:
return 0
elif target >= nums[-1]:
return len(nums)
else:
for (idx, val) in enumerate(nums):
if target < val:
nums.index(idx, target)
... |
# __init__.py
"""
Docstring TBD
"""
| """
Docstring TBD
""" |
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
# edge case
if not(grid): return 0
cnt = 0
n = len(grid)
if n == 0: return 0
m = len(grid[0])
for i in range(n):
... | class Solution(object):
def num_islands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid:
return 0
cnt = 0
n = len(grid)
if n == 0:
return 0
m = len(grid[0])
for i in range(n):
... |
l = [6,2,5,5,4,5,6,3,7,6]
for _ in range(int(input())):
a,b = map(int,input().split())
ans = a + b
val = 0
for i in str(ans):
val += l[int(i)]
print(val) | l = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
for _ in range(int(input())):
(a, b) = map(int, input().split())
ans = a + b
val = 0
for i in str(ans):
val += l[int(i)]
print(val) |
def measure(bucket1, bucket2, goal, start_bucket):
if start_bucket == "one":
liter1 = bucket1
liter2 = 0
elif start_bucket == "two":
liter1 = 0
liter2 = bucket2
return bfs(bucket1, bucket2, liter1, liter2, goal, start_bucket)
def bfs(bucket1, bucket2, liter1, liter2, goal,... | def measure(bucket1, bucket2, goal, start_bucket):
if start_bucket == 'one':
liter1 = bucket1
liter2 = 0
elif start_bucket == 'two':
liter1 = 0
liter2 = bucket2
return bfs(bucket1, bucket2, liter1, liter2, goal, start_bucket)
def bfs(bucket1, bucket2, liter1, liter2, goal, s... |
class SymbolManager:
def __init__(self):
self.symbol_dic = {}
def add_symbol(self, symbol):
if symbol is None:
return
self.symbol_dic[symbol.symbol_code] = symbol
def find_symbol(self, symbol_code):
for symbol in self.symbol_dic.items():
if symbol[1... | class Symbolmanager:
def __init__(self):
self.symbol_dic = {}
def add_symbol(self, symbol):
if symbol is None:
return
self.symbol_dic[symbol.symbol_code] = symbol
def find_symbol(self, symbol_code):
for symbol in self.symbol_dic.items():
if symbol[1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
numbers = []
# collect the 3 numbers
for i in range(3):
number = input("Please provide a number: ")
while True:
try:
number = int(number)
number... | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
numbers = []
for i in range(3):
number = input('Please provide a number: ')
while True:
try:
number = int(number)
numbers.append(number)
break
except ValueError:
print(... |
# Constants for the Lines and Boxes game
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 450
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (220, 220, 220)
FRAMES_PER_SECOND = 40
NROWS = 5
NCOLS = 5
NSQUARES = NROWS * NCOLS
SPACING = 43
NLINES = 60
EMPTY = 'empty'
HUMAN = 'human'
COMPUTER = 'computer'
STARTING_X = 72
STARTI... | window_width = 800
window_height = 450
white = (255, 255, 255)
black = (0, 0, 0)
gray = (220, 220, 220)
frames_per_second = 40
nrows = 5
ncols = 5
nsquares = NROWS * NCOLS
spacing = 43
nlines = 60
empty = 'empty'
human = 'human'
computer = 'computer'
starting_x = 72
starting_y = 48
box_size = 45
line_size = 13
box_and_... |
class LinkedList:
"""
We represent a Linked List using Linked List class
having states and behaviours
states of SLL includes- self.head as an instance variable.
Behaviour of LL class will include any behaviours that we implement on a Singly list list.
Whenever a LL instance is initialized
... | class Linkedlist:
"""
We represent a Linked List using Linked List class
having states and behaviours
states of SLL includes- self.head as an instance variable.
Behaviour of LL class will include any behaviours that we implement on a Singly list list.
Whenever a LL instance is initialized
i... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert_node(root, value):
if root.data:
if value < root.data:
if root.left is None:
root.left = Node(value)
else:
insert_node(ro... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert_node(root, value):
if root.data:
if value < root.data:
if root.left is None:
root.left = node(value)
else:
insert_node(ro... |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:08:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
class HttpQueryError(Exception):
def __init__(self, status_code, message=None, is_graphql_error=False, headers=None):
"""Create a HTTP query error.
You need to pass the HTTP status code, the message that shall be shown,
whether this is a GraphQL error, and the HTTP headers that shall be s... | class Httpqueryerror(Exception):
def __init__(self, status_code, message=None, is_graphql_error=False, headers=None):
"""Create a HTTP query error.
You need to pass the HTTP status code, the message that shall be shown,
whether this is a GraphQL error, and the HTTP headers that shall be se... |
#Programa para saber la nota
nota = int(input("Introduce tu nota: "))
if nota < 5:
print("Insuficiente: esfuerzate mas")
elif nota < 6:
print("Suficiente")
elif nota < 7:
print("Bien")
elif nota < 9:
print("Notable")
else:
print("Sobresaliente: eres un/a crack")
| nota = int(input('Introduce tu nota: '))
if nota < 5:
print('Insuficiente: esfuerzate mas')
elif nota < 6:
print('Suficiente')
elif nota < 7:
print('Bien')
elif nota < 9:
print('Notable')
else:
print('Sobresaliente: eres un/a crack') |
"""Utility for configurable dictionary merges."""
class NoValue(object):
""" Placeholder for a no-value type. """
pass
# singleton for NoValue
no_value = NoValue()
def discard(dst, src, key, default):
"""Does nothing, effectively discarding the merged value."""
return no_value
def override(left,... | """Utility for configurable dictionary merges."""
class Novalue(object):
""" Placeholder for a no-value type. """
pass
no_value = no_value()
def discard(dst, src, key, default):
"""Does nothing, effectively discarding the merged value."""
return no_value
def override(left, right, key, default):
"... |
# -*- coding: utf-8 -*-
"""Top-level package for PoC DependaBot."""
__author__ = """Ivan Ogasawara"""
__email__ = 'ivan.ogasawara@gmail.com'
__version__ = '1.0.0'
| """Top-level package for PoC DependaBot."""
__author__ = 'Ivan Ogasawara'
__email__ = 'ivan.ogasawara@gmail.com'
__version__ = '1.0.0' |
# Data Types
a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex)) | a = 5
print(a, 'is of type', type(a))
a = 2.0
print(a, 'is of type', type(a))
a = 1 + 2j
print(a, 'is complex number?', isinstance(1 + 2j, complex)) |
#! /usr/bin/python3
#Note: Binary to Decimal Calculator
#Author: Khondakar
choice = int(input("[1] Decimal to Binary conversion. " + "\n[2] Binary to Decimal conversion. \nEnter choice: "))
# print("1: Decimal to Binary")
# print("2: Binary to Decimal")
val = ""
if choice == 1:
numb = int(input("Enter your whole... | choice = int(input('[1] Decimal to Binary conversion. ' + '\n[2] Binary to Decimal conversion. \nEnter choice: '))
val = ''
if choice == 1:
numb = int(input('Enter your whole Decimal number (integer): '))
while numb > 1:
val = str(numb % 2) + val
numb = numb // 2
val = str(numb % 2) + val
... |
"""
Date: Jan 13 2022
Last Revision: N/A
General Notes:
- 2249ms runtime (10.57%) and 59MB (65.71%)
- Not a bad first attempt. I wonder if I could think of something that doesn't require sorting
- However, hard to think of a solution that is better than O(n) while mine is O(n*logn)... so is it worth considering the si... | """
Date: Jan 13 2022
Last Revision: N/A
General Notes:
- 2249ms runtime (10.57%) and 59MB (65.71%)
- Not a bad first attempt. I wonder if I could think of something that doesn't require sorting
- However, hard to think of a solution that is better than O(n) while mine is O(n*logn)... so is it worth considering the si... |
class doggy(object):
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def myNameIs(self):
print ('%s, %s, %s' % (self.name, self.age, self.color))
def bark(self):
print ("Wang Wang !!")
wangcai = doggy("Wangcai Masa... | class Doggy(object):
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def my_name_is(self):
print('%s, %s, %s' % (self.name, self.age, self.color))
def bark(self):
print('Wang Wang !!')
wangcai = doggy('Wangcai Masarchik', 17... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.