content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class ReflectionException(Exception): pass class SignatureException(ReflectionException): pass class MissingArguments(SignatureException): pass class UnknownArguments(SignatureException): pass class InvalidKeywordArgument(ReflectionException): pass
class Reflectionexception(Exception): pass class Signatureexception(ReflectionException): pass class Missingarguments(SignatureException): pass class Unknownarguments(SignatureException): pass class Invalidkeywordargument(ReflectionException): pass
class Solution: def generateParenthesis(self, n: int) -> [str]: res = [] def dfs(i, j, tmp): if not (i or j): res.append(tmp) return if i: dfs(i - 1, j, tmp + '(') if j > i: dfs(i, j - 1, tmp + ')') ...
class Solution: def generate_parenthesis(self, n: int) -> [str]: res = [] def dfs(i, j, tmp): if not (i or j): res.append(tmp) return if i: dfs(i - 1, j, tmp + '(') if j > i: dfs(i, j - 1, tmp + ')'...
x = 3 y = 4 def Double(x): return 2 * x def Product(x, y): return x * y def SayHi(): print("Hello World!!!")
x = 3 y = 4 def double(x): return 2 * x def product(x, y): return x * y def say_hi(): print('Hello World!!!')
def oddsum(): n= int(input("Enter the number of terms:")) sum=0 for i in range (1, 2*n+1, 2): sum += i print("The sum of first", n, "odd terms is:", sum) def evensum(): n= int(input("Enter the number of terms:")) sum=0 for i in range (0, 2*n+1, 2): sum += i ...
def oddsum(): n = int(input('Enter the number of terms:')) sum = 0 for i in range(1, 2 * n + 1, 2): sum += i print('The sum of first', n, 'odd terms is:', sum) def evensum(): n = int(input('Enter the number of terms:')) sum = 0 for i in range(0, 2 * n + 1, 2): sum += i p...
n = int(input()) # Opt1: Without map scores_str = input().split() scores = [] for score in scores_str: scores.append(int(score)) # Opt2: With map # map is a function that takes another function and a collection # e.g, list and applies function to all items in collection # scores = map(int, input().split()) # By ...
n = int(input()) scores_str = input().split() scores = [] for score in scores_str: scores.append(int(score)) scores.sort(reverse=True) score_first = scores[0] for score in scores: if score != score_first: print(score) break
h, w = map(int, input().split()) grid = [list(input()) for _ in range(h)] for i in range(h): for j in range(w): if grid[i][j] == '#': if i - 1 >= 0 and grid[i - 1][j] == '#': continue if i + 1 <= h - 1 and grid[i + 1][j] == '#': continue if...
(h, w) = map(int, input().split()) grid = [list(input()) for _ in range(h)] for i in range(h): for j in range(w): if grid[i][j] == '#': if i - 1 >= 0 and grid[i - 1][j] == '#': continue if i + 1 <= h - 1 and grid[i + 1][j] == '#': continue ...
def is_a_valid_message(message): index=0 while index<len(message): index2=next((i for i,j in enumerate(message[index:]) if not j.isdigit()), 0)+index if index==index2: return False index3=next((i for i,j in enumerate(message[index2:]) if j.isdigit()), len(message)-index2)+ind...
def is_a_valid_message(message): index = 0 while index < len(message): index2 = next((i for (i, j) in enumerate(message[index:]) if not j.isdigit()), 0) + index if index == index2: return False index3 = next((i for (i, j) in enumerate(message[index2:]) if j.isdigit()), len(me...
class Token: def __init__(self, token, value=None): self.token = token self.value = value def __str__(self): return "{}: {}".format(self.token, self.value) def __repr__(self): return "{}({}, value={})".format(self.__class__.__name__, self.token, self.value) CONCATENATE = ...
class Token: def __init__(self, token, value=None): self.token = token self.value = value def __str__(self): return '{}: {}'.format(self.token, self.value) def __repr__(self): return '{}({}, value={})'.format(self.__class__.__name__, self.token, self.value) concatenate = '...
def test1(): """A multi-line docstring. """ def test2(): """ A multi-line docstring. """ def test2(): """ A single-line docstring.""" """ A multi-line docstring. """
def test1(): """A multi-line docstring. """ def test2(): """ A multi-line docstring. """ def test2(): """ A single-line docstring.""" '\nA multi-line\ndocstring.\n'
#week 4 chapter 8 - assignment 8.4 #8.4 Open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split() method. # The program should build a list of words. For each word on each # line check to see if the word is already in the list and if not # append it to...
path = '/home/tbfk/Documents/VSC/Coursera/PythonDataStructures/' fname = path + 'romeo.txt' fh = open(fname) lst = list() for line in fh: line = line.rstrip() pieces = line.split() for word in pieces: if word in lst: continue else: lst.append(word) lst.sort() print(ls...
class APIException(Exception): """Exception raised when there is an API error.""" default_message = "A server error occurred" def __init__(self, message=None): self.message = message or self.default_message def __str__(self): return str(self.message) class PermissionDenied(APIExcept...
class Apiexception(Exception): """Exception raised when there is an API error.""" default_message = 'A server error occurred' def __init__(self, message=None): self.message = message or self.default_message def __str__(self): return str(self.message) class Permissiondenied(APIExceptio...
# -*- coding: utf-8 -*- def put_color(string, color): colors = { "red": "31", "green": "32", "yellow": "33", "blue": "34", "pink": "35", "cyan": "36", "white": "37", } return "\033[40;1;%s;40m%s\033[0m" % (colors[color], string)
def put_color(string, color): colors = {'red': '31', 'green': '32', 'yellow': '33', 'blue': '34', 'pink': '35', 'cyan': '36', 'white': '37'} return '\x1b[40;1;%s;40m%s\x1b[0m' % (colors[color], string)
class Trie: WORD_MARK = '*' ANY_CHAR_MARK = '.' def __init__(self): self.trie = {} def insert(self, word: str) -> None: trie = self.trie for ch in word: trie = trie.setdefault(ch, {}) trie[self.WORD_MARK] = self.WORD_MARK def search_regex(self, regex: ...
class Trie: word_mark = '*' any_char_mark = '.' def __init__(self): self.trie = {} def insert(self, word: str) -> None: trie = self.trie for ch in word: trie = trie.setdefault(ch, {}) trie[self.WORD_MARK] = self.WORD_MARK def search_regex(self, regex: s...
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: dp=[float("inf") for i in range(max(days)+1)] dp[0]=0 prices={1:costs[0],7:costs[1],30:costs[2]} for i in range(1,len(dp)): if i not in days: dp[i]=dp[i-1] ...
class Solution: def mincost_tickets(self, days: List[int], costs: List[int]) -> int: dp = [float('inf') for i in range(max(days) + 1)] dp[0] = 0 prices = {1: costs[0], 7: costs[1], 30: costs[2]} for i in range(1, len(dp)): if i not in days: dp[i] = dp[i -...
# https://www.acmicpc.net/problem/9019 def bfs(A, B): queue = __import__('collections').deque() queue.append((A, list())) visited = [False for _ in range(10000)] visited[A] = True while queue: cur, move = queue.popleft() nxt = (cur * 2) % 10000 if not visited[nxt]: ...
def bfs(A, B): queue = __import__('collections').deque() queue.append((A, list())) visited = [False for _ in range(10000)] visited[A] = True while queue: (cur, move) = queue.popleft() nxt = cur * 2 % 10000 if not visited[nxt]: if nxt == B: return m...
# Values for type component of FCGIHeader FCGI_BEGIN_REQUEST = 1 FCGI_ABORT_REQUEST = 2 FCGI_END_REQUEST = 3 FCGI_PARAMS = 4 FCGI_STDIN = 5 FCGI_STDOUT = 6 FCGI_STDERR = 7 FCGI_DATA = 8 FCGI_GET_VALUES = 9 FCGI_GET_VALUES_RESULT = 10 FCGI_UNKNOWN_TYPE = 11 # Mask for flags component of FCGIBeginRequestBody FCGI_KEEP_C...
fcgi_begin_request = 1 fcgi_abort_request = 2 fcgi_end_request = 3 fcgi_params = 4 fcgi_stdin = 5 fcgi_stdout = 6 fcgi_stderr = 7 fcgi_data = 8 fcgi_get_values = 9 fcgi_get_values_result = 10 fcgi_unknown_type = 11 fcgi_keep_conn = 1 fcgi_responder = 1 fcgi_authorizer = 2 fcgi_filter = 3 fcgi_request_complete = 0 fcgi_...
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Output: Alpha # COLOR: #699e69 # TEXTCOLOR: #ffffff # #-------------------------------------------------------------------------------------------...
ns = nuke.selectedNodes() for n in ns: n.knob('output1').setValue('alpha')
"""Document templates configuration file.""" reports = {} # Default if no template reports['NONE'] = (''' ''') # DSCE - Social enquiry reports['DSCE'] = (''' PERSONAL DETAILS Name of Child: %(name)s Age: %(age)s Nationality: %(nationality)s Religion: %(religion)s Physical/mental fitness: %(pad...
"""Document templates configuration file.""" reports = {} reports['NONE'] = ' ' reports['DSCE'] = '\n PERSONAL DETAILS\n Name of Child: %(name)s\n Age: %(age)s\n Nationality: %(nationality)s\n Religion: %(religion)s\n Physical/mental fitness: %(padd_dash)s\n Source of information: %(source)s\n E...
class Solution: def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int: special.sort() max_count = max(special[0] - bottom, top - special[-1]) for i in range(len(special) - 1): max_count = max(max_count, special[i+1] - special[i] - 1) return max_count
class Solution: def max_consecutive(self, bottom: int, top: int, special: List[int]) -> int: special.sort() max_count = max(special[0] - bottom, top - special[-1]) for i in range(len(special) - 1): max_count = max(max_count, special[i + 1] - special[i] - 1) return max_co...
r = int(input("Enter range: ")) print(f"\nThe first {r} Fibonacci numbers are:\n") n1 = n2 =1 print(n1) print(n2) for i in range(r-2): n3 = n1+n2 print(n3) n1 = n2 n2 = n3
r = int(input('Enter range: ')) print(f'\nThe first {r} Fibonacci numbers are:\n') n1 = n2 = 1 print(n1) print(n2) for i in range(r - 2): n3 = n1 + n2 print(n3) n1 = n2 n2 = n3
# Base Parameters assets = asset_list('FX') # Trading Parameters horizon = 'H1' pair = 0 # Mass Imports my_data = mass_import(pair, horizon) # Indicator Parameters lookback = 60 def ma(Data, lookback, close, where): Data = adder(Data, 1) for i in range(len(Data)): ...
assets = asset_list('FX') horizon = 'H1' pair = 0 my_data = mass_import(pair, horizon) lookback = 60 def ma(Data, lookback, close, where): data = adder(Data, 1) for i in range(len(Data)): try: Data[i, where] = Data[i - lookback + 1:i + 1, close].mean() except IndexError: ...
# # exceptions.py # # (c) 2017 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This module defines the exceptions used in various modules. # """ This sub-module defines the exceptions used in the onem2mlib module. """ class OneM2MLibError(Exception): """ Base c...
""" This sub-module defines the exceptions used in the onem2mlib module. """ class Onem2Mliberror(Exception): """ Base class for exceptions in this module. """ pass class Cseoperationerror(OneM2MLibError): """ Exception raised for errors when invoking operations on the CSE. """ def __...
def more(message): answer = input(message) while not (answer=="y" or answer=="n"): answer = input(message) return answer=="y"
def more(message): answer = input(message) while not (answer == 'y' or answer == 'n'): answer = input(message) return answer == 'y'
def get_input() -> list: with open(f"{__file__.rstrip('code.py')}input.txt") as f: return [l.strip().replace(" = ", " ").replace("mem[", "").replace("]", "") for l in f.readlines()] def parse_input(lines: list) -> list: instructions = [] for line in lines: if line.startswith('mask'): ...
def get_input() -> list: with open(f"{__file__.rstrip('code.py')}input.txt") as f: return [l.strip().replace(' = ', ' ').replace('mem[', '').replace(']', '') for l in f.readlines()] def parse_input(lines: list) -> list: instructions = [] for line in lines: if line.startswith('mask'): ...
# python2 (((((((( # noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): return u"Hello, " + friend_name + u"!"
def hello(friend_name): return u'Hello, ' + friend_name + u'!'
def test_time_traveling(w3): current_block_time = w3.eth.get_block("pending")['timestamp'] time_travel_to = current_block_time + 12345 w3.testing.timeTravel(time_travel_to) latest_block_time = w3.eth.get_block("pending")['timestamp'] assert latest_block_time >= time_travel_to
def test_time_traveling(w3): current_block_time = w3.eth.get_block('pending')['timestamp'] time_travel_to = current_block_time + 12345 w3.testing.timeTravel(time_travel_to) latest_block_time = w3.eth.get_block('pending')['timestamp'] assert latest_block_time >= time_travel_to
BASE_RATE = 59.94 # FEE RATES PREV_POLICY_CANCELLED_FEE_AMT = 0.50 STATE_FEE_AMT = 0.25 MILES_0_100_FEE_AMT = 0.50 MILES_101_200_FEE_AMT = 0.40 MILES_201_500_FEE_AMT = 0.35 # DISCOUNT RATES NO_PREV_POLICY_CANCELLED_DIS_AMT = 0.10 PROPERTY_OWNER_DIS_AMT = 0.20 STATES_WITH_VOLCANOES = [ 'AK', 'AZ', 'CA', ...
base_rate = 59.94 prev_policy_cancelled_fee_amt = 0.5 state_fee_amt = 0.25 miles_0_100_fee_amt = 0.5 miles_101_200_fee_amt = 0.4 miles_201_500_fee_amt = 0.35 no_prev_policy_cancelled_dis_amt = 0.1 property_owner_dis_amt = 0.2 states_with_volcanoes = ['AK', 'AZ', 'CA', 'CO', 'HI', 'ID', 'NV', 'NY', 'OR', 'UT', 'WA', 'WY...
class Solution: def kthFactor(self, n: int, k: int) -> int: factors = [i for i in range(1, n + 1) if n % i == 0] print(factors) if k <= len(factors): return factors[k - 1] return -1
class Solution: def kth_factor(self, n: int, k: int) -> int: factors = [i for i in range(1, n + 1) if n % i == 0] print(factors) if k <= len(factors): return factors[k - 1] return -1
""" Lecture 4 """ #my_tuple = 'a','b','c','d','e' #print(my_tuple) #print(my_tuple[1]) # using index numbers to find the letters we want #print(my_tuple[0:3]) # using slicing to find multiple letters at once #print(my_tuple[:]) #my_2nd_tuple = ('a','b','c','d','e') #as long as you have he commas, it is a tuple. #pri...
""" Lecture 4 """
# -*- coding: utf-8 -*- """ neutrino_api This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ). """ class UserAgentInfoResponse(object): """Implementation of the 'User Agent Info Response' model. TODO: type model description here. Attrib...
""" neutrino_api This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ). """ class Useragentinforesponse(object): """Implementation of the 'User Agent Info Response' model. TODO: type model description here. Attributes: mobile_screen_width (int): T...
prefix = "http://watch.peoplepower21.org" member_index = prefix + "/New/search.php" member_report = prefix +"/New/cm_info.php?member_seq=%s" bill_index = prefix + "/New/monitor_voteresult.php" bill_index_per_page = prefix + "/New/monitor_voteresult.php?page=%d" bill_vote = prefix + "/New/c_monitor_voteresult_detail.php...
prefix = 'http://watch.peoplepower21.org' member_index = prefix + '/New/search.php' member_report = prefix + '/New/cm_info.php?member_seq=%s' bill_index = prefix + '/New/monitor_voteresult.php' bill_index_per_page = prefix + '/New/monitor_voteresult.php?page=%d' bill_vote = prefix + '/New/c_monitor_voteresult_detail.ph...
class Timeframe: def __init__(self, pd_start_date, pd_end_date, pd_interval): if pd_end_date < pd_start_date: raise ValueError('Timeframe: end date is smaller then start date') if pd_interval.value <= 0: raise ValueError('Timeframe: timedelta needs to be positive') s...
class Timeframe: def __init__(self, pd_start_date, pd_end_date, pd_interval): if pd_end_date < pd_start_date: raise value_error('Timeframe: end date is smaller then start date') if pd_interval.value <= 0: raise value_error('Timeframe: timedelta needs to be positive') ...
# Python program for implementation of Level Order Traversal # Structure of a node class Node: def __init__(self ,key): self.data = key self.left = None self.right = None # print level order traversal def printLevelOrder(root): if root is None: return # create an empty ...
class Node: def __init__(self, key): self.data = key self.left = None self.right = None def print_level_order(root): if root is None: return node_queue = [] node_queue.append(root) while len(node_queue) > 0: print(node_queue[0].data) node = node_queu...
"""Base configuration""" DEBUG = False TESTING = False SECRET_KEY = b'' EXCHANGE_SECRET_KEY = b'' SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = '' """flask_mail configuration""" MAIL_SERVER = '' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TLS = False MAIL_USERNAME = '' MAIL_PASSWORD = '' # """Exch...
"""Base configuration""" debug = False testing = False secret_key = b'' exchange_secret_key = b'' sqlalchemy_track_modifications = False sqlalchemy_database_uri = '' 'flask_mail configuration' mail_server = '' mail_port = 465 mail_use_ssl = True mail_use_tls = False mail_username = '' mail_password = '' binance = 'http...
""" PlotPlayer Helpers Subpackage contains various generic miscellaneous modules and methods to ease development. Public Modules: * file_helper - Contains methods for interacting with the local file system * ui_helper - Contains methods for providing generic UI elements & dialogs """
""" PlotPlayer Helpers Subpackage contains various generic miscellaneous modules and methods to ease development. Public Modules: * file_helper - Contains methods for interacting with the local file system * ui_helper - Contains methods for providing generic UI elements & dialogs """
def get_formated_name (first_name, last_name): full_name = first_name + " "+last_name return full_name.title() musician = get_formated_name('jimi', 'hendrix') print(musician)
def get_formated_name(first_name, last_name): full_name = first_name + ' ' + last_name return full_name.title() musician = get_formated_name('jimi', 'hendrix') print(musician)
class GenericPlugin(object): ID = None NAME = None DEPENDENCIES = [] def __init__(self, app, view): self._app = app self._view = view @classmethod def id(cls): return cls.ID @classmethod def name(cls): return cls.NAME @classmethod def dependencies(cls): return cls.DEPENDENCI...
class Genericplugin(object): id = None name = None dependencies = [] def __init__(self, app, view): self._app = app self._view = view @classmethod def id(cls): return cls.ID @classmethod def name(cls): return cls.NAME @classmethod def dependenc...
def isValidChessBoard(board): """Validate counts and location of pieces on board""" # Define pieces and colors pieces = ['king', 'queen', 'rook', 'knight', 'bishop', 'pawn'] colors = ['b', 'w'] # Set of all chess pieces all_pieces = set(color + piece for piece in pieces for color in colors) ...
def is_valid_chess_board(board): """Validate counts and location of pieces on board""" pieces = ['king', 'queen', 'rook', 'knight', 'bishop', 'pawn'] colors = ['b', 'w'] all_pieces = set((color + piece for piece in pieces for color in colors)) valid_counts = {'king': (1, 1), 'queen': (0, 1), 'rook':...
def cache(func, **kwargs): attribute = '_{}'.format(func.__name__) @property def decorator(self): if not hasattr(self, attribute): setattr(self, attribute, func(self)) return getattr(self, attribute) return decorator
def cache(func, **kwargs): attribute = '_{}'.format(func.__name__) @property def decorator(self): if not hasattr(self, attribute): setattr(self, attribute, func(self)) return getattr(self, attribute) return decorator
# Third edit: done at github.com. # First edit. # Ask the user for a word. Add .lower() to the input return so it's easier to compare the letters. This method removes case sensitivity. word = input("Enter a word: ").lower() # Ask the user for a letter. Add .lower() to the input return so it's easier to compare the let...
word = input('Enter a word: ').lower() letter = input('Enter a letter: ').lower() if letter in word: letter_count = word.count(letter) message = f'The word "{word}" contains the letter "{letter}" {letter_count} times.' else: message = f'The letter "{letter}" is not in the word {word}.' print(message)
_base_ = [ '../_base_/default.py', '../_base_/logs/tensorboard_logger.py', '../_base_/optimizers/sgd.py', '../_base_/runners/epoch_runner_cancel.py', '../_base_/schedules/plateau.py', ] optimizer = dict( lr=0.001, momentum=0.9, weight_decay=0.0001, ) lr_config = dict(min_lr=1e-06) eva...
_base_ = ['../_base_/default.py', '../_base_/logs/tensorboard_logger.py', '../_base_/optimizers/sgd.py', '../_base_/runners/epoch_runner_cancel.py', '../_base_/schedules/plateau.py'] optimizer = dict(lr=0.001, momentum=0.9, weight_decay=0.0001) lr_config = dict(min_lr=1e-06) evaluation = dict(interval=1, metric=['mIoU'...
def reverseMapping(mapping): result = {} for i, segmentString in enumerate(mapping): result["".join(sorted(segmentString))]=i #print(result) return result def decode(p1): digitString = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] sixSegment = [] fiveSegment = [] for digit in p1: dg = ...
def reverse_mapping(mapping): result = {} for (i, segment_string) in enumerate(mapping): result[''.join(sorted(segmentString))] = i return result def decode(p1): digit_string = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] six_segment = [] five_segment = [] for digit in p1: dg = len(digit)...
__version_info__ = (1, 0, 0, '') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join(str(i) for i in __version_info__[:-1]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environmen...
__version_info__ = (1, 0, 0, '') __version__ = '.'.join((str(i) for i in __version_info__[:-1])) if __version_info__[-1] is not None: __version__ += '-%s' % (__version_info__[-1],) def version_context(request): return {'SW_VERSION': __version__}
# Copyright (c) Dietmar Wolz. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory. __version__ = '0.1.3' __all__ = [ 'rayretry', 'multiretry', ]
__version__ = '0.1.3' __all__ = ['rayretry', 'multiretry']
a = [] print(type(a)) #help(a) #print(dir(a)) #print(type(type(a)))
a = [] print(type(a))
''' Write a Binary Search Tree(BST) class. The class should have a "value" property set to be an integer, as well as "left" and "right" properties, both of which should point to either the None(null) value or to another BST. A node is said to be a BST node if and only if it satisfies the BST property: its value is stri...
""" Write a Binary Search Tree(BST) class. The class should have a "value" property set to be an integer, as well as "left" and "right" properties, both of which should point to either the None(null) value or to another BST. A node is said to be a BST node if and only if it satisfies the BST property: its value is stri...
#! /usr/bin/env python2 # Helpers def download_file(url): print("Downloading %s" % url) local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if ...
def download_file(url): print('Downloading %s' % url) local_filename = url.split('/')[-1] r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) return local_filename
class Solution(object): def getSum(self, num1, num2): """ :type a: int :type b: int :rtype: int """ ans = 0 mask = 0x01 carry = 0 for i in xrange(0, 32): a = num1 & mask b = num2 & mask c = carry...
class Solution(object): def get_sum(self, num1, num2): """ :type a: int :type b: int :rtype: int """ ans = 0 mask = 1 carry = 0 for i in xrange(0, 32): a = num1 & mask b = num2 & mask c = carry c...
''' import datetime from django.contrib.auth.models import User from django.core.mail import send_mail from tasks.models import Task, Report from datetime import timedelta, datetime, timezone from celery.decorators import periodic_task from celery import Celery from config.celery_app import app @periodic_task(ru...
""" import datetime from django.contrib.auth.models import User from django.core.mail import send_mail from tasks.models import Task, Report from datetime import timedelta, datetime, timezone from celery.decorators import periodic_task from celery import Celery from config.celery_app import app @periodic_task(ru...
# Databricks notebook source NRJXFYCZXPAPWUSDVWBQT YVDWRTQLOHHPYZUHJGTDMDYEZPHURUPFXD GMJLOPGLOTLZANILIDMCJSONOTNIZDYVSV HBUSZUHKJSRCMJQSJKGFSQAYLKPJUVKGUY FMJLCEHCNOQLGHLULYDPRUZUKMTWRBTLRASSIVMJ VJGQUSEDKRWDPXYLJMEEAMLNVBGMBVKRIYPGRJCKYKZX BLTCKGNOICKASIVEPWO RUJYBXAOS WGKYLEKOZP EKBYFUATSAEHQVRGCOHWHQVRMTEPOYLWLMCV...
NRJXFYCZXPAPWUSDVWBQT YVDWRTQLOHHPYZUHJGTDMDYEZPHURUPFXD GMJLOPGLOTLZANILIDMCJSONOTNIZDYVSV HBUSZUHKJSRCMJQSJKGFSQAYLKPJUVKGUY FMJLCEHCNOQLGHLULYDPRUZUKMTWRBTLRASSIVMJ VJGQUSEDKRWDPXYLJMEEAMLNVBGMBVKRIYPGRJCKYKZX BLTCKGNOICKASIVEPWO RUJYBXAOS WGKYLEKOZP EKBYFUATSAEHQVRGCOHWHQVRMTEPOYLWLMCVGHYHALUQKXHPLGIARGZHFLGMJFKWCG...
class RedisSet: def __init__(self, redis, key, converter, content=None): self.key_ = key self.redis_ = redis self.converter_ = converter if content: self.reset(content) def __len__(self): return self.redis_.scard(self.key_) def __call__(self): r...
class Redisset: def __init__(self, redis, key, converter, content=None): self.key_ = key self.redis_ = redis self.converter_ = converter if content: self.reset(content) def __len__(self): return self.redis_.scard(self.key_) def __call__(self): r...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def pairwiseSwap(self): temp = self.head if temp is None: return while temp is not None and temp.next is not None: ...
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def pairwise_swap(self): temp = self.head if temp is None: return while temp is not None and temp.next is not None: ...
# Copyright (c) 2013, Anders S. Christensen # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions...
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' lower_case_alphabet = alphabet.lower() numbers = '0123456789' regular_chars = alphabet + lower_case_alphabet + numbers + '._-' bb_smiles = dict([('HN', '[$([H]N(C=O)C)]'), ('NH', '[$([N](C=O)C)]'), ('XX', '[$([N])]'), ('CO', '[$([C](NC)=O)]'), ('OC', '[$([O]=C(NC)C)]'), ('CA', '[...
class ValidationResult(object): def __init__(self, valid, log, err): """ Constructor @type valid: Boolean @param valid: Path to file @type log: List[String] @param log: Processing log @type err: List[String] @param err:...
class Validationresult(object): def __init__(self, valid, log, err): """ Constructor @type valid: Boolean @param valid: Path to file @type log: List[String] @param log: Processing log @type err: List[String] @param err...
#27 # Time: O(n) # Space: O(1) # Given an array and a value, remove all instances # of that value in-place and return the new length. # Do not allocate extra space for another array, # you must do this by modifying the input array # in-place with O(1) extra memory. # The order of elements can be changed. # It d...
class Arraysol: def remove_elem(self, nums, target): length = 0 for idx in range(len(nums)): if nums[idx] != target: nums[length] = nums[idx] length += 1 return length
prompt123= ''' ************************ Rane Division Tools *************************** * Divide Range in bits or bytes * * Option.1 Divide Range in bits =1 * * Option.2 Divide Range in bytes =2 ...
prompt123 = '\n ************************ Rane Division Tools ***************************\n * Divide Range in bits or bytes *\n * Option.1 Divide Range in bits =1 *\n * Option.2 Divide Range in bytes =2 ...
# 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: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if not postorde...
class Solution: def build_tree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if not postorder: return None root_val = postorder.pop() root = tree_node(val=rootVal) index = inorder.index(rootVal) root.left = self.buildTree(inorder[:index],...
class Solution: def baseNeg2(self, N: int) -> str: res=[] while N: # and operation res.append(N&1) N=-(N>>1) return "".join(map(str,res[::-1] or [0]))
class Solution: def base_neg2(self, N: int) -> str: res = [] while N: res.append(N & 1) n = -(N >> 1) return ''.join(map(str, res[::-1] or [0]))
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d = {} for i in arr: temp = [] t = 0 c = i while i>1: if i%2==0: temp.append(0) i/=2 else: te...
class Solution: def sort_by_bits(self, arr: List[int]) -> List[int]: d = {} for i in arr: temp = [] t = 0 c = i while i > 1: if i % 2 == 0: temp.append(0) i /= 2 else: ...
""" appends JSON wine records from given data, formats and sort'em, output is JSON file, contains summary information by built-in parameters """ winedata_full = [] avg_wine_price_by_origin = [] ratings_count = [] def string_comb(raw_str): form_str = ' '.join( raw_str[1:-1].split() ).replace( ...
""" appends JSON wine records from given data, formats and sort'em, output is JSON file, contains summary information by built-in parameters """ winedata_full = [] avg_wine_price_by_origin = [] ratings_count = [] def string_comb(raw_str): form_str = ' '.join(raw_str[1:-1].split()).replace('price": ', 'price": "')....
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class ChevronModel(object): name = "" locked = False def __init__(self, name): self.name = name
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class Chevronmodel(object): name = '' locked = False def __init__(self, name): self.name = name
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=int(input()) a=[0]*(n+1) for i,x in enumerate(map(int,input().split())): a[x]=i x=y=0 input() for u in map(int,input().split()): x+=a[u]+1 y+=n-a[u] print(x,y)
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n = int(input()) a = [0] * (n + 1) for (i, x) in enumerate(map(int, input().split())): a[x] = i x = y = 0 input() for u in map(int, input().split()): x += a[u] + 1 y += n - a[u] print(x, y)
""" GENERATED FILE - DO NOT EDIT (created via @build_stack_rules_proto//cmd/depsgen) """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs) def core_deps(): io_bazel_rules...
""" GENERATED FILE - DO NOT EDIT (created via @build_stack_rules_proto//cmd/depsgen) """ load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name=name, **kwargs) def core_deps(): io_bazel_rules_go...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def shell_sort(arr): arr_size = len(arr) interval = arr_size // 2 while interval > 0: j = interval while j < arr_size: aux = arr[j] k = j while k >= interval and aux < arr[k-interval]: arr[k]...
def shell_sort(arr): arr_size = len(arr) interval = arr_size // 2 while interval > 0: j = interval while j < arr_size: aux = arr[j] k = j while k >= interval and aux < arr[k - interval]: arr[k] = arr[k - interval] k -= inter...
""" Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class crcl_plot: def __init__(self): rdus=int(input("please enter your radius for the circle: ")) self.radius=rdus def find_area(self): print(f'the area of ...
""" Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class crcl_plot: def __init__(self): rdus=int(input("please enter your radius for the circle: ")) self.radius=rdus def find_area(self): print(f'the area of ...
def bubblesort_once(l): res = l[:] for i in range(len(res)): for j in range(i+1, len(res)): if res[j-1] > res[j]: res[j], res[j-1] = res[j-1], res[j] return res return []
def bubblesort_once(l): res = l[:] for i in range(len(res)): for j in range(i + 1, len(res)): if res[j - 1] > res[j]: (res[j], res[j - 1]) = (res[j - 1], res[j]) return res return []
# imgur key client_id = '3cb7dabd0f805d6' client_secret = '30a9fb858f64bf4acc1651988e2fbc62e4fedaed' album_id = 'LeVFO62' album_id_lucky = '2aAnwnt' access_token = '52945d677b3e985c5e82ba7d1fbd96f52648a1bb' refresh_token = '46d87ffac8daa7d8ecd34c85b9db4c64dbc2c582' # line bot key line_channel_access_token = 'ozBtsH1AX...
client_id = '3cb7dabd0f805d6' client_secret = '30a9fb858f64bf4acc1651988e2fbc62e4fedaed' album_id = 'LeVFO62' album_id_lucky = '2aAnwnt' access_token = '52945d677b3e985c5e82ba7d1fbd96f52648a1bb' refresh_token = '46d87ffac8daa7d8ecd34c85b9db4c64dbc2c582' line_channel_access_token = 'ozBtsH1AXPn/0cgAA2HymGPHm5Hx4QYECJ1jU...
#!/usr/env/bin python # https://www.hackerrank.com/challenges/python-print # Python 2 N = int(raw_input()) # N = 3 print(reduce(lambda x, y: x + y, [str(n+1) for n in xrange(N)]))
n = int(raw_input()) print(reduce(lambda x, y: x + y, [str(n + 1) for n in xrange(N)]))
columns_to_change = set() for col in telecom_data.select_dtypes(include=['float64']).columns: if((telecom_data[col].fillna(-9999) % 1 == 0).all()): columns_to_change.add(col) print(len(columns_to_change)) columns_to_change.union(set(telecom_data.select_dtypes(include=['int64']).columns)) print(len(column...
columns_to_change = set() for col in telecom_data.select_dtypes(include=['float64']).columns: if (telecom_data[col].fillna(-9999) % 1 == 0).all(): columns_to_change.add(col) print(len(columns_to_change)) columns_to_change.union(set(telecom_data.select_dtypes(include=['int64']).columns)) print(len(columns_to...
# !/usr/bin/env python # -*- coding: utf-8 -*- """ @author: @file: ${NAME}.py @time: ${DATE} @version: """
""" @author: @file: ${NAME}.py @time: ${DATE} @version: """
s = input() if s: print('foo') else: print('bar') x = 1 y = x print(y)
s = input() if s: print('foo') else: print('bar') x = 1 y = x print(y)
# # PySNMP MIB module CHECKPOINT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHECKPOINT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:31:12 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...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ...
# # PySNMP MIB module CISCO-ITP-ACT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-ACT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:03:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ...
class MPRuntimeError(Exception): def __init__(self, msg, node): self.msg = msg self.node = node class MPNameError(MPRuntimeError): pass class MPSyntaxError(MPRuntimeError): pass # To be thrown from functions outside the interpreter -- # will be caught during execution and displayed as a runtim...
class Mpruntimeerror(Exception): def __init__(self, msg, node): self.msg = msg self.node = node class Mpnameerror(MPRuntimeError): pass class Mpsyntaxerror(MPRuntimeError): pass class Mpinternalerror(Exception): pass
with open("1.in") as file: lines = file.readlines() lines = [line.rstrip() for line in lines] # Part 1 increases = 0 for i in range(0, len(lines)-1): if int(lines[i]) < int(lines[i+1]): increases += 1 print(increases) # Part 2 increases = 0 for i in range(0, len(lines)-3): if (int(lines[i]) + ...
with open('1.in') as file: lines = file.readlines() lines = [line.rstrip() for line in lines] increases = 0 for i in range(0, len(lines) - 1): if int(lines[i]) < int(lines[i + 1]): increases += 1 print(increases) increases = 0 for i in range(0, len(lines) - 3): if int(lines[i]) + int(lines[i + 1...
class Pizza(): pass class PizzaBuilder(): def __init__(self, inches: int): self.inches = inches def addCheese(self): pass def addPepperoni(self): pass def addSalami(self): pass def addPimientos(self): pass def add...
class Pizza: pass class Pizzabuilder: def __init__(self, inches: int): self.inches = inches def add_cheese(self): pass def add_pepperoni(self): pass def add_salami(self): pass def add_pimientos(self): pass def...
# This script will create an ELF file ### SECTION .TEXT # mov ebx, 1 ; prints hello # mov eax, 4 # mov ecx, HWADDR # mov edx, HWLEN # int 0x80 # mov eax, 1 ; exits # mov ebx, 0x5D # int 0x80 ### SECTION .DATA # HWADDR db "Hello World!", 0x0A out = '' ...
out = '' out += '\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x10' out += '\x02\x00' out += '\x03\x00' out += '\x01\x00\x00\x00' out += '\x80\x80\x04\x08' out += '4\x00\x00\x00' out += '\x00\x00\x00\x00' out += '\x00\x00\x00\x00' out += '4\x00' out += ' \x00' out += '\x02\x00' out += '\x00\x00\x00\x00\x00\x00' o...
# Copyright 2020-2021 antillia.com Toshiyuki Arai # # 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 l...
loss = 'loss' val_loss = 'val_loss' ft_classification_acc = 'ft_classification_acc' classification_acc = 'classification_acc' regression_acc = 'regression_acc' val_ft_classification_acc = 'val_ft_classification_acc' val_classification_acc = 'val_classification_acc' val_regression_acc = 'val_regression_acc'
class Settings: CORRECTOR_DOCUMENTS_LIMIT = 20000 CORRECTOR_TIMEOUT_DAYS = 10 THREAD_COUNT = 4 CALC_TOTAL_DURATION = True CALC_CLIENT_SS_REQUEST_DURATION = True CALC_CLIENT_SS_RESPONSE_DURATION = True CALC_PRODUCER_DURATION_CLIENT_VIEW = True CALC_PRODUCER_DURATION_PRODUCER_VIEW = Tr...
class Settings: corrector_documents_limit = 20000 corrector_timeout_days = 10 thread_count = 4 calc_total_duration = True calc_client_ss_request_duration = True calc_client_ss_response_duration = True calc_producer_duration_client_view = True calc_producer_duration_producer_view = True ...
def trap(): left = [0]*n right = [0]*n s = 0 left[0] = A[0] for i in range( 1, n): left[i] = max(left[i-1], A[i]) right[n-1] = A[n-1] for i in range(n-2, -1, -1): right[i] = max(right[i + 1], A[i]); for i in range(0, n): s += min...
def trap(): left = [0] * n right = [0] * n s = 0 left[0] = A[0] for i in range(1, n): left[i] = max(left[i - 1], A[i]) right[n - 1] = A[n - 1] for i in range(n - 2, -1, -1): right[i] = max(right[i + 1], A[i]) for i in range(0, n): s += min(left[i], right[i]) - A[i...
class LoadSql(object): CREATE_DETECTION_TABLE = \ """ CREATE TABLE P2Detection( `objID` bigint NOT NULL, detectID bigint NOT NULL, ippObjID bigint NOT NULL, ippDetectID bigint NOT NULL, filterID smallint NOT NULL, imageID bigint NOT NULL, obsTime float NOT NULL DEFAULT -9...
class Loadsql(object): create_detection_table = "\nCREATE TABLE P2Detection(\n `objID` bigint NOT NULL,\n detectID bigint NOT NULL,\n ippObjID bigint NOT NULL,\n ippDetectID bigint NOT NULL,\n filterID smallint NOT NULL,\n imageID bigint NOT NULL,\n obsTime float NOT NULL DEFAULT -999,\n xPo...
# Copyright (c) 2022 Tulir Asokan # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. def _pluralize(count: int, singular: str) -> str: return singular if count == 1...
def _pluralize(count: int, singular: str) -> str: return singular if count == 1 else f'{singular}s' def _include_if_positive(count: int, word: str) -> str: return f'{count} {_pluralize(count, word)}' if count > 0 else '' def format_duration(seconds: int) -> str: """ Format seconds as a simple duration...
#!/usr/bin/env python3 def squares(start, end): """The squares function uses a list comprehension to create a list of squared numbers (n*n). It receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4,...
def squares(start, end): """The squares function uses a list comprehension to create a list of squared numbers (n*n). It receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4, 9].""" return [x...
def head(file_name: str, n: int = 10): try: with open(file_name) as f: for i, line in enumerate(f): if i == n: break print(line.rstrip()) except FileNotFoundError: print(f"No such file {file_name}") def tail(file_name: str, n: int...
def head(file_name: str, n: int=10): try: with open(file_name) as f: for (i, line) in enumerate(f): if i == n: break print(line.rstrip()) except FileNotFoundError: print(f'No such file {file_name}') def tail(file_name: str, n: int=...
ADMIN_INSTALLED_APPS = ( 'fluent_dashboard', 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', ) # FIXME: Move generic (not related to admin) context processors to base_settings # Note: replace 'django.core.context_processors' with 'djang...
admin_installed_apps = ('fluent_dashboard', 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin') admin_template_context_processors = ('django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processor...
# This is the qasim package, containing the module qasim.qasim in the .so file. # # Note that a valid module is one of: # # 1. a directory with a modulename/__init__.py file # 2. a file named modulename.py # 3. a file named modulename.PLATFORMINFO.so # # Since a .so ends up as a module all on its own, we have to includ...
name = 'qasim'
def test_unique_names(run_validator_for_test_files): errors = run_validator_for_test_files( 'test_not_unique.py', force_unique_test_names=True, ) assert len(errors) == 2 assert errors[0][2] == 'FP009 Duplicate name test case (test_not_uniq)' assert errors[1][2] == 'FP009 Duplicate n...
def test_unique_names(run_validator_for_test_files): errors = run_validator_for_test_files('test_not_unique.py', force_unique_test_names=True) assert len(errors) == 2 assert errors[0][2] == 'FP009 Duplicate name test case (test_not_uniq)' assert errors[1][2] == 'FP009 Duplicate name test case (test_not_...
num = 12 if num > 5: print("Bigger than 5") if num <= 47: print("Between 6 and 47")
num = 12 if num > 5: print('Bigger than 5') if num <= 47: print('Between 6 and 47')
class PlatformError(Exception): """ The error is thrown when you try to use function that are only available for windows """
class Platformerror(Exception): """ The error is thrown when you try to use function that are only available for windows """
''' Igmp Genie Ops Object Outputs for NXOS. ''' class IgmpOutput(object): ShowIpIgmpInterface = { "vrfs": { "default": { "groups_count": 2, "interface": { "Ethernet2/2": { "query_max_response_time": 10, ...
""" Igmp Genie Ops Object Outputs for NXOS. """ class Igmpoutput(object): show_ip_igmp_interface = {'vrfs': {'default': {'groups_count': 2, 'interface': {'Ethernet2/2': {'query_max_response_time': 10, 'vrf_name': 'default', 'statistics': {'general': {'sent': {'v2_reports': 0, 'v2_queries': 16, 'v2_leaves': 0}, 'r...
name = 'GLOBAL VARIABLE' def scope_func(): print('before initializing/assigning any local variables: ',locals()) pages = 10 print('after local variable declaration and assignment') print(locals()) # returns dictionary containing all local variable print('inside function name is : ', name) scope_...
name = 'GLOBAL VARIABLE' def scope_func(): print('before initializing/assigning any local variables: ', locals()) pages = 10 print('after local variable declaration and assignment') print(locals()) print('inside function name is : ', name) scope_func() print('outside function name is : ', name) pri...
class Complex: def __repr__(self): imag = self.imag sign = '+' if self.imag < 0: imag = -self.imag sign = '-' return f"{self.real} {sign} {imag}j" def __init__(self, real=None, imag=None): self.real = 0 if real == None else real; self.im...
class Complex: def __repr__(self): imag = self.imag sign = '+' if self.imag < 0: imag = -self.imag sign = '-' return f'{self.real} {sign} {imag}j' def __init__(self, real=None, imag=None): self.real = 0 if real == None else real self.imag...
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capi...
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capi...
# Databricks notebook source #setup the configuration for Azure Data Lake Storage Gen 2 configs = {"fs.azure.account.auth.type": "OAuth", "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider", "fs.azure.account.oauth2.client.id": "f62b9429-c55e-4ba...
configs = {'fs.azure.account.auth.type': 'OAuth', 'fs.azure.account.oauth.provider.type': 'org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider', 'fs.azure.account.oauth2.client.id': 'f62b9429-c55e-4ba4-bb93-bdfa4c0934b3', 'fs.azure.account.oauth2.client.secret': dbutils.secrets.get(scope='keyvaultscope', key=...
# problem 53 # Project Euler __author__ = 'Libao Jin' __date__ = 'July 17, 2015' def factorial(n): if n <= 1: return 1 product = 1 while n > 1: product *= n n -= 1 return product def factorialSeries(n): fSeries = [] for i in range(n): if i == 0: fSeries.append(1) else: value = fSeries[i-1] * i...
__author__ = 'Libao Jin' __date__ = 'July 17, 2015' def factorial(n): if n <= 1: return 1 product = 1 while n > 1: product *= n n -= 1 return product def factorial_series(n): f_series = [] for i in range(n): if i == 0: fSeries.append(1) else:...
numero = int(input("")) if numero < 5 or numero > 2000: numero = int(input("")) par = 1 while par <= numero: if par % 2 == 0: numero_quadrado = par ** 2 print("{}^2 = {}".format(par, numero_quadrado)) par += 1
numero = int(input('')) if numero < 5 or numero > 2000: numero = int(input('')) par = 1 while par <= numero: if par % 2 == 0: numero_quadrado = par ** 2 print('{}^2 = {}'.format(par, numero_quadrado)) par += 1
class Solution: def dailyTemperatures(self, temp: List[int]) -> List[int]: dp = [0] *len(temp) st = [] for i,n in enumerate(temp): while st and temp[st[-1]] < n : x = st.pop() dp[x] = i - x st.append(i) return dp
class Solution: def daily_temperatures(self, temp: List[int]) -> List[int]: dp = [0] * len(temp) st = [] for (i, n) in enumerate(temp): while st and temp[st[-1]] < n: x = st.pop() dp[x] = i - x st.append(i) return dp
# Basic Calculator II: https://leetcode.com/problems/basic-calculator-ii/ # Given a string s which represents an expression, evaluate this expression and return its value. # The integer division should truncate toward zero. # Note: You are not allowed to use any built-in function which evaluates strings as mathematica...
class Solution: def calculate(self, s: str) -> int: stack = [] operand = 0 sign = '+' for index in range(len(s)): if s[index].isdigit(): operand = operand * 10 + int(s[index]) if s[index] in '+-/*' or index == len(s) - 1: if si...
#this it the graphics file to Sam's Battle Simulator #Copyright 2018 Henry Morin def title(): print(""" _______ _______ _______ _ _______ ______ _________________________ _______ _______________________ ( ____ ( ___ | | | ____ \ ( ___ \( ___ )__ __|__ __( \ ( ____ \ (...
def title(): print('\n \n _______ _______ _______ _ _______ ______ _________________________ _______ _______________________ \n( ____ ( ___ | | | ____ \\ ( ___ \\( ___ )__ __|__ __( \\ ( ____ \\ ( ____ \\__ __( )\n| ( \\/ ( ) | () () |/| ( \\/ | ( ) ) ( ) ...
class SecunitError(Exception): ... class KeyNotInConfig(SecunitError): ... class InvalidFlaskEnv(SecunitError): ...
class Secuniterror(Exception): ... class Keynotinconfig(SecunitError): ... class Invalidflaskenv(SecunitError): ...