content stringlengths 7 1.05M |
|---|
#
# #
def palindrom(word):
try:
word = word[::-1]
except TypeError:
print("I execute myself only if an exception happens")
print("You can't type only strings")
else:
print("I just execute myself only if no exceptions happens")
print(word)
finally:
print(... |
f1 = 1.0
s1 = 'string'
s2 = "string"
s3 = '''multiline string'''
s4 = """multiline string"""
s5 = r'raw text'
s6 = r"more raw text"
s7 = r'''raw multiline string'''
s8 = r"""raw multiline string"""
print('done')
|
class Solution(object):
def max_sub_array(self, nums):
"""
Given an integer array nums, find the contiguous subarray (containing
at least one number) which has the largest sum and return its sum.
:type nums: List[int]
:rtype: int
"""
# NOTE: we are going to u... |
all_students = ["나연", "정연", "모모", "사나", "지효", "미나", "다현", "채영", "쯔위"]
present_students = ["정연", "모모", "채영", "쯔위", "사나", "나연", "미나", "다현"]
def get_absent_student(all_array, present_array):
student_dic = {}
for key in all_array:
student_dic[key] =True
for key in present_array:
del student_... |
"""
Copied from: https://github.com/jerrymarino/xcbuildkit/blob/master/third_party/repositories.bzl
"""
load(
"@bazel_tools//tools/build_defs/repo:git.bzl",
"git_repository",
"new_git_repository",
)
load("//rules/third_party:xcbuildkit_version.bzl", "repo_info")
NAMESPACE_PREFIX = "xcbuildkit-"
def names... |
def normal_function(func):
print(func(10))
normal_function(lambda value: 10 + value)
def normal_function2(func, *args):
for argument in args:
print(func(argument))
normal_function2(lambda value: value / 5, 10, 15, 20, 25, 30, 35, 40, 45, 50)
def normal_function3(func, *args):
for argument in ar... |
# Theory: Class instances
# By now, you already know what classes are and how they're
# created and used in Python, Now let's get into the details about
# class instances.
# A class instance is an object of the class. If, for example, there
# was a class River, we could create such instances as Volga,
# Seine, and Ni... |
#From https://notepad-plus-plus.org/community/topic/14501/has-a-plugin-like-sublime-plugin-brackethighlighter/7
try:
BH__dict
except NameError:
BH__dict = dict()
BH__dict['indic_for_box_at_caret'] = 10 # pick a free indicator number
def indicatorOptionsSet(indicator_number, indicator_style, rgb_c... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
num_stack = []
for token in tokens:
if token in "+-*/":
num2, num1 = num_stack.pop(), num_stack.pop()
if token == "+":
num_stack.append(num1 + num2)
el... |
#
# @lc app=leetcode id=221 lang=python3
#
# [221] Maximal Square
#
# @lc code=start
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] = int(matrix[i][j])
if i and ... |
seq_to_protein = dict(
AUG="Methionine",
UUU="Phenylalanine",
UUC="Phenylalanine",
UUA="Leucine",
UUG="Leucine",
UCU="Serine",
UCC="Serine",
UCA="Serine",
UCG="Serine",
UAU="Tyrosine",
UAC="Tyrosine",
UGU="Cysteine",
UGC="Cysteine",
UGG="Tryptophan",
UAA="STOP... |
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
res = 0
for i in xrange(1, len(nums) - 1):
if nums[i] == nums[i + 1]:
nums[i + 1], nu... |
poly = [2, 8]
const = 5
out = [const]
for index in range(len(poly)):
out.append(poly[index] / (index + 1))
print(out) |
'''
5. Escreva um programa que pergunte a idade de 6 pessoas, calcule e mostre:
a) a quantidade de pessoas menores de idade (idade < 18 anos)
b) média de idade destas pessoas
c) a idade da pessoa mais velha
d) percentual de pessoas com mais de 20 anos
'''
class Idades():
def __init__(self,vetor1,vetor2,vetor3)... |
token = '1111:example'
# @ShowJsonBot
chat_ids = [12345]
games = [
'monopoly',
]
|
'''
素数和问题
描述
Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number.
There are several combinations possible. Print only first such pair.
NOTE: A solution will always exist, read Goldbach’s conjecture.
Also, solve the problem in linear time complexity, i.e., O(n).
输入
T... |
#
# Write a query that returns all the species in the zoo, and how many animals of
# each species there are, sorted with the most populous species at the top.
#
# The result should have two columns: species and number.
#
# The animals table has columns (name, species, birthdate) for each individual.
#
QUERY ... |
while True:
numero=int(input(""))
if(numero==2002):
print("Accceso Permitido")
break
else:
print("Senha Invalida") |
"""
To work around the problem of python3 not properly unpickling
python2's datetime objects.
Taken from http://stackoverflow.com/questions/22840092/unpickling-data-from-python-2-with-unicode-strings-in-python-3
"""
def bytes_to_unicode(ob):
t = type(ob)
if t in (list, tuple):
l = [str(i, 'utf-8') if... |
x = 25
epsilon = 0.01
#step = epsilon ** 2
numGuesses = 0
low = 0
high = max(1, x)
ans = (high + low) / 2
while abs(ans**2 - x) >= epsilon:
print(f"low = {low}, high ={high} , ans = {ans}")
numGuesses += 1
if ans**2 < x :
low = ans
else:
high = ans
ans = (high + low) / 2
print(numG... |
# The optimized implementation
def fib(n):
if (n == 1 or n == 2):
return 1
prev = 1
curr = 1
for i in range(2, n):
sums = prev + curr
prev = curr
curr = sums
return curr
print(fib(50))
|
#@<OUT> get cluster status
{
"clusterName": "testCluster",
"defaultReplicaSet": {
"name": "default",
"topology": [
{
"address": "<<<hostname>>>:<<<__mysql_sandbox_port2>>>",
"label": "<<<hostname>>>:<<<__mysql_sandbox_port2>>>",
"ro... |
s = input().split()
for i in range(len(s)):
if int(s[i]) % 2 == 0:
print(s[i], end=' ')
|
CERT_FILE = 'release.pem'
SETUP_USERS_FILE = 'setup_users.sh'
CERTIFICATE_FOLDER = '/opt/instance'
ALLOWED_EXTENSIONS = {'pem'}
ISO_REPO_URL = 'https://yum.128technology.com/isos/'
ISO_RE = '(.+)\.iso$'
IMAGE_FOLDER = '/opt/images'
SCRIPT_FOLDER = '/opt/scripts'
PRE_BOOTSTRAP = 'pre'
POST_BOOTSTRAP = 'post'
PRE_BOOTSTR... |
num = []
numpar = []
numimpar = []
while True:
n = int(input('Digite um valor: '))
num.append(n)
respos = str(input('Quer continuar: [S/N] ')).strip().upper()[0]
while respos not in 'SN':
respos = str(input('Opção inválida..Quer continuar: [S/N] ')).strip().upper()[0]
if respos == 'N':
... |
viagem = float ( input (' Escreva aqui quantos quilômetros será a sua viagem: Km/h'))
if viagem <=200.00:
print (' Sua viagem irá custar R${}'.format(viagem* 0.50))
else:
print (' Sua viagem ira custar R${}'.format(viagem *0.45)) |
#Class for sources table
class Sources:
def __init__(self, cursor):
self.cursor = cursor
#read from db
#check existing pagespeed of stored sources
def getSpeed(cursor, hash):
sql= "SELECT sources_speed from sources WHERE sources_hash=%s LIMIT 1"
data = (hash,)
cursor.execut... |
class VectorizableBackedModel(object):
r"""
Mixin for models constructed from a set of :map:`Vectorizable` objects.
Supports models for which visualizing the meaning of a set of components
is trivial.
Requires that the following methods are implemented:
1. `component_vector(index)`
2. `ins... |
class Descritor:
def __init__(self, init=-1, init_list=-1, min_element=-1, max_element=-1,
maxm=-1, leng=-1, fim=-1, fim_list=-1):
self.init = init
self.init_list = init_list
self.min_element = min_element
self.max_element = max_element
self.maxm = maxm
... |
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print('Woof!')
fido = Dog("Fido", "brown")
print(fido.name)
print(fido.color)
fido.bark()
|
#!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------------
# Usage: python3 4-spam_class2.py
# Description: Code that needs to manage per-class instance counters, for example,
# might be best off leveraging class methods. In the following, the
# top-level supercla... |
a=int(input())
e=[]
def cont(no,arr):
arr=list(set(arr))
for i in range(len(arr)):
if(no==arr[i]):
return True
for i in range(a):
b=int(input())
c=list(map(int,input().split()))
e.append(c)
for i in range(len(e)):
e[i].sort()
for i in e:
f=[]
g=[]
for j in range(len(i)):
if(cont(i[j]... |
'''
序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
设计一个算法来序列化和反序列化二叉搜索树。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
编码的字符串应尽可能紧凑。
注意:不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
#... |
def three_highest(cars):
return sorted(cars, key=lambda car: car.dimensions[2], reverse=True)[:3]
def three_fastest(cars):
return sorted(cars, key=lambda car: car.to100km)[:3]
|
class VPNError(Exception):
"""Base exception for all other project exceptions.
"""
pass
class ConnectError(VPNError):
"""Exception raised on connection failure.
"""
pass
class ParseError(VPNError):
"""Exception for all management interface parsing errors.
"""
pass
|
dollar={"rupees":75.53,"yen":107.50,"dirham":3.67,"euro":0.91,"pound":0.81}
def mainCurrency(query):
splitQuery=query.split()
value,fromCurrency,toCurrency=splitQuery[1],splitQuery[2],splitQuery[4]
if fromCurrency=="dollars":finalValue=float(value)*dollar[toCurrency]
elif toCurrency=="dollars":finalValu... |
class Node:
def __init__(self, idx, name, shape="box", color="#d6d6d6"):
self.idx = idx
self.name = name
self.shape = shape
self.color = color
|
# -*- coding: utf-8 -*-
UNIVERSITY_DOMAINS = {
'um.edu.ar': [u'Universidad de Mendoza'],
'unsa.edu.ar': [u'Universidad Nacional de Salta'],
'uces.edu.ar': [u'Universidad de Ciencias Empresariales y Sociales'],
'unq.edu.ar': [u'Universidad Nacional de Quilmes'],
'ucel.edu.ar': [u'Universidad del Cen... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Cr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DEBUG = True
SECRET_KEY = 'development key'
WEB_HOST = '0.0.0.0'
WEB_PORT = 8888
REDIS_HOST = 'localhost'
REDIS_PORT = 7778
REDIS_PASS = 'r3'
|
m,n=map(int,input().split())
ip=[]
for i in range(m):
ip.append(list(map(int,input().split())))
'''
Traverse the rows once keeping track of all the rows
and columns which should finally be set to 0.
'''
rows=[0 for i in range(m)]
columns=[0 for i in range(n)]
for i in range(m):
for j in range(n):
if i... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = evaluate # train, test, test_episodes, evaluate
LOAD_MODEL_FROM = mlruns/0/eb021674da6d4662b5e360703c518476/artifacts/agent/data/model.pth
SAVE_MODELS_TO = None
# worker.py
ENV = Battle... |
"""
Faça um Programa que peça um número e então mostre a mensagem: O número informado foi [número].
"""
def ex002():
print("{:*^50}".format(" Ex002 "))
print()
num = int(input("Digite um número inteiro: "))
print()
print("O número informado foi [{}].".format(num))
print()
print("{:*^50}".format("... |
'''
This is the Entities module assigning unique features to an entity
'''
class Entity:
entity = None
def id(self):
pass
def toString(self):
line = ''
for i in self.entity:
line += str(self.entity[i]) + ', '
return line[:-2] + '\n'
'''
user resource entity:... |
{
"targets": [
{
"target_name": "node-dotnet-bridge",
"sources": [
"addon.cpp",
"Proxy.cpp",
"AsyncContext.cpp"
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
... |
class FocusTimeManager:
def __init__(self, client_class):
self._client = client_class
self.access_token = ''
# ---------------------------------------------------------------------------------------------------------------
# Focus Timer Methods
def start(self):
"""Starts t... |
BINARY_FNAME_TEMPLATE = "{version}-{platform}-{architecture}"
ARCHIVE_FNAME_TEMPLATE = BINARY_FNAME_TEMPLATE + ".{ext}"
CLOUD_STORAGE_URL = "http://cloud.raiden.network/"
|
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: proto
class ResultType(object):
Success = 0
Failed = 1
|
class Solution:
def countStrings(self,n):
a = 1
b = 1
for _ in range(n) :
c = (a + b) % 1000000007
a, b = b, c
return b
# Driver code
if __name__ == "__main__":
tc=int(input())
while tc > 0:
n=int(input())
... |
# HOMETASK 1 - UPPER AND LOWER CASES
print("# HOMETASK 1 - UPPER AND LOWER CASES")
p_phylosophy = "Beautiful is better than ugly \
Explicit is better than implicit \
Simple is better than complex \
Complex is better than complicated \
Readability counts"
# Printing in upper cases
print (p_phylosophy.upper())
p_phyloso... |
#!/usr/bin/env python
# AUTO GENERATED FILE - PLEASE CHECK gen.py! #
Instructions = [{'code': 0,
'cycles': 4,
'flagResult': {'carry': None, 'halfcarry': None, 'sub': None, 'zero': None},
'hexCode': '00',
'instruction': 'NOP',
'name': 'NOP',
'simpleFlags': ['-', '-', '-', '-'],
'size': '1',
'templateDa... |
# 334. Increasing Triplet Subsequence
class Solution:
def increasingTriplet(self, nums: [int]) -> bool:
"""
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
"""
first = second = float('inf')
for n in... |
# 99. Recover Binary Search Tree
# Runtime: 64 ms, faster than 95.92% of Python3 online submissions for Recover Binary Search Tree.
# Memory Usage: 14.6 MB, less than 57.01% of Python3 online submissions for Recover Binary Search Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, ... |
TRIPPIFY_DB_USER = 'trippify'
TRIPPIFY_DB_PASSWORD = 'trippify1234'
TRIPPIFY_DB_DB = 'trippify'
TRIPPIFY_DB_HOST = 'localhost'
TRIPPIFY_DB_PORT = 5432
MAPS_GEO_CODING_API_KEY = 'AIzaSyBUl98DdV0U05pu7spTcP-RIB_qoCkNcYU'
HERE_APP_ID = 'm7AG9dmM8HNO5ZnJWRVO'
HERE_APP_CODE = '2mCmRml-o_e3-uZuD_Z62A'
HERE_GEO_CODER_URL = ... |
#for x in range(0,5):
#print("Hello World",x)
#def recursive(string, num):
# if num == 5:
# return
# print(string,num)
#recursive(string,num+1)
#recursive("Hello World",0)
#def listsum(numList):
# sum = 0
# for i in numList:
# sum = sum + i
# return sum
#print(listsum([1,2,5,9,7]))
... |
class JsonResponser:
""" Set json response
Args:
code (int): response code
message (str): success or error message
data (list||dict): response data
errors(dict||None): errors if exists
"""
def __init__(self, data = None, code: int = 200, message: str =... |
# Solution to problem 9
# Open the file moby-dick.txt for reading and mark as "f"
with open('moby-dick.txt', 'r') as f:
count = 0 # set counter to zero
for line in f: # for every line in the file
count+=1 # count +1
if count % 2 == 0: # if the remainder is 0
print(line)
... |
class Solution:
def isToeplitzMatrix(self, matrix: list) -> bool:
# # m = len(matrix) #m行
# # n = len(matrix[0]) #n列
# res = matrix[0][:-1]
# for k, line in enumerate(matrix[1:]):
# tmp = line[1:]
# if res != tmp:
# return False
# r... |
"""
Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
"""
class RequestBuilderBase(object):
def __init__(self, request_url, client):
"""Initialize a request builder which returns a request
when req... |
#/usr/bin/env python3
def nth_prime(n):
ans = 2
known = []
for _ in range(n):
while not all(ans%x != 0 for x in known):
ans += 1
known.append(ans)
return ans
if __name__ == "__main__":
n = int(input("Which one? "))
print(nth_prime(n))
|
def factory(n):
def current():
return n
def counter():
return n + 1
return current, counter
f_current, f_counter = factory(int(input()))
|
numbers = [
-9,
+7,
+5,
-13,
+6,
+14,
-5,
-10,
-10,
-12,
+2,
+5,
+2,
-6,
-12,
+1,
+13,
+5,
+3,
-15,
-12,
+4,
-11,
+10,
-5,
-14,
-6,
+2,
-9,
-18,
+8,
-1,
+12,
+9,
+5,
-9,
+14,
+3,
-4,
-16,
+14,
+14,
+13,
-7,
-19,
+12,
-9,
+5,
+21,
-7,
+19,
-2,
+14,
+18,
+17,
+4,
+11,
-16,
-5,
-6,
-7,
-2,
-1,
-2,
-1,
+14,
-17,
+5,
+13,
+... |
METRICS_LABELS = {
'precision': 'Precision',
'recall': 'Recall',
'fmeasure': 'F-measure',
'auc': 'AUC',
'mcc': 'MCC',
}
MODELS_LABELS = {
'DummyClassifier(strategy=\'most_frequent\')': 'BM',
'DummyClassifier(strategy=\'prior\')': 'BP',
'DummyClassifier(strategy=\'stratified\')': 'BS',
... |
class Goat:
legs_number: int = 4
def __init__(self, height: int, weight: int, hungry: bool) -> None:
self._height: int = height
self._weight: int = weight
self._hungry: bool = hungry
def stats(self) -> str:
return f"Goat has {self._height} height and {self._weight} weight!"... |
colors = [
'\033[38;5;21m', # blue (cold)
'\033[38;5;39m',
'\033[38;5;50m',
'\033[38;5;48m',
'\033[38;5;46m', # green
'\033[38;5;118m',
'\033[38;5;190m',
'\033[38;5;226m', # yellow
'\033[38;5;220m',
'\033[38;5;214m', # orange
'\033[38;5;208m',
'\033[38;5;202m',
'\033[... |
"""
tn3270.ebcdic
~~~~~~~~~~~~~
EBCDIC constants
"""
DUP = 0x1c
FM = 0x1e
|
name1_1_1_0_0_0_0 = None
name1_1_1_0_0_0_1 = None
name1_1_1_0_0_0_2 = None
name1_1_1_0_0_0_3 = None
name1_1_1_0_0_0_4 = None |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
class NodeModel():
""" Node looku... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
### CONTROLS (non-tunable) ###
# general
TYPE_OF_RUN = train # train, test, test_episodes, render
LOAD_MODEL_FROM = None
SAVE_MODELS_TO = models/new_gru_flat_babyai.pth
# worker.py
ENV = BabyAI_Env
ENV_RANDOM_SEED = randint # Use an intege... |
"""
You're organizing a group dating activity for cats, i.e. a meeting where an equal number of male and female cats get together. For each cat you calculate their nature value, an integer that describes the cat's spirit. When a male and a female cat with the same nature value see each other, they become connected and ... |
#DictExample3.py
print("---------------------------------------------------")
student = {"name":"sumit","college":"stanford","grade":"1"}
print("Student information :\n")
print("Student Name : ",student['name'])
print("College : ",student['college'])
print("grade : ",student['grade'])
print("--------------... |
config = {
'username': 'demo',
'password': 'demo1',
'url': 'http://127.0.0.1:18800',
'upload_url': '/YouWillNeverGuess'
} |
class Settings:
WLAN_HOST = '$sudo'
WLAN_PASSWORD = 'HowNowBrownCow'
MQTT_BROKER_HOST = '192.168.0.136'
MQTT_BROKER_PORT = '1883'
API_URL = 'http://192.168.0.136:5000/api'
|
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
if not points or len(points) == 0:
return 0
points.sort(key = lambda x: x[1]) # 按右端点从小到大排序
temp_pos = points[0][1]
cnt = 1
... |
def calculate_period(x):
if x == 'weeks':
return x * 7
elif x == 'month':
return x * 30
else:
return x
def currentlyinfected(x):
return x * 10
def currently_infected(x):
return x * 50
def infectionbyrequestedattime(x,y):
factor = calculate_period(x) // 3
return ... |
# pylint: disable=line-too-long, no-member
def generator_name(identifier): # pylint: disable=unused-argument
return 'Voice Activity Detection'
def extract_secondary_identifier(properties):
if 'voices_present' in properties:
if properties['voices_present']:
return 'present'
return... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
def sol():
for i in range(int(input())):
R, S = input().split()
print("".join([i * int(R) for i in S]))
if __name__ == "__main__":
sol()
|
# 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 trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
if not root: return None
if r... |
class CustomException(Exception):
_message = ''
def __init__(self, message):
self._message = message
# Call the base class constructor with the parameters it needs
super().__init__(message)
|
# Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
# iterative solution
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result, curr = [], []
stk = [(1, (n, n))]
while stk:
step, args = stk.... |
# 快速排序
"""
https://en.wikipedia.org/wiki/Quicksort
"""
def quicksort(l):
if len(l) < 2:
return l
else:
mid_pivot = l[0]
lt_mid_pivot = [i for i in l if i < mid_pivot]
gt_mid_pivot = [i for i in l if i > mid_pivot]
et_mid_pivot = [i for i in l if i == mid_pivot]
... |
# Python Week-7 Day-44
# Python Inheritance 2
class car:
def __init__(self, carbrand, carcolor):
self.brand = carbrand
self.color = carcolor
def printname(self):
print(self.cbrand, self.cyear)
class prop(car):
def __init__(self, carbrand, carcolor, model):
super().__init_... |
__is_prod = False
def set_production(is_prod):
global __is_prod
__is_prod = is_prod
def is_production():
return __is_prod
|
def format(piece):
if piece.label:
txt_piece = '{0}\n\\label{{{1}}}'.format(str(piece),piece.label)
return txt_piece
else:
return str(piece)
|
expected_output = {
"hsrp_common_process_state": "not running",
"hsrp_ha_state": "capable",
"hsrp_ipv4_process_state": "not running",
"hsrp_ipv6_process_state": "not running",
"hsrp_timer_wheel_state": "running",
"mac_address_table": {
166: {"group": 10, "interface": "gi2/0/3", "mac_addr... |
# Copyright 2022 DeChainers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
class User:
"""
This is a class that will contain all the details of the user
"""
def __init__(self,login,password):
"""
This will create unique details for each instance of the User class
"""
self.login = login
self.password = password
def user_exists(self,p... |
# 001_init.py
def migrate(migrator, database, fake=False, **kwargs):
"""Write your migrations here."""
migrator.sql("""CREATE TABLE users (
id INTEGER PRIMARY KEY,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
em... |
#
# @lc app=leetcode id=712 lang=python3
#
# [712] Minimum ASCII Delete Sum for Two Strings
#
# https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
#
# algorithms
# Medium (59.81%)
# Total Accepted: 48.5K
# Total Submissions: 81K
# Testcase Example: '"sea"\n"eat"'
#
# Given two strin... |
########################################
# CS/CNS/EE 155 2017
# Problem Set 5
#
# Author: Avishek Dutta
# Description: Set 5
########################################
class Utility:
'''
Utility for the problem files.
'''
def __init__():
pass
@staticmethod
def load_poem():
... |
def factorial(num):
if num == 0:
return 1
return num * factorial(num-1)
print(factorial(int(input())))
|
#! /usr/bin/python
# create a list of float
# creating list of single data types
fam = [1.73, 1.68, 1.72, 1.89]
print(fam)
# creating list of different data types
|
# flake8: noqa
# Edit this file to override the default graphite settings, do not edit settings.py
# Turn on debugging and restart apache if you ever see an "Internal Server Error" page
# DEBUG = True
# Set your local timezone (django will try to figure this out automatically)
TIME_ZONE = 'Europe/Zurich'
# Secret ke... |
description = """
Adds Django Debug Toolbar support to your project.
For more information, visit:
https://github.com/django-debug-toolbar/django-debug-toolbar/blob/master/README.rst
""" |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n ) :
table = [ 0 for i in range ( n + 1 ) ]
table [ 0 ] = 1
for i in range ( 3 , n + 1 ) :
tab... |
#
# PySNMP MIB module HUAWEI-BGP-ACCOUNTING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-BGP-ACCOUNTING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:31:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
class Solution:
def intersection(self, nums1, nums2):
return list(set(nums1) & set(nums2))
if __name__ == '__main__':
print(Solution().intersection([4, 9, 5], [9, 4, 9, 8, 4]))
# [9, 4]
|
class Solution:
def hammingDistance(self, x, y):
result = x^y
return bin(result).count('1')
|
# Time: O(n * iter), iter is the number of iterations
# Space: O(1)
# see reference:
# - https://en.wikipedia.org/wiki/Geometric_median
# - https://wikimedia.org/api/rest_v1/media/math/render/svg/b3fb215363358f12687100710caff0e86cd9d26b
# Weiszfeld's algorithm
class Solution(object):
def getMinDistSum(self, posit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.