content stringlengths 7 1.05M |
|---|
""" Modules are contained in this package. Modules are the lowest tier of
the three-tiered processing chain. Each module is "owned" by a manager, that
decides whether or not to invoke the module's processing abilities.
A module does two things: first, it must decide if a chat or kmail is
applicable to its task. ... |
print("Enter a number")
num = int(input())
print("Type 1 or 0")
num2 = int(input())
b = bool(num2)
if(b == True):
for i in range(1, num+1):
for j in range(1, i+1):
print("*", end=" ")
print()
elif (b == False):
for i in range(num, 0, -1):
for j in range(1, i+1):
p... |
string = '012345678901234567890123456789012345678901234567890123456789'
n = 10
lista = [string[i:i+n] for i in range(0, len(string), n)]
listastring = '.'.join(lista)
print(listastring) |
# OpenWeatherMap API Key
weather_api_key = "4b6f407bc3690ac1562800a586bbda13"
# Google API Key
g_key = "AIzaSyBH17Xn87x8SM7waCAzHnS4gKMWRX96iDQ"
|
"""Shared constants for automation and script tracing and debugging."""
DATA_TRACE = "trace"
STORED_TRACES = 5 # Stored traces per automation
|
"""
The model level of application.
Contains modules which are the connectors between database and classes of
application level of system. Contained classes are responsible for the execution
of the right queries to access the required data.
Then initializes classes or returns data to the classes of application level
... |
t=int(input())
for i in range(t):
n=int(input())
h=0
for i in range(n+1):
if i%2==0:
h += 1
else:
h *= 2
print(h) |
"""
Write a program to calculate no of possible triangles in given array
Input: arr= {4, 6, 3, 7}
3, 4, 6, 7
Output: 3
Explanation: There are three triangles possible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}.
"""
class Geometry:
def __init__(self, arr, n):
self.arr = arr
self.n = n
def possible_tri... |
# Same as sorted_list_permutation [3 (ii)], however we are counting the number of occurring *columns* in A instead of number of occurrences itself.
#
# Goal: *no runtime goal*
def custom_sort(A,B):
C=B
i=1
while i < len(B):
j=i
while j > 0 and (count_occurring_columns(B[j-1],A) > count_occu... |
"""
For declaring inverse properties of GraphObjects
"""
InverseProperties = dict()
class InversePropertyMixin(object):
"""
Mixin for inverse properties.
Augments RealSimpleProperty methods to update inverse properties as well
"""
def set(self, other):
ip_key = (self.owner_type, self.l... |
hello = ''
with open('hello-world.txt', 'r') as f:
hello = f.read()
print(hello) |
# This is just for socgen-k test, you make sure Socgen-k server is working well.
# https://socgen-k-api.openbankproject.com/
# API server URL
BASE_URL = "https://socgen-k-api.openbankproject.com"
API_VERSION = "v2.0.0"
API_VERSION_V210 = "v2.1.0"
# API server will redirect your browser to this URL, should be non-funct... |
GOOD_HTTP_CODES = [200, 201, 202, 203]
USER_FIELD = 'username'
ACCESS_TOKEN_FIELD = 'access_token'
REFRESH_TOKEN_FIELD = 'refresh_token'
EXPIRE_TIME_TOKEN_FIELD = 'expires_in'
ERROR_CODE_FIELD = 'errcode'
MENSSAGE_FIELD = 'errmsg'
LIST_FIELD = 'list'
STATE_FIELD = 'state'
PAGES_FIELD = 'pages'
GATEWAY_MAC_FIELD = 'gat... |
def insertionSort(alist):
for index in range(1, len(alist)):
currentvalue = alist[index]
position = index
while position > 0 and alist[position - 1] > currentvalue:
alist[position] = alist[position - 1]
position = position - 1
alist[position] = currentvalue... |
# -*- coding: utf-8 -*-
"""save_princess_peach.constants.py
Constants for save-princes-peach.
"""
# Default file used as grid
DEFAULT_GRID = '/Users/JFermin/Documents/GitHub/itsMeMario/tests/test_grids/init_grid.txt'
# players
BOWSER = 'b'
PEACH = 'p'
MARIO = 'm'
PLAYERS = [BOWSER, PEACH, MARIO]
# additional tiles
... |
"Github API v2 library for Python"
VERSION = (0, 2, 0)
__author__ = "Ask Solem"
__contact__ = "askh@opera.com"
__homepage__ = "http://github.com/ask/python-github2"
__version__ = ".".join(map(str, VERSION))
|
N = 6
edge_list = [(0, 1, 30), (1, 0, 30), (0, 2, 25), (2, 0, 20), (1, 2, 40),
(2, 1, 35), (1, 3, 35), (2, 4, 15), (3, 1, 25), (3, 2, 20),
(3, 5, 45), (4, 3, 10), (4, 5, 40), (5, 3, 50), (5, 4, 50)]
dij = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N):
dij[i][i] = 0... |
#list
list = [1,2,3,4,8]
print(list)
list.append(6)
print(list)
list.pop(2)
print(list)
list.insert(1,7)
print(list)
list.extend([1,2,4,7])
print(list)
print(list.count(2))
print(1 in list)
list.sort()
print(list)
list.reverse()
print(list)
#dictionary
dict = {
1:'yasser',
'h':'honey',
... |
class Card:
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
def __init__(self, value, suit):
self.set_value(value)
self.set_suit(suit)
def __repr__(self):
return f"{self.value} of {self.suit}"
... |
# Criar programa que leia vários números inteiros e pare quando o número 999 for digitado.
# Mostre a soma e o número de termos, desconsiderando o flag.
c = s = 0
while True:
n = int(input('Digite um número: '))
if n == 999:
break
c = c + 1
s = s + n
print(f'A soma dos {c} termos é igual a {s}.... |
def running_sum(numbers, start=0):
if len(numbers) == 0:
print()
return
total = numbers[0] + start
print(total,end="")
running_sum(numbers[1:],total)
|
class MyClass:
var = "hello"
def say(a,b):
print("hello"+a.var+b) |
def parse_iteration(s):
if s[-1] == 'k':
return int(s[:-1])*1000
elif s[-1] == 'm':
return int(s[:-1])*1000000
else:
return int(s)
|
#ALGORITHM USED FOR GENERATING A MAGIC SQUARE USING FORMULA IS AS FOLLOWS:
#Step 1: Start in the middle of the top row, and let n=1
#Step 2: Insert n into the current grid position;
#Step 3: If n=N2 the grid is complete so stop. Otherwise increment n
#Step 4: Move diagonally up and right, wrapping to the first colu... |
'''
Erros mais comuns em Python
É importante prestar atenção e aprender a ler as saídas de erros geradas pela execução do
nosso código.
Os erros mais comuns:
SyntaxError - Ocorre quando o Python encontra um erro de sintaxe. Ous seja, vocÊ escreveu algo
que o Python não reconhece como parte da linguagem.
# Exemplo S... |
# this module is a place to store stuff that is used in multiple modules
# valorant client object
client = None
# websocket connections
sockets = []
# user configuration
config = None
# onboarding state
onboarding = False
# asyncio loop
loop = None |
def print_hello_world(n):
while n > 0:
print('Hello, world!')
n = n - 1
print_hello_world(3)
|
class DataErrorsChangedEventArgs(EventArgs):
""" DataErrorsChangedEventArgs(propertyName: str) """
@staticmethod
def __new__(self, propertyName):
""" __new__(cls: type,propertyName: str) """
pass
PropertyName = property(
lambda self: object(), lambda self, v: None, lam... |
class ReturnValuesWrapper(object):
"""
Wraps a return specification and a set of corresponding return values.
Enables comparison between value sets.
"""
def __init__(self, return_spec, values):
self.return_spec = return_spec
self.values = values
# TODO: Use something like funct... |
"""
https://leetcode-cn.com/problems/edit-distance/
https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode-solution/
https://leetcode-cn.com/problems/edit-distance/solution/zi-di-xiang-shang-he-zi-ding-xiang-xia-by-powcai-3/
"""
class Solution:
def minDistance(self, word1: str, word2: ... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Configuration for Invenio-Theme."""
BASE_TEMPLATE = 'invenio_theme/page.html'
"""... |
#! /usr/local/bin/env python3
# picture-grid.py
# Say you have a list of lists where each value in the inner lists is a
# one-character string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
... |
our_set = set()
our_set2 = {0}
print(our_set, type(our_set))
print(our_set2, type(our_set2))
our_set.add('tomato')
our_set2.add("potato")
print(our_set)
print(our_set2)
x = "tomato"
print(x in our_set)
print(x in our_set2)
print(our_set.isdisjoint(our_set2))
our_set3 = our_set.union(our_set2)
print(our_set3)
our_set.up... |
#
# PySNMP MIB module CISCO-XGCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-XGCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:21:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
#Given an array of integers, find the sum of its elements.
#Input Format
#The first line contains an integer, n, denoting the size of the array.
#The second line contains n space-separated integers representing the array's elements.
#Output Format
#Print the sum of the array's elements as a single integer.
#Sampl... |
"""
Organisation theme for CEDA Services web components.
"""
__author__ = "Matt Pritchard"
__copyright__ = "Copyright 2018 UK Science and Technology Facilities Council"
__version__ = "0.5"
|
#
# string1="aaa新年快乐bbb"
# string2=string1.replace("新年快乐", "恭喜发财")
# print(string2)
# # aaa恭喜发财bbb
#
# string3="aaa新年快乐bbb新年快乐ccc"
# string4=string3.replace("新年快乐", "恭喜发财", 2)
# print(string4)
#
#
# string5='aaa,."bbb'
# string6=string5.replace(',', ',')
# string6=string6.replace('.', '。')
# string6=string6.replace('"'... |
# --- Programa que imprime como um papel ficaria com um comprimento dado por nós e a largura dada pelo Dr. Mike ---
# variáveis
a, b, c = input('Digite as larguras a, b e c: ').split(' ')
a = int(a)
b = int(b)
c = int(c)
# função que imprime o papel
def print_rectangle(largura):
comp = 4
espacos = largura -... |
AUTH_LDAP_GLOBAL_OPTIONS = {
ldap.OPT_X_TLS_REQUIRE_CERT: True,
ldap.OPT_X_TLS_CACERTFILE: "/etc/certs/ldap.pem"
}
|
class Worker:
def __init__(self, number, name, age, salary):
self.number = number,
self.name = name,
self.age = age,
self.salary = salary
|
class SessionTimeOut(Exception):
pass
class InvalidFormat(Exception):
pass
class UserExists(Exception):
pass
class EmailAlreadyUsed(Exception):
pass
class SQLInjectionAlert(Exception):
pass
|
class Button:
def __init__(self, label, _x, _y, _w, _h):
self.label = label
self.position = PVector(_x, _y)
self.WIDTH = _w
self.HEIGHT = _h
def display(self):
fill(218)
stroke(0)
rect(self.position.x, self.position.y... |
test = {
'name': 'Problem 9',
'points': 3,
'suites': [
{
'cases': [
{
'answer': 'A TankAnt does damage to all Bees in its place each turn',
'choices': [
'A TankAnt does damage to all Bees in its place each turn',
'A TankAnt has greater health than a Bo... |
EXPECTED = {'X680': {'extensibility-implied': False,
'imports': {},
'object-classes': {'ATTRIBUTE-E-2-15': {'members': [{'name': '&AttributeType',
'type': 'OpenType'},
{'name'... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 10:18:58 2021
@author: dsd
"""
if __name__ == '__main__':
sent = input("Введите предложение: ")
sent = sent.replace(' ', '')
print(sent) |
def pairs(array: list) -> int:
""" This function returns the count of pairs that have consecutive numbers. """
pairs_from_array = list(zip(array[::2], array[1::2]))
count = 0
for i, j in pairs_from_array:
if (i - j == 1) or (i - j == -1):
count += 1
return count |
class Livro:
def __init__(self, titulo, autor, quantidade_paginas):
self.titulo = titulo
self.autor = autor
self.quantidade_paginas = quantidade_paginas
def exibir_dados(self):
print("_______________________________________________")
print("Título:", self.titulo)
... |
output_name = "test"
config = {
"_description": "Test configuration",
"gpu": [0],
# data
"dataset": "Lsun_church",
"data_path": "/home/yct/data/church_outdoor_train_lmdb/Lsun_church_unlabeled_64",
"data_size": 2000,
"use_image_generator": False,
# model & training
"model": ... |
#/usr/bin/python3
GPIO_NUM = 23
COLUMN_LEN = 16
COLUMN_GAP = 30
def read_file():
file = open("line")
count = 0
while 1:
for i in range(GPIO_NUM):
count = count + 1
if count > GPIO_NUM * COLUMN_LEN:
return
line = file.readline()
if not... |
class MangaDexException(Exception):
"""Base exception for MangaDex errors"""
pass
class HTTPException(MangaDexException):
"""HTTP errors"""
def __init__(self, *args: object, resp=None) -> None:
self.response = resp
super().__init__(*args)
class InvalidManga(MangaDexException):
"""R... |
n, k = map(int, input().split())
a = list(sorted(map(int, input().split()), reverse=True))
s = set()
for i in range(len(a)):
if a[i] * k not in s:
s.add(a[i])
print(len(s)) |
def smile():
return ":)"
def frown():
return ":("
|
# coding=utf-8
DEBUG = True
SITE_ID = 1
SECRET_KEY = 'blabla'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'south',
'contacts'... |
__author__ = ['Tom Van Mele', ]
__copyright__ = 'Copyright 2016 - Block Research Group, ETH Zurich'
__license__ = 'MIT License'
__email__ = 'vanmelet@ethz.ch'
__all__ = [
'get_axes_dimension',
'assert_axes_dimension',
'width_to_dict',
'size_to_sizedict',
]
def get_axes_dimension(axes):
... |
col_desc = {'Rk':'Rank This is a count of the rows from top to bottom. It is recalculated following the sorting of a column.',
'Pos':'Position',
'Name':'Player Name Bold can mean player is active for this team or player has appeared in MLB * means LHP or LHB, # means switch hitter, + can mean ... |
# pylint: disable=missing-docstring, invalid-name
MY_DICTIONARY = {"key_one": 1, "key_two": 2, "key_three": 3}
try: # [max-try-statements]
value = MY_DICTIONARY["key_one"]
value += 1
except KeyError:
pass
try:
value = MY_DICTIONARY["key_one"]
except KeyError:
value = 0
|
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [
dict(
section="notebook",
src="static",
# directory in the `nbextension/` namespace
dest="imjoy_jupyter_extension",
# _also_ in the `nbextension/` namespace
require="... |
#!/usr/bin/env python
"""
List of APIs supported by Gurunudi
"""
API_CHAT ='chatbot' #real time conversation and knowledge q&a - ideal for chatbots
"""
Fields returned in response JSON by Gurunudi API calls and Fields sent in request JSON to Gurunudi API calls
"""
FIELD_LANG='lang'
FIELD_TARGET_LANG='target'
FIELD_C... |
numero = int(input('Digite um número de quatro digitos: '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print(f'Analisando o número {numero}')
print('Unidade: ', u)
print('Dezena: ', d)
print('Centena: ', c)
print('milhar: ', m)
|
#! /root/anaconda3/bin/python
# 例子一 内置函数locals()可以返回其所在局部作用域的命名空间
"""
locals()并没有返回实际的命名空间,而是返回值的拷贝,所以通过locals()修改某个名字对应的值,对于实际的命名空间是没有影响的;但是,可以通过locals()向实际的命名空间中添加一个名字和值的映射。
"""
def f():
x = 8
print(locals()) # {'x': 8}
locals()['x'] = 9
locals()['y'] = 10
print(locals()) # {'x': 8, 'y': 10... |
COLOR_CANVAS_DARK = 'rgb(33,33,33)'
COLOR_CANVAS_LIGHT = 'rgb(252, 252, 252)'
COLOR_PLOT_TEXT_LIGHT = 'rgb(52, 49, 49)'
COLOR_PLOT_TEXT_DARK = 'rgb(252, 252, 252)'
COLOR_ZERO_LINE_LIGHT = "green"
COLOR_ZERO_LINE_DARK = "limegreen"
COLOR_BEAM = "red"
COLOR_DETECTOR = "#D3D3D3"
COLOR_PAD = "slateblue"
COLOR_PATIENT = "#C... |
#faça um programa que leia o nome de uma
#pessoa e mostre uma mensagem de boas-vindas
#nome = input('Qual é o seu nome?')
#print('Olá', nome,'. Prazer em conhece-lo')
nome = input('Qual é o seu nome?')
print('Prazer em te conhecer {}!'.format(nome))
|
#3) Largest prime factor
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
# Solution
def primes_naive(n):
if n < 2: return []
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i... |
f = open("twentyfive.txt", "r")
lines = [x.strip() for x in f.readlines()]
width = len(lines[0])
height = len(lines)
left = {}
down = {}
for y in range(len(lines)):
left[y] = []
down[y] = []
for x in range(len(lines[y])):
if lines[y][x] == ">":
left[y].append(x)
elif lines[y][... |
class dotPolymeshValidateInvalidInfo_t(object):
# no doc
ClientId=None
nInvalidFaces=None
|
"""
1) :
Faca um programa que possua um vetor denominado 'a' que armazene 6 valores inteiros.
O programa deve executar os seguintes passos:
"""
# A) Atribua os seguintes valores :
a = [1, 0, 5, -2, -5, 7]
# B) Armazene em uma variável inteira simples a soma dos seguintes valores das posicões :
b = a[0] + a[1]... |
def parse_svg(txt):
txt = txt.split('<path d="')[-1]
txt = txt.split('z"/>')[0]
txt = txt.replace('\n', ' ')
txt = txt.split(' ')
# Take out the initial M x y instruction
txt = txt[2:]
# Take out the initial c instruction
txt[0] = txt[0][1:]
txt = [int(num) for num in txt]
curves = []
cur_pos = (0, 0)
... |
# -*- coding: utf-8 -*-
"""Top-level package for tmrwppk."""
__author__ = """Nick Hobart"""
__email__ = 'nick@hobart.io'
__version__ = '0.0.6'
|
class LinkedList:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __init__(self):
self.head = None
def append(self, data):
"""Add a new node to the end of the list."""
node = self.head
if node is ... |
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
seen = set() # visited cells here
res = 0
for r, row in enumerate(grid):
for c, val in enumerate(row): # val is basically grid[r, c]
if val and (r,c) not in seen: # if val is 1 and not visi... |
# -*- coding: utf-8 -*-
'''
Generate baseline proxy minion grains
'''
__proxyenabled__ = ['rest_sample']
__virtualname__ = 'rest_sample'
def __virtual__():
if 'proxy' not in __opts__:
return False
else:
return __virtualname__
def kernel():
return {'kernel': 'proxy'}
def os():
retu... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Tests that custom auth works & is not impaired by CORS',
'category': 'Hidden',
'data': [],
}
|
#String unpack example
testString = '0xL08$#$john18:jcTeam01_@#@_https://docs.google.com/spreadsheetExampleUrl'
commandData, data = testString.split('_@#@_')
print(commandData)
print(data)
command, cData = commandData.split('$#$')
print(command)
print(cData)
username, fileName = cData.split(':')
print(username)
print(... |
print('Vamos ver números por extenso.')
print('Digite um número entre 0 e 20')
numeros = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez',
'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
opcao = 's'
while True:
... |
def format_bytes(n):
"""Format bytes as text
Copied from dask to avoid dependency.
"""
if n > 1e15:
return "%0.2f PB" % (n / 1e15)
if n > 1e12:
return "%0.2f TB" % (n / 1e12)
if n > 1e9:
return "%0.2f GB" % (n / 1e9)
if n > 1e6:
return "%0.2f MB" % (n / 1e6)... |
def canConstruct(target, word_bank):
tab = [False for _ in range(len(target)+1)]
# seed
tab[0] = True # creating an empty string is always possible
for i in range(len(target)+1):
if tab[i] is True:
for word in word_bank:
# If the word matches the characters starting at position i
if target[i:].start... |
#The urllib module has a function called urljoin which might be able to improve how I put together these urls.
DefaultBaseUrl = "https://api.idfy.io"
DefaultOAuthBaseUrl = DefaultBaseUrl #Could this lead to problems where the DefaultOAuthBaseUrl resets unexpectedly?
TestBaseUrl = "http://localhost:5000" #testing on... |
# APIs for Windows 32-bit user32 library.
# Format: retval, rettype, callconv, exactname, arglist(type, name)
# arglist type is one of ['int', 'void *']
# arglist name is one of [None, 'funcptr', 'obj', 'ptr']
api_defs = {
'user32.main_entry':( 'int', None, 'stdcall', 'user32.main_entry', (('int... |
# 삼각달팽이
# imp
def solution(n):
arr = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
ans = []
top = 1
btm = n
left = 1
right = 0
num = 1
MAX = (n * (n + 1)) // 2
state = 0
while num <= MAX:
if state == 0:
for i in range(top, btm + 1):
arr[i][... |
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
# dp[i][j] means minimum falling path ended with matrix[i][j]
# dp[i][j] = min(dp[i-1][j],dp[i-1][j-1], dp[i-1][j+1])
dp = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
for i in range(le... |
# A number of options exist when aiming to review how many components to include to reduce the dimensionality complexity
# Let PCA select 90% of the variance
pipe = Pipeline([('scaler', StandardScaler()),
('reducer', PCA(n_components=0.9))]) # By providing a percent ratio value this means the algorithm aims ... |
# ### Trees
# A tree is a widely used abstract data type that simulates a hierarchical tree structure, with a `root` value and subtrees of `children` with a `parent` node, represented as a set of linked nodes.
#
# A tree data structure can be defined recursively as a collection of nodes (starting at a root node), wher... |
"""
Get the editions per year.
"""
def do_query(archives, config_file=None, logger=None, context=None):
"""
Iterate through archives and get the title and editions per year
Returns result of form:
{ <YEAR>: [ (title, edition), (title, edition)] }
:param archives: RDD of defoe.nls.archive.Archive... |
"""Monkey patch the Django admin site to also allow a permission check"""
# I feel SO dirty doing this, but admin autodiscover doesn't work if I have a custom admin site,
# and all I want to do is allow you to get into the admin site if you have either the is_staff flag or
# a custom permission as defined on the accou... |
"""
Created on Fri Mar 25 22:43:42 2022
@author: zhzj
Scrivere un programma che stampa i primi 20 numeri altamente composti.
Un numero altamente composto è tale che qualunque numero minore di esso ha meno divisori.
I primi numeri altamente composti sono 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1... |
"""Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem,
cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas."""
dist = float(input('Qual a distancia da sua viagem ?'))
if dist <= 200:
valor = dist * 0.50
print('O preço da sua viagem ... |
#Not finished yet
# intervals = [[1,3],[2,6],[8,10],[15,18]]
# intervals = [[1,4],[4,5]]
intervals = [[2,3],[4,5],[6,7],[8,9],[1,10]]
intervals.sort(key = lambda it : it[0])
myList = [intervals[0]]
for i in range(1,len(intervals)):
# print(myList)
comp1i, comp1j = myList.pop()
comp2i, comp2j = intervals[i... |
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once.
Also, i... |
# -------------------------------------------------------
#
#
#
# -------------------------------------------------------
class ServiceCategory():
inpatient = 'inpatient'
other_services = 'other_services'
long_term = 'long_term'
prescription = 'prescription'
# -------------------------------------... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"make_session": "00_scrapers.ipynb",
"make_browser": "00_scrapers.ipynb",
"s": "00_scrapers.ipynb",
"browsers": "00_scrapers.ipynb",
"cache_db": "00_scrapers.ipynb",
... |
'''HashMap class to keep track of key value pairs'''
class HashMap:
'''HashMap class to keep track of key value pairs'''
def __init__(self):
'''initializes key val pair'''
self.inner_size = 7
self.array = [None] * self.inner_size
self.count = 0
def get(self, key):
''... |
def split_and_join(line):
# write your code here
line_splitted = line.split(' ')
return ('-').join(line_splitted)
# Or in one line:
# return ('-').join(line.split(' ')
|
""" Unit Test """
def main():
""" Main function """
root = "coco_dataset/train2017"
ann_file = "coco_dataset/annotations/captions_train2017.json"
dataset = Dataset(root, ann_file)
dataloader = DataLoader(dataset, batch_size=10, collate_fn=collate_fn)
vocab_size = dataset.tokenizer.vocab_size
... |
def multiplication(a, b):
a = float(a)
b = float(b)
value = a * b
return value |
level = 3
name = 'Pamengpeuk'
capital = 'Sukasari'
area = 14.62
|
def get_repo_path(path):
path = path.replace('\\\\', '/').replace('\\', '/')
url_array = path.split("/")
del url_array[len(url_array) - 1]
repo_path = ""
for word in url_array:
if word != url_array[len(url_array) - 1]:
repo_path += word + "/"
return repo_path + url_array[len(... |
"""
Problem Statement
Given an integer array, find and return all the subsets of the array.
The order of subsets in the output array is not important.
However the order of elements in a particular subset should remain the same as in the input array.
Note:
An empty set will be represented by an empty list.
If there are... |
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
def generateTrees(mini: int, maxi: int) -> List[Optional[int]]:
if mini > maxi:
return [None]
ans = []
for i in range(mini, maxi + 1):
for left in generateTrees(mini, i - 1):
... |
input = """
up(L,0) | -up(L,0) :- latch(L).
latch(a).
latch(b).
latch(c).
"""
output = """
up(L,0) | -up(L,0) :- latch(L).
latch(a).
latch(b).
latch(c).
"""
|
def taskA(data):
difference = ord('a') - ord('A')
stack = []
for c in data:
if len(stack) == 0:
stack.append(c)
elif c != stack[-1] and (ord(c)+difference == ord(stack[-1]) or ord(c) == ord(stack[-1]) + difference):
stack.pop()
else:
stack.appen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.