content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
class Base(RuntimeError):
"""An extendible class for responding to exceptions caused within your application.
Usage:
.. code-block: python
class MyRestError(errors.Base):
pass
# somewhere in your code...
raise MyRestError(c... | class Base(RuntimeError):
"""An extendible class for responding to exceptions caused within your application.
Usage:
.. code-block: python
class MyRestError(errors.Base):
pass
# somewhere in your code...
raise MyRestError(code=01, message='You bro... |
# initialize/define the blockchain list
blockchain = []
open_txs = []
def get_last_blockchain_val():
""" Returns the last element of the blockchain list. """
if len(blockchain) < 1:
return None
return blockchain[-1]
def add_tx(tx_amt, last_tx=[1]):
""" Adds the last transaction amount
... | blockchain = []
open_txs = []
def get_last_blockchain_val():
""" Returns the last element of the blockchain list. """
if len(blockchain) < 1:
return None
return blockchain[-1]
def add_tx(tx_amt, last_tx=[1]):
""" Adds the last transaction amount
and current transaction amount to the bl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: leepstools.file.angle
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Read angle distribution result from LEEPS simulation.
"""
###############################################################################
# Copyright 2017 He... | """
.. py:currentmodule:: leepstools.file.angle
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Read angle distribution result from LEEPS simulation.
"""
class Angle:
def __init__(self):
self.theta_deg = []
self.probability_1_sr = []
self.stu_1_sr = []
def read(self... |
# coding=utf-8
class AutumnInvokeException(Exception):
pass
class InvocationTargetException(Exception):
pass
if __name__ == '__main__':
pass
| class Autumninvokeexception(Exception):
pass
class Invocationtargetexception(Exception):
pass
if __name__ == '__main__':
pass |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
'''
T: O(n log n + n^3)
S: O(1)
'''
n = len(nums)
if n < 4: return []
nums.sort()
results = set()
for x in range(n):
for y in rang... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
"""
T: O(n log n + n^3)
S: O(1)
"""
n = len(nums)
if n < 4:
return []
nums.sort()
results = set()
for x in range(n):
for y in range(x ... |
class event_meta(object):
def __init__(self):
super(event_meta, self).__init__()
def n_views(self):
return max(self._n_views, 1)
def refresh(self, meta_vec):
self._n_views = len(meta_vec)
self._x_min = []
self._y_min = []
self._x_max = []
self._... | class Event_Meta(object):
def __init__(self):
super(event_meta, self).__init__()
def n_views(self):
return max(self._n_views, 1)
def refresh(self, meta_vec):
self._n_views = len(meta_vec)
self._x_min = []
self._y_min = []
self._x_max = []
self._y_ma... |
def sum(a, b):
return a + b
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
c = sum(a, b)
print("The sum of the two numbers is: ", c)
| def sum(a, b):
return a + b
a = int(input('Enter a number: '))
b = int(input('Enter another number: '))
c = sum(a, b)
print('The sum of the two numbers is: ', c) |
#testing_loops.py
"""n = 1
# while the value of n is less than 5, print n. add 1 to n each time
# use while loops for infinate loops or for a set number of executions/loops
while n<5:
print(n)
n = n + 1"""
"""
num = float(input("Enter a postive number:"))
while num <= 0:
print("That's not a positive numbe... | """n = 1
# while the value of n is less than 5, print n. add 1 to n each time
# use while loops for infinate loops or for a set number of executions/loops
while n<5:
print(n)
n = n + 1"""
'\nnum = float(input("Enter a postive number:"))\n\nwhile num <= 0:\n print("That\'s not a positive number!")\n\n num ... |
module_attribute = "hello!"
def extension(app):
"""This extension will work"""
return "extension loaded"
def assertive_extension(app):
"""This extension won't work"""
assert False
| module_attribute = 'hello!'
def extension(app):
"""This extension will work"""
return 'extension loaded'
def assertive_extension(app):
"""This extension won't work"""
assert False |
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
positives_and_zero = collections.deque()
negatives = collections.deque()
for x in nums:
if x < 0:
negatives.appendleft(x * x)
else:
positives_and_zero.append(x * x)... | class Solution:
def sorted_squares(self, nums: List[int]) -> List[int]:
positives_and_zero = collections.deque()
negatives = collections.deque()
for x in nums:
if x < 0:
negatives.appendleft(x * x)
else:
positives_and_zero.append(x * x... |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def computeGCD(self, x, y):
if x > y:
small = y
else:
small = x
gcd = 1
for i in range(1, small + 1):
if ((x % i == 0) and (y % i == 0)):
... | class Solution:
def compute_gcd(self, x, y):
if x > y:
small = y
else:
small = x
gcd = 1
for i in range(1, small + 1):
if x % i == 0 and y % i == 0:
gcd = i
return gcd
def max_points(self, A, B):
n = len(A)
... |
TVOC =2300
if TVOC <=2500 and TVOC >=2000:
print("Level-5", "Unhealty")
print("Hygienic Rating - Situation not acceptable")
print("Recommendation - Use only if unavoidable/Intense ventilation necessary")
print("Exposure Limit - Hours")
| tvoc = 2300
if TVOC <= 2500 and TVOC >= 2000:
print('Level-5', 'Unhealty')
print('Hygienic Rating - Situation not acceptable')
print('Recommendation - Use only if unavoidable/Intense ventilation necessary')
print('Exposure Limit - Hours') |
for i in range(10):
print(i)
i = 1
while i < 6:
print(i)
i += 1
| for i in range(10):
print(i)
i = 1
while i < 6:
print(i)
i += 1 |
'''Spiral Matrix'''
# spiral :: Int -> [[Int]]
def spiral(n):
'''The rows of a spiral matrix of order N.
'''
def go(rows, cols, x):
return [list(range(x, x + cols))] + [
list(reversed(x)) for x
in zip(*go(cols, rows - 1, x + cols))
] if 0 < rows else [[]]
return... | """Spiral Matrix"""
def spiral(n):
"""The rows of a spiral matrix of order N.
"""
def go(rows, cols, x):
return [list(range(x, x + cols))] + [list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols))] if 0 < rows else [[]]
return go(n, n, 0)
def main():
"""Spiral matrix of order 5, in... |
"""
This module contains some constants that can be reused
====================================
Copyright SSS_Says_Snek, 2021-present
====================================
"""
__version__ = "2.0"
__license__ = "MIT"
__name__ = "hisock"
__copyright__ = "SSS-Says-Snek, 2021-present"
__author__ = "SSS-Says-Snek"
| """
This module contains some constants that can be reused
====================================
Copyright SSS_Says_Snek, 2021-present
====================================
"""
__version__ = '2.0'
__license__ = 'MIT'
__name__ = 'hisock'
__copyright__ = 'SSS-Says-Snek, 2021-present'
__author__ = 'SSS-Says-Snek' |
class Flight:
def __init__(self, origin, destination, month, fare, currency, fare_type, date):
self.origin = origin
self.destination = destination
self.month = month
self.fare = fare
self.currency = currency
self.fare_type = fare_type
self.date = date
def... | class Flight:
def __init__(self, origin, destination, month, fare, currency, fare_type, date):
self.origin = origin
self.destination = destination
self.month = month
self.fare = fare
self.currency = currency
self.fare_type = fare_type
self.date = date
de... |
# Users to create/delete
users = [
{'name': 'user1', 'password': 'passwd1', 'email': 'mail@example.com',
'tenant': 'tenant1', 'enabled': True},
{'name': 'user3', 'password': 'paafdssswd1', 'email': 'mdsail@example.com',
'tenant': 'tenant1', 'enabled': False}
]
# Roles to create/delete
roles = [
{... | users = [{'name': 'user1', 'password': 'passwd1', 'email': 'mail@example.com', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': 'mdsail@example.com', 'tenant': 'tenant1', 'enabled': False}]
roles = [{'name': 'SomeRole'}]
keypairs = [{'name': 'key1', 'public_key': 'ssh-rsa AAA... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 16:13:20 2018
@author: efrem
"""
class Coordinate(object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better... | """
Created on Thu Mar 15 16:13:20 2018
@author: efrem
"""
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def __str__(self):
return '<' + str(self.getX()) + ',' + str(se... |
# -*- coding: utf-8 -*-
__title__ = 'ci_release_publisher'
__description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases'
__version__ = '0.2.0'
__url__ = 'https://github.com/nurupo/ci-release-publisher'
__author__ = 'Maxim Biro'
__author_email__ = 'nurupo.contributions@gmail.com'
__license__ ... | __title__ = 'ci_release_publisher'
__description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases'
__version__ = '0.2.0'
__url__ = 'https://github.com/nurupo/ci-release-publisher'
__author__ = 'Maxim Biro'
__author_email__ = 'nurupo.contributions@gmail.com'
__license__ = 'MIT'
__copyright__ = '... |
n=1260
count=0
list=[500,100,50,10]
for coin in list:
count += n//coin
n %= coin
print(count)
| n = 1260
count = 0
list = [500, 100, 50, 10]
for coin in list:
count += n // coin
n %= coin
print(count) |
# MEDIUM
# inorder traversal using iterative
# Time O(N) Space O(H)
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
return self.iterative(root,k)
self.index= 1
self.result = -1
self.inOrder(root,k)
return self.result
def iterative(self,root,k... | class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
return self.iterative(root, k)
self.index = 1
self.result = -1
self.inOrder(root, k)
return self.result
def iterative(self, root, k):
stack = []
i = 1
while root or stack:
... |
def solution(N):
A, B = 0, 0
mult = 1
while N > 0:
q, r = divmod(N, 10)
if r == 5:
A, B = A + mult * 2, B + mult * 3
elif r == 0:
A, B = A + mult, B + mult * 9
q -= 1
else:
A, B = A + mult, B + mult * (r - 1)
mult *= 10
... | def solution(N):
(a, b) = (0, 0)
mult = 1
while N > 0:
(q, r) = divmod(N, 10)
if r == 5:
(a, b) = (A + mult * 2, B + mult * 3)
elif r == 0:
(a, b) = (A + mult, B + mult * 9)
q -= 1
else:
(a, b) = (A + mult, B + mult * (r - 1))
... |
def sum_digits(n):
s=0
while n:
s += n % 10
n /= 10
return s
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def sum_factorial_digits(n):
return sum_digits(factorial(n))
def main():
print(sum_factorial_digits(10))
print(sum_factorial_digits(100))
print(sum_factorial_digits(500... | def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def sum_factorial_digits(n):
return sum_digits(factorial(n))
def main():
print(sum_factorial_digits(10))
print(sum_fac... |
username = input("Please enter your name: ")
lastLength = 0
while True:
f = open('msgbuffer.txt', 'r+')
messages = f.readlines()
mailboxSize = len(messages)
if mailboxSize > 0 and mailboxSize > lastLength:
print( messages[-1] )
lastLength = mailboxSize
message = ... | username = input('Please enter your name: ')
last_length = 0
while True:
f = open('msgbuffer.txt', 'r+')
messages = f.readlines()
mailbox_size = len(messages)
if mailboxSize > 0 and mailboxSize > lastLength:
print(messages[-1])
last_length = mailboxSize
message = input('|')
... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
if not p and not q:
return True
elif not p or not q:
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def is_same_tree(self, p, q):
if not p and (not q):
return True
elif not p or not q:
return False
elif p.val != q.val:... |
class disjoint_set:
def __init__(self,vertex):
self.parent = self
self.rank = 0
self.vertex = vertex
def find(self):
if self.parent != self:
self.parent = self.parent.find()
return self.parent
def joinSets(self,otherTree):
root = self.find()
otherTreeRoot = otherTree.find()
if root == otherTreeRoo... | class Disjoint_Set:
def __init__(self, vertex):
self.parent = self
self.rank = 0
self.vertex = vertex
def find(self):
if self.parent != self:
self.parent = self.parent.find()
return self.parent
def join_sets(self, otherTree):
root = self.find()
... |
def get_test_data():
return {
"contact": {
"name": "Paul Kempa",
"company": "Baltimore Steel Factory"
},
"invoice": {
"items": [
{
"quantity": 12,
"description": "Item description No.0",
"unitprice": 12000.3,
"linetotal": 20
},
... | def get_test_data():
return {'contact': {'name': 'Paul Kempa', 'company': 'Baltimore Steel Factory'}, 'invoice': {'items': [{'quantity': 12, 'description': 'Item description No.0', 'unitprice': 12000.3, 'linetotal': 20}, {'quantity': 1290, 'description': 'Item description No.0', 'unitprice': 12.3, 'linetotal': 2000... |
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self, *args, **kwargs):
self.head = Node(None)
def appende(self, data):
node = Node(data)
node.next = self.head
self.head = node
# Print l... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self, *args, **kwargs):
self.head = node(None)
def appende(self, data):
node = node(data)
node.next = self.head
self.head = node
def prin... |
#
# PySNMP MIB module Wellfleet-NPK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NPK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:34:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
def retrieveDB_data(db, option, title):
data_ref = db.collection(option).document(title)
docs = data_ref.get()
return docs.to_dict()
async def initDB(db, objectList, objectDb, firestore):
if objectList is None:
data = {"create": "create"}
objectDb.set(data)
objectDb.update({"cr... | def retrieve_db_data(db, option, title):
data_ref = db.collection(option).document(title)
docs = data_ref.get()
return docs.to_dict()
async def initDB(db, objectList, objectDb, firestore):
if objectList is None:
data = {'create': 'create'}
objectDb.set(data)
objectDb.update({'cr... |
class Board:
def __init__(self, data):
self.rows = data
self.marked = [[0 for _ in range(0, 5)] for _ in range(0, 5)]
def __str__(self):
"""String representation"""
res = "BOARD:"
for r in self.rows:
res = res + "\n" + str(r)
res = res + "\nMARKED:"
... | class Board:
def __init__(self, data):
self.rows = data
self.marked = [[0 for _ in range(0, 5)] for _ in range(0, 5)]
def __str__(self):
"""String representation"""
res = 'BOARD:'
for r in self.rows:
res = res + '\n' + str(r)
res = res + '\nMARKED:'
... |
BLACK = -999
DEFAULT = 0
NORMAL = 1
PRIVATE = 10
ADMIN = 21
OWNER = 22
WHITE = 51
SUPERUSER = 999
SU = SUPERUSER
| black = -999
default = 0
normal = 1
private = 10
admin = 21
owner = 22
white = 51
superuser = 999
su = SUPERUSER |
#################################################
Cars = [["Lamborghini", 1000000, 2, 40000],
["Ferrari", 1500000, 2.5, 50000],
["BMW", 800000, 1.5, 20000]]
#################################################
print("#"*80)
print("#" + "Welcome to XYZ Car Dealership".center(78) + "#")
print("#"*80 + "\n")
while True:
... | cars = [['Lamborghini', 1000000, 2, 40000], ['Ferrari', 1500000, 2.5, 50000], ['BMW', 800000, 1.5, 20000]]
print('#' * 80)
print('#' + 'Welcome to XYZ Car Dealership'.center(78) + '#')
print('#' * 80 + '\n')
while True:
print('#' * 80)
print('#' + 'What Would You Like To Do Today?'.center(78) + '#')
print('... |
n1 = 0
n2 = 0
choice = 4
high_number = n1
while choice != 5:
while choice == 4:
print('=' * 50)
n1 = int(input('Choose a number: '))
n2 = int(input('Choose another number: '))
if n1 > n2:
high_number = n1
else:
high_number = n2
print('=' * 45)
... | n1 = 0
n2 = 0
choice = 4
high_number = n1
while choice != 5:
while choice == 4:
print('=' * 50)
n1 = int(input('Choose a number: '))
n2 = int(input('Choose another number: '))
if n1 > n2:
high_number = n1
else:
high_number = n2
print('=' * 45)
... |
white = {
"Flour": "100",
"Water": "65",
"Oil": "4",
"Salt": "2",
"Yeast": "1.5"
}
| white = {'Flour': '100', 'Water': '65', 'Oil': '4', 'Salt': '2', 'Yeast': '1.5'} |
class Row:
def __init__(self, title=None, columns=None, properties=None):
self.title = title
self.columns = columns or []
self.properties = properties or []
def __str__(self):
return str(self.title)
def __len__(self):
return len(self.title or '')
def __iter__(s... | class Row:
def __init__(self, title=None, columns=None, properties=None):
self.title = title
self.columns = columns or []
self.properties = properties or []
def __str__(self):
return str(self.title)
def __len__(self):
return len(self.title or '')
def __iter__(... |
"""6.1.5 Multiple Definition of Product Group ID
For each Product Group ID (type /$defs/product_group_id_t) Product Group elements (/product_tree/product_groups[])
it must be tested that the group_id was not already defined within the same document.
The relevant path for this test is:
/product_tree/product_group... | """6.1.5 Multiple Definition of Product Group ID
For each Product Group ID (type /$defs/product_group_id_t) Product Group elements (/product_tree/product_groups[])
it must be tested that the group_id was not already defined within the same document.
The relevant path for this test is:
/product_tree/product_group... |
#!/usr/bin/env python3
def readFile(filename):
#READFILE reads a file and returns its entire contents
# file_contents = READFILE(filename) reads a file and returns its entire
# contents in file_contents
#
# Load File
with open(filename) as fid:
file_contents = fid.read()
... | def read_file(filename):
with open(filename) as fid:
file_contents = fid.read()
return file_contents |
# values_only
# Function which accepts a dictionary of key value pairs and returns a new flat list of only the values.
#
# Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and
# returns a new list by appending the values to it. Best used on 1 level-deep key:v... | def values_only(dictionary):
lst = []
for v in dictionary.values():
lst.append(v)
return lst
ages = {'Peter': 10, 'Isabel': 11, 'Anna': 9}
print(values_only(ages)) |
# Example 1: Showing the Root Mean Squared Error (RMSE) metric. Penalises large residuals
# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary: params
params = {"objective":"reg:linear", "max_depth":4}
# Perform cross-validation: cv_results
cv_results ... | housing_dmatrix = xgb.DMatrix(data=X, label=y)
params = {'objective': 'reg:linear', 'max_depth': 4}
cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123)
print(cv_results)
print(cv_results['test-rmse-mean'].tail(1))
housing_dmatrix = xgb.DMatrix... |
buildcode="""
function Get-ExternalIP(){
$extern_ip_mask = @()
while ($response.IPAddress -eq $null){
$response = Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com
Start-Sleep -s 1
}
$octet1, $octet2, $octet3, $octet4 = $response.IPAddress.Split(".")
$extern_ip_mask += $response.IPAddress
... | buildcode = '\nfunction Get-ExternalIP(){\n\t$extern_ip_mask = @()\n\twhile ($response.IPAddress -eq $null){\n\t\t$response = Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com\n\t\tStart-Sleep -s 1\n\n\t}\n\t$octet1, $octet2, $octet3, $octet4 = $response.IPAddress.Split(".")\n\t$extern_ip_mask += $re... |
"""
Constants definition
"""
##########################################
## Configurable constants
#
AREA_WIDTH = 40.0 # width (in meters) of the drawing area
CANVAS_WIDTH = 900 # width (in pixels) of the drawing area
CANVAS_HEIGHT = 700 # height (in pixels) of the drawing area
SCROLLABLE_CANVAS_WIDTH = 4 ... | """
Constants definition
"""
area_width = 40.0
canvas_width = 900
canvas_height = 700
scrollable_canvas_width = 4 * CANVAS_WIDTH
scrollable_canvas_height = 4 * CANVAS_HEIGHT
track_width = 3.0
waypoints_radius = 5
cone_radius = 0.3
default_spacing_cones = 3.0
default_spacing_orange = 0.5
default_turning_radius = 10.... |
# Author: Isabella Doyle
# this is the menu
def displayMenu():
print("What would you like to do?")
print("\t(a) Add new student")
print("\t(v) View students")
print("\t(q) Quit")
# strips any whitespace from the left/right of the string
option = input("Please select an option (a/v/q): ").strip... | def display_menu():
print('What would you like to do?')
print('\t(a) Add new student')
print('\t(v) View students')
print('\t(q) Quit')
option = input('Please select an option (a/v/q): ').strip()
return option
def do_add(students):
student_dict = {}
studentDict['Name'] = input("Enter st... |
def my_sum(n):
return sum(list(map(int, n)))
def resolve():
n, a, b = list(map(int, input().split()))
counter = 0
for i in range(n + 1):
if a <= my_sum(str(i)) <= b:
counter += i
print(counter)
| def my_sum(n):
return sum(list(map(int, n)))
def resolve():
(n, a, b) = list(map(int, input().split()))
counter = 0
for i in range(n + 1):
if a <= my_sum(str(i)) <= b:
counter += i
print(counter) |
"""
Billing tests docstring
"""
# from django.test import TestCase
# Create your tests here.
| """
Billing tests docstring
""" |
class AllJobsTerminated(Exception):
"""This class is a special exception that is raised if a job assigned to
a thread should be properly terminated
"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
def signal_cleanup_handler(signum, frame):
"""... | class Alljobsterminated(Exception):
"""This class is a special exception that is raised if a job assigned to
a thread should be properly terminated
"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
def signal_cleanup_handler(signum, frame):
"""A function... |
"""
Mergesort in Python
https://en.wikipedia.org/wiki/Merge_sort
"""
def merge(left, right):
"""
Take two sorted lists and merge them into sorted list
"""
left_len = len(left)
right_len = len(right)
min_len = min(left_len, right_len)
merged_lis = []
i, j = 0, 0
while i < min_len an... | """
Mergesort in Python
https://en.wikipedia.org/wiki/Merge_sort
"""
def merge(left, right):
"""
Take two sorted lists and merge them into sorted list
"""
left_len = len(left)
right_len = len(right)
min_len = min(left_len, right_len)
merged_lis = []
(i, j) = (0, 0)
while i < min_len... |
def main():
n=int(input())
a=list(map(int, input().split()))
mp=(None,None)
d=0
for i in range(0, n-1, 2):
if a[i+1] - a[i] > d:
mp=(i,i+1)
a[mp[0]], a[mp[1]] = a[mp[1]], a[mp[0]]
print(sum(a[::2]))
if __name__ == '__main__':
t=int(input())
for _ in range... | def main():
n = int(input())
a = list(map(int, input().split()))
mp = (None, None)
d = 0
for i in range(0, n - 1, 2):
if a[i + 1] - a[i] > d:
mp = (i, i + 1)
(a[mp[0]], a[mp[1]]) = (a[mp[1]], a[mp[0]])
print(sum(a[::2]))
if __name__ == '__main__':
t = int(input())
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__all__ = ["CoordinateFrame"]
class CoordinateFrame(object):
"""
CoordinateFrame: Base coordinate frame class.
Parameters
----------
frameName : str
Name of the coordinate system.
coordinateRanges : dict
Dictionary with coordinate ... | __all__ = ['CoordinateFrame']
class Coordinateframe(object):
"""
CoordinateFrame: Base coordinate frame class.
Parameters
----------
frameName : str
Name of the coordinate system.
coordinateRanges : dict
Dictionary with coordinate names as keys and two-element lists
con... |
x = int(input('Enter an integer:'))
y = int(input('Enter an integer:'))
if x ^ y!=0:
print(x,' and ', y, ' are different')
else:
print(x,' and ', y, ' are same') | x = int(input('Enter an integer:'))
y = int(input('Enter an integer:'))
if x ^ y != 0:
print(x, ' and ', y, ' are different')
else:
print(x, ' and ', y, ' are same') |
#!/usr/bin/env python
#######################################
# Installation module for AttackSurfaceMapper
#######################################
DESCRIPTION="This module will install/update Attack Surface Mapper (ASM) by Andreas Georgiou - A tool that aim to automate the recon process"
AUTHOR="Andrew Schwartz"
IN... | description = 'This module will install/update Attack Surface Mapper (ASM) by Andreas Georgiou - A tool that aim to automate the recon process'
author = 'Andrew Schwartz'
install_type = 'GIT'
repository_location = 'https://github.com/superhedgy/AttackSurfaceMapper.git'
install_location = 'ASM'
debian = 'python3,pip'
af... |
def k_to_c(k):
c = (k - 273.15)
return c
k = 268.0
c = k_to_c(k)
print("kelvin of" + str(k) + "is" + str(c) + "in kelvin" )
| def k_to_c(k):
c = k - 273.15
return c
k = 268.0
c = k_to_c(k)
print('kelvin of' + str(k) + 'is' + str(c) + 'in kelvin') |
# Autogenerated file for Reflected light
# Add missing from ... import const
_JD_SERVICE_CLASS_REFLECTED_LIGHT = const(0x126c4cb2)
_JD_REFLECTED_LIGHT_VARIANT_INFRARED_DIGITAL = const(0x1)
_JD_REFLECTED_LIGHT_VARIANT_INFRARED_ANALOG = const(0x2)
_JD_REFLECTED_LIGHT_REG_BRIGHTNESS = const(JD_REG_READING)
_JD_REFLECTED_L... | _jd_service_class_reflected_light = const(309087410)
_jd_reflected_light_variant_infrared_digital = const(1)
_jd_reflected_light_variant_infrared_analog = const(2)
_jd_reflected_light_reg_brightness = const(JD_REG_READING)
_jd_reflected_light_reg_variant = const(JD_REG_VARIANT)
_jd_reflected_light_ev_dark = const(JD_EV... |
# https://leetcode.com/problems/unique-morse-code-words/
mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
class Solution:
def uniqueMorseRepresentations(self, words):
"""
:t... | mapping = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
class Solution:
def unique_morse_representations(self, words):
"""
:type words: List[str]
:rt... |
#!/bin/python3
# Designer Door Mat
# https://www.hackerrank.com/challenges/designer-door-mat/problem
n, m = map(int, input().split())
init = ".|."
for i in range(n // 2):
print(init.center(m, "-"))
init = ".|." + init + ".|."
print("WELCOME".center(m, "-"))
for i in range(n // 2):
linit = list(init)
... | (n, m) = map(int, input().split())
init = '.|.'
for i in range(n // 2):
print(init.center(m, '-'))
init = '.|.' + init + '.|.'
print('WELCOME'.center(m, '-'))
for i in range(n // 2):
linit = list(init)
init = ''.join(linit[3:len(linit) - 3])
print(init.center(m, '-')) |
# albus.exceptions
class AlbusError(Exception):
def __init__(self, message, inner=None, detail=None):
self.message = message
self.inner = inner
self.detail = detail
| class Albuserror(Exception):
def __init__(self, message, inner=None, detail=None):
self.message = message
self.inner = inner
self.detail = detail |
# Created by MechAviv
# Nyen Damage Skin | (2438086)
if sm.addDamageSkin(2438086):
sm.chat("'Nyen Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() | if sm.addDamageSkin(2438086):
sm.chat("'Nyen Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# -*- coding: utf-8 -*-
#
# Copyright 2016 Civic Knowledge. All Rights Reserved
# This software may be modified and distributed under the terms of the BSD license.
# See the LICENSE file for details.
def get_root():
return ['do some magic?','or don\'t']
def get_measure_root(id):
return "got id {} ({}) ... | def get_root():
return ['do some magic?', "or don't"]
def get_measure_root(id):
return 'got id {} ({}) '.format(id, type(id)) |
#
# PySNMP MIB module CHANNEL-CHANGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHANNEL-CHANGE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:31:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = (y2 - y1) / (x2 - x1)
print(f'Slope = {m2:.2f}') # 9
| x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = (y2 - y1) / (x2 - x1)
print(f'Slope = {m2:.2f}') |
def read_delimited_lines(file_handle, delimiter='|',
omit_delimiter=False, read_size=4):
delimited_line = ""
data = file_handle.read(read_size)
while data:
delimiter_index = data.find(delimiter)
if delimiter_index < 0:
delimited_line += data
... | def read_delimited_lines(file_handle, delimiter='|', omit_delimiter=False, read_size=4):
delimited_line = ''
data = file_handle.read(read_size)
while data:
delimiter_index = data.find(delimiter)
if delimiter_index < 0:
delimited_line += data
else:
delimited_li... |
"""
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Thoughts:
1. I... | """
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Thoughts:
1. I... |
"""Posenet model benchmark case list."""
POSE_ESTIMATION_MODEL_BENCHMARK_CASES = [
# PoseNet
{
"benchmark_name": "BM_PoseNet_MobileNetV1_075_353_481_WithDecoder",
"model_path": "posenet/posenet_mobilenet_v1_075_353_481_16_quant_decoder",
},
{
"benchmark_name": "BM_PoseNet_Mobile... | """Posenet model benchmark case list."""
pose_estimation_model_benchmark_cases = [{'benchmark_name': 'BM_PoseNet_MobileNetV1_075_353_481_WithDecoder', 'model_path': 'posenet/posenet_mobilenet_v1_075_353_481_16_quant_decoder'}, {'benchmark_name': 'BM_PoseNet_MobileNetV1_075_481_641_WithDecoder', 'model_path': 'posenet/p... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... | response.logo = a(b(span('M'), 'eta', span('B'), 'ase'), xml('™ '), _class='navbar-brand', _href=url('default', 'index'), _id='web2py-logo')
response.title = request.application.replace('_', ' ').title()
response.subtitle = ''
response.meta.author = 'Ryan Marquardt <ryan.marquardt@gmail.com>'
response.meta.d... |
def cluster_it(common_pos,no_sup,low_sup):
topla=[]
for x in common_pos:
if x in no_sup+low_sup:
continue
else:
topla.append(x)
topla.sort()
cluster={}
r_cluster={}
c_num=1
cluster['c_'+str(c_num)]=[]
for i in range (0,len(topla)-1):
po... | def cluster_it(common_pos, no_sup, low_sup):
topla = []
for x in common_pos:
if x in no_sup + low_sup:
continue
else:
topla.append(x)
topla.sort()
cluster = {}
r_cluster = {}
c_num = 1
cluster['c_' + str(c_num)] = []
for i in range(0, len(topla) - ... |
#
# PySNMP MIB module HIST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:31:14 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:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ... |
# ** CONTROL FLOW **
# IF, ELIF AND ELSE
age = 21
if age >= 21:
print("You can drive alone")
elif age < 16:
print("You are not allow to drive")
else:
print("You can drive with supervision")
# FOR LOOPS
# Iterate a List
print("\nIterate a List:")
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(... | age = 21
if age >= 21:
print('You can drive alone')
elif age < 16:
print('You are not allow to drive')
else:
print('You can drive with supervision')
print('\nIterate a List:')
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
print('\nIterate a Dictionary:')
my_dict = {'One': 1, 'Two': 2, 'Thre... |
###################################
# SOLUTION
###################################
def no_boring_zeros(n):
j = n
if j <= 0:
j = -j
x = list(range(0,100))
z = []
for k in x:
if j/(10**k) != int(j/(10**k)):
z.append((j/(10**k))*10)
if n < 0:
return -max(z)
... | def no_boring_zeros(n):
j = n
if j <= 0:
j = -j
x = list(range(0, 100))
z = []
for k in x:
if j / 10 ** k != int(j / 10 ** k):
z.append(j / 10 ** k * 10)
if n < 0:
return -max(z)
if n == 0:
return 0
else:
return max(z) |
x = [ 100, 100, 100, 100, 100 ]
y = 100
s = 50
speed = [ 1, 2, 3, 4, 5 ]
def setup():
size(640, 360, P2D)
def draw():
global x, y, s, speed
background(127)
for i in range(0, len(x)):
ellipse(x[i], y + (i * s), s, s)
x[i] += speed[i]
if x[i] > width or x[i... | x = [100, 100, 100, 100, 100]
y = 100
s = 50
speed = [1, 2, 3, 4, 5]
def setup():
size(640, 360, P2D)
def draw():
global x, y, s, speed
background(127)
for i in range(0, len(x)):
ellipse(x[i], y + i * s, s, s)
x[i] += speed[i]
if x[i] > width or x[i] < 0:
speed[i] *... |
def mph2fps(mph):
return mph*5280/3600
def myhello():
print("Konchi_wa")
| def mph2fps(mph):
return mph * 5280 / 3600
def myhello():
print('Konchi_wa') |
aux=0
aux2=0
while True:
string=list(map(str,input().split()))
if string[0]=="ABEND":break
elif string[0]=='SALIDA':
aux+=int(string[1])
aux2+=1
else:
aux-=int(string[1])
aux2-=1
print(aux)
print(aux2)
| aux = 0
aux2 = 0
while True:
string = list(map(str, input().split()))
if string[0] == 'ABEND':
break
elif string[0] == 'SALIDA':
aux += int(string[1])
aux2 += 1
else:
aux -= int(string[1])
aux2 -= 1
print(aux)
print(aux2) |
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
l1 = arr[0:(len(arr)-1)]
l2 = arr[1:]
diffs = [abs(i-j) for i,j in zip(l1, l2)]
if len(set(diffs)) == 1:
return True
return False
| class Solution:
def can_make_arithmetic_progression(self, arr: List[int]) -> bool:
arr.sort()
l1 = arr[0:len(arr) - 1]
l2 = arr[1:]
diffs = [abs(i - j) for (i, j) in zip(l1, l2)]
if len(set(diffs)) == 1:
return True
return False |
class Flower:
"""A flower."""
def __init__(self, name, petals, price):
"""Create a new flower instance.
name the name of the flower (e.g. 'Spanish Oyster')
petals the number of petals exists (e.g. 50)
price price of each flower (measured in euros)
"""
self... | class Flower:
"""A flower."""
def __init__(self, name, petals, price):
"""Create a new flower instance.
name the name of the flower (e.g. 'Spanish Oyster')
petals the number of petals exists (e.g. 50)
price price of each flower (measured in euros)
"""
self... |
class LanguageUtility:
LANGUAGES = {
"C": ("h",),
"Clojure": ("clj",),
"C++": ("cpp", "hpp", "h++",),
"Crystal": ("cr",),
"C#": ("cs", "csharp",),
"CSS": (),
"D": (),
"Go": ("golang",),
"HTML": ("htm",),
"Java": (),
"JavaScript"... | class Languageutility:
languages = {'C': ('h',), 'Clojure': ('clj',), 'C++': ('cpp', 'hpp', 'h++'), 'Crystal': ('cr',), 'C#': ('cs', 'csharp'), 'CSS': (), 'D': (), 'Go': ('golang',), 'HTML': ('htm',), 'Java': (), 'JavaScript': ('ecma', 'ecmascript', 'es', 'js'), 'Julia': (), 'Less': (), 'Lua': (), 'Nim': (), 'PHP':... |
# Recursion
# Base Case: n < 2, return lst
# Otherwise:
# Divide list into 2, Sort each of them, Merge!
def merge(left, right):
# Compare first element
# Take the smaller of the 2
# Repeat until no more elements
results = []
while left and right:
if left[0] < right[0]:
results.a... | def merge(left, right):
results = []
while left and right:
if left[0] < right[0]:
results.append(left.pop(0))
else:
results.append(right.pop(0))
results.extend(right)
results.extend(left)
return results
def merge_sort(lst):
if len(lst) < 2:
return... |
__about__ = "Maximum no in a binary tree."
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right= None
class Tree:
@staticmethod
def insert(root = None,data = None):
if root is None and data is not None:
root = Node(data)
| __about__ = 'Maximum no in a binary tree.'
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
@staticmethod
def insert(root=None, data=None):
if root is None and data is not None:
root = node(data) |
E, F, C = map(int, input().split())
bottles = E + F
drank = 0
while bottles >= C:
# while he still has enough empty bottles to purchase more
bottles -= C - 1 # used F empty bottles to buy 1
drank += 1
print(drank) | (e, f, c) = map(int, input().split())
bottles = E + F
drank = 0
while bottles >= C:
bottles -= C - 1
drank += 1
print(drank) |
NOTES = {
'C3': 130.8,
'CS3': 138.6,
'DF3': 138.6,
'D3': 146.8,
'DS3': 155.6,
'EF3': 155.6,
'E3': 164.8,
'F3': 174.6,
'FS3': 185.0,
'GF3': 185.0,
'G3': 196.0,
'GS3': 207.7,
'AF3': 207.7,
'A3': 220.0,
'AS3': 233.1,
'BF3': 233.1,
'B3': 246.9,
'C4': ... | notes = {'C3': 130.8, 'CS3': 138.6, 'DF3': 138.6, 'D3': 146.8, 'DS3': 155.6, 'EF3': 155.6, 'E3': 164.8, 'F3': 174.6, 'FS3': 185.0, 'GF3': 185.0, 'G3': 196.0, 'GS3': 207.7, 'AF3': 207.7, 'A3': 220.0, 'AS3': 233.1, 'BF3': 233.1, 'B3': 246.9, 'C4': 261.6, 'CS4': 277.2, 'DF4': 277.2, 'D4': 293.7, 'DS4': 311.1, 'EF4': 311.1... |
# -*- coding: utf-8 -*-
class HelloWorldController:
__defaultName = None
def __init__(self):
self.__defaultName = "Pip User"
def configure(self, config):
self.__defaultName = config.get_as_string_with_default("default_name", self.__defaultName)
def greeting(self, name):
retur... | class Helloworldcontroller:
__default_name = None
def __init__(self):
self.__defaultName = 'Pip User'
def configure(self, config):
self.__defaultName = config.get_as_string_with_default('default_name', self.__defaultName)
def greeting(self, name):
return f'Hello, {(name if nam... |
edge_array = [0,100,-1,-30,130,-150,-1,-1,-1,10,10,-120,-10,160,-180,0,10,-180,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,120,-120,-100,30,-200,30,30,-200,20,30,-200,30,220,-230,40,20,-220,0,50,-30,-200,30,-30,30,30,-200,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,60,-160,-10,130,-190,0,40,-2... | edge_array = [0, 100, -1, -30, 130, -150, -1, -1, -1, 10, 10, -120, -10, 160, -180, 0, 10, -180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 120, -120, -100, 30, -200, 30, 30, -200, 20, 30, -200, 30, 220, -230, 40, 20, -220, 0, 50, -30, -200, 30, -30, 30, 30, -200, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1... |
class LoginResponse:
def __init__(
self, access_token: str,
fresh_token: str,
token_type: str = "bearer"
):
self.access_token = access_token
self.fresh_token = fresh_token
self.token_type = token_type
def json(self):
return dict(
access_... | class Loginresponse:
def __init__(self, access_token: str, fresh_token: str, token_type: str='bearer'):
self.access_token = access_token
self.fresh_token = fresh_token
self.token_type = token_type
def json(self):
return dict(access_token=self.access_token, fresh_token=self.fres... |
# Iterating Through Dictionaries
contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"}
# iterate through each key
for name in contacts:
print(name)
# or, use keys() method
for name in contacts.keys():
print(name)
# using each key to print each value
for name in contacts:
# prints e... | contacts = {'Daisy Johnson': '2468 Park Ave', 'Leo Fitz': '1258 Monkey Dr'}
for name in contacts:
print(name)
for name in contacts.keys():
print(name)
for name in contacts:
print(contacts[name])
for address in contacts.values():
print(address)
for (name, address) in contacts.items():
print(name + ',... |
to_do_list = ["0"] * 10
while True:
command = input().split("-", maxsplit=1)
if "End" in command:
break
to_do_list.insert(int(command[0]), command[1])
while "0" in to_do_list:
to_do_list.remove("0")
print(to_do_list) | to_do_list = ['0'] * 10
while True:
command = input().split('-', maxsplit=1)
if 'End' in command:
break
to_do_list.insert(int(command[0]), command[1])
while '0' in to_do_list:
to_do_list.remove('0')
print(to_do_list) |
N = int(input())
data = open("{}.txt".format(N), 'r')
data = data.readline()
data = [int(i) for i in data.split()]
def parr(array):
for i in array:
print('{:4d}'.format(i), end=" ")
def insertionsort(x):
for i in range(1, len(x)):
j = i - 1; key = x[i]
while(x[j] > key and j>= 0):
x[j+1] = x[j]
j = j-1
... | n = int(input())
data = open('{}.txt'.format(N), 'r')
data = data.readline()
data = [int(i) for i in data.split()]
def parr(array):
for i in array:
print('{:4d}'.format(i), end=' ')
def insertionsort(x):
for i in range(1, len(x)):
j = i - 1
key = x[i]
while x[j] > key and j >= ... |
def resolve():
n = int(input())
for i in range(1, n + 1):
if i % 3 == 0 or "3" in str(i):
print(" {}".format(i), end="")
print()
| def resolve():
n = int(input())
for i in range(1, n + 1):
if i % 3 == 0 or '3' in str(i):
print(' {}'.format(i), end='')
print() |
'''
Make a 3x3 matrix and fill with numbers
at the end show the matrix in a right format
'''
cr = [[],[],[]]
for c in range(0,3):
cr[0].append(int(input(f'First line [1, {c+1}]: ')))
for c in range(0,3):
cr[1].append(int(input(f'Second line [2, {c+1}]: ')))
for c in range(0,3):
cr[2].append(int(input(f'Thir... | """
Make a 3x3 matrix and fill with numbers
at the end show the matrix in a right format
"""
cr = [[], [], []]
for c in range(0, 3):
cr[0].append(int(input(f'First line [1, {c + 1}]: ')))
for c in range(0, 3):
cr[1].append(int(input(f'Second line [2, {c + 1}]: ')))
for c in range(0, 3):
cr[2].append(int(inp... |
load(
"@io_bazel_rules_dotnet//dotnet/private:context.bzl",
"dotnet_context",
)
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetLibrary",
)
load(
"@io_bazel_rules_dotnet//dotnet/private:common.bzl",
"paths",
)
def _dotnet_nuget_impl(ctx,
... | load('@io_bazel_rules_dotnet//dotnet/private:context.bzl', 'dotnet_context')
load('@io_bazel_rules_dotnet//dotnet/private:providers.bzl', 'DotnetLibrary')
load('@io_bazel_rules_dotnet//dotnet/private:common.bzl', 'paths')
def _dotnet_nuget_impl(ctx, build_file=None, build_file_content=None):
"""dotnet_nuget_impl e... |
n = int(input())
for i in range(n):
x = int(input())
print(len(bin(x)) - 2)
| n = int(input())
for i in range(n):
x = int(input())
print(len(bin(x)) - 2) |
"""NA (Non-Available) values in R."""
NA_Character = None
NA_Integer = None
NA_Logical = None
NA_Real = None
NA_Complex = None
| """NA (Non-Available) values in R."""
na__character = None
na__integer = None
na__logical = None
na__real = None
na__complex = None |
'''
The class derived from more than 1 base called as a Multiple Inheritence.
Programmer_name : BALAVIGNESH.M
Implemented_Date : 11-11-2018
'''
class OS:
SecurityOS = "Linux"
DeveloperlikeOS = "Mac OS"
Most_Personal_usage_OS = "Windows"
class KernerlType:
SecurityOS_Kernel = "MonoLit... | """
The class derived from more than 1 base called as a Multiple Inheritence.
Programmer_name : BALAVIGNESH.M
Implemented_Date : 11-11-2018
"""
class Os:
security_os = 'Linux'
developerlike_os = 'Mac OS'
most__personal_usage_os = 'Windows'
class Kernerltype:
security_os__kernel = 'MonoLi... |
class RecentCounter:
def __init__(self):
self.queue = []
def ping(self, t: int) -> int:
self.queue.append(t)
if len(self.queue) > 3001:
self.queue.pop(0)
start = 0
for idx, item in enumerate(self.queue):
if item >= t-3000:
... | class Recentcounter:
def __init__(self):
self.queue = []
def ping(self, t: int) -> int:
self.queue.append(t)
if len(self.queue) > 3001:
self.queue.pop(0)
start = 0
for (idx, item) in enumerate(self.queue):
if item >= t - 3000:
sta... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
# sort the list in descending order
quicksort(input_list)
# fill max with ... | def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
quicksort(input_list)
number_1 = 0
for i in range(0, len(input_list), 2):
... |
#!/bin/python3
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
height = list(map(int, input().strip().split(' ')))
max_height = max(height)
if max_height - k >= 1:
print (max_height-k)
else:
print (0)
| (n, k) = input().strip().split(' ')
(n, k) = [int(n), int(k)]
height = list(map(int, input().strip().split(' ')))
max_height = max(height)
if max_height - k >= 1:
print(max_height - k)
else:
print(0) |
#!/usr/local/bin/python3
s1 = "floor"
s2 = "brake"
print(s1)
for i in range(len(s1)):
if s1[i] != s2[i]:
print(s2[:i+1] + s1[i+1:])
| s1 = 'floor'
s2 = 'brake'
print(s1)
for i in range(len(s1)):
if s1[i] != s2[i]:
print(s2[:i + 1] + s1[i + 1:]) |
def solve() -> None:
# person whose strength is i can only carry parcels whose weight is less than or equal to i.
# check in descending order of degree of freedom of remained parcels.
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
# for i in range(1, 6... | def solve() -> None:
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
if a[5] > b[5]:
print('No')
return
b[5] -= a[5]
a[5] = 0
if a[4] <= b[4]:
b[4] -= a[4]
a[4] = 0
else:
a[4] -= b[4]
b[4] = 0
if a[4]... |
class WayPoint:
code = None
state = None
location = None
coordinate = None
def __init__(self, code=None, state=None, location=None, coordinate=None):
self.code = code
self.state = state
self.location = location
self.coordinate = coordinate
if self.code is No... | class Waypoint:
code = None
state = None
location = None
coordinate = None
def __init__(self, code=None, state=None, location=None, coordinate=None):
self.code = code
self.state = state
self.location = location
self.coordinate = coordinate
if self.code is Non... |
class Solution:
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre:
return None
if len(pre) == 1:
return TreeNode(pre[0])
lroot = post.index(pre[1])
l = self.constructFromPrePost(pre[1:lroot+2], post[:lroot+1])
r = ... | class Solution:
def construct_from_pre_post(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre:
return None
if len(pre) == 1:
return tree_node(pre[0])
lroot = post.index(pre[1])
l = self.constructFromPrePost(pre[1:lroot + 2], post[:lroot + 1])
... |
BIGINT = "BIGINT"
NUMERIC = "NUMERIC"
NUMBER = "NUMBER"
BIT = "BIT"
SMALLINT = "SMALLINT"
DECIMAL = "DECIMAL"
SMALLMONEY = "SMALLMONEY"
INT = "INT"
TINYINT = "TINYINT"
MONEY = "MONEY"
FLOAT = "FLOAT"
REAL = "REAL"
DATE = "DATE"
DATETIMEOFFSET = "DATETIMEOFFSET"
DATETIME2 = "DATETIME2"
SMALLDATETIME = "SMALLDATETIME"
DA... | bigint = 'BIGINT'
numeric = 'NUMERIC'
number = 'NUMBER'
bit = 'BIT'
smallint = 'SMALLINT'
decimal = 'DECIMAL'
smallmoney = 'SMALLMONEY'
int = 'INT'
tinyint = 'TINYINT'
money = 'MONEY'
float = 'FLOAT'
real = 'REAL'
date = 'DATE'
datetimeoffset = 'DATETIMEOFFSET'
datetime2 = 'DATETIME2'
smalldatetime = 'SMALLDATETIME'
da... |
class Solution(object):
def uniquePathsIII(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
R = len(grid)
C = len(grid[0])
ans = 0
zero_count = 0
extra_count = 0
... | class Solution(object):
def unique_paths_iii(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
r = len(grid)
c = len(grid[0])
ans = 0
zero_count = 0
extra_count = 0
po... |
xCoordinate = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
def setup():
size(500,500)
smooth()
noStroke()
myInit()
def myInit():
println ("New coordinates : ")
for i in range(len(xCoordinate)):
xCoordinate [i] = 250 + random ( -100 ,100)
prin... | x_coordinate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
def setup():
size(500, 500)
smooth()
no_stroke()
my_init()
def my_init():
println('New coordinates : ')
for i in range(len(xCoordinate)):
xCoordinate[i] = 250 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.