content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class GameContainer:
def __init__(self, lowest_level, high_score, stat_diffs, points_available):
self.lowest_level = lowest_level
self.high_score = high_score
self.stat_diffs = stat_diffs
self.points_available = points_available
| class Gamecontainer:
def __init__(self, lowest_level, high_score, stat_diffs, points_available):
self.lowest_level = lowest_level
self.high_score = high_score
self.stat_diffs = stat_diffs
self.points_available = points_available |
class Foo:
class Bar:
def baz(self):
pass
| class Foo:
class Bar:
def baz(self):
pass |
def main():
return "foo"
def failure():
raise RuntimeError("This is an error")
| def main():
return 'foo'
def failure():
raise runtime_error('This is an error') |
"""
Model Synoptic Module
"""
simple_tree_model_sklearn = (
"<class 'sklearn.ensemble._forest.ExtraTreesClassifier'>",
"<class 'sklearn.ensemble._forest.ExtraTreesRegressor'>",
"<class 'sklearn.ensemble._forest.RandomForestClassifier'>",
"<class 'sklearn.ensemble._forest.RandomForestReg... | """
Model Synoptic Module
"""
simple_tree_model_sklearn = ("<class 'sklearn.ensemble._forest.ExtraTreesClassifier'>", "<class 'sklearn.ensemble._forest.ExtraTreesRegressor'>", "<class 'sklearn.ensemble._forest.RandomForestClassifier'>", "<class 'sklearn.ensemble._forest.RandomForestRegressor'>", "<class 'sklearn.ensemb... |
def lily_format(seq):
return " ".join(point["lilypond"] for point in seq)
def output(seq):
return "{ %s }" % lily_format(seq)
def write(filename, seq):
with open(filename, "w") as f:
f.write(output(seq))
| def lily_format(seq):
return ' '.join((point['lilypond'] for point in seq))
def output(seq):
return '{ %s }' % lily_format(seq)
def write(filename, seq):
with open(filename, 'w') as f:
f.write(output(seq)) |
print("Iterando sobre o arquivo")
with open("dados.txt", "r") as arquivo:
for linha in arquivo:
print(linha)
print("Fim do arquivo", arquivo.name)
| print('Iterando sobre o arquivo')
with open('dados.txt', 'r') as arquivo:
for linha in arquivo:
print(linha)
print('Fim do arquivo', arquivo.name) |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
sum = 0
def DFS(self,node: TreeNode, path: str):
if node is N... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
sum = 0
def dfs(self, node: TreeNode, path: str):
if node is None:
return
if node.left is None and node.right is None:
... |
N=int(input())
count=0
for i in range(1,N+1):
if len(str(i))%2==1:count+=1
print(count) | n = int(input())
count = 0
for i in range(1, N + 1):
if len(str(i)) % 2 == 1:
count += 1
print(count) |
#
# PySNMP MIB module CXCFG-IPX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXCFG-IPX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:32:22 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... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, constraints_union, value_size_constraint) ... |
#
# PySNMP MIB module RBN-ENVMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-ENVMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ... |
# https://www.codechef.com/problems/MNMX
for T in range(int(input())):
n,a=int(input()),list(map(int,input().split()))
print((n-1)*min(a))
# If order matters
# s=0
# for z in range(n-1):
# if(a[0]>=a[1]):
# s+=a[1]
# a.pop(0)
# else:
# s+=a[0]... | for t in range(int(input())):
(n, a) = (int(input()), list(map(int, input().split())))
print((n - 1) * min(a)) |
class NoLastBookException (Exception):
pass
class OpenLastBookFileFailed (Exception):
pass
| class Nolastbookexception(Exception):
pass
class Openlastbookfilefailed(Exception):
pass |
"""
Contains custom core exceptions
"""
class UnsupportedNews(Exception):
"""
Custom exception for raising when a news type is unsupported
"""
pass
| """
Contains custom core exceptions
"""
class Unsupportednews(Exception):
"""
Custom exception for raising when a news type is unsupported
"""
pass |
fruta = []
fruta.append('Banana')
fruta.append('Tangerina')
fruta.append('uva')
fruta.append('Laranja')
fruta.append('Melancia')
for f,p in enumerate(fruta):
print(f'Na prateleira {f} temos {p}')
| fruta = []
fruta.append('Banana')
fruta.append('Tangerina')
fruta.append('uva')
fruta.append('Laranja')
fruta.append('Melancia')
for (f, p) in enumerate(fruta):
print(f'Na prateleira {f} temos {p}') |
rows_count = int(input())
def get_snake_pos(matrix):
for i, row in enumerate(matrix):
if "S" in row:
j = row.index("S")
snake_pos = [i, j]
return snake_pos
def get_food_pos(matrix):
food_positions = []
for i, row in enumerate(matrix):
for j, _ in enume... | rows_count = int(input())
def get_snake_pos(matrix):
for (i, row) in enumerate(matrix):
if 'S' in row:
j = row.index('S')
snake_pos = [i, j]
return snake_pos
def get_food_pos(matrix):
food_positions = []
for (i, row) in enumerate(matrix):
for (j, _) in e... |
#!python3
class Map:
"""
Map
A Map class.
"""
def __init__(self, map_list):
"""
Map(map_list ::= 2D list of MapObjects)
Example:
a = MapObject("Path", " ", True)
b = MapObject("Rock", "X", False)
map_list = [[a, a, a, a, a]
... | class Map:
"""
Map
A Map class.
"""
def __init__(self, map_list):
"""
Map(map_list ::= 2D list of MapObjects)
Example:
a = MapObject("Path", " ", True)
b = MapObject("Rock", "X", False)
map_list = [[a, a, a, a, a]
[... |
#!/usr/bin/env python
# TODO: import the random module
# This function parses both the player
# and monster files
def parse_file(filename):
members = {}
file = open(filename,"r")
lines = file.readlines()
for line in lines:
name, diff = line.split(";")
members[name] = {"str": int(diff)... | def parse_file(filename):
members = {}
file = open(filename, 'r')
lines = file.readlines()
for line in lines:
(name, diff) = line.split(';')
members[name] = {'str': int(diff)}
return members
def fight_monster(diff, roll):
if diff > roll:
return -1
return 1
def do_ro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/12 16:25
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : setdefault.py
# @Software: PyCharm
cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
print(cars.setdefault('PORSCHE', 9.2))
print(cars)
print(cars.setdefault('BMW', 4.5))... | cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
print(cars.setdefault('PORSCHE', 9.2))
print(cars)
print(cars.setdefault('BMW', 4.5))
print(cars) |
NUMBER_OF_ROWS = 8
NUMBER_OF_COLUMNS = 8
DIMENSION_OF_EACH_SQUARE = 64
BOARD_COLOR_1 = "#DDB88C"
BOARD_COLOR_2 = "#A66D4F"
X_AXIS_LABELS = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
Y_AXIS_LABELS = (1, 2, 3, 4, 5, 6, 7, 8)
SHORT_NAME = {
'R':'Rook', 'N':'Knight', 'B':'Bishop',
'Q':'Queen', 'K':'King', 'P':'Paw... | number_of_rows = 8
number_of_columns = 8
dimension_of_each_square = 64
board_color_1 = '#DDB88C'
board_color_2 = '#A66D4F'
x_axis_labels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
y_axis_labels = (1, 2, 3, 4, 5, 6, 7, 8)
short_name = {'R': 'Rook', 'N': 'Knight', 'B': 'Bishop', 'Q': 'Queen', 'K': 'King', 'P': 'Pawn'}
st... |
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
if (x == 0) :
return 0
while (y > 0) :
# If y is odd, multiply
# x with result
if ((y & 1) == 1) :
res = (re... | def power(x, y, p):
res = 1
x = x % p
if x == 0:
return 0
while y > 0:
if y & 1 == 1:
res = res * x % p
y = y >> 1
x = x * x % p
return res
mod = int(1000000000.0) + 7
for i in range(int(input())):
(n, a) = [int(j) for j in input().split()]
c = a %... |
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
# back tracking
# Runtime: 40 ms, faster than 26.72% of Python3 online submissions for Generate P... | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
target = {'left... |
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while(l < r):
while(l < r and s[l].isalnum() == False):
l+=1
while(l < r and s[r].isalnum() == False):
r-=1
if(s[l].lower() != s[r].lower()):
... | class Solution:
def is_palindrome(self, s: str) -> bool:
(l, r) = (0, len(s) - 1)
while l < r:
while l < r and s[l].isalnum() == False:
l += 1
while l < r and s[r].isalnum() == False:
r -= 1
if s[l].lower() != s[r].lower():
... |
class Solution:
def solve(self, nums):
if len(nums) <= 2: return 0
l_maxes = []
l_max = -inf
for num in nums:
l_max = max(l_max,num)
l_maxes.append(l_max)
r_maxes = []
r_max = -inf
for num in nums[::-1]:
r_max = max(r_ma... | class Solution:
def solve(self, nums):
if len(nums) <= 2:
return 0
l_maxes = []
l_max = -inf
for num in nums:
l_max = max(l_max, num)
l_maxes.append(l_max)
r_maxes = []
r_max = -inf
for num in nums[::-1]:
r_max ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
return self.swap(head)
def swap(self, head: ListNode) -> ListNode:
if head == None:
return ... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
return self.swap(head)
def swap(self, head: ListNode) -> ListNode:
if head == None:
return None
if head.next == None:... |
def FermatPrimalityTest(number):
''' if number != 1 '''
if (number > 1):
''' repeat the test few times '''
for time in range(3):
''' Draw a RANDOM number in range of number ( Z_number ) '''
randomNumber = random.randint(2, number)-1
''' Test if a... | def fermat_primality_test(number):
""" if number != 1 """
if number > 1:
' repeat the test few times '
for time in range(3):
' Draw a RANDOM number in range of number ( Z_number ) '
random_number = random.randint(2, number) - 1
' Test if a^(n-1) = 1 mod n '
... |
# Using Array slicing in python to reverse arrays
# defining reverse function
def reversedArray(array):
print(array[::-1])
# Creating a Template Array
array = [1, 2, 3, 4, 5]
print("Current Array Order:")
print(array)
print("Reversed Array Order:")
reversedArray(array)
| def reversed_array(array):
print(array[::-1])
array = [1, 2, 3, 4, 5]
print('Current Array Order:')
print(array)
print('Reversed Array Order:')
reversed_array(array) |
#Get a left position and a right
# iterative uses a loop
def is_palindrome(string):
left_index = 0
right_index = len(string) - 1
#repeat, or loop
while left_index < right_index:
#check if dismatch
if string[left_index] != string[right_index]:
return False
#move to th... | def is_palindrome(string):
left_index = 0
right_index = len(string) - 1
while left_index < right_index:
if string[left_index] != string[right_index]:
return False
left_index += 1
right_index -= 1
return True
def is_palindrome_recursive(string, left_index, right_index... |
#!/usr/bin/env python3
def char_frequency(filename):
"""
Counts the frequency of each character in the given file.
"""
# First try to open the file
try:
f = open(filename)
# code in the except block is only executed if one of the instructions in the try block raise an error of the match... | def char_frequency(filename):
"""
Counts the frequency of each character in the given file.
"""
try:
f = open(filename)
except OSError:
return None
characters = {}
for line in f:
for char in line:
characters[char] = characters.get(char, 0) + 1
f.close(... |
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
r = [0 for _ in range(num_people)]
i = 0
c = 1
while candies != 0:
if i > num_people - 1:
i = 0
if c > candies:
r[i] += candies
break
r[i] += c
candies -= c
... | def distribute_candies(self, candies: int, num_people: int) -> List[int]:
r = [0 for _ in range(num_people)]
i = 0
c = 1
while candies != 0:
if i > num_people - 1:
i = 0
if c > candies:
r[i] += candies
break
r[i] += c
candies -= c
... |
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
FIRST_LETTER = LETTERS[0]
def get_sequence(column, count, step=1):
column = validate(column)
count = max(abs(count), 1)
sequence = []
if column:
sequence.append(column)
count = count - 1
for i in range(count):
previous ... | letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
first_letter = LETTERS[0]
def get_sequence(column, count, step=1):
column = validate(column)
count = max(abs(count), 1)
sequence = []
if column:
sequence.append(column)
count = count - 1
for i in range(count):
previous = sequence[-1] if... |
def evalRec(env, rec):
"""hearing_loss_genes"""
return (len(set(rec.Symbol) &
{
'ABCD1',
'ABHD12',
'ABHD5',
'ACOT13',
'ACTB',
'ACTG1',
'ADCY1',
'ADGRV1',
'ADK',
'AIFM1',
'A... | def eval_rec(env, rec):
"""hearing_loss_genes"""
return len(set(rec.Symbol) & {'ABCD1', 'ABHD12', 'ABHD5', 'ACOT13', 'ACTB', 'ACTG1', 'ADCY1', 'ADGRV1', 'ADK', 'AIFM1', 'AK2', 'ALMS1', 'AMMECR1', 'ANKH', 'ARSB', 'ATP13A4', 'ATP2B2', 'ATP2C2', 'ATP6V1B1', 'ATP6V1B2', 'BCAP31', 'BCS1L', 'BDNF', 'BDP1', 'BSND', 'B... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | """Test data for firewall rules scanners."""
fake_firewall_rule_for_test_project = {'name': 'policy1', 'full_name': 'organization/org/folder/folder1/project/project0/firewall/policy1/', 'network': 'network1', 'direction': 'ingress', 'allowed': [{'IPProtocol': 'tcp', 'ports': ['1', '3389']}], 'sourceRanges': ['0.0.0.0/0... |
# ToDo: Make it configurable
DEFAULT_PARAMS = {
"os_api": "23",
"device_type": "Pixel",
"ssmix": "a",
"manifest_version_code": "2018111632",
"dpi": 420,
"app_name": "musical_ly",
"version_name": "9.1.0",
"is_my_cn": 0,
"ac": "wifi",
"update_version_code": "2018111632",
"chann... | default_params = {'os_api': '23', 'device_type': 'Pixel', 'ssmix': 'a', 'manifest_version_code': '2018111632', 'dpi': 420, 'app_name': 'musical_ly', 'version_name': '9.1.0', 'is_my_cn': 0, 'ac': 'wifi', 'update_version_code': '2018111632', 'channel': 'googleplay', 'device_platform': 'android', 'build_number': '9.9.0', ... |
def Ispalindrome(usrname):
return usrname==usrname[::-1]
def main():
usrname=input("Enter the String :")
#temp=usrname[::-1]
if Ispalindrome(usrname):
print("String %s is palindrome"%(usrname))
else:
print("String %s is not palindrome"%(usrname))
if __name__ == '__main__':
main()
| def ispalindrome(usrname):
return usrname == usrname[::-1]
def main():
usrname = input('Enter the String :')
if ispalindrome(usrname):
print('String %s is palindrome' % usrname)
else:
print('String %s is not palindrome' % usrname)
if __name__ == '__main__':
main() |
# Advent of Code 2015
#
# From https://adventofcode.com/2015/day/3
#
inputs = [data.strip() for data in open('../inputs/Advent2015_03.txt', 'r')][0]
move = {'^': 0 + 1j, ">": 1, "v": 0 - 1j, "<": -1}
def visit(inputs):
position = 0 + 0j
visited = {position}
for x in inputs:
position = position +... | inputs = [data.strip() for data in open('../inputs/Advent2015_03.txt', 'r')][0]
move = {'^': 0 + 1j, '>': 1, 'v': 0 - 1j, '<': -1}
def visit(inputs):
position = 0 + 0j
visited = {position}
for x in inputs:
position = position + move[x]
visited.add(position)
return visited
print(f'AoC 20... |
def bisect(f, a, b, tol=10e-5):
"""
Implements the bisection root finding algorithm, assuming that f is a
real-valued function on [a, b] satisfying f(a) < 0 < f(b).
"""
lower, upper = a, b
while upper - lower > tol:
middle = 0.5 * (upper + lower)
# === if root is between lower a... | def bisect(f, a, b, tol=0.0001):
"""
Implements the bisection root finding algorithm, assuming that f is a
real-valued function on [a, b] satisfying f(a) < 0 < f(b).
"""
(lower, upper) = (a, b)
while upper - lower > tol:
middle = 0.5 * (upper + lower)
if f(middle) > 0:
... |
# -*- coding: utf-8 -*-
"""Products are standard objects that Loaders add to the data store."""
# For now Products are simple dictionaries.
class Product(dict):
"""Standardised product data."""
pass | """Products are standard objects that Loaders add to the data store."""
class Product(dict):
"""Standardised product data."""
pass |
age1 = 12
age2 = 18
print("age1 + age2")
print(age1 + age2)
print("age1 - age2")
print(age1 - age2)
print("age1 * age2")
print(age1 * age2)
print("age1 / age2")
print(age1 / age2)
print("age1 % age2")
print(age1 % age2)
sent1 = "Today is a beautiful day"
firstName = "Marlon"
lastName = "Monzon"
print(firstName + " "... | age1 = 12
age2 = 18
print('age1 + age2')
print(age1 + age2)
print('age1 - age2')
print(age1 - age2)
print('age1 * age2')
print(age1 * age2)
print('age1 / age2')
print(age1 / age2)
print('age1 % age2')
print(age1 % age2)
sent1 = 'Today is a beautiful day'
first_name = 'Marlon'
last_name = 'Monzon'
print(firstName + ' ' ... |
a = input()
s = [int(x) for x in input().split()]
ans = [str(x) for x in sorted(s)]
print(' '.join(ans))
| a = input()
s = [int(x) for x in input().split()]
ans = [str(x) for x in sorted(s)]
print(' '.join(ans)) |
# Equations (c) Baltasar 2019 MIT License <baltasarq@gmail.com>
class TDS:
def __init__(self):
self._vbles = {}
def __iadd__(self, other):
self._vbles[other[0]] = other[1]
return self
def __getitem__(self, item):
return self._vbles[item]
def __setitem__(self, item, v... | class Tds:
def __init__(self):
self._vbles = {}
def __iadd__(self, other):
self._vbles[other[0]] = other[1]
return self
def __getitem__(self, item):
return self._vbles[item]
def __setitem__(self, item, value):
self._vbles[item] = value
def get_vble_names(... |
x = int(input("enter percentage\n"))
if(x>=65):
print("Excellent")
elif(x>=55 and x<65):
print("Good")
elif(x>=40 and x<55):
print("Fair")
else:
print("Failed")
| x = int(input('enter percentage\n'))
if x >= 65:
print('Excellent')
elif x >= 55 and x < 65:
print('Good')
elif x >= 40 and x < 55:
print('Fair')
else:
print('Failed') |
WORK_PATH = "/tmp/posts"
PORT = 8000
AUTHOR = "@asadiyan"
TITLE = "fsBlog"
DESCRIPTION = "<h3></h3>"
| work_path = '/tmp/posts'
port = 8000
author = '@asadiyan'
title = 'fsBlog'
description = '<h3></h3>' |
"""
written and developed by Daniel Temkin
please refer to LICENSE for ownership and reference information
"""
| """
written and developed by Daniel Temkin
please refer to LICENSE for ownership and reference information
""" |
def TwosComplementOf(n):
if isinstance(n,str) == True:
binintnum = int(n)
binmun = int("{0:08b}".format(binintnum))
strnum = str(binmun)
size = len(strnum)
idx = size -1
while idx >= 0:
... | def twos_complement_of(n):
if isinstance(n, str) == True:
binintnum = int(n)
binmun = int('{0:08b}'.format(binintnum))
strnum = str(binmun)
size = len(strnum)
idx = size - 1
while idx >= 0:
if strnum[idx] == '1':
break
idx = idx... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class GcloudComputeZones(GcloudCLI):
''' Class to wrap the gcloud compute zones command'''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self, region=None, verbose=False):
''' Constructor for gcloud resour... | class Gcloudcomputezones(GcloudCLI):
""" Class to wrap the gcloud compute zones command"""
def __init__(self, region=None, verbose=False):
""" Constructor for gcloud resource """
super(GcloudComputeZones, self).__init__()
self._region = region
self.verbose = verbose
@proper... |
class Stack:
def __init__(self, *objects):
self.stack = []
if len(objects) > 0:
for obj in objects:
self.stack.append(obj)
def push(self, *objects):
for obj in objects:
self.stack.append(obj)
def pop(self, obj):
... | class Stack:
def __init__(self, *objects):
self.stack = []
if len(objects) > 0:
for obj in objects:
self.stack.append(obj)
def push(self, *objects):
for obj in objects:
self.stack.append(obj)
def pop(self, obj):
if self.stack != []:
... |
class CalcError(Exception):
def __init__(self, error):
self.message = error
super().__init__(self.message)
| class Calcerror(Exception):
def __init__(self, error):
self.message = error
super().__init__(self.message) |
#Binary to Decimal conversion
def binDec(n):
num = int(n);
value = 0;
base = 1;
flag = num;
while(flag):
l = flag%10;
flag = int(flag/10);
print(flag);
value = value+l*base;
base = base*2;
return value
num = input();
a = binDec(num);
print(a)
| def bin_dec(n):
num = int(n)
value = 0
base = 1
flag = num
while flag:
l = flag % 10
flag = int(flag / 10)
print(flag)
value = value + l * base
base = base * 2
return value
num = input()
a = bin_dec(num)
print(a) |
{
'targets': [
{
'target_name': 'lb_shell_package',
'type': 'none',
'default_project': 1,
'dependencies': [
'lb_shell_contents',
],
'conditions': [
['target_arch=="android"', {
'dependencies': [
'lb_shell_android.gyp:lb_shell_apk',
... | {'targets': [{'target_name': 'lb_shell_package', 'type': 'none', 'default_project': 1, 'dependencies': ['lb_shell_contents'], 'conditions': [['target_arch=="android"', {'dependencies': ['lb_shell_android.gyp:lb_shell_apk']}, {'dependencies': ['lb_shell_exe.gyp:lb_shell']}], ['target_arch not in ["linux", "android", "wi... |
# PRINT OUT A WELCOME MESSAGE.
print('Welcome to Food Funhouse!')
# LOOP UNTIL THE USER CHOOSES TO EXIT.
order_total_in_dollars_and_cents = 0.0
while True:
# PRINT OUT THE MENU OPTIONS.
print('1. Cheeseburger - $5.50')
print('2. Pizza - $5.00')
print('3. Taco - $3.00')
print('4. Cookie - $1.99')
... | print('Welcome to Food Funhouse!')
order_total_in_dollars_and_cents = 0.0
while True:
print('1. Cheeseburger - $5.50')
print('2. Pizza - $5.00')
print('3. Taco - $3.00')
print('4. Cookie - $1.99')
print('5. Milk - $0.99')
print('6. Pay for Order/Exit')
print('7. Cancel Order/Exit')
selec... |
# Simple Calculator
def calculate(x,y,operator):
if operator == "*":
result = float(x * y)
print(f"The answer is {result} ")
elif operator == "/":
result = float(x / y)
print(f"The answer is {result} ")
elif operator == "+":
result = float(x + y)
print(f"The ... | def calculate(x, y, operator):
if operator == '*':
result = float(x * y)
print(f'The answer is {result} ')
elif operator == '/':
result = float(x / y)
print(f'The answer is {result} ')
elif operator == '+':
result = float(x + y)
print(f'The answer is {result} ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | """
List resources from the Key Manager service.
"""
def create_secret(conn):
print('Create a secret:')
conn.key_manager.create_secret(name='My public key', secret_type='public', expiration='2020-02-28T23:59:59', payload='ssh rsa...', payload_content_type='text/plain') |
# Outputs string representation of a unicode hex representation
def uc(hex):
return chr(int(hex))
'''CONSONANTS. Format: Place_Manner_Voicing;
Place:
L=labial, LD=labiodental, D=dental, A=alveolar, R=retroflex,
PA=postalveolar, P=palatal, V=velar, U=uvular, PH=pharyngeal, G=glottal;
Mann... | def uc(hex):
return chr(int(hex))
'CONSONANTS. Format: Place_Manner_Voicing;\n\n Place:\n L=labial, LD=labiodental, D=dental, A=alveolar, R=retroflex,\n PA=postalveolar, P=palatal, V=velar, U=uvular, PH=pharyngeal, G=glottal;\n\n Manner:\n P=plosive, N=nasal, TR=trill, TF=tap/flap, F=fric... |
# 8.2) find path to robot in a c*r grid, robot can only move right and down.
def find_path(c, r, off_limits):
path = []
move_robot(0, 0, c, r, off_limits, path)
return path
def move_robot(x, y, c, r, off_limits, path):
if x == (c - 1) and y == (r - 1):
return
elif [x + 1, y] not in off_li... | def find_path(c, r, off_limits):
path = []
move_robot(0, 0, c, r, off_limits, path)
return path
def move_robot(x, y, c, r, off_limits, path):
if x == c - 1 and y == r - 1:
return
elif [x + 1, y] not in off_limits and x + 1 < c:
path.append([x + 1, y])
move_robot(x + 1, y, c,... |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... | test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not s... |
# Tristan Protzman
# Created 2019-02-07
# Holds the note patters
class Pattern:
def __init__(self, beats, subdivisions, notes):
self.beats = beats # How many beats per measure
self.subdivisions = subdivisions # How many divisions per beat
self.divisions = self.beats * self.subdivisions ... | class Pattern:
def __init__(self, beats, subdivisions, notes):
self.beats = beats
self.subdivisions = subdivisions
self.divisions = self.beats * self.subdivisions
self.notes = notes
self.pattern = [set() for _ in range(self.divisions)]
def __str__(self):
"""
... |
class Chat:
START_TEXT = """This is a Telegram Bot to Mux subtitle into a video
<b>Send me a Telegram file to begin</b>
/help for more details..
Credits :- @mohdsabahat
"""
HELP_USER = "??"
HELP_TEXT ="""<b>Welcome to the Help Menu</b>
1.) Send a Video file or url.
2.) Send a subtitle file (ass ... | class Chat:
start_text = 'This is a Telegram Bot to Mux subtitle into a video\n\n<b>Send me a Telegram file to begin</b>\n\n/help for more details..\n\nCredits :- @mohdsabahat\n '
help_user = '??'
help_text = '<b>Welcome to the Help Menu</b>\n\n1.) Send a Video file or url.\n2.) Send a subtitle file (ass... |
# To Find an algorithm for giving selected attributes in a formal concept analysis acc to given conditions
a,arr= [],[]
start,end = 3,5
with open('Naive Algo/Input/test2.txt') as file:
for line in file:
line = line.strip()
for c in line:
if c != ' ':
# print(int(c))
... | (a, arr) = ([], [])
(start, end) = (3, 5)
with open('Naive Algo/Input/test2.txt') as file:
for line in file:
line = line.strip()
for c in line:
if c != ' ':
a.append(int(c))
arr.append(a)
a = []
s = set()
for st in range(start, end + 1):
for i in range... |
class Configuracoes:
"""Armazena as configuracoes do jogo estrela."""
def __init__(self):
"""Inicializa as configuracoes do jogo."""
# Configuracoes de tela
self.tela_largura = 1200
self.tela_altura = 600
self.cor_fundo = (46, 46, 46)
| class Configuracoes:
"""Armazena as configuracoes do jogo estrela."""
def __init__(self):
"""Inicializa as configuracoes do jogo."""
self.tela_largura = 1200
self.tela_altura = 600
self.cor_fundo = (46, 46, 46) |
"""Project Euler problem 9"""
def calculate(perimeter):
"""Returns the product a*b*c of a Pythagorean triplet for which a + b + c == perimeter"""
for a in range(1, perimeter):
if a > perimeter:
break
for b in range(1, perimeter):
if a + b > perimeter:
br... | """Project Euler problem 9"""
def calculate(perimeter):
"""Returns the product a*b*c of a Pythagorean triplet for which a + b + c == perimeter"""
for a in range(1, perimeter):
if a > perimeter:
break
for b in range(1, perimeter):
if a + b > perimeter:
bre... |
## Copyright 2020 Google LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## https://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in ... | """To be documented."""
def grpc_web_dependencies():
"""An utility method to load all dependencies of `gRPC-Web`."""
fail('Loading dependencies through grpc_web_dependencies() is not supported yet.')
def grpc_web_toolchains():
"""An utility method to load all gRPC-Web toolchains."""
native.register_to... |
#=========================================================================================
class Job():
"""Represent job to-do in schedule"""
def __init__(self, aItineraryName, aItineraryColor, aTaskNumber, aItineraryNumber, aMachineName, aDuration):
self.itinerary = aItineraryName
self.machine... | class Job:
"""Represent job to-do in schedule"""
def __init__(self, aItineraryName, aItineraryColor, aTaskNumber, aItineraryNumber, aMachineName, aDuration):
self.itinerary = aItineraryName
self.machine = aMachineName
self.startTime = 0
self.duration = aDuration
self.end... |
def palin(n,m):
if n<l//2:
if arr[n]==arr[m]:
return palin(n+1,m-1)
else:
return False
else:
return True
try:
arr= []
print(" Enter the array inputs and type 'stop' when you are done\n" )
while True:
arr.append(int(input()))
except:# if th... | def palin(n, m):
if n < l // 2:
if arr[n] == arr[m]:
return palin(n + 1, m - 1)
else:
return False
else:
return True
try:
arr = []
print(" Enter the array inputs and type 'stop' when you are done\n")
while True:
arr.append(int(input()))
except:... |
""" What are Python Packages?
Packages are just folders(directories) that contain modules.
They contain a special python file named:__init__.py
The __init__.py file can be empty. The file tells Python that the directory of folder contains a python package which can be imported like a module.
Packag... | """ What are Python Packages?
Packages are just folders(directories) that contain modules.
They contain a special python file named:__init__.py
The __init__.py file can be empty. The file tells Python that the directory of folder contains a python package which can be imported like a module.
Packag... |
'''
Created on 1 dec. 2021
@author: laurentmichel
'''
class TableIterator(object):
'''
Simple wrapper iterating over table rows
'''
def __init__(self,
name,
data_table):
"""
Constructor
:param name: table name : not really used
:param ... | """
Created on 1 dec. 2021
@author: laurentmichel
"""
class Tableiterator(object):
"""
Simple wrapper iterating over table rows
"""
def __init__(self, name, data_table):
"""
Constructor
:param name: table name : not really used
:param data_table: Numpy table returned b... |
__version__ = "v0.6.1-1"
__author__ = "Kanelis Elias"
__email__ = "hkanelhs@yahoo.gr"
__license__ = "MIT"
| __version__ = 'v0.6.1-1'
__author__ = 'Kanelis Elias'
__email__ = 'hkanelhs@yahoo.gr'
__license__ = 'MIT' |
## https://leetcode.com/problems/count-and-say/
## this problem seems hard at first, but that's mostly
## because it's incredibly poorly described. went to
## wikipedia and it makes sense. for ease, I went ahead
## and hard-coded in the first 5; after that, we generate
## from the previous one.
## generating the ... | class Solution:
def generate_next(self, seq: str) -> str:
char = seq[0]
count = 1
out = ''
for c in seq[1:]:
if c == char:
count = count + 1
else:
out = out + str(count) + char
char = c
count = 1... |
soma = 0
for n in range(1, 500, 2):
if n % 3 == 0:
soma = soma + n
print(soma)
| soma = 0
for n in range(1, 500, 2):
if n % 3 == 0:
soma = soma + n
print(soma) |
# Times Tables
# Ask the user to input the number they would like the times tables for
tTable = int(input("What number would you like to see the times table for? "))
# Loop through 12 times
for number in range(12):
print("{0} times {1} equals {2}" .format(number+1, tTable, (number+1) * tTable))
input()
| t_table = int(input('What number would you like to see the times table for? '))
for number in range(12):
print('{0} times {1} equals {2}'.format(number + 1, tTable, (number + 1) * tTable))
input() |
expected_output = {
"GigabitEthernet3/8/0/38": {
"auto_negotiate": True,
"counters": {
"normal": {
"in_broadcast_pkts": 1093,
"in_mac_pause_frames": 0,
"in_multicast_pkts": 18864,
"in_octets": 0,
"in_pkts": 7... | expected_output = {'GigabitEthernet3/8/0/38': {'auto_negotiate': True, 'counters': {'normal': {'in_broadcast_pkts': 1093, 'in_mac_pause_frames': 0, 'in_multicast_pkts': 18864, 'in_octets': 0, 'in_pkts': 7446905, 'in_unicast_pkts': 7426948, 'out_broadcast_pkts': 373635, 'out_mac_pause_frames': 0, 'out_multicast_pkts': 3... |
"""
Write an iterative implementation of a binary search function.
"""
def binary_search(haystack, needle):
first = 0
last = len(haystack) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
print('haystack is {}, mid is {}, first is {}, last is {}'.format(
... | """
Write an iterative implementation of a binary search function.
"""
def binary_search(haystack, needle):
first = 0
last = len(haystack) - 1
found = False
while first <= last and (not found):
mid = (first + last) // 2
print('haystack is {}, mid is {}, first is {}, last is {}'.format(h... |
"""These keypoint formats are taken from https://github.com/CMU-Perceptual-
Computing-Lab/openpose/blob/master/src/openpose/pose/poseParameters.cpp."""
OPENPOSE_135_KEYPOINTS = [
'nose',
'left_eye',
'right_eye',
'left_ear',
'right_ear',
'left_shoulder',
'right_shoulder',
'left_elbow',
... | """These keypoint formats are taken from https://github.com/CMU-Perceptual-
Computing-Lab/openpose/blob/master/src/openpose/pose/poseParameters.cpp."""
openpose_135_keypoints = ['nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
__all__ = ['SE_Block',
]
'''see: Squeeze-and-Excitation Networks'''
def SE_Block(sym, data, num_out, name):
if type(num_out) ... | __all__ = ['SE_Block']
'see: Squeeze-and-Excitation Networks'
def se__block(sym, data, num_out, name):
if type(num_out) is tuple:
num_mid = (int(sum(num_out) / 16), 0)
else:
num_mid = int(num_out / 16)
out = sym.Pooling(data=data, pool_type='avg', kernel=(1, 1), global_pool=True, stride=(1,... |
__title__ = "access-client"
__version__ = "0.0.1"
__summary__ = "Client for accessai solutions"
__uri__ = "http://accessai.co"
__author__ = "ConvexHull Technology"
__email__ = "support@accessai.co"
__license__ = "Apache 2.0"
__release__ = True
| __title__ = 'access-client'
__version__ = '0.0.1'
__summary__ = 'Client for accessai solutions'
__uri__ = 'http://accessai.co'
__author__ = 'ConvexHull Technology'
__email__ = 'support@accessai.co'
__license__ = 'Apache 2.0'
__release__ = True |
'''
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
'''
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
ret... | """
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
ret... |
# @lc app=leetcode id=2139 lang=python3
#
# [2139] Minimum Moves to Reach Target Score
#
# https://leetcode.com/problems/minimum-moves-to-reach-target-score/
# @lc code=start
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
steps = 0
while maxDoubles > 0 and... | class Solution:
def min_moves(self, target: int, maxDoubles: int) -> int:
steps = 0
while maxDoubles > 0 and target > 1:
if target % 2 == 0:
target /= 2
steps = steps + 1
max_doubles -= 1
else:
target -= 1
... |
# Truncatable primes
def prime_test_list(numbers):
return all(prime_test(elem) for elem in numbers)
def prime_test(num):
try:
if num == 2:
return True
if num == 0 or num == 1 or num % 2 == 0:
return False
for i in range(3, int(num**(1/2))+1, 2):... | def prime_test_list(numbers):
return all((prime_test(elem) for elem in numbers))
def prime_test(num):
try:
if num == 2:
return True
if num == 0 or num == 1 or num % 2 == 0:
return False
for i in range(3, int(num ** (1 / 2)) + 1, 2):
if num % i == 0:
... |
class RunnerMixin(object):
def add_artifacts(self, artifacts):
url = self._url('/runner/artifacts')
data = [{'filename': d} for d in artifacts]
return self._result(self.post(url, json={
'artifacts': data
}))
def add_logs(self, logs):
url = self._url('/runner... | class Runnermixin(object):
def add_artifacts(self, artifacts):
url = self._url('/runner/artifacts')
data = [{'filename': d} for d in artifacts]
return self._result(self.post(url, json={'artifacts': data}))
def add_logs(self, logs):
url = self._url('/runner/log')
return ... |
# -*- encoding: utf-8 -*-
"""
@File : __init__.py.py
@Time : 2020/2/29 11:57 AM
@Author : zhengjiani
@Email : 936089353@qq.com
@Software: PyCharm
"""
| """
@File : __init__.py.py
@Time : 2020/2/29 11:57 AM
@Author : zhengjiani
@Email : 936089353@qq.com
@Software: PyCharm
""" |
def load(h):
return ({'abbr': 'a', 'code': 1, 'title': '70 332.5 40 10'},
{'abbr': 'b', 'code': 2, 'title': '72.5 0 50 45'},
{'abbr': 'c', 'code': 3, 'title': '57.5 345 32.5 17.5'},
{'abbr': 'd', 'code': 4, 'title': '57.5 2.5 32.5 42.5'},
{'abbr': 'e', 'code': 5, 'tit... | def load(h):
return ({'abbr': 'a', 'code': 1, 'title': '70 332.5 40 10'}, {'abbr': 'b', 'code': 2, 'title': '72.5 0 50 45'}, {'abbr': 'c', 'code': 3, 'title': '57.5 345 32.5 17.5'}, {'abbr': 'd', 'code': 4, 'title': '57.5 2.5 32.5 42.5'}, {'abbr': 'e', 'code': 5, 'title': '75 340 30 45'}, {'abbr': 'f', 'code': 6, '... |
def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=10,
power=0.75, init_lr=0.001,weight_decay=0.0005,
max_iter=10000):
#10000
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
#max_iter = 10000
gamma = 10.0
lr = init_lr * (1 +... | def inv_lr_scheduler(param_lr, optimizer, iter_num, gamma=10, power=0.75, init_lr=0.001, weight_decay=0.0005, max_iter=10000):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
gamma = 10.0
lr = init_lr * (1 + gamma * min(1.0, iter_num / max_iter)) ** (-power)
i = 0
for param... |
"""A module with errors used in the qtools3 package."""
class XlsformError(Exception):
pass
class ConvertError(Exception):
pass
class XformError(Exception):
pass
class QxmleditError(Exception):
pass
| """A module with errors used in the qtools3 package."""
class Xlsformerror(Exception):
pass
class Converterror(Exception):
pass
class Xformerror(Exception):
pass
class Qxmlediterror(Exception):
pass |
description = 'Devices for the first detector assembly'
pvpref = 'SQ:ZEBRA:mcu3:'
excludes = ['wagen2']
devices = dict(
nu = device('nicos_ess.devices.epics.motor.EpicsMotor',
description = 'Detector tilt',
motorpv = pvpref + 'A4T',
errormsgpv = pvpref + 'A4T-MsgTxt',
precision = ... | description = 'Devices for the first detector assembly'
pvpref = 'SQ:ZEBRA:mcu3:'
excludes = ['wagen2']
devices = dict(nu=device('nicos_ess.devices.epics.motor.EpicsMotor', description='Detector tilt', motorpv=pvpref + 'A4T', errormsgpv=pvpref + 'A4T-MsgTxt', precision=0.01), detdist=device('nicos_ess.devices.epics.mot... |
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
| class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = person('John', 'Doe')
x.printname() |
name = "Maedeh Ashouri"
for i in name:
print(i) | name = 'Maedeh Ashouri'
for i in name:
print(i) |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
__all__ = ["ConfigError", "ConfigWarning"]
class ConfigError(ValueError):
pass
class ConfigWarning(Warning):
pass
| __all__ = ['ConfigError', 'ConfigWarning']
class Configerror(ValueError):
pass
class Configwarning(Warning):
pass |
# coding: utf-8
# In[3]:
class RuleClass:
attributes = []
attributes_value = []
attributes_cover = []
decision_cover =[]
false_cover =[]
Decision = ''
def __cmp__(self, other):
if self.strength > other.strength:
return 1
elif self.strength < other.strength:
... | class Ruleclass:
attributes = []
attributes_value = []
attributes_cover = []
decision_cover = []
false_cover = []
decision = ''
def __cmp__(self, other):
if self.strength > other.strength:
return 1
elif self.strength < other.strength:
return -1
... |
def convert_lambda_to_def(string):
args=string[string.index("lambda ")+7:string.index(":")]
name=string[:string.index(" ")]
cal=string[string.index(":")+2:]
return f"def {name}({args}):\n return {cal}" | def convert_lambda_to_def(string):
args = string[string.index('lambda ') + 7:string.index(':')]
name = string[:string.index(' ')]
cal = string[string.index(':') + 2:]
return f'def {name}({args}):\n return {cal}' |
# -*- coding: utf-8 -*-
class SigfoxBaseException(BaseException):
pass
class SigfoxConnectionError(SigfoxBaseException):
pass
class SigfoxBadStatusError(SigfoxBaseException):
pass
class SigfoxResponseError(SigfoxBaseException):
pass
class SigfoxTooManyRequestsError(SigfoxBaseException):
pass... | class Sigfoxbaseexception(BaseException):
pass
class Sigfoxconnectionerror(SigfoxBaseException):
pass
class Sigfoxbadstatuserror(SigfoxBaseException):
pass
class Sigfoxresponseerror(SigfoxBaseException):
pass
class Sigfoxtoomanyrequestserror(SigfoxBaseException):
pass |
#To find factorial of number
num = int(input('N='))
factorial = 1
if num<0:
print('Number is not accepted')
elif num==0:
print(1)
else:
for i in range(1,num+1):
factorial = factorial * i
print(factorial)
| num = int(input('N='))
factorial = 1
if num < 0:
print('Number is not accepted')
elif num == 0:
print(1)
else:
for i in range(1, num + 1):
factorial = factorial * i
print(factorial) |
income = float(input())
gross_pay = income
taxes_owed = income * .12
net_pay = gross_pay - taxes_owed
print(gross_pay)
print(taxes_owed)
print(net_pay) | income = float(input())
gross_pay = income
taxes_owed = income * 0.12
net_pay = gross_pay - taxes_owed
print(gross_pay)
print(taxes_owed)
print(net_pay) |
'''Plotting utility functions'''
def remove_top_right_borders(ax):
'''Remove top and right borders from Matplotlib axis'''
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
| """Plotting utility functions"""
def remove_top_right_borders(ax):
"""Remove top and right borders from Matplotlib axis"""
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') |
first_wire = ['R8', 'U5', 'L5', 'D3']
second_wire = ['U7', 'R6', 'D4', 'L4']
def wire_path(wire):
path = {}
x = 0
y = 0
count = 0
dirs = {"R": 1,
"L": -1,
"U": 1,
"D": -1}
for i in wire:
dir = i[0]
mov = int(i[1:])
for _ in range(mov... | first_wire = ['R8', 'U5', 'L5', 'D3']
second_wire = ['U7', 'R6', 'D4', 'L4']
def wire_path(wire):
path = {}
x = 0
y = 0
count = 0
dirs = {'R': 1, 'L': -1, 'U': 1, 'D': -1}
for i in wire:
dir = i[0]
mov = int(i[1:])
for _ in range(mov):
count += 1
... |
class Solution:
def calculate(self, s: str) -> int:
stack = [1]
sign = 1
res = 0
i = 0
while i < len(s):
if s[i].isdigit():
val = 0
while i < len(s) and s[i].isdigit():
val = val * 10 + int(s[i])
... | class Solution:
def calculate(self, s: str) -> int:
stack = [1]
sign = 1
res = 0
i = 0
while i < len(s):
if s[i].isdigit():
val = 0
while i < len(s) and s[i].isdigit():
val = val * 10 + int(s[i])
... |
class Calculator:
def __init__(self, ss, am, fsp, sc, isp, bc, cgtr):
self.ss = ss
self.am = int(am)
self.fsp = float(fsp)
self.sc = float(sc)
self.isp = float(isp)
self.bc = float(bc)
self.cgtr = float(cgtr)
def get_pc(self):
pc = self.am * self.... | class Calculator:
def __init__(self, ss, am, fsp, sc, isp, bc, cgtr):
self.ss = ss
self.am = int(am)
self.fsp = float(fsp)
self.sc = float(sc)
self.isp = float(isp)
self.bc = float(bc)
self.cgtr = float(cgtr)
def get_pc(self):
pc = self.am * self... |
"""igcollect - Library Entry Point
Copyright (c) 2018 InnoGames GmbH
"""
| """igcollect - Library Entry Point
Copyright (c) 2018 InnoGames GmbH
""" |
# -*- coding: utf-8 -*-
"""The Windows Registry definitions."""
KEY_PATH_SEPARATOR = '\\'
# The Registry value types.
REG_NONE = 0
REG_SZ = 1
REG_EXPAND_SZ = 2
REG_BINARY = 3
REG_DWORD = 4
REG_DWORD_LITTLE_ENDIAN = 4
REG_DWORD_LE = REG_DWORD_LITTLE_ENDIAN
REG_DWORD_BIG_ENDIAN = 5
REG_DWORD_BE = REG_DWORD_BIG_ENDIAN
R... | """The Windows Registry definitions."""
key_path_separator = '\\'
reg_none = 0
reg_sz = 1
reg_expand_sz = 2
reg_binary = 3
reg_dword = 4
reg_dword_little_endian = 4
reg_dword_le = REG_DWORD_LITTLE_ENDIAN
reg_dword_big_endian = 5
reg_dword_be = REG_DWORD_BIG_ENDIAN
reg_link = 6
reg_multi_sz = 7
reg_resource_list = 8
reg... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79343638
# IDEA : DFS
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
prin... | class Solution(object):
def combination_sum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
print(candidates)
res = []
self.dfs(candidates, target, 0, res, [])
... |
'''
https://leetcode.com/problems/maximum-length-of-pair-chain/solution/
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a ... | """
https://leetcode.com/problems/maximum-length-of-pair-chain/solution/
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.