content stringlengths 7 1.05M |
|---|
contractions_pt_br = {
# da, do, dos, deste, disso, daquilo...
r'\b(D|d)(\')?(ele|el|est|este|aquel|aquele|ist|iss|ess|esse|aquil)?(a|o)?(s)?':'\\1e \\3\\4\\5',
# na, no, nos, neste, nisso, naquilo...
r'\bN(\')?(ele|el|est|este|aquel|aquele|ist|iss|ess|esse|aquil)?(a|o)?(s)?':'Em \\2\\3\\4',
r'\bn(\... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author:
@file: ${NAME}.py
@time: ${DATE}
@version:
""" |
s = input()
if s:
print('foo')
else:
print('bar')
x = 1
y = x
print(y)
|
#
# PySNMP MIB module CHECKPOINT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHECKPOINT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:31:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
#
# PySNMP MIB module CISCO-ITP-ACT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-ACT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:03:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
class MPRuntimeError(Exception):
def __init__(self, msg, node):
self.msg = msg
self.node = node
class MPNameError(MPRuntimeError): pass
class MPSyntaxError(MPRuntimeError): pass
# To be thrown from functions outside the interpreter --
# will be caught during execution and displayed as a runtim... |
with open("1.in") as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
# Part 1
increases = 0
for i in range(0, len(lines)-1):
if int(lines[i]) < int(lines[i+1]):
increases += 1
print(increases)
# Part 2
increases = 0
for i in range(0, len(lines)-3):
if (int(lines[i]) + ... |
class Pizza():
pass
class PizzaBuilder():
def __init__(self, inches: int):
self.inches = inches
def addCheese(self):
pass
def addPepperoni(self):
pass
def addSalami(self):
pass
def addPimientos(self):
pass
def add... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Copyright (C) 2020 All rights reserved.
#
# @Author Kaco
# @Version 1.0
#深信服SSLVPN服务器地址
API_SERVER = 'https://x.x.x.x:4430'
#深信服SSLVPN密钥
API_KEY = '66931f1342b1f462d4156e968feaa458'
# SSL证书校验关闭
SSL_ENABLE= False
#请求头部,请勿修改
CONTENT_TYPE = "application/x-www-form-urlencod... |
# This script will create an ELF file
### SECTION .TEXT
# mov ebx, 1 ; prints hello
# mov eax, 4
# mov ecx, HWADDR
# mov edx, HWLEN
# int 0x80
# mov eax, 1 ; exits
# mov ebx, 0x5D
# int 0x80
### SECTION .DATA
# HWADDR db "Hello World!", 0x0A
out = ''
... |
# Copyright 2020-2021 antillia.com Toshiyuki Arai
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
class Settings:
CORRECTOR_DOCUMENTS_LIMIT = 20000
CORRECTOR_TIMEOUT_DAYS = 10
THREAD_COUNT = 4
CALC_TOTAL_DURATION = True
CALC_CLIENT_SS_REQUEST_DURATION = True
CALC_CLIENT_SS_RESPONSE_DURATION = True
CALC_PRODUCER_DURATION_CLIENT_VIEW = True
CALC_PRODUCER_DURATION_PRODUCER_VIEW = Tr... |
def trap():
left = [0]*n
right = [0]*n
s = 0
left[0] = A[0]
for i in range( 1, n):
left[i] = max(left[i-1], A[i])
right[n-1] = A[n-1]
for i in range(n-2, -1, -1):
right[i] = max(right[i + 1], A[i]);
for i in range(0, n):
s += min... |
class LoadSql(object):
CREATE_DETECTION_TABLE = \
"""
CREATE TABLE P2Detection(
`objID` bigint NOT NULL,
detectID bigint NOT NULL,
ippObjID bigint NOT NULL,
ippDetectID bigint NOT NULL,
filterID smallint NOT NULL,
imageID bigint NOT NULL,
obsTime float NOT NULL DEFAULT -9... |
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
def _pluralize(count: int, singular: str) -> str:
return singular if count == 1... |
#!/usr/bin/env python3
def squares(start, end):
"""The squares function uses a list comprehension to create a list of
squared numbers (n*n). It receives the variables start and end, and returns
a list of squares of consecutive numbers between start and end inclusively.
For example, squares(2, 3) should return [4,... |
def head(file_name: str, n: int = 10):
try:
with open(file_name) as f:
for i, line in enumerate(f):
if i == n:
break
print(line.rstrip())
except FileNotFoundError:
print(f"No such file {file_name}")
def tail(file_name: str, n: int... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 14 14:19:50 2021
@author: qizhe
"""
# 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且
# 有效的 括号组合。
#
# 现在还有错误,123 124 133 134 144 序列不会生成
class Solution:
def generateParenthesis(self, n: int):
"""
典型的回溯问题
8月14 一开始完全不懂怎么做,在找规律啥的
9月30 学了回溯算法之后,基本是几... |
ADMIN_INSTALLED_APPS = (
'fluent_dashboard',
'admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.admin',
)
# FIXME: Move generic (not related to admin) context processors to base_settings
# Note: replace 'django.core.context_processors' with 'djang... |
# This is the qasim package, containing the module qasim.qasim in the .so file.
#
# Note that a valid module is one of:
#
# 1. a directory with a modulename/__init__.py file
# 2. a file named modulename.py
# 3. a file named modulename.PLATFORMINFO.so
#
# Since a .so ends up as a module all on its own, we have to includ... |
def test_unique_names(run_validator_for_test_files):
errors = run_validator_for_test_files(
'test_not_unique.py',
force_unique_test_names=True,
)
assert len(errors) == 2
assert errors[0][2] == 'FP009 Duplicate name test case (test_not_uniq)'
assert errors[1][2] == 'FP009 Duplicate n... |
num = 12
if num > 5:
print("Bigger than 5")
if num <= 47:
print("Between 6 and 47")
|
"""
* Nas listas o python gera os índices, no dicinário o programador controla o índice (também chamado de cahve)
* Chaves precisam ser únicas
"""
d1 = {'chave1': 'Valor da chave'}
print(d1)
d1['nova_chave'] = 'Valor da nova chave'
print(d1)
print(d1['chave1'])
# Outra forma de criar dicionários
d2 = dict(chave1='Val... |
class PlatformError(Exception):
"""
The error is thrown when you try to use function
that are only available for windows
"""
|
# coding: utf-8
#3) Leia um caractere e informe se ele é vogal ou consoante.
#Se prestar bastante atenção, vai perceber que a solução do exercício 2 é exatamente igual ao do exercício 3
caractere = input("Informe o caractere que deseja verificar: ")
caracteresNumerais = "aeiou"
paraLooping = False
contador = 0
while(... |
'''
Igmp Genie Ops Object Outputs for NXOS.
'''
class IgmpOutput(object):
ShowIpIgmpInterface = {
"vrfs": {
"default": {
"groups_count": 2,
"interface": {
"Ethernet2/2": {
"query_max_response_time": 10,
... |
name = 'GLOBAL VARIABLE'
def scope_func():
print('before initializing/assigning any local variables: ',locals())
pages = 10
print('after local variable declaration and assignment')
print(locals()) # returns dictionary containing all local variable
print('inside function name is : ', name)
scope_... |
class Complex:
def __repr__(self):
imag = self.imag
sign = '+'
if self.imag < 0:
imag = -self.imag
sign = '-'
return f"{self.real} {sign} {imag}j"
def __init__(self, real=None, imag=None):
self.real = 0 if real == None else real;
self.im... |
def is_palindrome(phrase):
"""Is phrase a palindrome?
Return True/False if phrase is a palindrome (same read backwards and
forwards).
>>> is_palindrome('tacocat')
True
>>> is_palindrome('noon')
True
>>> is_palindrome('robert')
False
Should ignore capi... |
# Databricks notebook source
#setup the configuration for Azure Data Lake Storage Gen 2
configs = {"fs.azure.account.auth.type": "OAuth",
"fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
"fs.azure.account.oauth2.client.id": "f62b9429-c55e-4ba... |
# problem 53
# Project Euler
__author__ = 'Libao Jin'
__date__ = 'July 17, 2015'
def factorial(n):
if n <= 1:
return 1
product = 1
while n > 1:
product *= n
n -= 1
return product
def factorialSeries(n):
fSeries = []
for i in range(n):
if i == 0:
fSeries.append(1)
else:
value = fSeries[i-1] * i... |
#definimos bloque como conjunto de lineas que poseen una funcion
# Presentación del programa
print ("BIENVENIDO A 'TRANSFORMADOR DE CADENAS DE CARACTERES'")
print ("")
print ("Ingrese a continuación la cadena de caracteres que desea modificar:")
cadena = input() #ingreso de la cadena a editar
Cadena_Inicial = cade... |
numero = int(input(""))
if numero < 5 or numero > 2000:
numero = int(input(""))
par = 1
while par <= numero:
if par % 2 == 0:
numero_quadrado = par ** 2
print("{}^2 = {}".format(par, numero_quadrado))
par += 1
|
class Solution:
def dailyTemperatures(self, temp: List[int]) -> List[int]:
dp = [0] *len(temp)
st = []
for i,n in enumerate(temp):
while st and temp[st[-1]] < n :
x = st.pop()
dp[x] = i - x
st.append(i)
return dp
|
# Basic Calculator II: https://leetcode.com/problems/basic-calculator-ii/
# Given a string s which represents an expression, evaluate this expression and return its value.
# The integer division should truncate toward zero.
# Note: You are not allowed to use any built-in function which evaluates strings as mathematica... |
#Adicionar dois números e mostrar a soma
print("==========Exercicio 3 ==========")
numero1 = int(input("Digite um número: "))
numero2 = int(input("Digite outro número: "))
print(numero1,"+",numero2,"=",numero1+numero2) |
lanche = ['Hamburguer', 'Suco', 'Pizza', 'Pudim']
if 'Picolé' in lanche:
lanche.remove('Picolé')
print(lanche)
valores = [8, 2, 5, 4, 9, 3, 0]
print(valores)
valores.sort()
print(valores)
valores.sort(reverse=True)
print(valores)
|
#this it the graphics file to Sam's Battle Simulator
#Copyright 2018 Henry Morin
def title():
print("""
_______ _______ _______ _ _______ ______ _________________________ _______ _______________________
( ____ ( ___ | | | ____ \ ( ___ \( ___ )__ __|__ __( \ ( ____ \ (... |
p = int(input('Digite o primeiro termo: ' ))
r = int(input('Digite a razão: '))
s = p
x = 0
while x < 10:
print(p, end='')
print(end=' → ' if x < 9 else print(end=' → FIM'))
p += r
x += 1
print('Acima os primeiros dez termos da PA de razão {} e primeiro termo {}.'.format(r, s))
|
class SecunitError(Exception):
...
class KeyNotInConfig(SecunitError):
...
class InvalidFlaskEnv(SecunitError):
...
|
N = int(input())
waiting = list(map(int, input().split()))
# 정렬
waiting.sort()
time = 0 #기다리는 시간
total = 0 #기다리는 총 시간
for t in waiting:
total += (time + t) #여태까지 기다린 시간 + 인출하는 시간
time += t #t만큼 시간 지남
print(total)
|
"""
应用: 文件的备份copy
"""
old_file = open("Test.txt", "r")
result = old_file.readlines()
print(result)
# for循环开始进行copy写入
new_file = open("Test(附件).txt", "w")
for line in result:
new_file.write(line)
old_file.close()
new_file.close()
"""
上面的例子直接readlines(),并不是完美的copy方法
如果文件过大,一点点的读取写入,内存问题,防止电脑变卡
在读取... |
class Limit:
def __init__(self, ratio=1, knee=0, gain=1, enable=True):
"""
:param float ratio: the compression ratio (1 means no compression).
ratio should usually between 0 and 1.
:param float knee: the ratio where the compression starts to kick in.
knee should usua... |
# Aula 12 - Desafio 37: Conversor de bases numericas
# Leia um numero inteiro e peça pra usuario escolher a base de conversao:
# 1 - p/ binario; 2 - p/ octal; 3 - hexadecimal
num = int(input('Digite um numero: '))
print('Escolha uma das opçoes de conversao abaixo')
print('[ 1 ] Binario | [ 2 ] Octal | [ 3 ] Hexadecima... |
'''
Gui/Views/Visualizer
____________________
Contains QTreeView, QWidget and PyQtGraph canvas definitions for
visualizer displays.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
__all__ = []
|
n=int(input())
L=input().split()
k=dict()
for i in range(len(L)):
k[L[i]]=i
L2=input().split()
ans = 0
for i in range(n):
for j in range(i+1,n):
if k[L2[i]] < k[L2[j]]:
ans+=1
print("{}/{}".format(ans,n*(n-1)//2))
|
'''
Exercicio 007
Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
'''
lado = float(input('Digite o valor do lado do quadrado: '))
dobroDaAreaQuadrado = lado * lado * 2
print(f'O dobro da área do quadrado equivale à {dobroDaAreaQuadrado:.2f}') |
#1 Write a python program, which adds a new value with the given key in dict.
dic = {"A":5,"B":9,"C":25}
def new_value(key,value,d):
d[key] = value
return d
#2 Write a python program which concat 2 dicts.
def concat(d1,d2):
d1.update(d2)
return d1
# 3 Write a python program, which create a dictiona... |
prompt = """
<|endoftext|># I am a voice assistant. I execute commands on behalf of the user and answer their questions
# I have access to the following APIs:
# Spotipy
import spotipy
from spotipy.oauth2 import SpotifyOAuth as OAuth
spotify = spotipy.Spotify(auth_manager=OAuth(scope="user-read-recently-played,user-rea... |
"""
Deep inverse problems in Python
Multi-channel MRI forward operator
"""
|
__author__ = 'Jeffrey Seifried'
__description__ = 'Scraping tools for getting me a damn Nintendo Switch'
__email__ = 'jeffrey.seifried@gmail.com'
__program__ = 'switch'
__url__ = 'http://github.com/jeffseif/{}'.format(__program__)
__version__ = '1.0.0'
__year__ = '2017'
HEADERS = {
'Accept': '*/*',
'Accept-En... |
class Player:
"""A person taking part in a game.
The responsibility of Player is to record player moves and hints.
Stereotype:
Information Holder
Attributes:
_name (string): The player's name.
_move (Move): The player's last move.
"""
def __init__(self, players=list)... |
class FibonacciImpl:
arr = [0,1,1]
def calculate(self, num: int):
if num < len(self.arr):
return self.arr[num]
else:
for i in range(len(self.arr)-1, num):
new_fib = self.arr[i-1] + self.arr[i]
self.arr.append(new_fib)
return se... |
class Color(object):
def __init__(self, rgb_value, name):
self.rgb_value = rgb_value
self.name = name
if __name__ == "__main__":
c = Color("#ff0000", "bright_red")
print(c.name)
c.name = "red"
|
def balanced_brackets(inp):
# if odd number, can't be balanced
if len(inp) % 2 is not 0: return False
# opening brackets
opening = set('[{(')
s = [] # functions as a stack (last in, first out)
for c in inp:
# if no items in stack, add first character
if len(s) is 0: s.append(c)
else:
# if ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : constant.py
@Contact : 379327479@qq.com
@License : MIT
@Modify Time @Author @Version @Description
------------ ------- -------- -----------
2021/10/25 16:34 zxd 1.0 None
"""
APP_PACKAGE = 'com.ss.android.u... |
def binarySearchSortedArray(nums, s):
"""
Args:
{List<int>} nums
{int} s
Returns:
{boolean} Whether s is in nums.
"""
# Write your code here.
beginning = 0
end = len(nums) - 1
found = False
while beginning <= end and not found:
mid = (beginning + end) // 2
... |
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if not root:
return 0
def dfs(root: TreeNode, sum: int) -> int:
if not root:
return 0
return (sum == root.val) + \
dfs(root.left, sum - root.val) + \
dfs(root.right, sum - root.val)
return d... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author JourWon
# @date 2022/1/7
# @file ListNode.py
def __init__(self, x):
self.val = x
self.next = None
|
#!/usr/bin/env python
def main():
print("Start training")
x_array = [1.0, 2.0, 3.0, 4.0, 5.0]
# y = 2x + 3
y_array = [5.0, 7.0, 9.0, 11.0, 13.0]
instance_number = len(x_array)
learning_rate = 0.01
epoch_number = 100
w = 1.0
b = 1.0
for epoch_index in range(epoch_number):
w_grad = 0.0
... |
def chunks(messageLength, chunkSize):
chunkValues = []
for i in range(0, len(messageLength), chunkSize):
chunkValues.append(messageLength[i:i+chunkSize])
return chunkValues
def leftRotate(chunk, rotateLength):
return ((chunk << rotateLength) | (chunk >> (32 - rotateLength))) & ... |
'''
- Leetcode problem: 937
- Difficulty: Easy
- Brief problem description:
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
Each word after the identifier will consist only of lowercase letters, or;
Ea... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 14:53:39 2021
@author: akladke
"""
s = "azcbobobegghakl"
count = 0
for i in range(len(s)):
if s[i:i+3] == "bob":
count += 1
print("Number of times bob occurs is: " + str(count))
|
def add_arg(*args, **kwargs):
"""Used for shell argument parsing"""
return (args, kwargs)
def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out
def unescape(str):
... |
"""
1) Data structure: Dictionary, Tuple, Set
Assignment
1) create dictionary of user data
2) Create list of user data dictionary with minimum of 10 user data
3) create 5 dictionaries which have list values
"""
# [] = List
# {} = Dictionary
# () = Tuple
dictionary_variable = {
'name': 'Kiran',
'address': 'ho... |
n, k = map(int, input().split())
participants = list(map(int, input().split()))
target_score = participants[k - 1]
total = 0
for participant in participants:
if participant >= target_score and participant > 0:
total += 1
print(total) |
'''Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação.
Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time da Bragantino.'''
print('-='*10)
print... |
"""
Advent of Code 2017
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> ...
Input was:
368078
Answer is:
65, (-4, -4) =
369601
"""
DIR_RIGHT = 1
DIR_UP = 2
DIR_LEFT = 3
DIR_DOWN = 4
i = 1
data = { (0,0): 1 } # key = coords, val = position
data_vals = { (0,0): 1 }
x = 0
y... |
# https://leetcode.com/problems/find-all-anagrams-in-a-string/
class Solution(object):
# Submitted by Jiganesh
# TC : O(LenP * LenS)
# SC : O(LenP + LenS)
# Runtime: 148 ms, faster than 50.90% of Python online submissions for Find All Anagrams in a String.
# Memory Usage: 1... |
""" note that the whole configuration is passed in the
form of a Python dictionary """
{
# App metadadta
'service_metadata': {
'service_name': 'iris',
'service_version': '0.1',
},
# Configure the dataset loader to help loading the data from the CSV file
'dataset_loader_train': {
... |
a,b,c,d = map(int, input().split())
if b > c and d > a and (c+d) > (a+b) and c > 0 and d > 0 and a%2 == 0:
print("Valores aceitos")
else:
print("Valores nao aceitos") |
# creo el string
letters = "abcdefghij"
numbers = "0123456789"
# La sintáxis del slicing es la siguiente string[start:end:step]
# start = start || start es el indice en el que empieza el slice
# end = end-1 || end es el elemento en el que termina el slice
# step = step || step es el avance del slice (por defecto es 1, ... |
def get_all_directions_values(row, col, board):
total = 0
total += int(board[0][col])
total += int(board[-1][col])
total += int(board[row][0])
total += int(board[row][-1])
return total
def outside_board(shoot):
row, col = shoot
return 0 > row or row > 6 or 0 > col or col > 6
def bu... |
bridgelist = []
with open('input.txt') as infile:
for line in infile.readlines():
i, o = line.strip().split('/')
i, o = int(i), int(o)
bridgelist.append((i,o,))
def build_bridge(bridgelist, already_used=None, current_value=0, connector_used=0):
if already_used == None:
already_u... |
# https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
length = 0
curNum = None
for idx in range(len(nums)):
if nums[idx] != curNum:
curNum = nums[idx]
... |
class workspaceApiPara:
getWorkspace_POST_request = {"ad_group_list": {"type": list, "default": []}}
setWorkspace_POST_request = {},
updateWorkspace_POST_request = {},
getWorkspace_GET_response = {},
setWorkspace_POST_response = {}
updateWorkspace_POST_response = {} |
#Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
#A) quantas pessoas tem mais de 18 anos.
#B) quantos homens foram cadastrados.
#C) quantas mulheres tem menos de 20 anos.
maiores = homens = mulheres... |
expected_output = {
"interfaces": {
"Port-channel1": {
"name": "Port-channel1",
"protocol": "lacp",
"members": {
"GigabitEthernet2": {
"interface": "GigabitEthernet2",
"oper_key": 1,
"admin_key": ... |
#Kullanıcıdan alınan değer uzunluktaki bir dizi içindeki üçün katları için "Fizz", beşin katları için "Buzz",
#hem beş hem de üçün katları için "FizzBuzz", her üçü de değilse sayının kendisini yazdırır.
def fizzbuzz(number):
if number%3==0 and number%5==0:
return "FIZZBUZZ !"
elif number%3==0 and numbe... |
#
# PySNMP MIB module CONTIVITY-INFO-V1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONTIVITY-INFO-V1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
def domain_name(url):
st = url.replace("http://", "")
tt = st.replace("https://","")
ut = tt.replace("www.","")
s = ut.split(".")
return s[0]
print(domain_name("http://github.com/carbonfive/raygun")) |
START_INITIALIZATION_PD = 'START_INIT_PD'
BASE_FOR_ACCEPT = 'PD_'
CORRECT = 'PD_CORRECT'
WRONG = 'PD_WRONG'
BASE_FOR_PD_MENU = 'MENU_EDIT_'
BACK = 'MENU_EDIT_BCK'
REMOVE_KEYBOARD = 'MENU_EDIT_RMV_KBRD'
MENU_EDIT_PD_MAIN = 'MENU_EDIT_PD_MAIN'
MENU_EDIT_PD_PD = 'MENU_EDIT_PD_PD'
MENU_EDIT_CONTACTS = 'MENU_EDIT_CNTCTS... |
class BrainError(Exception):
"""
base class of brain_plasma exceptions
"""
pass
class BrainNamespaceNameError(BrainError):
pass
class BrainNamespaceRemoveDefaultError(BrainError):
pass
class BrainNamespaceNotExistError(BrainError):
pass
class BrainNameNotExistError(BrainError):
... |
print('-='*20)
print('Analizador de triangulos')
print('-='*20)
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r2 <r1 + r3 and r3 < r1 +r2:
print('Os segmentos acima PODEM FORMAR triangulo')
else:
print('Os segmentos... |
fullSWOF2DPath='../FullSWOF_2D'
def getFullSWOF2DPath():
return fullSWOF2DPath
|
# INSTRUCTIONS
# ------------
# Create ```config.py``` in this folder, take this file as reference.
# ```config.py``` will not be committed to Git, added in .gitignore
# Add project settings and API_KEYS here...
NEWS_API_KEY = ""
|
# -*- coding: utf-8 -*-
'''
File name: code\maximum_path_sum_ii\sol_67.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #67 :: Maximum path sum II
#
# For more information see:
# https://projecteuler.net/problem=67
# Problem Statement
''... |
#
# PySNMP MIB module DIFF-SERV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DIFF-SERV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
# 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 hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
# return true, if adding up values alo... |
USERNAME = 'super.user.1'
PASSWORD = 'X!16a99a4e'
CONSUMER_KEY = 'f3haancaj0vm4lkx2erk3uwdzy2elz00of513u5w'
TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyIiOiIifQ.Qjz0-kry1Yb7PH0Pw1PbRWrgaqsFYPbac3RHQ-eykk4'
# API server URL
BASE_URL = "https://openlab.openbankproject.com"
API_VERSION = "v3.0.0"
CONTENT_JSON =... |
class Alerts:
def _init_ (self,Alert_Id, Alert_Name, Alert_Code):
self.Alert_Id= AlertId
self.Alert_Name = Alert_Name
self.Alert_Code = Alert_Code
|
def ggg(x, y=5):
"""
Привет, меня зовут f и я люблю пельмени
"""
z = x**2 + 2*x*y + y**2
return z |
class Solution:
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
chars1 = list(num1)
chars2 = list(num2)
chars1.reverse()
chars2.reverse()
i, j, sumValue, carry = 0, 0, 0, 0
res = list()
... |
n = int(input('me diga um numero: '))
s = n + 1
a = n - 1
print ('o sucessor de {} e {}'. format(n, s))
print ('o antecessor de {} e {}'.format(n, a))
|
def main():
a = 0
while True:
a += 1
if a % 1000 == 0:
print(a)
if __name__ == "__main__":
main()
|
def get_words(wordlist, resume=None):
with open(wordlist) as f:
raw_words = f.read()
found_resume = False
words = list()
for word in raw_words.split():
if resume is not None:
if found_resume:
words.append(word)
else:
if word == re... |
# Exercício 095 - Aprimorando os Dicionários
time = []
while True:
jogador = {'nome': input('Nome do Jogador: ')}
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
gols = [int(input(f'\tQuantos gols na partida {i+1}? ')) for i in range(partidas)]
jogador['gols'] = gols
time.appen... |
def sort_dictionary(dict_unsort: dict) -> dict:
"""Формирует словарь, отсортированный по ключам (по алфавиту по всей глубине вложенности)
:param dict_unsort: словарь передаваемый для сортировки
:return: новый словарь, отсортированной по ключам по алфавиту"""
dict_sort = {}
key_list = sorted(list(... |
def fact(x):
if x == 1:
return 1
return x * fact(x-1)
if __name__=='__main__':
print("fact(5) = %s" % fact(5))
|
"""
Utility functions for CICERO-SCM adapter
"""
def _get_unique_index_values(idf, index_col, assert_all_same=True):
"""
Get unique values in index column from a dataframe
Parameters
----------
idf : :obj:`pd.DataFrame`
Dataframe to get index values from
index_col : str
Colum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.