content stringlengths 7 1.05M |
|---|
def depth(obj):
"""
"""
if obj == []:
return 1
elif isinstance(obj, list):
return 1 + max([depth(x) for x in obj])
else:
return 0
def nested_contains(L, value):
"""
"""
return True in [nested_contains(x, value) if isinstance(x, list) else x == value for x in ... |
class RequestAdapter(object):
"""
RequestAdapters bridge transmute's
representation of a request, with the framework's
implementation.
implement the unimplemented methods.
"""
@property
def body(self):
""" return the request body. """
raise NotImplementedError()
de... |
class Context:
def __init__(self):
self.data = {}
def __getitem__(self, key):
return self.data.get(self.convert_key(key), None)
def __setitem__(self, key, value):
self.data[self.convert_key(key)] = value
def get(self, key, default):
return self.data.get(self.convert_ke... |
#
# PySNMP MIB module S5-ETH-REDUNDANT-LINKS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/S5-ETH-REDUNDANT-LINKS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:59:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#
# PySNMP MIB module Wellfleet-DSUCSU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-DSUCSU-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# 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 la... |
pkgname = "u-boot-tools"
pkgver = "2021.10"
pkgrel = 0
build_style = "makefile"
make_cmd = "gmake"
make_build_target = "tools"
make_build_args = ["envtools", "HOSTSTRIP=:", "STRIP=:", "NO_SDL=1"]
hostmakedepends = ["gmake", "bison", "flex", "linux-headers"]
makedepends = ["openssl-devel", "linux-headers"]
pkgdesc = "Da... |
## https://www.youtube.com/watch?v=PGXwNophTOQ
class Produto:
def __init__(self, nome, preco):
self.nome = nome
self.preco = preco
def desconto (self, percentual):
self.preco = self.preco - (self.preco * (percentual / 100 ))
# Getters note que o nome do metodo Getter é o mesmo da v... |
"""
Test environment for The Bowling Game
"""
def log(message):
"""
generic log function
"""
print(message)
def init():
"""
set up environment for testing
"""
log("""
... environment setup started ...
""")
init()
|
def infer_ref_stem(src, ref):
n, remainder = divmod(len(ref), len(src))
if n < 0 or remainder != 0:
raise ValueError('mismatched src and refs. (len(src)=%d and len(ref)= %d)' % (len(src), len(ref)))
ref_stem = []
for i in xrange(0, len(ref), n):
ref_i = ref[i:i + n]
prefix = ref_... |
# Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in the array,
# and it should return false if every element is distinct.
# Example 1:
# Input: [1,2,3,1]
# Output: true
# Example 2:
# Input: [1,2,3,4]
# Output: false
# Exa... |
"""converted from ..\fonts\M32_8x14.bin """
WIDTH = 8
HEIGHT = 14
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x18\x3c\x3c\x3c\x18\x18\x00\x18\x18\x00\x00\x00'\
b'\x00\x36\x36\x36\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x6c\x6c\x6c\xfe\x6c\x6c\xf... |
rename_dictionary = {
"base": {
# key -> file_name: value -> list of dictionaries of words to replace.
'_data_manager.py': {
"words": [{"word": 'DataManager', "word_format": 'str_capitalize', 'word_type': 'append-left'}]
},
'_model_manager.py': {
"words": [{"w... |
#
# PySNMP MIB module DELL-WLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-WLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:38:17 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... |
class SyscallHandler:
def __init__(self, idx, name, arg_count, callback):
self.idx = idx
self.name = name
self.arg_count = arg_count
self.callback = callback
|
"""
Determine whether the sequence of elements `items` is ascending so that
each element is strictly larger than (and not merely equal to) the element
that precedes it.
Input: Iterable with ints.
Output: Bool.
The mission was taken from Python CCPS 109 Fall 2018. It is taught for
Ryerson Chang School of Continuing... |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals: List[Interval]) -> List[Interval]:
result = []
for interval in sorted(intervals, key=lambda x:x.start):
... |
#!/usr/bin/env python3
class ConfKeys:
''' A central place to keep all the cashshuffle-related config and
wallet.storage keys for easier code maintenance. '''
class Global:
'''The below go in the global config '''
# keys to be deleted if we ever see them. This keys are from older versions ... |
L = [
lambda x: x**2,
lambda x: x**3,
lambda x: x**4]
for f in L:
print(f(3)) # call the 3 lamnda expression, i.e. print 2**2, 2**3, 2**4
print('L[0]={0}'.format(L[0]))
print(L[0](2))
sum = lambda x, y : x + y
print('sum = ', sum(1, 2))
f = print
f('sum == ', sum(200,100)) |
# A rule that declares all the files needed to run an Android emulator.
# Targets that depend on this rule can then launch the emulator using
# the script that is generated by this rule.
def _avd_impl(ctx):
# Look for the source.properties file in the system image to get information
# about the image from.
... |
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
n = len(A)
i = 0
j = 1
while i < n:
while i < n and A[i] % 2 == 0:
i += 2
while j < n and A[j] % 2 == 1:
j += 2
if i < n:
A[i], A[j] = A[j], A[i]
i += 2
j += 2
return A... |
description = 'Devices for configuring Histogram Memory'
excludes = ['hm_config_strobo']
devices = dict(
hm_connector = device('nicos_sinq.devices.sinqhm.connector.HttpConnector',
description = "Connector for Histogram Memory Server",
byteorder = configdata('config.HISTOGRAM_MEMORY_ENDIANESS'),
... |
a=[]
n=int(input("Range: "))
for i in range(1,n+1):
num=int(input("Enter Values: "))
a.append(num)
for i in range(1,n+1):
if(i not in a):
print(i)
|
SCREENWIDTH = 288
SCREENHEIGHT = 512
FPS = 30
totalPlayers = 50
totalParents = 20
PIPEGAPSIZE = 150
BASEY = SCREENHEIGHT * 0.79
PLAYER_IMAGE = (
'assets/sprites/bluebird-upflap.png',
'assets/sprites/bluebird-midflap.png',
'assets/sprites/bluebird-downflap.png',
)
BACKGROUND_IMAGE = (
'assets/spr... |
# Version number of the latest code of conduct
CONDUCT_VERSION = 1
# Number of elements in each page of ratings
RATING_PAGE_SIZE = 10
# Threshold of number of ratings to display overall rating
NUM_RATING_SIGNIFICANT = 3
# Maximum number of characters of comment
MAX_COMMENT_LENGTH = 25565
|
"""Example Process class."""
class Process(object):
"""Example process."""
def __init__(self, num=0):
"""Initialize a new Process.
:num: Number
"""
self.num = num
def get_double(self):
"""Return the number."""
return {"double": (2 * self.num)}
|
_base_ = ['../_base_/base_dynamic.py', '../../_base_/backends/ncnn.py']
codebase_config = dict(model_type='ncnn_end2end')
onnx_config = dict(output_names=['detection_output'], input_shape=None)
|
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
""" sent when a user parts a subscribed voice channel"""
# TODO: Implement event
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018, Sujeet Akula <sujeet@freeboson.org>
# Distributed under terms of the MIT license.
__version__ = '0.1.0'
|
N = int(input())
S = input()
for kind1 in range(2):
for kind2 in range(2):
T = [0] * (N + 2)
T[0] = kind1
T[1] = kind2
for i in range(1, N + 1):
if T[i] == 0 and S[i % N] == 'o':
T[i + 1] = T[i - 1]
elif T[i] == 0 and S[i % N] == 'x':
... |
nome = input('Digite o nome do cliente: ')
dia = input('Digite o dia de vencimento: ')
mes = input('Digite o mês de vencimento: ')
valor = input('Digite o valor da fatura: ')
print('Olá,',nome)
print('A sua fatura com vencimento em',dia,'de',mes,'no valor de R$',valor,'está fechada.') |
print("Bitwise Operator")
# 0 - 00
# 1 - 01
# 2 - 10
# 3 - 11
print(0 | 1) # OR
print(0 | 2)
print(1 | 3)
print(2 | 3)
print(0 & 1) # AND |
'''
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlock... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
constants.py
Contains all the application constants. As a rule all constants are named in all caps.
'''
APPLICATION = "countdown"
QTGUI = True
PYPROPS_CORELIBPATH = '../../core'
PUBLISHALLDATA_PERIOD = 30.0
USE_GPIO = True
#______________________________________... |
print('Calories Burned Running Calculator')
km = float(input('Please enter your km: '))
weight = float(input('Please enter your weight: '))
kcal = km*weight*1.036
print('This is your burn running: '+ str(kcal))
|
word = list(input())
word[0] = word[0].upper()
print(''.join(word)) |
## https://leetcode.com/problems/reverse-words-in-a-string-iii
## this one is actually easier than II because we just split on
## empty space, then join the reversed words around a space
## comes in at ~91st percentile for runtime and 91st for memory.
class Solution:
def reverseWords(self, s: str) -> str:
... |
with open('inputs/input15.txt') as fin:
a = [int(x) for x in (fin.read()).split(',')]
def solve(data, number):
loc = {index: value for value, index in enumerate(data[:-1])}
num = data[-1]
index = len(data) - 2
while index < (number - 2):
if num in loc:
store = loc[num]
... |
"""Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.
Return the largest lucky integer in the array. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because fre... |
#!/usr/bin/python
def solution(S, C):
pass
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
solution("abccdb", [0, 1, 2, 3, 4, 5])
|
class BeanUtil:
@staticmethod
def dict_to_model(obj: object, **data):
"""
将 dict 转为对象
使用示例:
dic = {'name': 'python', 'price': 10}
model = Model()
BeanUtil.dict_to_model(model, **dic)
"""
obj.__dict__.update(data)
return obj
|
#Exemplo 1:
lista1 = []
lista2 = [1, 2, 3, 3, 4, 5, 8, 8, 10]
lista3 = [3.4, 23.42, 532.12]
lista4 = [True, False, True, True]
lista5 = ['tatu', 'roxo', 'a']
lista6 = list('Silvio Santos 1898') #Torna uma String em uma lista
print(lista6)
lista7 = [43, True, 23.1, 'abacate', 'Russia', 12, 'x', False, [1, 3, 5, 7]]
... |
'''
A class is a structure that allows you to combine the data and functionality associated with a particular task. The variables of a class are attributes. The functions of a class are methods.
'''
class Arithmetic:
#def __init__(self, number1=10, number2=20):
#def __init__(self, number1=4, number2=8):
de... |
class RequestOptionsBase(object):
def apply_query_params(self, url):
raise NotImplementedError()
class RequestOptions(RequestOptionsBase):
class Operator:
Equals = 'eq'
GreaterThan = 'gt'
GreaterThanOrEqual = 'gte'
LessThan = 'lt'
LessThanOrEqual = 'lte'
... |
# Note:
# 1. the test() will execute the decorator inner function first
# 2. and then it will execute the normal function afterwards
# define a decorator
def calculate(callback):
def run():
# decorator program
result=0
for n in range(51):
result+=n
callback(result)
... |
def increment(n):
return n+1
def square(n):
return n*n
def imperative (initial, goal):
list_functions=[(" increment", increment),(" square", square)]
candidates=[(str(initial), initial)]
for x in range (goal-initial+1):
newCandidates=[]
for (action,result) in candidates:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class MorsecodeError(Exception):
# 自定义异常
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Morsecoder:
VERSION = 0.5
AUTHOR = 'Lemonix'
_en_list = {'A': '.-',
'B': '-...'... |
def sales_sum(key):
total = 0
nums = []
while True:
x = yield
print(key + "销量:", x)
if not x:
break
total += x
nums.append(x)
return total, nums
if __name__ == "__main__":
my_gen = sales_sum("bobby牌手机")
my_gen.send(None)
my_gen.send(1200)
my_gen.send(1500)
my_gen.send(2000)
try:
my_gen.send(N... |
'''
Q: 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
'''
'''
final answer: 1366
'''
# init constant
pwr = 1000
base = 2
# compute
def compute():
result = str(base ** pwr)
digits = [int(d) for d in result]
return (sum(digits))
if _... |
# Load csv with no additional arguments
data = pd.read_csv("vt_tax_data_2016.csv")
# Print the data types
print(data.dtypes)
'''
<script.py> output:
STATEFIPS int64
N00700 int64
...
N85770 int64
A85770 int64
Length: 147, dtype: object
'''
# Crea... |
"""
sciwebvis.JSRenderable
----------------------
:copyright: 2015, Juan David Adarve. See AUTHORS for more details
:license: 3-clause BSD, see LICENSE for more details
"""
__all__ = ['JSRenderable']
class JSRenderable(object):
"""
Base class for Javascript render classes
"""
def __i... |
#Pig Latin - Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules.
st = input('Giv... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
""" Advent of Code, 2020: Day 15, b """
with open(__file__[:-5] + "_input") as f:
inputs = [line.strip() for line in f]
def run():
""" Maintain a dictionary of last-positions instead of counting """
numbers = [int(n) for n in inputs[0].split(",")]
seen = {n: i for (i, n) in enumerate(numbers)}
la... |
def test_in(neuron_instance):
"""Test 1D diffusion in a single section"""
h, rxd, data = neuron_instance
soma = h.Section(name='soma')
dend = h.Section(name='dend')
soma.nseg = 3
cyt = rxd.Region(h.allsec(), name='cyt')
c = rxd.Species(cyt, name='c')
for node in c.nodes(soma):
... |
# __init__.py
# Copyright 2019 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""Provide an identical interface to several Python database modules.
The supported modules, or packages, are apsw, bsbdb3, dbm, dptdb, ndbm,
sqlite3, unqlite, and vedis.
"""
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python3
# Copyright (c) 2011 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any l... |
"""
Give three strings ‘m’, ‘n’, and ‘p’, write a method to find out if ‘p’
has been formed by interleaving ‘m’ and ‘n’. ‘p’ would be considered
interleaving ‘m’ and ‘n’ if it contains all the letters from ‘m’ and ‘n’ and the
order of letters is preserved too.
Example 1:
Input: m="abd", n="cef", p="abcdef"
Outp... |
class InstallNotFoundError(FileNotFoundError):
def __init__(self):
super().__init__("Could not find a ProPresenter 6 installation on your system.")
class InvalidInstallError(BaseException):
def __init__(self, sub):
super().__init__("A problem was found with your ProPresenter 6 installation: %... |
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
ls_s, ls_t = len(s) ,len(t)
# reverse to reduce conditions
if ls_s > ls_t:
return self.isOneEditDistance(t, s)
# edit distance... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def rec(n):
if n == 1:
return 1
return n + rec(n - 1)
if __name__ == '__main__':
n = int(input("Enter n: "))
sum = 0
for i in range(1, n + 1):
sum += i
print(f"Сумма без рекурсии: {sum}")
print(f"Сумма с рекурсией: {rec(n)}")... |
#!/usr/bin/env python
class Solution:
def longestConsecutive(self, nums) -> int:
consecutive, self.longest = dict(), 1 if len(nums) > 0 else 0
def union(i, j): # merge i with j
if len(consecutive[i]) > len(consecutive[j]):
i, j = j, i
consecutive[j] += consec... |
#!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# 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 ag... |
# $Id: constants.py,v 1.1 2010-09-07 15:09:35 wirawan Exp $
#
# pyqmc.libs.constants module
# Created: 20100902
# Wirawan Purwanto
#
"""
Library of constants from various computational packages.
At present it contain constants from:
* nwchem 5.1.1
* MPQC 2.3.1
"""
class nwchem_5_1_1:
"""Constants from NWCHEM 5.1.1 ... |
#! python3
print("4.1")
pizzas = ['pepperoni', 'capricosa', 'rimini']
for pizza in pizzas:
print(f"I like pizza' {pizza.title()}")
print('I love pizza!')
print("4.2")
animals = ['dog', 'cat', 'monkey']
for animal in animals:
print(f'{animal.title()} is a good friend.')
print("All of this animals are great!"... |
def some_fun(name, /, pos_or_keyword, *a, content, **b):
print("Positional args:\n", name, "\n", pos_or_keyword, sep="")
for i in a:
print(i)
print("\nKeyword args:\n", content, sep="")
for key, val in b.items():
print(key, "->", val)
if __name__ == "__main__":
some_fun("trayan", 1,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-12-22 11:16:42
#
# 堆排序 纯粹练手
class HeapSort(object):
def __init__(self, data):
self.data = data
def sort(self):
# 建立最大堆
for i in range(len(self.data)//2-1, -1, -1):
# 从第一个非叶子结点从下至上,从右至左调整结构
self.sin... |
# Time: O(n^2)
# Space: O(n)
class MyCalendarTwo(object):
def __init__(self):
self.__overlaps = []
self.__calendar = []
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
for i, j in self.__overlaps:
i... |
def provide_test_geojson():
d = {
"type": 'FeatureCollection',
"features": [
{
"type": 'Feature',
"properties": {
"name": 'Lafayette (LAFY)',
"code": 'LF',
"address": '3601 Deer Hill Road, Lafayet... |
# 1520. Maximum Number of Non-Overlapping Substrings
# User Accepted:274
# User Tried:1333
# Total Accepted:283
# Total Submissions:3130
# Difficulty:Medium
# Given a string s of lowercase letters,
# you need to find the maximum number of non-empty substrings of s that meet the following conditions:
# The substrings d... |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSub = nums[0]
cur_sum = 0
for num in nums:
if cur_sum < 0:
cur_sum = 0
cur_sum += num
maxSub = max(maxSub, cur_sum)
print(maxSub)
return maxSub
|
# apis_v1/documentation_source/office_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def office_retrieve_doc_template_values(url_root):
"""
Show documentation about officeRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_i... |
#!/usr/bin/env python
try:
x = (1 / 0)
print (x)
except ZeroDivisionError:
print('Erro ao tentar dividir por zero.')
|
USD = "米ドル"
EUR = "ユーロ"
CAD = "カナダ・ドル"
GBP = "英ポンド"
CHF = "スイス・フラン"
DKK = "デンマーク・クローネ"
NOK = "ノルウェー・クローネ"
SEK = "スウェーデン・クローネ"
AUD = "オーストラリア・ドル"
NZD = "ニュージーランド・ドル"
HKD = "香港ドル"
MYR = "マレーシア・リンギット"
SGD = "シンガポール・ドル"
SAR = "サウジ・リアル"
AED = "UAEディルハム"
CNH = "中国・人民元"
THB = "タイ・バーツ"
INR = "インド・ルピー"
PKR = "パキスタン・ルピー"
KWD = "... |
#!/usr/bin/env python
# coding=utf-8
################################################################################
# sdk错误码
################################################################################
class CosErr(object):
PARAMS_ERROR = -1 # 参数错误
NETWORK_ERROR = -2 # 网络错误
SERVER_ERROR = -3 # serv... |
# 1. ------------------------------------
def logistic_map(x, r):
return r * x * (1 - x)
# 2. ------------------------------------
initial_condition = 0.5
t_final = 10
r = 1.0
trajectory = [initial_condition]
for t in range(1, t_final):
trajectory[t] = logistic_map(trajectory[t-1], r)
# 3. -----------... |
#
# PySNMP MIB module REPEATER-REV4-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REPEATER-REV4-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
def math():
a, b, c = input().split()
a, b, c = float(a), float(b), float(c)
pi = 3.14159
triangle = (.5 * a * c).__format__('.3f')
circular = (pi * (c**2)).__format__('.3f')
trapezium = (((a + b) / 2) * c).__format__('.3f')
area = (b**2).__format__('.3f')
rectangle = (a * b).__format__... |
if a>b:
print ("a")
elif 20>10:
print ("b")
elif 15>10:
print ("c")
|
def calcular_area(_largura, _comprimento):
return _largura * _comprimento
print('\nControle de Terrenos')
print('-' * 20)
largura = float(input('Largura (m): '))
comprimento = float(input('Comprimento (m): '))
print('A área de um terreno {:.1f} x {:.1f} é de {:.1f} m2.'
.format(largura, comprimento, calc... |
#
# pystylus/ast/selectorlist.py
#
"""
Defines the SelectorList node type in the pystylus AST
"""
class SelectorList:
"""
The selector list is a list of valid CSS selectors. This is found at the
beginning of a Style Block
"""
def __init__(self, *selectors):
self.selectors = selectors
|
#First test evolution function. Oddly, performs only a little worse than Runge-Kutta.
def Euler_Step(x,xres,dydx,Y):
return dydx(x,xres,Y)*xres,xres
def Ystep_euler(g,mx,sigmav,xstep=1e-2,Deltax=1e-4):
Yeqset = lambda x: Yeq(mx,mx/x,g,0,0)
neqset = lambda x: neq(mx,mx/x,g,0,0)
#Find a point shortly be... |
def BFS(graph: dict, s: str):
# graph 无向图
# s 开始的节点
# 一层一层走,每次只找相邻的节点
queue = [s]
seen = [s]
path = []
parent = {s: None}
while queue:
node = queue.pop(0)
nodes = graph[node]
for w in nodes:
if w not in seen:
queue.append(w)
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'netfields',
}
}
INSTALLED_APPS = (
'netfields',
)
SECRET_KEY = "notimportant"
|
centerX = 0
centerY = 0
angle = 0
fsize = 0
weight = 0
counter = 0
centerX= 500/2
centerY= 500/2
angle= 0
fsize= 150
weight = 1
class MyEllipse():
cX = centerX
cY = centerY
cA = angle
eS = fsize
Ew = weight
def render(self, fsize):
fill(200, fsize/20)... |
# PyAlgoTrade
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
x = int(input())
y = int(input())
day = 1
while y - x > 0:
x = x + (x * 0.1)
day += 1
print(day) |
_windows_build_file_content = """
alias(
name = "doxygen",
visibility = ["//visibility:public"],
actual = "{DOXYGEN_VERSION}/doxygen.exe",
)
"""
_known_archives = {
"1.8.19": {
"windows64": struct(
urls = ["https://doxygen.nl/files/doxygen-1.8.19.windows.x64.bin.zip"],
... |
# 입력
c = int(input())
# C(n)이 1이 되면 break
for n in range(1, 100001):
if c == 1:
print(n)
break
# 짝수일 때
if c % 2 == 0:
c //= 2
# 홀수일 때
else:
c = 3*c + 1
|
lista = list()
pessoas = dict()
idad = media = 0
alt = altu_med = 0
while True:
pessoas.clear()
pessoas['codigo'] = int( input('Código: '))
pessoas['nome'] = str( input('Nome: '))
pessoas['idade']=int( input('Idade: '))
idad += pessoas['idade']
pessoas['altura'] = float( input('Altura: '))
a... |
TELEGRAM_API_TOKEN = 'Tel Bot Token By @BotFather'
UPLOADER = {
'uploader': 'reverse_image_search_bot.uploaders.ssh.SSHUploader',
'url': 'Host Domain Name',
'configuration': {
'host': 'Host IP (PUBLIC)',
'user': 'Yourname',
'password': 'Password',
'upload_dir': '/path/to/ReV... |
# Time: O(n * m^2), n is the number of rows with 1s, m is the number of cols with 1s
# Space: O(n * m)
class Solution(object):
def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = [[c for c, val in enumerate(row) if val]
... |
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
#
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
#
# The replacement must be in-place and use only constant extra memory.
#
# ... |
# https://www.geeksforgeeks.org/basic/cryptography/
# SGVP387900|14:43 27F19
# Hill Cipher implementation
keyMatrix = [[0] * 3 for i in range(3)]
# Genrate vector for the message
messageVector = [[0] for i in range(3)]
# Genrate vector for the cipher
cipherMatrix = [[0] for i in range(3)]
# Following function gene... |
def weakNumbers(n):
all_factors = [count_factors(num) for num in range(1, n + 1)]
weaknesses = []
for num, num_factors in enumerate(all_factors, 1):
weakness = 0
for factor in all_factors[:num]:
if factor > num_factors:
weakness += 1
weaknesses.append(weak... |
#!/usr/bin/env python
#
# Copyright (C) 2014 The Android Open Source Project
#
# 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 req... |
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/
# Device List
devices = {
'analyzer':[
'lantz.drivers.spectrum.MS2721B',
['USB0::0x0B5B::0xFFF9::1118010_150_11::INSTR'],
{}
],
'source':[
'lantz.drivers.mwsource.SynthNVPro',
['ASRL16::INSTR'],
... |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x}, {self.y})'
|
numero_por_extenso = ("zero", "um", "dois", "três", "quatro", "cinco", "seis",
"sete", "oito", "nove", "dez", "onze", "doze", "treze",
"catorze", "quinze", "dezesseis", "dezesete", "dezoito",
"dezenove", "vinte")
sair = "N"
while sair == "N":
nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.