content stringlengths 7 1.05M |
|---|
try:
raise Exception()
except Exception as e:
print("hello", str(e))
|
database = {
'default': 'mysql',
'connections': {
'mysql': {
'name': 'mytodo',
'username': 'root',
'password': '',
'connection': 'mysql:host=127.0.0.1',
},
},
'migrations': 'migrations',
}
|
# CONCATENATION
firstName = "Helder"
lastName = "Pereira"
fullName = "Helder" + " " + lastName
print(fullName) |
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
sqlmapapi restful interface
by zhangh (zhanghang.org#gmail.com)
'''
# api
task_new = "task/new"
task_del = "task/<taskid>/delete"
admin_task_list = "admin/<taskid>/list"
admin_task_flush = "admin/<taskid>/flush"
option_task_list = "option/<taskid>/list"
option_task_get = ... |
def path_initial_steps(path, node):
'''
takes in a list of arcs and a node and returns the list of nodes the node can reach
'''
initial_steps = []
for arc in path:
if arc[0] == node:
initial_steps.append(arc)
return initial_steps
def path_end_points(path, node):
'''
... |
print('-- ์ฑ์ ์ฒ๋ฆฌ ํ๋ก๊ทธ๋จ v1 --')
name = input("์ด๋ฆ์ ์
๋ ฅํ์ธ์")
kor = int(input("๊ตญ์ด ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
eng = int(input("์์ด ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
mat = int(input("์ํ ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
def getTotal():
tot = kor + mat + eng
return tot
def getAverage():
avg = getTotal() / 3
return avg
def getGrade():
avg = getAverage()
grd ... |
#!/usr/bin/env python3
"""
determine the shape of a matrix
"""
def matrix_shape(matrix):
"""
function to calculatre matrix shape
"""
shape = []
while type(matrix) is list:
shape.append(len(matrix))
matrix = matrix[0]
return shape
|
try:
palavra = 'Palavrinha'
print(palavra)
except NameError as erro:
print('Ocorreu um NameError ', erro) # (Neste caso nรฃo serรก executado).
except (KeyError, IndexError) as erro:
print('Ocorreu um KeyError ou um IndexError ', erro) # (Neste caso nรฃo serรก executado).
except Exception as erro:
p... |
"""Basic registry for model builders."""
BUILDERS = dict()
def register(name):
"""Registers a new model builder function under the given model name."""
def add_to_dict(func):
BUILDERS[name] = func
return func
return add_to_dict
def get_builder(model_name):
"""Fetches the model bui... |
"""
Title | Project
Author: Keegan Skeate
Contact: <keegan@cannlytics.com>
Created:
Updated:
License: MIT License <https://github.com/cannlytics/cannlytics-ai/blob/main/LICENSE>
"""
# Initialize a Socrata client.
# app_token = os.environ.get('APP_TOKEN', None)
# client = Socrata('opendata.mass-cannabis-control.com... |
# ืืฉืืช ืขืจืืื "ืฉืื ,ืฉืืจ ืขืฉืจืื ื ืืืืจืืืช ืืชืื ืชื
#a=5 #ืืฉืืช ืขืจื ืืชื
#print(a) #ืคืื ืืขืจื ืฉื ืชื
#b=6 #ืืฉืืช ืขืจื ืืชื
#a=b #ืืฉืืช ืขืจื ืฉื ืชื ืื ืืชืื ืืื
#print(a) #ืคืื ืฉื ืขืจื ืชื ืืื-ืืชืืฆืื 6
#print(b) #ืคืื ืฉื ืชื ืื - ืืชืืฆืื 6
#print(a,b) #ืคืื ืฉื ืขืจืื 2 ืชืื... |
def x():
return 1
x()
|
class Constants:
ha2kcalmol = 627.509 # Hartee^-1 kcal mol^-1
ha2kJmol = 2625.50 # Hartree^-1 kJ mol^-1
eV2ha = 0.0367493 # Hartree ev^-1
a02ang = 0.529177 # ร
bohr^-1
ang2a0 = 1.0 / a02ang # bohr ร
^-1
kcal2kJ = 4.184 # kJ kcal^-1
|
class Screen:
"""
Abstract class for drawing to the LCD
The main program will transition between
displaying various "screens" based on
high-level logic
"""
def draw(self, cr):
raise NotImplementedError("Must implement draw")
def stop(self):
"""
Some screens may ... |
class MudAction:
"""
Contains all of the information about attempted physical actions within
the world. Whenever a Mob, Item, Character, etc tries to do anything in
the game world, an instance is created and sent around to all the other
chars, items, room, etc.
"""
def __init__(self, actio... |
def internet_on():
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,Testing Internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
global ledSwitch
global connected
global powerSwitch
try:
powerSwitch = 0
urllib.request.urlopen('http://216.58.207.206')
#urllib.urlopen('htt... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
# encoding: utf-8
# module System.Linq.Dynamic calls itself Dynamic
# from Wms.RemotingImplementation,Version=1.23.1.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no important
# no functions
# classes
class DynamicClass(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instan... |
"""
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and
negative numbers as well.
For example, the input [3, 4,... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 15:57:01 2014
Reference URL: http://carina.fcaglp.unlp.edu.ar/ida/archivos/tabla_constantes.pdf
@author: yang
"""
# ---- Universal constants
# universal gravitational constant: N/m^2/kg^{-2}
G = 6.67e-11
# ---- Earth
# acceleration due to gravity at sea level: m/s^2... |
#
# PySNMP MIB module ATM-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:04:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
class Member(object):
"""
A member of the etcd cluster.
:ivar id: ID of the member
:ivar name: human-readable name of the member
:ivar peer_urls: list of URLs the member exposes to the cluster for
communication
:ivar client_urls: list of URLs the member exposes to clients f... |
def expectOne(vals):
assert len(vals) == 1
return vals[0]
|
class CSVDumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields... |
'''Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return... |
# Radix Sort is an improvement over Counting Sort
# Counting Sort is highly inefficient with large ranges
# Radix sort sorts digit by digit from least to most significant digit.
# It can be imagined as a bucket sort based on place values.
def radixSort(array, base=10):
# Get the maximum in the array to find the ma... |
'''
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base p... |
# *Exercรญcio Python 14: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
celsius = float(input('Insira a temperatura em Celsius: '))
faren = 9 * celsius / 5 + 32
print('A temperatura {:.0f} em Fahrenheit รฉ {:.0f}'.format(celsius, faren))
|
ME = '''
query getMe {
me {
username
isStaff
isSuperuser
isAgreed
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organiz... |
# Saber se algo รฉ numรฉrico, nรฃo pode colocar o tipo primitivo.
n = input('Digite algo: ')
print(n.isnumeric())
|
# -*- coding: utf-8 -*-
args = input().split()
n1, n2, n3 = list(map (int, args))
average = (lambda a, b, c: (a + b + c)/3)(n1, n2, n3)
result = (lambda av: "Approved" if av >= 6 else "Disapproved")
print(result(average))
|
# leetcode
class Solution:
def isPalindrome(self, s: str) -> bool:
s_cp = s.replace(" ", "").lower()
clean_s = ''
for l in s_cp:
# check if num
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <... |
'''
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with ... |
"""
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
... |
"""Utility to store int or float parameters with a label
The label is added merely for information: there is no
extra functionality associated with it.
The module has a factory class Parameter(value, label)
which returns either ParameterInt ot ParameterFloat
depending on type(value).
"""
class ParameterInt(int):
... |
#
# PySNMP MIB module Nortel-Magellan-Passport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user ... |
numbers = [-1,0]
target = -1
hashMap = {}
for index, num in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff]+1, index+1])
hashMap[num] = index |
#SCOPE USING NONLOCAL KEYWORD
x = 10#GLOBAL VARIABLE X
def outer():
x=20#LOCAL VARIABLE X
y=30#LOCAL VARIABLE Y
print("outer func x before inner call:", x)
print("outer func y before inner call:", y)
def inner():
nonlocal y#LOCAL VARIABLE Y REFERS TO ITS ABOVE LEVEL OUTER Y
global x#... |
"""
1. Clarification
2. Possible solutions
- dp
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
# dp[i][j], i: day, j:
# 0 - have a share of stock
# 1 - have no stock and cool down next day
# 2 - have no stock and no cool down next day
class Solution:
def maxProfit(self, prices: List[int]) -> ... |
#========================================================================================================
# TOPIC: PYTHON - Modules
#========================================================================================================
# NOTES: * Any Python file is a module.
# * Module is a file with Python ... |
# Define a sum_of_lengths function that accepts a list of strings.
# The function should return the sum of the string lengths.
#
# EXAMPLES
# sum_of_lengths(["Hello", "Bob"]) => 8
# sum_of_lengths(["Nonsense"]) => 8
# sum_of_lengths(["Nonsense", "or", "confidence"]) => 20
def sum... |
# Generates an infinite series of odd numbers
def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += (4 / next(odd_nums))
yield approximation
approxim... |
data = [
{'v': 'v0.1', 't': 1391},
{'v': 'v0.1', 't': 1394},
{'v': 'v0.1', 't': 1300},
{'v': 'v0.1', 't': 1321},
{'v': 'v0.1.3', 't': 1491},
{'v': 'v0.1.3', 't': 1494},
{'v': 'v0.1.3', 't': 1400},
{'v': 'v0.1.3', 't': 1421},
{'v': 'v0.1.2', 't': 1291},
{'v': 'v0.1.2', 't': 1294},... |
# Najdi palindrom
# Napรญลกte definรญciu funkcie najdi_palindrom, ktorรก berie parametre veta a n. Funkcia vo vete nรกjde palindrรณm dฤบลพky n a vrรกti ho ako nรกvratovรบ hodnotu. Ak sa vo vete ลพiadny takรฝto palindrรณm nenachรกdza, funkcia vyhodรญ chybu typu LookupError. (Funkcia bude ignorovaลฅ veฤพkosลฅ pรญsmen a medzery.)
# Sample ... |
def minimum(a):
b=list[0]
i=0
while i<len(list):
if list[i]<b:
b=list[i]
i=i+1
return(b)
list=[5,3,1,6,5,4,7,6]
print(minimum(list))
|
lista = []
for i in range(5):
lista.append(int(input(f'numero {i}: ')))
if i == 0:
maior_valor = menor_valor = lista[i]
if lista[i] > maior_valor:
maior_valor = lista[i]
elif lista[i] < menor_valor:
menor_valor = lista[i]
print('=-'*30)
print(f'maior valor digitado:{... |
__about__="Class method vs Static Method."
class MyClass:
def method(self):
print("Instance of method called", self)
@classmethod
def classmethod(cls):
print("Instance of classmethod called", cls)
@staticmethod
def staticmethod():
print("Instance of staticmethod called")
... |
'''
Class for adding the expreimental data for the cell model
'''
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for exp_type, data in kwargs.items():
self.experimental_data.update({exp_type: data})
|
def get_hard_coded_app_id_dict():
# Matches, manually added, from game names to Steam appIDs
hard_coded_dict = {
# Manually fix matches for which the automatic name matching (based on Levenshtein distance) is wrong:
"The Missing": "842910",
"Pillars of Eternity 2": "560130",
"Dr... |
rates = list() # Equals to: rates = []
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as '
... |
# Forma procedural de criar uma conta
def cria_conta(numero, titular, saldo, limite):
'''
-> Cria uma conta bancรกria
:param numero: nรบmero da conta bancรกria (string)
:param titular: nome do titular (string)
:param saldo: saldo inicial da conta (float)
:param limite: limite de saldo da conta (flo... |
def euclidean_distance(x1, y1, x2, y2):
"""Compute euclidean distance between two points."""
def which_start_and_pitstop(pitstop_num, pitstop_coords, start_coords):
"""Computes the relevant pitstop and startpoint info.
Extracts the pitstop coordinates, relevant startpoint number and
startpoint co... |
greetings = ["hey", "howdy", "hi", "hello", "hi there"]
questions = ["how_are_you_feeling", "how_are_you", "what_is_your_name", "how_old_are_you", "where_are_you_from", "are_you_a_boy_or_a_girl", "what_up"]
insults = ["dumb", "stupid", "Ugly", "Retard", "Retarded", "suck"]
complements = ["great", "awesome"]
cuss_wo... |
#Desenvolver um algoritmo que faรงa a leitura de um nรบmero inteiro positivo e que,
#para esse nรบmero, mostre todos os seus divisores.
def divisor():
try:
num=int(input('Indique um nรบmero: '))
while num<0:
num=int(input('Nรบmero Invรกlido!\nIndique um nรบmero: '))
except ValueErr... |
def extractEachKth(inputArray, k):
return [x for i, x in enumerate(inputArray) if (i + 1) % k != 0]
print(extractEachKth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07'
|
_attrs = {
"base": attr.string(
mandatory = True
),
# See: https://github.com/opencontainers/image-spec/blob/main/config.md#properties
"entrypoint": attr.string_list(),
"cmd": attr.string_list(),
"labels": attr.string_list(),
"tag": attr.string_list(),
"layers": attr.label_list(... |
"""DESAFIO 44"""
print('-=-'*13)
valor = float(input('Qual o valor do pagamento? R$ '))
print('-=-'*13)
print("""Qual a forma de pagamento?
[1]โ ร vista dinheiro/cheque: 10% de desconto
[2]โ ร vista no cartรฃo: 5% de desconto
[3]โ em atรฉ 2x no cartรฃo: preรงo formal
[4]โ 3x ou mais no cartรฃo: 20% de juros""")
forma = int... |
def numsum(n):
''' The recursive sum of all digits in a number
unit a single character is obtained'''
res = sum([int(i) for i in str(n)])
if res < 10: return res
else : return numsum(res)
for n in range(1,101):
response = 'Fizz'*(numsum(n) in [3,6,9]) + \
'Buzz'*(str(n)[-1] in ['5','0'... |
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A or not A[0]: return 0
n, m = len(A), len(A[0])
tot = n*2**(m-1)
for i in range(1, m):
zero = sum(A[j][0]^A[j][i] for j in range(n))
... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import plotly\n",
"import pandas as pd\n",
"\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import word_tokenize\n",
"\n",
"fr... |
# Solution 1
# O(n^2) time / O(1) space
# n - number of buildings
def largestRectangleUnderSkyline(buildings):
maxArea = 0
for pillarIdx in range(len(buildings)):
currentHeight = buildings[pillarIdx]
furthestLeft = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
... |
t=int(input())
while(t):
t=t-1
n=int(input())
c=0
a=list(map(int,input().split()))
b=[]
b.append(int(a[0]))
for i in range(1,len(a)):
b.append(min(int(a[i]),int(b[i-1])))
for i in range(0,len(a)):
if(int(a[i])==int(b[i])):
c+=1
print(c)
|
#!/usr/bin/env python3
__author__ = "Mert Erol"
# This signature is required for the automated grading to work.
# Do not rename the function or change its list of parameters!
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
... |
# Dummy class for packages that have no MPI
class MPIDummy(object):
def __init__(self):
pass
def Get_rank(self):
return 0
def Get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=5... |
def gcd(a, b):
factors_a = []
for i in range(1, a+1):
if (a%i) == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b+1):
if (b%i) == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_facto... |
"""Pygame Zero, a zero-boilerplate game framework for education.
You shouldn't need to import things from the 'pgzero' package directly; just
use 'pgzrun' to run the game file.
"""
__version__ = '1.2'
|
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 3 Module Part 1 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 1 Practice Quiz:
# 02. Fill in the blanks to make the print_prime_f... |
test = """2H2 + O2 -> 2H2O"""
def times_sep(s):
elem = []
times = []
checking_pro = False
last = 0
for i in range(len(s)):
if checking_pro:
if s[i].isalpha() and not s[i].islower() or s[i].isdigit():
elem.append(s[last])
checking_pro = False
... |
#4: Skriv alle primtal mellem 1 og 100
for primtal in range(2, 101):
for i in range(2, primtal):
if (primtal % i) == 0:
break
else:
print(primtal)
|
class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/',
'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True
|
# noinspection PyUnusedLocal
# skus = unicode string
class InvalidOfferException(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {
'A': productA, 'B': productB, 'C': productC,'D': productD,'E': prod... |
str = "RahulShettyAcademy.com"
str1 = "Consulting firm"
str3 = "RahulShetty"
print(str[1]) #a
print(str[0:5]) # if you want substring in python
print(str+str1) # concatenation
print(str3 in str) # substring check
var = str.split(".")
print(var)
print(var[0])
str4 = " great "
print(str4.strip())
print(str4.ls... |
class Solution:
def secondHighest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.pop... |
'''
Fibonacci Sequence
'''
print("Enter a number for Fibonacci")
f = input()
|
def get_common_elements(seq1,seq2,seq3):
common = set(seq1) & set(seq2) & set(seq3)
return tuple(common)
print(get_common_elements("abcd",['a','b', 'd'],('b','c', 'd')))
# , {"a","b","c","d", "e"}
def get_common_elements_multi(*multy_arg):
if len(multy_arg) == 0:
return ()
my_set = set(mult... |
class Duration:
def __init__(self, hours: int = 0, minutes: int = 0, seconds: int = 0):
# setup the class instance and convert any provided times to seconds
self.total_duration: int = (hours * 60 * 60) + (minutes * 60) + seconds
def __add__(self, other):
new_total: int = self.total_dur... |
# https://lospec.com/palette-list/pear36
COLORS = [
"#5e315b",
"#8c3f5d",
"#ba6156",
"#f2a65e",
"#ffe478",
"#cfff70",
"#8fde5d",
"#3ca370",
"#3d6e70",
"#323e4f",
"#322947",
"#473b78",
"#4b5bab",
"#4da6ff",
"#66ffe3",
"#ffffeb",
"#c2c2d1",
"#7e7e8... |
nome=(input("Informe o nome do aluno: "))
n1=int(input("Informe a nota da prova: "))
n2=int(input("Informe a nota do trabalho: "))
n3=int(input("Informe a nota do seminรกrio: "))
media = (n1 + n2 + n3) /3
if media >= 7:
print(nome," APROVADO!")
elif media >=3 :
nf = (50 - (media * 7))/3
print(n... |
fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = "the emblem of our land.\n"
fout.write(line2)
fout.close()
|
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
"""Prefix sum.
Running time: O(n) where n is the length of A.
"""
n = len(A)
pre = 0
res = 0
d = {0: 1}
for a in A:
pre = (pre + a) % K
res += d.get(pre, 0... |
def unique_markers(n_markers):
"""Returns a unique list of distinguishable markers. These are predominantly based
on the default seaborn markers.
Parameters
----------
n_markers
The number of markers to return (max=11).
"""
markers = [
"circle",
"x",
"diamon... |
"""
This file contains the functional tests for the `devices` blueprint.
These tests use GETs and POSTs to different URLs to check for the
proper behavior of the `devices` blueprint.
"""
def test_inventory(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/inventory/<category>' page... |
def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
is_looping, acc = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds... |
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(word, idx, r, c):
m, n = len(board), len(board[0])
if idx == len(word):
return True
if (... |
print ('hello world')
print ('hello second time')
print ('Again and Again')
|
#!/usr/bin/env python3
disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i]+i+1)%disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i]+1)%disc_size[i] for i in range(len(shift_pos))]
t += 1... |
'''
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": ... |
"""
Person class
"""
# Create a Person class with the following properties
# 1. name
# 2. age
# 3. social security number
|
class Config:
def __init__(self):
self.DARKNET_PATH = "lib/pyyolo/darknet"
self.DATACFG = "data/obj.data"
self.CFGFILE = "cfg/yolo-obj.cfg"
self.WEIGHTFILE_SKETCH = "models/yolo-obj_final_sketch.weights"
self.WEIGHTFILE_TEMPLATES = "models/yolo-obj_45000.weights"
self... |
# coding = utf-8
# Create date: 2018-11-6
# Author :Bowen Lee
def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url),
is_install_to_hard_dr... |
NAME='router_xmldir'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['router_xmldir']
|
class Solution:
def brokenCalc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
Y = (Y + 1) // 2
return res + X - Y |
class RemoteDockerException(RuntimeError):
pass
class InstanceNotRunning(RemoteDockerException):
pass
|
# 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 flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.... |
"""
@author: magician
@date: 2019/12/19
@file: key_word_demo.py
"""
def safe_division(number, divisor, ignore_overflow=False, ignore_zero_division=False):
"""
safe_division
:param number:
:param divisor:
:param ignore_overflow:
:param ignore_zero_division:
:return:
"""
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Tencent is pleased to support the open source community by making Metis available.
Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with th... |
def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result["continue_workflow"]:
run_api_workflow_with_assertions(
workflow_specification,... |
INPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Input",
"description": ("Input schema for the demo DERIVA ingest Action Provider. This Action "
"Provider can restore a DERIVA backup to a new or existing catalog, "
"or creat... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 2 07:15:26 2022
@author: ACER
"""
# lista en blanco
lista = []
#lista con elementos
รฑistElementos = [1,3,4,5]
#acceder a los elementos
listAlumnos = ["adri","rither","jose","juan"]
alumnoPos_1 =listAlumnos[len(listAlumnos)-1] #'juan'
#obtener el tamanio de la lista
ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.