content stringlengths 7 1.05M |
|---|
def even(n):
return n/2
def odd(n):
return (3*n)+1
if __name__ == '__main__':
appeared = []
z = 0
x = 0
for i in range(1,1000000):
y = 0
a = i
while a != 1:
if i not in appeared:
if a % 2 == 0:
a = even(a... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def arm_toolchains_repositories():
rules_pkg()
org_linaro_components_toolchain_gcc_5_3_1()
raspi_components_toolchain_gcc_4_8_3()
def org_linaro_components_toolchain_gcc_5_3_1():
http_archive(
name = 'org_linaro_components_to... |
class Solution:
def solve(self, a, b):
def bin_sum(x,y,c):
x = int(x)
y = int(y)
c = int(c)
si = (x+y+c)%2
c = (x+y+c)//2
if c:
c = 1
return str(si),str(c)
n , m = len(a),len(b)
... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Defines exceptions.'''
class CuteBaseException(BaseException):
'''
Base exception that uses its first docstring line in lieu of a message.
'''
def __init__(self, message=None):
# We use `None` as the de... |
"""
Top-level package for Python AvSong.
"""
__app_name__ = "pyavsong"
__version__ = "0.1"
|
class RoutingRulesList:
TITLE = "Maintain case routing rules"
CREATE_BUTTON = "Create new routing rule"
NO_CONTENT_NOTICE = "There are no registered routing rules at the moment."
ACTIVE = "Active"
DEACTIVATED = "Deactivated"
DEACTIVATE = "Deactivate"
REACTIVATE = "Reactivate"
EDIT = "Edi... |
__all__ = ["_nsgroup", "association_api", "association_service_api", "codesystem_api",
"codesystem_service_api", "codesystemversion_api", "codesystemversion_service_api", "conceptdomain_api",
"conceptdomain_service_api", "conceptdomainbinding_api", "conceptdomainbinding_service_api",
"c... |
"""
A `Command` is something that causes a change of state to
a persistant store.
"""
class Command(object):
"""
Inherit `Command` for specific commands that cause a chage
of state in a persisted database.
"""
def __init__(self, *args, **kwargs):
pass
def run(self):
"""
... |
# webex integration credentials
webex_integration_client_id = ""
webex_integration_client_secret= ""
webex_integration_redirect_uri = "http://localhost:5000/webexoauth"
webex_integration_scope = "spark:all meeting:schedules_write"
|
"""Top-level package for openapi-to-markdown."""
__author__ = """Shinji Matsumoto"""
__email__ = 'shinji.mtsmt@gmail.com'
__version__ = '0.1.0'
|
# Advent of Code - Day 6 - Part Two
class LanterFishPopulation:
def __init__(self, initial_state):
self.population = initial_state
def tick(self, reset, gestation):
spawn_count = self.population[0]
# decrement all lantern fish timers
for k in self.population.keys():
... |
#conexoes entre pontos
conexoes = {}
conexoes["Casa"] = {"Santo Amaro"}
conexoes["Santo Amaro"] = {"Pinheiros","Santa Cruz"}
conexoes["Santa Cruz"] = {"Santo Amaro", "Sé"}
conexoes["Pinheiros"] = {"República", "Luz","Presidente Altino"}
conexoes["Presidente Altino"] = {"Barra Funda"}
conexoes["República"] = {"Barra Fu... |
nombreACalculer = str(2**1000)
somme=0
for i in nombreACalculer:
somme += int(i)
print(somme)
input() |
# --------------
print(bool)
# --------------
print(bool)
|
pytest_plugins = ("pytester",)
def test_help_message(testdir):
result = testdir.runpytest("--help")
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines(
[
"stress:",
"*--delay=DELAY*The amount of time to wait between each test loop.",
"*--ho... |
class Solution:
def nextClosestTime(self, time):
t = sorted(set(time))[:-1]
nex = {a: b for a, b in zip(t, t[1:])}
for i, d in enumerate(time[::-1]):
if d in nex:
if i == 0:
return time[:4] + nex[d]
elif i == 1 and nex[d] < '6... |
"""
******
######
******
######
"""
# 4 6
for r in range(4): # 0 1 2 3
for c in range(6):
if r % 2 == 0:
print("*", end="")
else:
print("#", end="")
print()
|
class Solution:
#Function to return a list containing the DFS traversal of the graph.
def dfs(self,i,vis,q,adj):
vis[i]=1
q.append(i)
for i in adj[i]:
if(vis[i]==0):
self.dfs(i,vis,q,adj)
def dfsOfGraph(self, V, adj):
vis=[0 for i in... |
# -*- coding: utf-8 -*-
timeout = 8
keysize = 512
operator_root_path="/api/1.2"
operator_cr_path="/cr"
operator_slr_path="/slr"
account_management_url="http://myaccount.dy.fi/"
account_management_username="test_sdk"
account_management_password="test_sdk_pw"
operator_url="http://localhost:5000"
service_url ="http://... |
def in1to10(n, outside_mode):
if not outside_mode and n>=1 and n<=10:
return True
elif outside_mode:
if n<=1 or n>=10:
return True
else:
return False
else:
return False
|
''' Serialize objects into SQLITE database calls. '''
class Serializable:
''' Serializable class that implements methods for objects wishing to
serialize to SQLITE tables. This is done with a serialize table that maps
property names to SQLITE table columns. When insert_into is called it takes
the prop... |
# FMSPy - Copyright (c) 2009 Andrey Smirnov.
#
# See COPYRIGHT for details.
"""
RTMP (Real Time Messaging Protocol) implementation.
U{http://en.wikipedia.org/wiki/Real_Time_Messaging_Protocol}
"""
|
#!/usr/bin/env python3
SLIDE_WINDOWS = 3
f = open("input.txt", "r")
window = []
for i in range(SLIDE_WINDOWS):
window.append(int(f.readline()))
count = 0
for cur in f:
#print(f'current: {cur}')
window.append(int(cur))
if sum(window[1:]) > sum(window[0:-1]):
count +=1
window.pop(0)
print(... |
# Copyright (c) 2017 StackHPC Ltd.
#
# 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 writ... |
def scale_01(feature,n_feature):
for i in range(n_feature):
feature_i=feature[:,i]
feature[:,i]=0+(feature_i-min(feature_i))/(max(feature_i)-min(feature_i))
return feature |
# -*- coding: utf-8 -*-
"""Module defining Interval model and operations"""
# ActiveState recipe 576816
class Interval(object):
"""
Represents an interval.
Defined as closed interval [start,end), which includes the start and
end positions.
Start and end do not have to be numeric types.
"""
... |
class DriverBase(object):
def __init__(self, wheel_radius=0.06, wheel_track=0.33):
self.wheel_speeds = [0.0, 0.0, 0.0, 0.0]
self.wheel_radius = wheel_radius
self.wheel_track = wheel_track
def set_motors(self, linear, angular):
raise NotImplementedError()
class DriverStraight... |
# -*- coding: utf-8 -*-
#
# Custom package settings
#
# Copyright (C)
# Honda Research Institute Europe GmbH
# Carl-Legien-Str. 30
# 63073 Offenbach/Main
# Germany
#
# UNPUBLISHED PROPRIETARY MATERIAL.
# ALL RIGHTS RESERVED.
#
#
name = 'ToolBOSCore'
package = 'ToolBOSCore'
version ... |
INSTALLED_APPS = (
'automatica_prometheus',
)
TELEGRAM_BOT_NAME = 'name_bot'
|
#Exercise 5.2.1
def check_fermat(a,b,c,n):
a = int(a)
b = int(b)
c = int(c)
n = int(n)
if n>2 and a>0 and b>0 and c>0 and a**n + b**n == c**n:
print('Holy smokes, Fermat was wrong!')
else:
print("No, that doesn't work")
#Exercise 5.2.2
def prompting_fermat():
a = int(input('... |
a,b,c=map(int,input().split())
x,d=0,0
while x<c:
d+=1
x+=a
if d%7==0: x+=b
print(d) |
load("//csharp:csharp_grpc_compile.bzl", "csharp_grpc_compile")
load("//:compile.bzl", "invoke_transitive")
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library")
def csharp_grpc_library(**kwargs):
kwargs["srcs"] = [invoke_transitive(csharp_grpc_compile, "_pb", kwargs)]
kwargs["deps"] = [
"... |
# Programa baseado no algoritmo de Zeller, que calcula o dia da semana em que uma determinada data caiu (ou cairá).
year = 2017
month = 1
day = 9
def zellerAlgorithm(year, month, day):
if month in [1, 2]:
y1 = year - 1
m1 = month + 12
else:
y1 = year
m1 = month
y2 = y1 % 10... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
def is_number(s):
"""
Take a string and determin if it is a number
Arguments:
s (str): A string
Returns:
bool: True if it is a number, False otherwise
"""
try:
float(s)
return True
except ValueError:
return False
def check_info_annotation(a... |
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root_node = self.TrieNode()
def getNewNode(self):
return TrieNode()
def char_to_index(self, char):
return ord(char) - ord('a')
... |
def reverseWords(string: str) -> str:
words = " ".join(string.split())
words = [word for word in words.split(' ')]
left, right = 0, len(words) - 1
while left < right:
temp = words[left]
words[left] = words[right]
words[right] = temp
left += 1
right -= 1
... |
pessoasmaisdezoito=0
quanthomens=0
mulheresmensvinte=0
print('-'*23)
print('- CADASTRO DE PESSOAS -')
print('-'*23)
while True:
idade = int(input('Informe sua idade: '))
while True:
sexo = str(input('Informe o sexo [M/F] ')).strip().upper()[0]
if sexo in 'FM':
break
print('-' * 2... |
# -*- coding: utf-8 -*-
"""Dork Game main module.
"""
__version__ = '0.1.0'
__author__ = ", ".join([
"Luke Smith",
])
|
bind = "0.0.0.0:5000"
workers = 1
worker_class = "eventlet"
reload = True
|
'''
http://pythontutor.ru/lessons/ifelse/problems/chess_board/
Заданы две клетки шахматной доски.
Если они покрашены в один цвет, то выведите слово YES, а если в разные цвета — то NO.
Программа получает на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, потом для вто... |
class Timespan:
def __init__(
self,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: int = 0,
milliseconds: int = 0):
conv_days = days * 3600 * 24 * 1000
conv_hours = hours * 3600000
conv_minutes = minutes * 60... |
def merge(alist):
if len(alist) > 1:
mid = len(alist)//2
left = alist[:mid]
right = alist[mid:]
merge(left)
merge(right)
i,j,k = 0, 0, 0
while i<len(left) and j<len(right):
if left[i]<right[j]:
alist[k] = left[i]
i... |
exp = str(input('DIgite a expressao: '))
if exp.count('(') == exp.count(')'):
print('Não a parenteses faltando')
for s in exp:
if s in '+-*/':
p = exp.index(s)
n1 = exp[p - 1]
n2 = exp[p + 1]
if not n1.isalnum() and not n2.isalnum():
print('algo de errado nao esta ce... |
class MACAddress:
@staticmethod
def isValid(macAddress):
sanitizedMACAddress = macAddress.strip().upper()
if sanitizedMACAddress == "":
return False
# Ensure that we have 6 sections
items = sanitizedMACAddress.split(":")
if len(items) != 6:
return... |
# -*- coding: utf-8 -*-
"""
Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
Permission to use, copy, modify, and distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
he... |
# GYP file to build experimental directory.
{
'targets': [
{
'target_name': 'experimental',
'type': 'static_library',
'include_dirs': [
'../include/config',
'../include/core',
],
'sources': [
'../experimental/SkSetPoly3To3.cpp',
'../experimental/SkSetP... |
def gem_id_compat(ob):
"""Compatibility for old files from v1.5, should be removed at some point"""
if ob.type == 'MESH' and 'gem' in ob.data:
if 'gem' not in ob:
ob['gem'] = {}
for k in ('TYPE', 'type'):
if k in ob.data['gem']:
ob['gem']['stone'] = ob.data['gem'][k]
for k in ('CUT', 'cut'):
... |
# N stands for North
# S stands for south
# E stands for east
# W stands for west
#Oeste es West y Este es East
#NoSe == NWSE North and South are opposites, so are West and East
# N
# |
# W---+--E
# |
# S
# L stands for Left
# R stands for right
# F sta... |
def divisors_count(n):
count = 0
for i in range(1, n+1):
if (n % i) == 0:
count += 1
return count
def triangulate(n):
y = [int(x) for x in list(str(n))]
return sum(y)
triangle = 1
while divisors_count(triangle) <= 500:
triangle += triangulate(triangle)
print(triangle)
|
class Solution:
def countElements(self, nums: List[int]) -> int:
nums.sort()
k=0
for i in nums:
if i+1 in nums:
k=k+1
return k
|
# -*- coding: utf-8 -*-
N = int(input())
answer = " ".join(["Ho"] * N) + "!"
print(answer) |
'''
The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners.
If there are no ... |
for _ in range(int(input())):
n,k=map(int,input().split())
a=bin(k)[2:]
a=str(a)
a=a.zfill(n)
a=a[::-1]
print(int(a,2))
|
'''
Goals:
-Have more options
-Make code much more clean
'''
class Temperature:
def __init__(self, degrees, kind):
self.degrees = degrees
self.kind = kind
def input(self):
Player_input = float(input("How many degrees?"))
self.degrees = Player_input
def Repeat():
while True:
try:
... |
# -*- coding: utf-8 -*-
'''
This module contains basic form access control classes.
You can set permissions to form and fields like this::
class SampleForm(form.Form):
permissions = 'rwcx'
fields=[fields.Field('input',
permissions='rw')]
or define your own permission log... |
#!/usr/bin/env python
class Link(object):
"""docstring for Link"""
def __init__(self, url):
super(Link, self).__init__()
self.url = url
self.in_link = 1
self.out_link = 0
self.visited = False
self.round = 1
self.outs = set()
self.ins = set()
... |
# WAP in python to check the given year is leap or not.
year=int(input("Enter Year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a le... |
def power(n, m):
if m == 0:
return 1
elif m == 1:
return n
return (n*power(n, m-1))
print(power(2,3)) |
def convert_to_strsid(binsid):
if len(binsid) < 24:
return None
dashes = int(binsid[2:4])
list_sid = ["S", "1"]
range_parts = range(16, dashes*8+16, 8)
list_sid.append(str(int(binsid[4:16], 16)))
for i in range_parts:
list_sid.append(str(int(invert_endian(binsid[i:i+8]), 16)))
... |
# global settings
data_root = "../../data/winequality_dataset/"
feature_save_dir = data_root + "features/"
img_save_dir = data_root + "imgs/"
# split chunk settings
split_chunk_path = data_root + 'chunk/'
raw_train_file = dict(
file_path=data_root + 'raw_data/train.csv',
size=3397,
split_mode=['train', 'va... |
Import("env")
src_filter = ["+<TRB_MCP23017.h>"]
env.Replace(SRC_FILTER=src_filter)
build_flags = env.ParseFlags(env['BUILD_FLAGS'])
cppdefines = build_flags.get("CPPDEFINES")
if "TRB_MCP23017_ESP_IDF" in cppdefines:
env.Append(SRC_FILTER=["+<TRB_MCP23017.c>", "+<sys/esp_idf>"])
if "TRB_MCP23017_ARDUINO_WIRE" in ... |
SEQUENCE_FILE = "data\\test_action_20_maxSeq15_20K.txt"
CRASH_INDEX = "1"
# SEQUENCE_FILE = "data\\activityseq_balanced_2018-02-05_2018-02-09_Excel_apphangb1_Production.tsv"
# SEQUENCE_FILE = r"C:\Users\mahajiag\Documents\tmp\crash\eventseq_balanced_2018-02-05_2018-02-09_Excel_apphangb1_Production.tsv"
ROOT_DIR = 'tf... |
major_colors = ["White", "Red", "Black", "Yellow", "Violet"]
minor_colors = ["Blue", "Orange", "Green", "Brown", "Slate"]
def color_mapping():
cp_rows = []
for i, major_color in enumerate(major_colors):
for j, minor_color in enumerate(minor_colors):
print_color_map((i * 5 + j)+1 ... |
'''
Nd Genie Ops Object Outputs for IOSXR.
'''
class NdOutput(object):
ShowIpv6Neighbors = {
'interfaces': {
'GigabitEthernet0/0/0/0.90': {
'interface': 'Gi0/0/0/0.90',
'neighbors': {
'fe80::f816:3eff:fe26:1224': {
... |
"""Transaction unit."""
class TransactionUnit:
"""Transaction unit."""
def __init__(
self: "TransactionUnit", txid: str, fee: str, weight: str, parents: str
) -> None:
"""Initialize transaction unit.
Args:
txid (str): Txn ID
fee (str): fee of txn
... |
def solution():
sum = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 == 0: sum += i
return sum
def test_MultiplesOf3And5():
assert solution() == 233168 |
__all__ = ["__version__", "__version_info__"]
__version__ = "0.0.3"
__version_info__ = tuple(int(x) for x in __version__.split("."))
|
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
bot.reply_to(message, "You are banned!")
return
markup = types.ReplyKeyboardMarkup()
numbers = list(range(3, 300... |
src = Split('''
uart_test.c
''')
component = aos_component('uart_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def pad(s: bytes, bs=8) -> bytes:
pad_size = bs - (len(s) % bs)
return s + bytes([pad_size] * pad_size)
def unpad(s: bytes) -> bytes:
pad_size = s[-1]
return s[:-pad_size]
if __name__ == '__main__':
data = b'Hello'
pad... |
#Helpfer Function:
def create_scoring_schema(number_objects):
_field = "id*:int64,image:blob,_image_:blob,_nObjects_:double,"
for obj in range(0,number_objects):
_field += "_Object" + str(obj) + "_:string,"
_field += "_P_Object" + str(obj) + "_:double,"
_field += "_Object" + str(obj) + "... |
def load():
with open("input") as f:
return [int(x) for x in f.read().strip().split(",")]
def align_crabs():
crabs = load()
min_fuel = None
for pos in range(min(crabs), max(crabs) + 1):
fuel = sum(abs(c - pos) for c in crabs)
min_fuel = fuel if min_fuel is None else min(min_fu... |
a = [
1, 2, 3, 6, 10, 14,
]
t = 10
l = 0
r = len(a) - 1
while l != r:
c = (l + r) // 2
if a[c] < t:
l = c + 1
elif a[c] > t:
r = c - 1
else:
r = l = c
print(l, r, a[l], a[r])
|
# Runtime: 1007 ms, faster than 66.76% of Python3 online submissions for 3Sum.
# Memory Usage: 18.1 MB, less than 38.93% of Python3 online submissions for 3Sum.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
res = []
for i in range(len(nums)):
... |
## Script eleminates rows that are having zero RPKM value then, divides replicate A of each damage type to corresponding XR-seq damage repair.
# If DMG_PPD_column and DMG_CPD_column column number changed to the replicate B of (6-4)PP and CPD damage, the Replicate B normalization could be performed.
### REMOVE RO... |
# SPDX-FileCopyrightText: 2021 Mark Komus
# SPDX-License-Identifier: MIT
"""
LED glasses mappings
"""
# Maps to link IS31FL3741 LEDs to pixels
# Full LED glasses 18 x 5 matrix
glassesmatrix_ledmap = (
65535,
65535,
65535, # (0,0) (clipped, corner)
10,
8,
9, # (0,1) / right ring pixel 20
... |
# Adjusts numerical digits by a specified amount
class Offsetter:
# numericOffset is only altered by init
numericOffset=0
def __init__(self, offset):
self.numericOffset = int(offset)
# apply offset
def setOff(self, input_int):
return (( int(input_int) + self.numericOffset ) % 10)
# remov... |
#!/usr/bin/env python3
"""
Node Class
This are the single blocks in the grid, which can be blocked or passable.
"""
class Node(object):
def __init__(self, x, y, blocked=False):
self.x = x
self.y = y
self.blocked = blocked
# calculate the distance to another node with the normal and ... |
## Sum of Intervals
## 4 kyu
## https://www.codewars.com/kata/52b7ed099cdc285c300001cd
def sum_of_intervals(intervals):
seen = set()
for (low,high) in intervals:
for length in range(low, high):
seen.add(length)
return len(seen)
|
produtos_prec = ("Croissant", 2.0, "Leite", 5.0, "Mix de grãos", 8.0 , "Mix de nozes", 7.55,
"Café", 3.45, "Bolo", 13.66, "Torta gelada", 6.77, "Suco", 3.27 )
print("="*38)
print(f"{'LISTAGEM DE PREÇOS':^38}")
print("="*38)
prod = 0
while prod < len(produtos_prec):
print(f'{produtos_prec[prod]:.... |
# https://leetcode.com/problems/guess-number-higher-or-lower/
# We are playing the Guess Game. The game is as follows:
#
# I pick a number from 1 to n. You have to guess which number I picked.
#
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
#
# You call a pre-defined API guess(int n... |
#6. 有有这样一个字典d = {"chaoqian":87, “caoxu”:90, “caohuan”:98, “wuhan”:82, “zhijia”:89}
# 1)将以上字典按成绩排名
d = {"chaoqian":87,"caoxu":90,"caohuan":98,"wuhan":82, "zhijia":89}
s = sorted(d.items(), key = lambda k:k[1],reverse = True)
print(s)
|
m,n,field = 1,1,0
while(m!= 0 and n!=0): #Salida del programa
tamaño = input("")
tamaño = tamaño.split()
m = int(tamaño[0]) #Obtenemos los datos del tamaño del buscaminas
n = int(tamaño[1])
if(n<0 or m>100): #Verificacion de dimensiones
print("dimensiones incorrectas")
m = 0
... |
def isPalindrome(number):
ispalindrome = True
list = intToList(number)
#if list is not an even number it can't be a palindrome
if len(list) % 2 != 0:
ispalindrome = False
for x in range(0,int(len(list)/2)):
if(ispalindrome):
ispalindrome = (list[x] == list[len(list)-(x+... |
sites = [
'https://yii2-menu.pceuropa.net/',
'https://pceuropa.net',
]
smtp = {
'server': 'smtp@example.com:587',
'login': 'info@example.com',
'password': 'pass',
'From': 'info@example.com',
'to': 'info@example.com',
}
|
broker_url = 'amqp://guest:guest@localhost:5672//'
accept_content = ['application/json']
result_serializer = 'pickle'
task_serializer = 'pickle'
|
word = "bottles"
for beer_num in range(99, 0, -1):
print(beer_num, word, " of beer on the wall,")
print(beer_num, word, " bottles of beer.")
print("You take one down,")
print("You pass it around,")
if (beer_num == 1):
print("No more bottles of beer on the wall.")
else:
new_num =... |
"""This problem was asked by Oracle.
Given a binary search tree, find the floor and ceiling of a given integer.
The floor is the highest element in the tree less than or equal to an integer,
while the ceiling is the lowest element in the tree greater than or equal to an integer.
If either value does not exist, retu... |
## Mel-filterbank
mel_n_channels = 80
win_length = 512
hop_length = 128
n_fft = 512
mel_window_length = 25 # In milliseconds
mel_window_step = 10 # In milliseconds
## Audio
sampling_rate = 24000
# Number of spectrogram frames in a partial utterance
partials_n_frames = 240 # 2400 ms
# Number of spectrogram fra... |
class CollapseRenderMixin:
render_template = "djangocms_frontend/bootstrap5/collapse.html"
class CollapseContainerRenderMixin:
render_template = "djangocms_frontend/bootstrap5/collapse-container.html"
def render(self, context, instance, placeholder):
instance.add_classes("collapse")
retur... |
#
# PySNMP MIB module AtiL2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AtiL2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:33:22 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:23... |
TEST_CHANGES = {
('+1', '+1', '+1'): 3,
('+1', '+1', '-2'): 0,
('-1', '-2', '-3'): -6,
}
TEST_CHANGES_2 = {
('+1', '-1'): 0,
('+3', '+3', '+4', '-2', '-4'): 10,
('-6', '+3', '+8', '+5', '-6'): 5,
('+7', '+7', '-2', '-7', '-4'): 14,
}
def calibrate(deltas):
frequency = 0
for delta i... |
"""
* Assignment: Protocol Descriptor ValueRange
* Complexity: easy
* Lines of code: 9 lines
* Time: 13 min
English:
1. Define descriptor class `ValueRange` with attributes:
a. `name: str`
b. `min: float`
c. `max: float`
d. `value: float`
2. Define class `Astronaut` with attribu... |
if __name__ == '__main__':
"""
https://archive.ics.uci.edu/ml/datasets/Ecoli
"""
replacement = ""
with open('ecoli.data') as file:
line = file.readline()
i = 1
while line:
i += 1
elements = [el.strip() for el in line.split(' ')][1:]
elem... |
# Crie um programa que leia um numero qualquer pelo teclado e mostre na tela a sua porção inteira.
''' from math import floor, trunc
num = float(input('Digite um número com casas decimais: '))
print(f'\nA porção inteira de {num} é {floor(num)}.')'''
# ou
num = float(input('Digite um número com casas decimais: '))
prin... |
years = (1990, 1991, 1993, 1991, 1993, 1993, 1993)
print("Years: ", years)
print("\n")
# Trả về số lần xuất hiện của 1993
print("years.count(1993): ", years.count(1993))
# Tìm vị trí xuất hiện 1993
print("years.index(1993): ", years.index(1993))
# Tìm vị trí xuất hiện 1993, bắt đầu từ chỉ số 3
print("years.index(1... |
class Solution:
def reinitializePermutation(self, n: int) -> int:
perm = []
for i in range(n):
perm.append(i)
def op(perm):
arr = [0] * len(perm)
for i in range(len(perm)):
if i % 2 == 0:
arr[i] = perm[int(i / 2)]
... |
"""
zhushi
python组成
程序由模块组成
模块由语句,函数,类,数据
语句包含表达式
表达式建立并处理数据对象
python核心类型
数字:int-- 0和负数,float,布尔True/值为1,False/值为0
字符串:str
列表
字典
查看变量类型:type()
算数运算符+,-,*,/,//(地板除--取整),**(幂运算 --求次方),%(取余) 除数不能为0
+ 一,数值运算(同类型相加)
二,字符类-拼接字符串
- 一,数值运算
* 一,数值运算
二... |
E_HOOK_ALREADY_EXISTS = u'Hook already exists on this repository'
def matches_github_exception(e, description, code=422):
"""Returns True if a GithubException was raised for a single error
matching the provided dict.
The error code needs to be equal to `code`, unless code is
None. For each field in `... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.