content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Converts a given temperature from Celsius to Fahrenheit # Prompt user for Celsius temperature degreesCelsius = float(input('\nEnter the temperature in Celsius: ')) # Calculate and display the converted # temperature in Fahrenheit degreesFahrenheit = ((9.0 / 5.0) * degreesCelsius) + 32 print('Fahrenheit equivalent:...
degrees_celsius = float(input('\nEnter the temperature in Celsius: ')) degrees_fahrenheit = 9.0 / 5.0 * degreesCelsius + 32 print('Fahrenheit equivalent: ', format(degreesFahrenheit, ',.1f'), '\n', sep='')
class Solution: def subtractProductAndSum(self, n: int) -> int: x = n add = 0 mul = 1 while x > 0 : add += x%10 mul *= x%10 x = x//10 return mul - add
class Solution: def subtract_product_and_sum(self, n: int) -> int: x = n add = 0 mul = 1 while x > 0: add += x % 10 mul *= x % 10 x = x // 10 return mul - add
"""Helper initialising functions """ #pylint: disable=I0011, C0321, C0301, C0103, C0325, R0902, R0913, no-member, E0213 def init_fuel_tech_p_by(all_enduses_with_fuels, nr_of_fueltypes): """Helper function to define stocks for all enduse and fueltype Parameters ---------- all_enduses_with_fuels : dict ...
"""Helper initialising functions """ def init_fuel_tech_p_by(all_enduses_with_fuels, nr_of_fueltypes): """Helper function to define stocks for all enduse and fueltype Parameters ---------- all_enduses_with_fuels : dict Provided fuels nr_of_fueltypes : int Nr of fueltypes Retur...
# Implementation of Shell Sort algorithm in Python def shellSort(arr): interval = 1 # Initializes interval while (interval < (len(arr) // 3)): interval = (interval * 3) + 1 while (interval > 0): for i in range(interval, len(arr)): # Select val to be inserted ...
def shell_sort(arr): interval = 1 while interval < len(arr) // 3: interval = interval * 3 + 1 while interval > 0: for i in range(interval, len(arr)): val = arr[i] j = i while j > interval - 1 and arr[j - interval] >= val: arr[j] = arr[j - i...
"""Classes implementing the descriptor protocol.""" __all__ = ("classproperty",) class classproperty: """Like the builtin :py:func:`property` but takes a single classmethod. Essentially, it allows you to use a property on a class itself- not just on its instances. Used like this: >>> from sna...
"""Classes implementing the descriptor protocol.""" __all__ = ('classproperty',) class Classproperty: """Like the builtin :py:func:`property` but takes a single classmethod. Essentially, it allows you to use a property on a class itself- not just on its instances. Used like this: >>> from snakeo...
TASK_STATUS = [ ('TD', 'To Do'), ('IP', 'In Progress'), ('QA', 'Testing'), ('DO', 'Done'), ] TASK_PRIORITY = [ ('ME', 'Medium'), ('HI', 'Highest'), ('HG', 'High'), ('LO', 'Lowest'), ]
task_status = [('TD', 'To Do'), ('IP', 'In Progress'), ('QA', 'Testing'), ('DO', 'Done')] task_priority = [('ME', 'Medium'), ('HI', 'Highest'), ('HG', 'High'), ('LO', 'Lowest')]
def main(): total = 0 for i in range(0, 1000): if i % 3 == 0: total += i elif i % 5 == 0: total += i print(total) if __name__ == '__main__': main()
def main(): total = 0 for i in range(0, 1000): if i % 3 == 0: total += i elif i % 5 == 0: total += i print(total) if __name__ == '__main__': main()
class BaseTransform: def transform_s(self, s, training=True): return s def transform_batch(self, batch, training=True): return batch def write_logs(self, logger): pass
class Basetransform: def transform_s(self, s, training=True): return s def transform_batch(self, batch, training=True): return batch def write_logs(self, logger): pass
elements = { 'em': '', 'blockquote': '<br/>' }
elements = {'em': '', 'blockquote': '<br/>'}
def rate_diff_percentage(previous_rate, current_rate, percentage=False): diff_percentage = (current_rate - previous_rate) / previous_rate if percentage: return diff_percentage * 100 return diff_percentage
def rate_diff_percentage(previous_rate, current_rate, percentage=False): diff_percentage = (current_rate - previous_rate) / previous_rate if percentage: return diff_percentage * 100 return diff_percentage
# Assume that we execute the following assignment statements # width = 17 # height = 12.0 width = 17 height = 12.0 value_1 = width // 2 value_2 = width / 2.0 value_3 = height / 3 value_4 = 1 + 2 * 5 print(f"value_1 is {value_1} and it's type is {type(value_1)}") print(f"value_2 is {value_2} and it's type is {type(va...
width = 17 height = 12.0 value_1 = width // 2 value_2 = width / 2.0 value_3 = height / 3 value_4 = 1 + 2 * 5 print(f"value_1 is {value_1} and it's type is {type(value_1)}") print(f"value_2 is {value_2} and it's type is {type(value_2)}") print(f"value_3 is {value_3} and it's type is {type(value_3)}") print(f"value_4 is ...
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: start, end = rounds[0], rounds[-1] if end >= start: return list(range(start, end + 1)) else: return list(range(1, end + 1)) + list(range(start, n + 1))
class Solution: def most_visited(self, n: int, rounds: List[int]) -> List[int]: (start, end) = (rounds[0], rounds[-1]) if end >= start: return list(range(start, end + 1)) else: return list(range(1, end + 1)) + list(range(start, n + 1))
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ __all__ = ['xep_0004', 'xep_0012', 'xep_0030', 'xep_0033', 'xep_0045', 'xep_0050', 'xep_0085', 'xep_0092', 'xep_0199', 'gmail_notify', ...
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ __all__ = ['xep_0004', 'xep_0012', 'xep_0030', 'xep_0033', 'xep_0045', 'xep_0050', 'xep_0085', 'xep_0092', 'xep_0199', 'gmail_notify', 'xep_0060',...
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = set("aeiouAEIOU") s = list(s) i = 0 j = len(s) - 1 while i < j: while i < j and s[i] not in vowels: i +=...
class Solution(object): def reverse_vowels(self, s): """ :type s: str :rtype: str """ vowels = set('aeiouAEIOU') s = list(s) i = 0 j = len(s) - 1 while i < j: while i < j and s[i] not in vowels: i += 1 w...
__author__ = 'Evan Cordell' __copyright__ = 'Copyright 2012-2015 Localmed, Inc.' __version__ = "0.1.6" __version_info__ = tuple(__version__.split('.')) __short_version__ = __version__
__author__ = 'Evan Cordell' __copyright__ = 'Copyright 2012-2015 Localmed, Inc.' __version__ = '0.1.6' __version_info__ = tuple(__version__.split('.')) __short_version__ = __version__
# -*- coding: utf-8 -*- # Copyright (c) 2013 Australian Government, Department of the Environment # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without...
""" base 64 encoded gif images for the GUI buttons """ class App_Img: format = 'gif' data = 'R0lGODlhEAAQAOeRACcLIiAbCSAjCjMdMzsfMjUkGUcmRjwwJ0YqRj4xJVwoUFguRkU2MS0/LzQ8\n PC8/LzM+QTJCMDJCQTpCQCxIME1CIXQyYW48KTpLO1REPEpKSktKS01KSkpLSkxLTE1LS0VNUDtS\n PD9PT0tMTExMTE1MTUxNTU1NTU5NTUFUQFFOTk...
def is_true(a,b,c,d,e,f,g): if a>10: print(10)
def is_true(a, b, c, d, e, f, g): if a > 10: print(10)
""" Sliding window Given a string S, return the number of substrings of length K with no repeated characters. Example 1: Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. cou...
""" Sliding window Given a string S, return the number of substrings of length K with no repeated characters. Example 1: Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. cou...
#~ Copyright 2014 Wieger Wesselink. #~ Distributed under the Boost Software License, Version 1.0. #~ (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) def read_text(filename): with open(filename, 'r') as f: return f.read() def write_text(filename, text): with open(filenam...
def read_text(filename): with open(filename, 'r') as f: return f.read() def write_text(filename, text): with open(filename, 'w') as f: f.write(text)
def is_descending(input_list: list, step: int = -1) -> bool: r"""llogic.is_descending(input_list[, step]) This function returns True if the input list is descending with a fixed step, otherwise it returns False. Usage: >>> alist = [3, 2, 1, 0] >>> llogic.is_descending(alist) True The fina...
def is_descending(input_list: list, step: int=-1) -> bool: """llogic.is_descending(input_list[, step]) This function returns True if the input list is descending with a fixed step, otherwise it returns False. Usage: >>> alist = [3, 2, 1, 0] >>> llogic.is_descending(alist) True The final v...
class FeatureRegistration: def __init__(self, key, failoverVariant, variants=[]): """docstring for __init__""" self.key = key self.failoverVariant = failoverVariant self.variants = [v.toJSON() for v in variants] def toJSON(self): """docstring for toJSON""" self._...
class Featureregistration: def __init__(self, key, failoverVariant, variants=[]): """docstring for __init__""" self.key = key self.failoverVariant = failoverVariant self.variants = [v.toJSON() for v in variants] def to_json(self): """docstring for toJSON""" self...
_base_ = "./resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO_01_02MasterChefCan.py" OUTPUT_DIR = ( "output/gdrn/ycbvPbrSO/resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO/09_10PottedMeatCan" ) DATASETS = dict(TRAIN=("ycbv_010_potted_meat_can_train_pbr",))
_base_ = './resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO_01_02MasterChefCan.py' output_dir = 'output/gdrn/ycbvPbrSO/resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO/09_10PottedMeatCan' datasets = dict(TRAIN=('ycbv_010_potted_meat_can_train_pbr',))
# https://leetcode.com/problems/palindrome-partitioning/ class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """
"""Information for the outgoing response code - the HTTP response code (default is "200 Ok") headers - a list of key/value pairs used for the WSGI start_response """ code = None headers = [] def add_header(key, value): """Helper function to append (key, value) to the list of response headers""" headers....
"""Information for the outgoing response code - the HTTP response code (default is "200 Ok") headers - a list of key/value pairs used for the WSGI start_response """ code = None headers = [] def add_header(key, value): """Helper function to append (key, value) to the list of response headers""" headers.a...
# -*- coding: utf-8 -*- # __author__= "Ruda" # Date: 2018/10/16 ''' import os from rongcloud import RongCloud app_key = os.environ['APP_KEY'] app_secret = os.environ['APP_SECRET'] rcloud = RongCloud(app_key, app_secret) r = rcloud.User.getToken(userId='userid1', name='username', portraitUri='http://www.rongcloud.c...
""" import os from rongcloud import RongCloud app_key = os.environ['APP_KEY'] app_secret = os.environ['APP_SECRET'] rcloud = RongCloud(app_key, app_secret) r = rcloud.User.getToken(userId='userid1', name='username', portraitUri='http://www.rongcloud.cn/images/logo.png') print(r) {'token': 'P9YNVZ2cMQwwaADiNDVrtRZK...
''' If the child is currently on the nth step, then there are three possibilites as to how it reached there: 1. Reached (n-3)th step and hopped 3 steps in one time 2. Reached (n-2)th step and hopped 2 steps in one time 3. Reached (n-1)th step and hopped 2 steps in one time The total number of possibilities is the sum...
""" If the child is currently on the nth step, then there are three possibilites as to how it reached there: 1. Reached (n-3)th step and hopped 3 steps in one time 2. Reached (n-2)th step and hopped 2 steps in one time 3. Reached (n-1)th step and hopped 2 steps in one time The total number of possibilities is the sum...
class Solution: def runningSum(self, nums: List[int]) -> List[int]: for index in range(1, len(nums)): nums[index] = nums[index - 1] + nums[index] return nums
class Solution: def running_sum(self, nums: List[int]) -> List[int]: for index in range(1, len(nums)): nums[index] = nums[index - 1] + nums[index] return nums
class PrefabError(Exception): pass class HashAlgorithmNotFound(PrefabError): pass class ImageAccessError(PrefabError): pass class ImageBuildError(PrefabError): pass class ImageNotFoundError(PrefabError): pass class ImagePushError(PrefabError): pass class ImageValidationError(PrefabEr...
class Prefaberror(Exception): pass class Hashalgorithmnotfound(PrefabError): pass class Imageaccesserror(PrefabError): pass class Imagebuilderror(PrefabError): pass class Imagenotfounderror(PrefabError): pass class Imagepusherror(PrefabError): pass class Imagevalidationerror(PrefabError): ...
class Opt: def __init__(self): self.dataset = "fashion200k" self.dataset_path = "./dataset/Fashion200k" self.batch_size = 32 self.embed_dim = 512 self.hashing = False self.retrieve_by_random = True
class Opt: def __init__(self): self.dataset = 'fashion200k' self.dataset_path = './dataset/Fashion200k' self.batch_size = 32 self.embed_dim = 512 self.hashing = False self.retrieve_by_random = True
# Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it. # Lily decides to share a contiguous segment of the bar selected such that: # The length of the segment matches Ron's birth month, and, # The sum of the integers on the squares is equal to his birth day. # Determine...
def birthday(s, d, m): number_diveded = 0 number_iteration = len(s) - (m - 1) if numberIteration == 0: number_iteration = 1 for k in range(0, numberIteration): new_array = s[k:k + m] sum_array = sum(newArray) if sumArray == d: number_diveded += 1 return nu...
N = int(input()) entry = [input().split() for _ in range(N)] phoneBook = {name: number for name, number in entry} while True: try: name = input() if name in phoneBook: print(f"{name}={phoneBook[name]}") else: print("Not found") except: break
n = int(input()) entry = [input().split() for _ in range(N)] phone_book = {name: number for (name, number) in entry} while True: try: name = input() if name in phoneBook: print(f'{name}={phoneBook[name]}') else: print('Not found') except: break
pet = { "name":"Doggo", "animal":"dog", "species":"labrador", "age":"5" } class Pet(object): def __init__(self, name, age, animal): self.name = name self.age = age self.animal = animal self.hungry = False self.mood= "happy" def eat(self): print("> %s is eating....
pet = {'name': 'Doggo', 'animal': 'dog', 'species': 'labrador', 'age': '5'} class Pet(object): def __init__(self, name, age, animal): self.name = name self.age = age self.animal = animal self.hungry = False self.mood = 'happy' def eat(self): print('> %s is eati...
# Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): node = root ...
class Treelinknode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: def connect(self, root): node = root current = None candidate = None next_start = None if node is None: ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_device": "00_basics.ipynb", "settings_template": "00_basics.ipynb", "read_settings": "00_basics.ipynb", "DEVICE": "00_basics.ipynb", "settings": "00_basics.ipynb", ...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_device': '00_basics.ipynb', 'settings_template': '00_basics.ipynb', 'read_settings': '00_basics.ipynb', 'DEVICE': '00_basics.ipynb', 'settings': '00_basics.ipynb', 'DATA_STORE': '00_basics.ipynb', 'LOG_STORE': '00_basics.ipynb', 'MODEL_STORE': ...
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: """Hash table. Running time: O(n) where n == len(arr). """ d = collections.defaultdict(int) for a in arr: d[a % k] += 1 for key, v in d.items(): if key == 0 and v % 2 == 1: ...
class Solution: def can_arrange(self, arr: List[int], k: int) -> bool: """Hash table. Running time: O(n) where n == len(arr). """ d = collections.defaultdict(int) for a in arr: d[a % k] += 1 for (key, v) in d.items(): if key == 0 and v % 2 ==...
# Define a procedure, fibonacci, that takes a natural number as its input, and # returns the value of that fibonacci number. # Two Base Cases: # fibonacci(0) => 0 # fibonacci(1) => 1 # Recursive Case: # n > 1 : fibonacci(n) => fibonacci(n-1) + fibonacci(n-2) def fibonacci(n): return n if n ==...
def fibonacci(n): return n if n == 0 or n == 1 else fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(0)) print(fibonacci(1)) print(fibonacci(15))
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @file : __init__.py.py @Time : 2020/11/12 13:37 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ """ phoronix-test-suite: Main for Performance Test =================== https://github.com/phoronix-test-suite/phoronix-test-suite The Phoronix Test Suite is the most compr...
""" @file : __init__.py.py @Time : 2020/11/12 13:37 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ '\nphoronix-test-suite: Main for Performance Test\n===================\nhttps://github.com/phoronix-test-suite/phoronix-test-suite\nThe Phoronix Test Suite is the most comprehensive testing and \nbenchmarking platf...
errorFound = False def hasError(): global errorFound return errorFound def clearError(): global errorFound errorFound = False def error(message, lineNo = 0): report(lineNo, "", message) def report(lineNo, where, message): global errorFound errorFound = True if lineNo == 0: ...
error_found = False def has_error(): global errorFound return errorFound def clear_error(): global errorFound error_found = False def error(message, lineNo=0): report(lineNo, '', message) def report(lineNo, where, message): global errorFound error_found = True if lineNo == 0: ...
class AnythingType(set): def __contains__(self, other): return True def intersection(self, other): return other def union(self, other): return self def __str__(self): return '*' def __repr__(self): return "Anything" Anything = AnythingType()
class Anythingtype(set): def __contains__(self, other): return True def intersection(self, other): return other def union(self, other): return self def __str__(self): return '*' def __repr__(self): return 'Anything' anything = anything_type()
allct_dat = { "TYR": { "HB2":{'torsion': 300.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 9, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, "HB3":{'torsion': 60.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 10, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, "impropTors":[['-M', 'CA'...
allct_dat = {'TYR': {'HB2': {'torsion': 300.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 9, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, 'HB3': {'torsion': 60.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 10, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, 'impropTors': [['-M', 'CA',...
def kelime_sayisi(string): counter = 1 for i in range(0,len(string)): if string[i] == ' ': counter += 1 return counter cumle = input("Cumlenizi giriniz : ") print("Cumlenizdeki kelime sayisi = {}".format(kelime_sayisi(cumle)))
def kelime_sayisi(string): counter = 1 for i in range(0, len(string)): if string[i] == ' ': counter += 1 return counter cumle = input('Cumlenizi giriniz : ') print('Cumlenizdeki kelime sayisi = {}'.format(kelime_sayisi(cumle)))
class Solution: def paintHouse(self, cost:list, houses:int, colors:int)->int: if houses == 0: # no houses to paint return 0 if colors == 0: # no colors to paint houses return 0 dp = [[0]*colors for _ in range(houses)] dp[0] = cost[0]...
class Solution: def paint_house(self, cost: list, houses: int, colors: int) -> int: if houses == 0: return 0 if colors == 0: return 0 dp = [[0] * colors for _ in range(houses)] dp[0] = cost[0] for i in range(1, houses): mincost = 100000000...
''' Created on Dec 21, 2014 @author: Ben ''' def create_new_default(directory: str, dest: dict, param: dict): ''' Creates new default parameter file based on parameter settings ''' with open(directory, 'w') as new_default: new_default.write( '''TARGET DESTINATION = {} SAVE DESTINATION = {}...
""" Created on Dec 21, 2014 @author: Ben """ def create_new_default(directory: str, dest: dict, param: dict): """ Creates new default parameter file based on parameter settings """ with open(directory, 'w') as new_default: new_default.write('TARGET DESTINATION = {} \nSAVE DESTINATION = {}\nS...
"""Exceptions for Renault API.""" class RenaultException(Exception): # noqa: N818 """Base exception for Renault API errors.""" pass class NotAuthenticatedException(RenaultException): # noqa: N818 """You are not authenticated, or authentication has expired.""" pass
"""Exceptions for Renault API.""" class Renaultexception(Exception): """Base exception for Renault API errors.""" pass class Notauthenticatedexception(RenaultException): """You are not authenticated, or authentication has expired.""" pass
def grayscale(image): for row in range(image.shape[0]): for col in range(image.shape[1]): avg = sum(image[row][col][i] for i in range(3)) // 3 image[row][col] = [avg for _ in range(3)]
def grayscale(image): for row in range(image.shape[0]): for col in range(image.shape[1]): avg = sum((image[row][col][i] for i in range(3))) // 3 image[row][col] = [avg for _ in range(3)]
def get_cross_sum(n): start = 1 total = 1 for i in range(1, n): step = i * 2 start = start + step total += start * 4 + step * 6 start = start + step * 3 return total print(get_cross_sum(501))
def get_cross_sum(n): start = 1 total = 1 for i in range(1, n): step = i * 2 start = start + step total += start * 4 + step * 6 start = start + step * 3 return total print(get_cross_sum(501))
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 15:31:57 2020 @author: Tarun Jaiswal """ dictone = { "bookname": "Recursion Sutras", "subject": "Recursion", "author": "Champak Roy" } dicttwo = dict(dictone) print(dicttwo)
""" Created on Sat Oct 10 15:31:57 2020 @author: Tarun Jaiswal """ dictone = {'bookname': 'Recursion Sutras', 'subject': 'Recursion', 'author': 'Champak Roy'} dicttwo = dict(dictone) print(dicttwo)
class Analyser: def __init__(self, callbacks, notifiers, state): self.cbs = callbacks self.state = state self.notifiers = notifiers def on_begin_analyse(self, timestamp): pass def on_end_analyse(self, timestamp): pass def analyse(self, event): event_nam...
class Analyser: def __init__(self, callbacks, notifiers, state): self.cbs = callbacks self.state = state self.notifiers = notifiers def on_begin_analyse(self, timestamp): pass def on_end_analyse(self, timestamp): pass def analyse(self, event): event_na...
GOV_AIRPORTS = { "Antananarivo/Ivato": "big", "Antsiranana/Diego": "small", "Fianarantsoa": "small", "Tolagnaro/Ft. Dauphin": "small", "Mahajanga": "medium", "Mananjary": "small", "Nosy Be": "medium", "Morondava": "small", "Sainte Marie": "small", "Sambava": "small", "Toamasi...
gov_airports = {'Antananarivo/Ivato': 'big', 'Antsiranana/Diego': 'small', 'Fianarantsoa': 'small', 'Tolagnaro/Ft. Dauphin': 'small', 'Mahajanga': 'medium', 'Mananjary': 'small', 'Nosy Be': 'medium', 'Morondava': 'small', 'Sainte Marie': 'small', 'Sambava': 'small', 'Toamasina': 'small', 'Toliary': 'small'}
def fibonacci(n): fibonacci = np.zeros(10, dtype=np.int32) fibonacci_pow = np.zeros(10, dtype=np.int32) fibonacci[0] = 0 fibonacci[1] = 1 for i in np.arange(2, 10): fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2] fibonacci[i] = int(fibonacci[i]) print(fibonacci) for i in np.arange(10): fibonacci_pow[i] ...
def fibonacci(n): fibonacci = np.zeros(10, dtype=np.int32) fibonacci_pow = np.zeros(10, dtype=np.int32) fibonacci[0] = 0 fibonacci[1] = 1 for i in np.arange(2, 10): fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2] fibonacci[i] = int(fibonacci[i]) print(fibonacci) for i in n...
# Copyright (c) 2020 NVIDIA Corporation # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, d...
"""Convert a .mesh file (fTetWild format) to .tet (IsaacGym format).""" def convert_mesh_to_tet(mesh_file_path, tet_output_path): """Convert a .mesh file to a .tet file.""" mesh_file = open(mesh_file_path, 'r') tet_output = open(tet_output_path, 'w') mesh_lines = list(mesh_file) mesh_lines = [line....
def split_in_three(data_real, data_fake): min_v = min(data_fake.min(), data_real.min()) max_v = max(data_fake.max(), data_real.max()) tercio = (max_v - min_v) / 3 # Calculate 1/3 th_one = min_v + tercio # Calculate 2/3 th_two = max_v - tercio first_f, second_f, third_f = split_data(th_...
def split_in_three(data_real, data_fake): min_v = min(data_fake.min(), data_real.min()) max_v = max(data_fake.max(), data_real.max()) tercio = (max_v - min_v) / 3 th_one = min_v + tercio th_two = max_v - tercio (first_f, second_f, third_f) = split_data(th_one, th_two, data_fake) (first_r, se...
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums_set = set(nums) full_length = len(nums) + 1 for num in range(full_length): if num not in nums_set: return num
class Solution(object): def missing_number(self, nums): """ :type nums: List[int] :rtype: int """ nums_set = set(nums) full_length = len(nums) + 1 for num in range(full_length): if num not in nums_set: return num
"""Below Python Programme demonstrate rpartition functions in a string""" string = "Python is fun" # 'is' separator is found print(string.rpartition('is ')) # 'not' separator is not found print(string.rpartition('not ')) string = "Python is fun, isn't it" # splits at last occurence of 'is' print(string.rpartition('...
"""Below Python Programme demonstrate rpartition functions in a string""" string = 'Python is fun' print(string.rpartition('is ')) print(string.rpartition('not ')) string = "Python is fun, isn't it" print(string.rpartition('is'))
data = ( 'Mie ', # 0x00 'Xu ', # 0x01 'Mang ', # 0x02 'Chi ', # 0x03 'Ge ', # 0x04 'Xuan ', # 0x05 'Yao ', # 0x06 'Zi ', # 0x07 'He ', # 0x08 'Ji ', # 0x09 'Diao ', # 0x0a 'Cun ', # 0x0b 'Tong ', # 0x0c 'Ming ', # 0x0d 'Hou ', # 0x0e 'Li ', # 0x0f 'Tu ', # 0x10 'Xiang ...
data = ('Mie ', 'Xu ', 'Mang ', 'Chi ', 'Ge ', 'Xuan ', 'Yao ', 'Zi ', 'He ', 'Ji ', 'Diao ', 'Cun ', 'Tong ', 'Ming ', 'Hou ', 'Li ', 'Tu ', 'Xiang ', 'Zha ', 'Xia ', 'Ye ', 'Lu ', 'A ', 'Ma ', 'Ou ', 'Xue ', 'Yi ', 'Jun ', 'Chou ', 'Lin ', 'Tun ', 'Yin ', 'Fei ', 'Bi ', 'Qin ', 'Qin ', 'Jie ', 'Bu ', 'Fou ', 'Ba ', '...
divisor = int(input()) bound = int(input()) for num in range(bound, 0, -1): if num % divisor == 0: print(num) break
divisor = int(input()) bound = int(input()) for num in range(bound, 0, -1): if num % divisor == 0: print(num) break
cities = [ 'Budapest', 'Debrecen', 'Miskolc', 'Szeged', 'Pecs', 'Zuglo', 'Gyor', 'Nyiregyhaza', 'Kecskemet', 'Szekesfehervar', 'Szombathely', 'Jozsefvaros', 'Paradsasvar', 'Szolnok', 'Tatabanya', 'Kaposvar', 'Bekescsaba', 'Erd', 'Veszprem', ...
cities = ['Budapest', 'Debrecen', 'Miskolc', 'Szeged', 'Pecs', 'Zuglo', 'Gyor', 'Nyiregyhaza', 'Kecskemet', 'Szekesfehervar', 'Szombathely', 'Jozsefvaros', 'Paradsasvar', 'Szolnok', 'Tatabanya', 'Kaposvar', 'Bekescsaba', 'Erd', 'Veszprem', 'Erzsebetvaros', 'Zalaegerszeg', 'Kispest', 'Sopron', 'Eger', 'Nagykanizsa', 'Du...
def read_file(test = True): if test: filename = '../tests/day1.txt' else: filename = '../input/day1.txt' with open(filename) as file: temp = list() for line in file: temp.append(line.strip()) return temp def puzzle1(): temp = read_file(False)[0] floo...
def read_file(test=True): if test: filename = '../tests/day1.txt' else: filename = '../input/day1.txt' with open(filename) as file: temp = list() for line in file: temp.append(line.strip()) return temp def puzzle1(): temp = read_file(False)[0] floor =...
""" The key is to use a set to remember if we seen the node or not. Next, think about how we are going to *remove* the duplicate node? The answer is to simply link the previous node to the next node. So we need to keep a pointer `prev` on the previous node as we iterate the linked list. So, the solution. Create a set ...
""" The key is to use a set to remember if we seen the node or not. Next, think about how we are going to *remove* the duplicate node? The answer is to simply link the previous node to the next node. So we need to keep a pointer `prev` on the previous node as we iterate the linked list. So, the solution. Create a set ...
def firstDuplicate(a): number_frequencies, number_indices, duplicate_index = {}, {}, {} # Iterate through list and increment frequency count # if number not in dict. Also, note the index asscoiated # with the value for i in range(len(a)): if a[i] not in number_frequencies: numbe...
def first_duplicate(a): (number_frequencies, number_indices, duplicate_index) = ({}, {}, {}) for i in range(len(a)): if a[i] not in number_frequencies: number_frequencies[a[i]] = 1 number_indices[a[i]] = i elif a[i] in number_frequencies: if number_frequencies...
""" CONFIGURATION FILE This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 18 oct. 2018 @author: Roi Sucasas...
""" CONFIGURATION FILE This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 18 oct. 2018 @author: Roi Sucasas...
# # PySNMP MIB module IANA-MALLOC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-MALLOC-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:50:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) ...
""" 1208. Get Equal Substrings Within Budget Straight forward. Asked the max len, so count the max each time. """ class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: cost = 0 window_start = 0 result = 0 for window_end in range(...
""" 1208. Get Equal Substrings Within Budget Straight forward. Asked the max len, so count the max each time. """ class Solution: def equal_substring(self, s: str, t: str, maxCost: int) -> int: cost = 0 window_start = 0 result = 0 for window_end in range(len(s)): cost...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
""" OpenERP core exceptions. This module defines a few exception types. Those types are understood by the RPC layer. Any other exception type bubbling until the RPC layer will be treated as a 'Server error'. """ class Warning(Exception): pass class Accessdenied(Exception): """ Login/password error. No messa...
class File: @staticmethod def tail(self, file_path, lines=10): with open(file_path, 'rb') as f: total_lines_wanted = lines block_size = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 ...
class File: @staticmethod def tail(self, file_path, lines=10): with open(file_path, 'rb') as f: total_lines_wanted = lines block_size = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 ...
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" class Reverse_Stack: def __init__(self): self.items = [] def is_empty(self): # test to see whether the stack is empty. return self.items == [] def push(self, item): # adds a new item to the bas...
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" class Reverse_Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.insert(0, item) def pop(self): return se...
class Solution: def isStrobogrammatic(self, num: str) -> bool: strobogrammatic = { '1': '1', '0': '0', '6': '9', '9': '6', '8': '8' } for idx, digit in enumerate(num): if digit not in strobogrammatic or strobogrammatic[...
class Solution: def is_strobogrammatic(self, num: str) -> bool: strobogrammatic = {'1': '1', '0': '0', '6': '9', '9': '6', '8': '8'} for (idx, digit) in enumerate(num): if digit not in strobogrammatic or strobogrammatic[digit] != num[len(num) - idx - 1]: return False ...
class Solution(object): def dfs(self,stones,graph,curpos,lastjump): if curpos==stones[-1]: return True # since the jump need based on lastjump # only forward,get rid of the stay at the same pos rstart=max(curpos+lastjump-1,curpos+1) rend=min(curpos+lastjump+1,ston...
class Solution(object): def dfs(self, stones, graph, curpos, lastjump): if curpos == stones[-1]: return True rstart = max(curpos + lastjump - 1, curpos + 1) rend = min(curpos + lastjump + 1, stones[-1]) + 1 for nextpos in xrange(rstart, rend): if nextpos in g...
def check_candidate(a, candidate, callback_when_different, *args, **kwargs): control_result = None candidate_result = None control_exception = None candidate_exception = None reason = None try: control_result = a(*args, **kwargs) except BaseException as e: control_exception ...
def check_candidate(a, candidate, callback_when_different, *args, **kwargs): control_result = None candidate_result = None control_exception = None candidate_exception = None reason = None try: control_result = a(*args, **kwargs) except BaseException as e: control_exception =...
n = int(input()) % 8 if n == 0: print(2) elif n <= 5: print(n) else: print(10 - n)
n = int(input()) % 8 if n == 0: print(2) elif n <= 5: print(n) else: print(10 - n)
""" A fixed-capacity queue implemented as circular queue. Queue can become full. * enqueue is O(1) * dequeue is O(1) """ class Queue: """ Implementation of a Queue using a circular buffer. """ def __init__(self, size): self.size = size self.storage = [None] * size self.first =...
""" A fixed-capacity queue implemented as circular queue. Queue can become full. * enqueue is O(1) * dequeue is O(1) """ class Queue: """ Implementation of a Queue using a circular buffer. """ def __init__(self, size): self.size = size self.storage = [None] * size self.first = ...
""" A simple script for numbering nUp tickets for the print shop. """ def numbering_main() -> None: """ Gets numbering sequences for nUp ticket numbering. Gets the total number of tickets requested along with now many will fit on a sheet (n_up) as well as the starting ticket number and prints the tic...
""" A simple script for numbering nUp tickets for the print shop. """ def numbering_main() -> None: """ Gets numbering sequences for nUp ticket numbering. Gets the total number of tickets requested along with now many will fit on a sheet (n_up) as well as the starting ticket number and prints the tick...
def arg_to_step(arg): if isinstance(arg, str): return {'run': arg} else: return dict(zip(['run', 'parameters', 'cache'], arg)) def steps(*args): return [arg_to_step(arg) for arg in args]
def arg_to_step(arg): if isinstance(arg, str): return {'run': arg} else: return dict(zip(['run', 'parameters', 'cache'], arg)) def steps(*args): return [arg_to_step(arg) for arg in args]
#inputFile = 'sand.407' inputFile = 'sand.407' outputFile= 'sand.out' def joinLine(): pass with open(inputFile) as OF: lines = OF.readlines() print(lines[0:3])
input_file = 'sand.407' output_file = 'sand.out' def join_line(): pass with open(inputFile) as of: lines = OF.readlines() print(lines[0:3])
class MergeSort: def __init__(self, lst): self.lst = lst def mergeSort(self, a): midPoint = len(a) // 2 if a[len(a) - 1] < a[0]: left = self.mergeSort(a[:midPoint]) right = self.mergeSort(a[midPoint:]) return self.merge(left, right) else: ...
class Mergesort: def __init__(self, lst): self.lst = lst def merge_sort(self, a): mid_point = len(a) // 2 if a[len(a) - 1] < a[0]: left = self.mergeSort(a[:midPoint]) right = self.mergeSort(a[midPoint:]) return self.merge(left, right) else: ...
''' There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. ''' ### Nature: the meaning of MEDIAN, is that, the number of elements less than it, ##...
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. """ def find_median_sorted_arrays(nums1, nums2): (m, n) = (len(nums1), len(nums2)) ...
# Copyright 2019 The SQLNet Company GmbH # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, ...
""" This module contains the loss functions for the getml library. """ class _Lossfunction(object): """ Base class. Should not ever be directly initialized! """ def __init__(self): self.thisptr = dict() self.thisptr['type_'] = 'none' class Crossentropyloss(_LossFunction): """ ...
def container_image_is_external(biocontainers, app): """ Return a boolean: is this container going to be run using an external URL (quay.io/biocontainers), or is it going to use a local, named Docker image? """ d = biocontainers[app] if (('use_local' in d) and (d['use_local'] is True)): ...
def container_image_is_external(biocontainers, app): """ Return a boolean: is this container going to be run using an external URL (quay.io/biocontainers), or is it going to use a local, named Docker image? """ d = biocontainers[app] if 'use_local' in d and d['use_local'] is True: re...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root: 'TreeNode', sum: 'int') -> 'bool': if not root: return False def helper(node,val):...
class Solution: def has_path_sum(self, root: 'TreeNode', sum: 'int') -> 'bool': if not root: return False def helper(node, val): if not node: return False val -= node.val if node.left is None and node.right is None: re...
""" quant_test ~~~~~~ The quant_test package - a Python package template project that is intended to be used as a cookie-cutter for developing new Python packages. """
""" quant_test ~~~~~~ The quant_test package - a Python package template project that is intended to be used as a cookie-cutter for developing new Python packages. """
class Solution: def maxArea(self, ls): n = len(ls) - 1 v, left, right = [], 0, n while 0 <= left < right <= n: h = min(ls[left], ls[right]) v += [h * (right - left)] while ls[left] <= h and left < right: left += 1 while ls[right...
class Solution: def max_area(self, ls): n = len(ls) - 1 (v, left, right) = ([], 0, n) while 0 <= left < right <= n: h = min(ls[left], ls[right]) v += [h * (right - left)] while ls[left] <= h and left < right: left += 1 while ls...
def _check_stamping_format(f): if f.startswith("{") and f.endswith("}"): return True return False def _resolve_stamp(ctx, string, output): stamps = [ctx.info_file, ctx.version_file] args = ctx.actions.args() args.add_all(stamps, format_each = "--stamp-info-file=%s") args.add(string, for...
def _check_stamping_format(f): if f.startswith('{') and f.endswith('}'): return True return False def _resolve_stamp(ctx, string, output): stamps = [ctx.info_file, ctx.version_file] args = ctx.actions.args() args.add_all(stamps, format_each='--stamp-info-file=%s') args.add(string, forma...
__author__ = "Rob MacKinnon <rome@villagertech.com>" __package__ = "DOMObjects" __name__ = "DOMObjects.schema" __license__ = "MIT" class DOMSchema(object): """ @abstract Structure object for creating more advanced DOM trees @params children [dict] Default structure of children @params dictgroups [...
__author__ = 'Rob MacKinnon <rome@villagertech.com>' __package__ = 'DOMObjects' __name__ = 'DOMObjects.schema' __license__ = 'MIT' class Domschema(object): """ @abstract Structure object for creating more advanced DOM trees @params children [dict] Default structure of children @params dictgroups [d...
""" 1375. Substring With At Least K Distinct Characters """ class Solution: """ @param s: a string @param k: an integer @return: the number of substrings there are that contain at least k distinct characters """ def kDistinctCharacters(self, s, k): # Write your code here n = len...
""" 1375. Substring With At Least K Distinct Characters """ class Solution: """ @param s: a string @param k: an integer @return: the number of substrings there are that contain at least k distinct characters """ def k_distinct_characters(self, s, k): n = len(s) left = 0 ...
def extract_stack_from_seat_line(seat_line: str) -> float or None: # Seat 3: PokerPete24 (40518.00) if 'will be allowed to play after the button' in seat_line: return None return float(seat_line.split(' (')[1].split(')')[0])
def extract_stack_from_seat_line(seat_line: str) -> float or None: if 'will be allowed to play after the button' in seat_line: return None return float(seat_line.split(' (')[1].split(')')[0])
def infer_from_clause(table_names, graph, columns): tables = list(table_names.keys()) if len(tables) == 1: # no JOINS needed - just return the simple "FROM" clause. return f"FROM {tables[0]} " else: # we have to deal with multiple tables - and find the shortest path between them join_clau...
def infer_from_clause(table_names, graph, columns): tables = list(table_names.keys()) if len(tables) == 1: return f'FROM {tables[0]} ' else: (join_clauses, cross_join_clauses) = generate_path_by_graph(graph, table_names, tables) if len(_tables_in_join_clauses(join_clauses)) >= 3: ...
def comment_dialog(data=None): """ Function takes in a JSON object, and uses the following format: https://api.slack.com/dialogs Returns created JSON object, then is sent back to Slack. """ text = "" state = "" project_holder = None item_holder = None if data is not None: ...
def comment_dialog(data=None): """ Function takes in a JSON object, and uses the following format: https://api.slack.com/dialogs Returns created JSON object, then is sent back to Slack. """ text = '' state = '' project_holder = None item_holder = None if data is not None: ...
class Table: # Constructor # Defauls row and col to 0 if less than 0 def __init__(self, col_count, row_count, headers = [], border_size = 0): self.col_count = col_count if col_count >= 0 else 0 self.row_count = row_count if row_count >= 0 else 0 self.border_size = border_size if ...
class Table: def __init__(self, col_count, row_count, headers=[], border_size=0): self.col_count = col_count if col_count >= 0 else 0 self.row_count = row_count if row_count >= 0 else 0 self.border_size = border_size if border_size > 0 else 0 self.headers = headers def get_row_...
class cluster(object): def __init__(self,members=[]): self.s=set(members) def merge(self, other): self.s.union(other.s) return self class clusterManager(object): def __init__(self,clusters={}): self.c=clusters def merge(self, i, j): self.c[i]=self.c[j]=self.c[i...
class Cluster(object): def __init__(self, members=[]): self.s = set(members) def merge(self, other): self.s.union(other.s) return self class Clustermanager(object): def __init__(self, clusters={}): self.c = clusters def merge(self, i, j): self.c[i] = self.c[j...
#backslash and new line ignored print("one\ two\ three")
print('one two three')
jogador = dict() partidas = list() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for c in range(0, tot): partidas.append(int(input(f' Quantos gols na partida {c}? '))) jogador['gols'] = partidas[:] jogador['total'] = sum(partidas) print(30*'-=')...
jogador = dict() partidas = list() jogador['nome'] = str(input('Nome do jogador: ')) tot = int(input(f"Quantas partidas {jogador['nome']} jogou? ")) for c in range(0, tot): partidas.append(int(input(f' Quantos gols na partida {c}? '))) jogador['gols'] = partidas[:] jogador['total'] = sum(partidas) print(30 * '-=...
#skip.runas import Image; im = Image.open("Scribus.gif"); image_list = list(im.getdata()); cols, rows = im.size; res = range(len(image_list)); sobelFilter(image_list, res, cols, rows) #runas cols = 100; rows = 100 ;image_list=[x%10+y%20 for x in xrange(cols) for y in xrange(rows)]; sobelFilter(image_list, cols, rows) #...
def sobel_filter(original_image, cols, rows): edge_image = range(len(original_image)) for i in xrange(rows): edge_image[i * cols] = 255 edge_image[(i + 1) * cols - 1] = 255 for i in xrange(1, cols - 1): edge_image[i] = 255 edge_image[i + (rows - 1) * cols] = 255 for iy in...
# This file is only used to generate documentation # VM class class vm(): def getGPRState(): """Obtain the current general purpose register state. :returns: GPRState (an object containing the GPR state). """ pass def getFPRState(): """Obtain the current floating p...
class Vm: def get_gpr_state(): """Obtain the current general purpose register state. :returns: GPRState (an object containing the GPR state). """ pass def get_fpr_state(): """Obtain the current floating point register state. :returns: FPRState (an ob...
# -*- coding: utf-8 -*- """Scrapy settings.""" BOT_NAME = 'krkbipscraper' SPIDER_MODULES = ['krkbipscraper.spiders'] NEWSPIDER_MODULE = 'krkbipscraper.spiders' ITEM_PIPELINES = ['krkbipscraper.pipelines.JsonWriterPipeline']
"""Scrapy settings.""" bot_name = 'krkbipscraper' spider_modules = ['krkbipscraper.spiders'] newspider_module = 'krkbipscraper.spiders' item_pipelines = ['krkbipscraper.pipelines.JsonWriterPipeline']
def sum_digit(n): total = 0 while n != 0: total += n % 10 n /= 10 return total def factorial(n): if n <= 0: return 1 return n * factorial(n - 1)
def sum_digit(n): total = 0 while n != 0: total += n % 10 n /= 10 return total def factorial(n): if n <= 0: return 1 return n * factorial(n - 1)
# Copyright (c) 2020 # Author: xiaoweixiang """Contains purely network-related utilities. """
"""Contains purely network-related utilities. """
class Global: sand_box = True app_key = None # your secret secret = None callback_url = None server_url = None log = None def __init__(self, config): Global.sand_box = config.get_env() Global.app_key = config.get_app_key() Global.secret = config.get_secret()...
class Global: sand_box = True app_key = None secret = None callback_url = None server_url = None log = None def __init__(self, config): Global.sand_box = config.get_env() Global.app_key = config.get_app_key() Global.secret = config.get_secret() Global.callbac...
DEFAULT_KUBE_VERSION=1.14 KUBE_VERSION="kubeVersion" USER_ID="userId" DEFAULT_USER_ID=1 CLUSTER_NAME="clusterName" CLUSTER_MASTER_IP="masterHostIP" CLUSTER_WORKER_IP_LIST="workerIPList" FRAMEWORK_TYPE= "frameworkType" FRAMEWORK_VERSION="frameworkVersion" FRAMEWORK_RESOURCES="frameworkResources" FRAMEWORK_VOLUME_SIZE= ...
default_kube_version = 1.14 kube_version = 'kubeVersion' user_id = 'userId' default_user_id = 1 cluster_name = 'clusterName' cluster_master_ip = 'masterHostIP' cluster_worker_ip_list = 'workerIPList' framework_type = 'frameworkType' framework_version = 'frameworkVersion' framework_resources = 'frameworkResources' frame...
# Python3 def makeArrayConsecutive2(statues): return (max(statues) - min(statues) + 1) - len(statues)
def make_array_consecutive2(statues): return max(statues) - min(statues) + 1 - len(statues)
"""from django.contrib import admin from .models import DemoModel admin.site.register(DemoModel)"""
"""from django.contrib import admin from .models import DemoModel admin.site.register(DemoModel)"""