content stringlengths 7 1.05M |
|---|
{
'%Y-%m-%d':'%Y-%m-%d',
'%Y-%m-%d %H:%M:%S':'%Y-%m-%d %H:%M:%S',
'%s rows deleted':'%s records cancellati',
'%s rows updated':'*** %s records modificati',
'Hello World':'Salve Mondo',
'Invalid Query':'Query invalida',
'Sure you want to delete this object?':'Sicuro che vuoi cancellare questo oggetto?',
'Welcome to web2... |
def clean_split(text, delim=','):
text = text.strip()
return map(lambda o: o.strip(), text.split(delim))
def read_notes(file):
notes = {}
for line in file:
split = clean_split(line, ',')[:-1]
if split[-1] == '':
continue
notes[(split[0], int(split[1]))] = float(spli... |
# Game Objects
class Space(object):
def __init__(self,name):
self.name = name
def get_name(self):
return self.name
class Property(Space):
set_houses = {
"Violet":2,
"Light blue":3,
"Purple":3,
"Orange":3,
... |
class Hourly:
def __init__(self, temp, feels_like, pressure, humidity, wind_speed, date, city, weather):
self.temp=temp;
self.feels_like=feels_like;
self.pressure=pressure;
self.humidity=humidity;
self.wind_speed=wind_speed;
self.date=date;
self.city=city;
... |
class InvalidQNameError(RuntimeError):
def __init__(self, qname):
message = "Invalid qname: " + qname
super(InvalidQNameError, self).__init__(message)
|
# selection sort algorithm
# time complexity O(n^2)
# space complexity O(1)
def selectionsort(list, comp):
for x in range(len(list)):
curr = x
for y in range(x, len(list)):
if (comp(list[curr], list[y]) > 0):
curr = y
swap = list[x]
list[x] = li... |
def rpn_eval(tokens):
def op(symbol, a, b):
return {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b
}[symbol](a, b)
stack = []
for token in tokens:
if isinstance(token, float):
... |
#coding=utf-8
#使用递归计算n的阶乘(5!=5*4*3*2*1)
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
print(factorial(5))
|
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
odd = head
even = head.next
even_head = head.next
while even and even.next:
odd.next = odd.next.next
even.next = even.next.next
odd = odd.next
even = even.next
... |
# Represents a single space within the board.
class Tile():
# Initializes the tile.
# By default, each tile is a wall until a board is built
def __init__(self):
self.isWall = True
# Renders the object character in this tile
def render(self):
if self.isWall == True:
return '0';
# Represents the game board... |
__title__ = 'dtanys'
__description__ = 'Python structured data parser.'
__url__ = 'https://github.com/luxuncang/dtanys'
__version__ = '1.0.5'
__author__ = 'ShengXin Lu'
__author_email__ = 'luxuncang@qq.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 ShengXin Lu' |
class Clock:
def __init__(self, hour, minute):
self.total: int = hour * 60 + minute # in minutes
def __repr__(self):
hour, minute = (self.total // 60) % 24, self.total % 60
return '{:02d}:{:02d}'.format(hour, minute)
def __eq__(self, other):
return repr(self) == repr(oth... |
file=open("circulations.txt")
data=[]
date=int(input())
for line in file:
[book,member,due]=line.strip().split()
if date>int(due):
data.append([book,member,due])
i=0
while i<len(data)-1:
j=0
while j<len(data)-1:
if int(data[j][2])>int(data[j+1][2]):
data[j], data[j+1] = ... |
BASE_URL = "https://api.stlouisfed.org"
SERIES_ENDPOINT = "fred/series/observations"
SERIES = ["GDPC1", "UMCSENT", "UNRATE"]
FILE_TYPE = "json"
|
"""
Module: 'uasyncio.__init__' on micropython-rp2-1.15
"""
# MCU: {'family': 'micropython', 'sysname': 'rp2', 'version': '1.15.0', 'build': '', 'mpy': 5637, 'port': 'rp2', 'platform': 'rp2', 'name': 'micropython', 'arch': 'armv7m', 'machine': 'Raspberry Pi Pico with RP2040', 'nodename': 'rp2', 'ver': '1.15', 'release'... |
f90 = {}
cxx = {}
cc = {}
is_arch_valid = 1
flags_arch = '-g -pg -O3 -Wall'
# -lpthread: not needed?
# -rdynamic: required for backtraces
balancer = 'RotateLB'
flags_prec_single = '-fdefault-real-4 -fdefault-double-8'
flags_prec_double = '-fdefault-real-8 -fdefault-double-8'
flags_cxx_charm = '-balancer '... |
"""Holds cerberus validation schemals for each yml parsed by any of the sheetwork system."""
config_schema = {
"sheets": {
"required": True,
"type": "list",
"schema": {
"type": "dict",
"schema": {
"sheet_name": {"required": True, "type": "string"},
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
ptr = ListNode(-1)
ptr.next = head
current = head
head = ptr
... |
#!/usr/bin/env python
"""
Library of functions to help output data in reStructuredText format
"""
## functions
def print_rest_table_contents(columns,items,withTrailing=True):
"""
function needs to be turned into a class
"""
row = "+"
head = "+"
for col in columns:
row += "-"*col+"-+"
... |
add_library('opencv_processing')
src = loadImage("test.jpg")
size(src.width, src.height, P2D)
opencv = OpenCV(this, src)
opencv.findCannyEdges(20, 75)
canny = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findScharrEdges(OpenCV.HORIZONTAL)
scharr = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findSobelEdge... |
#
# PySNMP MIB module RAPID-HA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPID-HA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:51:59 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,... |
test = {
'name': 'q1c',
'points': 3,
'suites': [
{
'cases': [
{
'code': r"""
>>> manhattan_taxi.shape
(82800, 9)
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum(manhattan_taxi['duratio... |
# Ex056.2
"""Develop a program that reads the name, age and sex of for people. At the end of the program, show:
The average age of the group,
What's the name of the older man,
How many women are under 20"""
total_age = 0
older_man = 0
name_over_man = ''
women20_cont = 0
for n in range(1, 4 + 1):
print(f'\033[32mPers... |
# -*- encoding: utf-8 -*-
# auto-learner v0.1.0
# my machine learning project
# Copyright © 2018, Arash Eghtesadi.
# See /LICENSE for licensing information.
"""
Main routine of auto-learner.
:Copyright: © 2018, Arash Eghtesadi.
:License: BSD (see /LICENSE).
"""
__all__ = ('main',)
def main():
"""Main routine o... |
def get_date_from_zip(zip_name: str) -> str:
"""
Helper function to parse a date from a ROM zip's name
"""
return zip_name.split("-")[-1].split(".")[0]
def get_metadata_from_zip(zip_name: str) -> (str, str, str, str):
"""
Helper function to parse some data from ROM zip's name
"""
d... |
filt_dict = {
'db': [['Emissions', '(Kyoto Gases|co2)$', '(|Energy and Industrial Processes|AFOLU)$', '', '(world|r5.*)'],
['Policy cost', '(Additional Total Energy System Cost|consumption Loss|gdp Loss)', '', '', '(world|r5.*)'],
['Price', 'Carbon', '$', '', '(world|r5.*)'],
],
}
|
# https://leetcode.com/problems/insert-interval/
# Given a set of non-overlapping intervals, insert a new interval into the
# intervals (merge if necessary).
# You may assume that the intervals were initially sorted according to their start
# times.
###################################################################... |
#!/usr/bin/env python3
def merge(L1, L2):
L3 = L1+L2
for j in range(len(L3)):
for i in range(0, len(L3)-j-1):
if L3[i]> L3[i+1]:
L3[i],L3[i+1] = L3[i+1] , L3[i]
return (L3)
def main():
print((merge([1,2,3],[1,6,7])))
pass
if __name__ == "__main__":
main(... |
class ControllerBase:
@staticmethod
def base():
return True
|
__author__ = 'fatih'
class SQL():
"""
This class includes all using database commands such as insert, remove, select etc.
Only need to do is you will write your sql command and format it into running command by given values
"""
#insert commands
SQL_INSERT_CONFIG = "INSERT INTO apc_confi... |
'''
You are given an array of length n which only contains the elements 0,1 and 2.
You are supposed to sort the array in ascending order without the use of any sorting algorithms. Minimize time complexity.
Input Format:
The first line of input contains the value of n i.e. size of array.
The next line contains n space... |
"""
author: Akshay Chawla (https://github.com/akshaychawla)
TEST:rs
Test convert.py's ability to handle Deconvolution and Crop laye
by converting voc-fcn8s .prototxt and .caffemodel present in the caffe/models/segmentation folder
"""
# import os
# import inspect
# import numpy as np
# import keras.caffe.convert as conv... |
class BlocoMemoria:
palavra: list
endBlock: int
atualizado: bool
custo: int
cacheHit: int
ultimoUso: int
def __init__(self):
self.endBlock = -1
self.atualizado = False
self.custo = 0
self.cacheHit = 0
ultimoUso: 2**31-1 |
AzToolchainInfo = provider(
doc = "Azure toolchain rule parameters",
fields = [
"az_tool_path",
"az_tool_target",
"azure_extension_dir",
"az_extensions_installed",
"jq_tool_path",
],
)
AzConfigInfo = provider(
fields = [
"debug",
"global_args",
... |
# Copyright 2018- The Pixie Authors.
#
# 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 w... |
package(default_visibility = [ "//visibility:public" ])
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "net_import_library", "core_import_library")
net_import_library(
name = "net45",
src = "lib/netstandard1.0/System.Threading.Tasks.Extensions.dll",
)
core_import_library(
name = "netcore",
src = "lib/netstan... |
class Solution:
def repeatedStringMatch(self, A: str, B: str) -> int:
if B in A:
return 0
counter = 1
repeatedA = A
while len(repeatedA) < len(B)*2:
repeatedA += A
if B in repeatedA:
return counter
counter += 1
r... |
# File03.py
user = 'Ali'
f1 = open('./Users/users01.txt', mode = 'a+', encoding = 'cp949') # a+ : 읽기와 쓰기 같이
users1 = f1.write('\n' + user)
f1.seek(0) # 커서의 위치변경
users1 = f1.read()
print("닫힘" if f1.closed else "안닫힘")
f1.close()
print("닫힘" if f1.closed else "안닫힘")
print(users1)
|
WIDTH = 50
HEIGHT = 10
MAX_WIDTH = WIDTH - 2
MAX_HEIGHT = HEIGHT - 2
|
# coding: utf-8
class CorpusInterface(object):
def load_corpus(self, corpus):
pass
def read_corpus(self, filename):
pass
class Corpus(object):
def load_corpus(self, corpus):
raise NotImplementedError()
def read_corpus(self, filename):
raise NotImplementedError()
|
x = int(input())
for i in range(1, 11):
resultado = i * x
print("{} x {} = {}".format(i, x, resultado))
|
patches = [
# Rename AWS::Lightsail::Instance.Disk to AWS::Lightsail::Instance.DiskProperty
{
"op": "move",
"from": "/PropertyTypes/AWS::Lightsail::Instance.Disk",
"path": "/PropertyTypes/AWS::Lightsail::Instance.DiskProperty",
},
{
"op": "replace",
"path": "/Prop... |
maximum = float("-inf")
def max_path_sum(root):
helper(root)
return maximum
def helper(root):
if not root:
return 0
left = helper(root.left)
right = helper(root.right)
maximum = max(maximum, left+right+root.val)
return root.val + max(left, right)
|
fruit = input()
size_set = input()
count_sets = float(input())
price_set = 0
if fruit == 'Watermelon':
if size_set == 'small':
price_set = count_sets * 56 * 2
elif size_set == 'big':
price_set = count_sets * 28.7 * 5
elif fruit == 'Mango':
if size_set == 'small':
price_set = count_s... |
def test_socfaker_timestamp_in_the_past(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_past()
def test_socfaker_timestamp_in_the_future(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_future()
def test_socfaker_timestamp_current(socfaker_fixture):
assert socfaker_fixture.timestamp... |
"""
NewsTrader - a framework of news trading for individual investors
This package is inspired by many other awesome Python packages
"""
# Shortcuts for key modules or functions
__VERSION__ = "0.0.1"
|
releases = [
{
"ocid": "A",
"id": "1",
"date": "2014-01-01",
"tag": ["tender"],
"tender": {
"items": [
{
"id": "1",
"description": "Item 1",
"quantity": 1
},
{
"id": "2",
"desc... |
# -*- coding: utf-8 -*-
"""
exceptions.py
Exceptions raised by the Kite Connect client.
:copyright: (c) 2017 by Zerodha Technology.
:license: see LICENSE for details.
"""
class KiteException(Exception):
"""
Base exception class representing a Kite client exception.
Every specific Kite c... |
__title__ = "PyMatting"
__version__ = "1.1.3"
__author__ = "The PyMatting Developers"
__email__ = "pymatting@gmail.com"
__license__ = "MIT"
__uri__ = "https://pymatting.github.io"
__summary__ = "Python package for alpha matting."
|
"""Chapter 12 - Be a pythonista"""
# vars
def dump(func):
"""Print input arguments and output value(s)"""
def wrapped(*args, **kwargs):
print("Function name: %s" % func.__name__)
print("Input arguments: %s" % ' '.join(map(str, args)))
print("Input keyword arguments: %s" % kwargs.items(... |
class Matrix:
def __init__(self, mat):
l_size = len(mat[0])
for line in mat:
if l_size != len(line):
raise ValueError('invalid matrix sizes')
self._raw = mat
@property
def raw(self):
return self._raw
@property
def trace(self):
if ... |
# todo remove in next major release as we no longer support django < 3.2 anyway. Note this would make dj-stripe unuseable for djang0 < 3.2
# for django < 3.2
default_app_config = "djstripe.apps.DjstripeAppConfig"
|
valores = []
index = 0
for c in range(0, 5):
valor = int(input(f'Digite um valor para a posição {index}: '))
valores.append(valor)
index += 1
print('-=-' * 15)
print(f'Você digitou os valores {valores}.')
print(f'O maior valor digitado foi {max(valores)} nas posições ', end='')
for i, v in enumerat... |
with open("mynewtextfile.txt","w+") as f:
f.writelines("\nOtus we are learning python\nOtus we are learning python\nOtus we are learning python")
f.seek(0)
print(f.readlines())
print("Is readable:", f.readable())
print("Is writeable:", f.writable())
print("File no:", f.fileno())
print("Is co... |
class Solution:
def traverse(self, node: TreeNode, deep: int):
if node is None: return deep
deep += 1
if node.left is None:
return self.traverse(node.right, deep)
elif node.right is None:
return self.traverse(node.left, deep)
else:
left_de... |
def rotation_saxs(t = 1):
#sample = ['Hopper2_AGIB_AuPd_top', 'Hopper2_AGIB_AuPd_mid', 'Hopper2_AGIB_AuPd_bot'] #Change filename
sample = ['AGIB3N_1top', 'AGIB3N_1mid', 'AGIB3N_1cen'] #Change filename
#y_list = [-6.06, -6.04, -6.02] #hexapod is in mm
#y_list = [-10320, -10300, -10280] #SmarAct i... |
def factory(classToInstantiate):
def f(*arg):
def g():
return classToInstantiate(*arg)
return g
return f |
class EmailBuilder:
def __init__(self):
self.message = {}
def set_from_email(self, email):
self.message['from'] = email
return self
def set_receiver_email(self, email):
self.message['receiver'] = email
def set_cc_emails(self, emails):
self.message['cc'] = email... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 o... |
#! /usr/bin/env python3
def main():
try:
name = input('\nHello! What is your name? ')
if name:
print(f'\nWell, {name}, it is nice to meet you!\n')
except:
print('\n\nSorry. Something went wrong, please try again.\n')
if __name__ == '__main__':
main()
|
def binary_search(element, some_list):
# 코드를 작성하세요.
start_index = 0
end_index = len(some_list) - 1
while (start_index <= end_index):
mid_index = (end_index + start_index) // 2
if(some_list[mid_index] == element):
return mid_index
elif(some_list[mid_index] < element):
... |
#for循环方法
a=1
for i in range(0,101):
if i%2!=0:
print(i,end=' ')
#换行打印
print('')
while a<=100:
if a % 2!=0:
print(a,end=' ')
a+=1
|
meta_pickups={
'aux_domains': lambda r, common, data: {
'pos': r['head_pos'], 'head': r['head'], 'head_word': r['head_word'],
**common, **data},
'root_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **common, **data},
'verb_domains': lambda r, common, data: {'pos': r['u... |
#
# PySNMP MIB module CISCO-WAN-BBIF-ATM-CONN-STAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-BBIF-ATM-CONN-STAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
things = ['a', 'b', 'c', 'd']
print(things)
print(things[1])
things[1] = 'z'
print(things[1])
print(things)
things = ['a', 'b', 'c', 'd']
print("=" * 50)
stuff = {'name' : 'Jinkyu', 'age' : 40, 'height' : 6 * 12 + 2}
print(stuff)
print(stuff['name'])
print(stuff['age'])
print(stuff['height'])
stuff['city'] = "SF"
print... |
class Solution(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
seen = [False] * len(rooms)
seen[0] = True
stack = [0, ]
while stack:
roomIdx = stack.pop()
for key in rooms[roomIdx]:
... |
# https://leetcode.com/problems/surface-area-of-3d-shapes
class Solution:
def surfaceArea(self, grid):
N = len(grid)
ans = 0
for i in range(N):
for j in range(N):
if grid[i][j] == 0:
continue
height = grid[i][j]
... |
USERDV = [
"USER_NAME",
"USER_USERNAME",
"USER_ID",
"USER_PIC",
"USER_BIO"
]
class UserConfig(object):
def UserName(self):
"""returns name of user"""
return self.getdv("USER_NAME") or self.USER_NAME or self.name or None
def UserUsername(self):
"""returns username of user"""
return self.getdv("USER... |
tempo = int(input())
velocida_media = int(input())
gasto_carro = 12
distancia = velocida_media * tempo
print(f'{distancia / 12:.3f}') |
rows, cols = [int(n) for n in input().split(", ")]
matrix = []
for _ in range(rows):
matrix.append([int(n) for n in input().split(" ")])
for j in range(cols):
total = 0
for row in matrix:
total += row[j]
print(total)
|
# Available methods
METHODS = {
# Dummy for HF
"hf": ["hf"],
"ricc2": ["rimp2", "rimp3", "rimp4", "ricc2"],
# Hardcoded XC-functionals that can be selected from the dft submenu
# of define.
"dft_hardcoded": [
# Hardcoded in V7.3
"s-vwn",
"s-vwn_Gaussian",
"pwlda",... |
def sumValues(a, b, *others):
retValue = a + b
# Tham số 'others' giống như một mảng.
for other in others:
retValue = retValue + other
return retValue |
class Config:
'''
General configuration parent class
'''
NEWS_API_BASE_URL ='https://newsapi.org/v2/sources?apiKey={}'
ARTICLE_API_BASE_URL = 'https://newsapi.org/v2/everything?sources={}&apiKey={}'
class ProdConfig(Config):
'''
Production configuration child class
Args:
Config: The parent con... |
def main() -> None:
K, X = map(int, input().split())
assert 1 <= K <= 100
assert 1 <= X <= 10**5
if __name__ == '__main__':
main()
|
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Remoting tests.
@since: 0.1.0
"""
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumNumsR(self, root, s):
if root is None:
return 0
s = s * 10 + root.val
if not root.left and not root.rig... |
# Copyright 2018 Google Inc. 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 law or a... |
__all__ = ('ascii_art_title_4client', 'ascii_art_title_4server')
ascii_art_title_4client = r"""
/$$$$$$ /$$ /$$
/$$__ $$| $$ | $$
/$$$$$$ /$... |
# -*- coding: utf-8 -*-
description = "Setup for the LakeShore 340 temperature controller"
group = "optional"
includes = ["alias_T"]
tango_base = "tango://phys.kws3.frm2:10000/kws3"
tango_ls340 = tango_base + "/ls340"
devices = dict(
T_ls340 = device("nicos.devices.entangle.TemperatureController",
descr... |
def response(status, message, data, status_code=200):
return {
"status": status,
"message": message,
"data": data,
}, status_code
|
"""
Blocks
TODO:
* Avoid newline/indent on certain tags, like Blank/Pre: self.__class__.__name__ != "Pre" (necessary?)
* Fixed: () popped len(token) twice
"""
## +block
def indented_block(self):
print(f"Indent-dependent {self.tag} block started")
start_O_line = self.O.line_number
block_indent = self.I.... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mErro:Por favor, digite um número inteiro válido\033[m')
continue
except (keyboardInterrupt):
print('\n\033[31mUsuário preferiu não digitar ess... |
x = 0
for n in range(10):
x = x + 1
assert x == 10
|
# Aula 016:
'''Nessa aula, vamos aprender o que são TUPLAS e como utilizar tuplas em Python. As tuplas são variáveis
compostas e imutáveis que permitem armazenar vários valores em uma mesma estrutura, acessíveis por
chaves individuais.'''
# Variáveis compostas (Tuplas):
lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim... |
#Queue.py
#20 Oct 2017
#Written By Amin Dehghan
#DS & Algorithms With Python
class Queue:
def __init__(self):
self.items=[]
self.fronIdx=0
def __compress(self):
newlst=[]
for i in range(self.frontIdx,len(self.items)):
newlst.append(self.items[i])
... |
patches = [
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::Server/Propert... |
def foo(x):
if x == 0:
return 1
elif x % 2 == 0:
return 2 * x * foo(x - 2)
else:
return (x -3) * x * foo(x + 1)
print(foo(4)) |
def goGame():
persAcc = 0.0
history=[] # [покупка, сумма, счет]
while True:
print('1. пополнение счета')
print('2. покупка')
print('3. история покупок')
print('4. выход')
choice = input('Выберите пункт меню: ')
if choice == '1':
s = float( inp... |
def diff(n, mid) :
if (n > (mid * mid * mid)) :
return (n - (mid * mid * mid))
else :
return ((mid * mid * mid) - n)
# Returns cube root of a no n
def cubicRoot(n) :
# Set start and end for binary
# search
start = 0
end = n
# Set precision ... |
# Base Parameters
assets = asset_list('FX')
# Trading Parameters
horizon = 'H1'
pair = 0
# Mass Imports
my_data = mass_import(pair, horizon)
# Parameters
long_ema = 26
short_ema = 12
signal_ema = 9
def ma(Data, lookback, close, where):
Data = adder(Data, 1)
for i in ... |
x = 'heLLo world'
print("Swap the case: " + x.swapcase())
print("Set all cast to upper: " + x.upper())
print("Set all cast to lower: " + x.lower())
print("Set all cast to lower aggresivly: " + x.casefold())
print("Set every word\'s first letter to upper: " + x.title())
print("Set the first word\'s first letter to... |
'''
constants for the project
'''
TRAIN_LOSS = 0
TRAIN_ACCURACY = 1
VAL_LOSS = 2
VAL_ACCURACY = 3
|
# -*- coding: utf-8 -*-
STATSD_ENABLED = False
STATSD_HOST = "localhost"
STATSD_PORT = 8125
STATSD_LOG_PERIODIC = True
STATSD_LOG_EVERY = 5
STATSD_HANDLER = "scrapy_statsd_extension.handlers.StatsdBase"
STATSD_PREFIX = "scrapy"
STATSD_LOG_ONLY = []
STATSD_TAGGING = False
STATSD_TAGS = {"spider_name": True}
STATSD_IGNOR... |
N, r = map(int, input().split())
for i in range(N):
R = int(input())
if R>=r:
print('Good boi')
else:
print('Bad boi') |
# WRITE YOUR SOLUTION HERE:
class Employee:
def __init__(self, name: str):
self.name = name
self.subordinates = []
def add_subordinate(self, employee: 'Employee'):
self.subordinates.append(employee)
def count_subordinates(employee: Employee):
count = len(employee.subordinates)
... |
jogador = dict()
golList = list()
cadastro = list()
while True:
print('°~~'*15)
jogador['nome'] = str(input('Nome do jogador: ')).strip().title()
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
print('°~~'*15)
for g in range(0, partidas):
golList.append(int(in... |
#!/usr/bin/env python3
def palindrome(x):
return str(x) == str(x)[::-1]
def number_palindrome(n, base):
if base == 2:
binary = bin(n)[2:]
return palindrome(binary)
if base == 10:
return palindrome(n)
return False
def double_base_palindrome(x):
return number_palindrome(x... |
#for request headers
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
} |
# Create an array for the points of the line
line_points = [ {"x":5, "y":5},
{"x":70, "y":70},
{"x":120, "y":10},
{"x":180, "y":60},
{"x":240, "y":10}]
# Create style
style_line = lv.style_t()
style_line.init()
style_line.set_line_width(8)
style_line.... |
# In case it's not obvious, a list comprehension produces a list, but
# it doesn't have to be given a list to iterate over.
#
# You can use a list comprehension with any iterable type, so we'll
# write a comprehension to convert dimensions from inches to centimetres.
#
# Our dimensions will be represented by a tuple, f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.