content stringlengths 7 1.05M |
|---|
def compare(s, m):
""" Compute a scatter plot
Args:
s (ndarray): astrocat's true position over time
m (ndarray): astrocat's measured position over time according to the sensor
"""
fig = plt.figure()
ax = fig.add_subplot(111)
sbounds = 1.1*max(max(np.abs(s)), max(np.abs(m)))
ax.plot([-sbounds, ... |
FLOAT_PRECISION = 3
DEFAULT_MIN_TIME_IN_HOUR = 0
DEFAULT_MAX_TIME_IN_HOUR = 230
MINUTES_IN_AN_HOUR = 60
FS = "Fs"
FOIL = "Foil"
FG = "Fg"
PRES = "pressure"
DISCHARGE = "discharge"
WATER = "Fw"
PAA = "Fpaa"
DEFAULT_PENICILLIN_RECIPE_ORDER = [FS, FOIL, FG, PRES, DISCHARGE, WATER, PAA]
FS_DEFAULT_PROFILE = [
{"time... |
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass():
def test(self):
print(id(self))
class Singleton(object):
_instance = No... |
""" Drop unnecessary information """
def drop_dict(directory, dict_list):
"""drop record"""
target_dict_list = dict_list
target_dict_list = list(filter(
lambda any_dict:(directory not in any_dict["name"]) or ("stat" in any_dict),
target_dict_list))
target_dict_list = list(filter(
... |
class BaseTextOpinionsLinkageInstancesProvider(object):
def iter_instances(self, text_opinion_linkage):
raise NotImplementedError()
@staticmethod
def provide_label(text_opinion_linkage):
return text_opinion_linkage.First.Sentiment |
class SkyblockProfileMember:
def __init__(self, member_data: dict) -> None:
"""
Parameters
----------
data: dict
The JSON data received from the Hypixel API.
"""
self.COIN_PURSE = member_data["coin_purse"]
self.DEATH_COUNT = member_data["death_coun... |
# AC 05
# Nathalia Escarlate - RA 1800179
# Tiberio Cruz - Ra 1800110
#Crie uma função que receba como parâmetro um número natural N e devolva o termial deste valor.
#Obs: crie 5 testes automatizados para a função (casos errados e casos corretos)
def termial(n):
n_termial = 0
for i in range(1,n+1):
n_... |
"""
常见的颜色名称
"""
color_dict={
"almond":(239,222,205),
"amaranth":(229,43,80),
"amazon":(59,122,87),
"amber":(255,191,0),
"sae":(255,126,0),
"amethyst":(153,102,204),
"ao":(0,128,0),
"apricot":(251,206,177),
"aqua":(0,255,255),
"aquamarine":(127,255,212),
"arsenic":(59,68,75),
"artichoke":(143,151,121),
"asparagus":(135,... |
def pattern_occurence(pattern, dna):
list_occurences=[]
k = len(pattern)
for i in range(len(dna)-k+1):
if(dna[i:i+k]==pattern):
list_occurences.append(i)
return list_occurences
def main():
with open('datasets/rosalind_ba1d.txt') as input_file:
pattern, dna =... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
# generated by generate_indicestest.py
def test_indices(self):
def t(i, j, k, l, r):
rr = slice(i, ... |
"""Test package.
Modules:
conftest
"""
|
casa = float(input('Qual o valor da casa? R$:'))
salario = float(input('Quanto é o seu salario? R$:'))
anos = int(input('Em quantas parcelas você vai pagar?:'))
prestação = casa/(anos*12)
minimo = salario*30/100
if prestação <= minimo:
print('você pode finaciar essa casa')
print('A prestação será de {:.2f}'.fo... |
# for index, character in enumerate("abcdefgh"):
# print(index, character)
for t in enumerate("abcdefgh"):
index, character = t
print(index, character)
print(t)
# the output has 8 tuples
# unpacking tuples is a valuable technique
index, character = [0, 'a']
print(index)
print(character)
|
user_bin = int(input(), 2)
one = int(1)
zero = int(0)
user_int = int(user_bin)
user_int = int(user_int * 1)
oct_str = str(oct(user_int))
print(oct_str[2:])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
n = int(input("Введите число n:"))
r = n % 7
k = n // 7
if r == 0:
print(f"n = 7 * {k}")
else:
print(f"n = 7 * {k} + {r}") |
# Pre-built tokens for each version of docreader (taken from Fred issues 17, 28)
# V10 & V11 tokens from Fred 28 DOCREADER.
TOKENSV10 = {129: b'address ', 130: b'screens ', 131: b'screen ', 132: b' issue ', 133: b'memory ', 134: b'screen ', 135: b" don't ", 136: b' SAMCO ', 137: b' SAMCo ', 138: b'Coupe ', 139: b' FR... |
controller = '''
from fastapi import APIRouter, HTTPException,Cookie, Depends,Header,File, Body,Query
from starlette.responses import JSONResponse
from core.factories import settings
import httpx
router = APIRouter()
''' |
# parse file
file_names = []
with open("train_file_controller.txt", 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
with open("val_file_controller.txt", 'r') as f:
for line in f:
file_names.append(line.strip().replace('\n', ''))
file_names.sort()
for file in file_names:
print(fi... |
__all__ = ['InputError']
class InputError(BaseException):
def __init__(self, errors):
self.errors = errors
super().__init__()
|
# Шаховий король ходить по горизонталі, вертикалі та діагоналі, але тільки на 1 клітинку. Дано дві різні клітинки шахової дошки, визначте, чи може король потрапити з першої клітинки на другу за один хід.
## Формат введення
# Програма отримує на вхід чотири числа від 1 до 8 кожне, що задають номер стовпця і номер рядк... |
class BadGrammar(Exception):
"""The rule definitions passed to Grammar contain syntax errors."""
class VisitationError(Exception):
"""Something went wrong while traversing a parse tree.
This exception exists to augment an underlying exception with information
about where in the parse tree the error o... |
"""
백준 4153번 : 직각 삼각형
"""
while True:
numbers = list(map(int, input( ).split( )))
if numbers[0] == numbers[1] == numbers[2] == 0:
break
else:
sqr_num = [x ** 2 for x in numbers]
biggest = max(sqr_num)
sqr_num.remove(biggest)
if biggest == sum(sqr_num):
p... |
#
# PySNMP MIB module PDN-CP-IWF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-CP-IWF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:29:19 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... |
numero = int(input('Digite um número de 0 a 9999 '))
if numero >= 0 and numero <= 9999:
numero = str(numero)
print('Unidade {}'.format(numero[3]))
print('Dezena {}'.format(numero[2]))
print('Centena {}'.format(numero[1]))
print('Milhar {}'.format(numero[0]))
else:
print('Atenção numero de 0 a 9... |
def u64ToCounts(number):
"""
Convert an unsigned 64 bit number to a 25 element array containing the
photon counts for each of the 25 detector elements during a single dwell
time.
========== ===============================================================
Input Meaning
---------- ---... |
# -*- coding: utf-8 -*-
class StringMutations:
@classmethod
def _list_shift(cls, l, n):
return l[n:] + l[:n]
@classmethod
def length(cls, mutation, value, story, line, operator, operand):
return len(value)
@classmethod
def replace(cls, mutation, value, story, line, operator,... |
# Copyright 2016 Cisco Systems, 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 requir... |
# Tuplas são imutáveis
tupla1 = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
# tupla1[1] = 'Refrigerante'
print(tupla1)
print(tupla1[0]) # Hambúrguer
print(tupla1[3]) # Pudim
print(tupla1[-1]) # Batata Frita
print(tupla1[-2]) # Pudim
print(tupla1[1:3]) # Suco e Pizza
print(tupla1[2:]) # Pizza,... |
# Given an list , use bucket sort to sort the elements of the list and return
# Input: [1, 2, 4, 3, 5]
# Output: [1, 2, 3, 4, 5]
# divide the elements into several lists known as buckets
# loop through each buckets and sort them(insertion/quick sort)
# return each element of the buckets since they would be sorted al... |
class Error(Exception):
"""Handles general exceptions."""
class AbilityScoreImprovementError(Error):
"""Handles ability score improvement errors."""
class AnthropometricCalculatorError(Error):
"""Handles anthropometric calculator errors."""
class BlueprintError(Error):
"""Handles an invalid seamst... |
class A:
def __repr__(self):
True
a = A()
print(a.__repr__()) # ok
print(repr(a)) # fail
|
# Declaring a list
L = [1, "a" , "string" , 1+2]
print (L)
L.append(6)
print (L)
L.pop()
print (L)
print (L[1]) |
def func(a, b, *args, **kwargs):
print(a, b)
for arg in args:
print(arg)
for key, val in kwargs.items():
print (key, val)
def func2(a, b, c=30, d=40, **kwargs):
print(a, b)
print(c, d)
for key, val in kwargs.items():
print (key, val)
def func3(a, b, c=100, d=200):
p... |
__title__ = 'hrflow'
__description__ = 'Python hrflow.ai API package'
__url__ = 'https://github.com/hrflow/python-hrflow-api'
__version__ = '1.9.0'
__author__ = 'HrFlow.ai'
__author_email__ = 'contact@hrflow.ai'
__license__ = 'MIT' |
dummy_registry = {}
def dummy_register(name, value):
dummy_registry[name] = value
return value
|
# 695. 岛屿的最大面积
# 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
# 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
# 示例 1:
# [[0,0,1,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,1,1,0,0,0],
# [0,1,1,0,1,0,0,0,0,0,0,0,0],
# [0,1,0,0,1,1,0,0,1,0,1,0,0],
# [0,1,0,0,1,1,0,0,1,1,1,0,0],
# [... |
#
# Copyright (C) 2020 Square, Inc.
#
# 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,... |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Date: 2018-07-12 21:01:08
# @Last Modified by: jpch89
# @Last Modified time: 2018-07-12 21:07:53
people = 30
cars = 40
trucks = 15
if cars > people:
print ("We should take the cars.")
elif cars < people:
print("We should not take t... |
# A base sentence model for storing information related to sentences
# Created by: Mark Mott
class Sentence:
# A single underline denotes a private method/variable.
# Default is the property category
def __init__(self, sentence, subject, category='Property'):
self.setsentence(sentence)
self.... |
# Practice debug statement
print("Hello Python")
a = 10
b = 5
c = a + b
print("Hello Python2")
print(c)
c = 99
print("Hello Python3:%d", c)
#####################################################
# ** operator has high precedences than *
print(2**3*4)
print(4*2**3)
def changeVal(x):
x += 2;
###################... |
_base_ = [
'../../_base_/datasets/query_aware/few_shot_coco.py',
'../../_base_/schedules/schedule.py', '../attention-rpn_r50_c4.py',
'../../_base_/default_runtime.py'
]
# classes splits are predefined in FewShotCocoDataset
# FewShotCocoDefaultDataset predefine ann_cfg for model reproducibility
num_support_w... |
"""Top-level package for CT Parsers."""
__author__ = """Nick Cannariato"""
__email__ = 'devrel@birdcar.dev'
__version__ = '0.1.0'
|
TRAINING_FILE = "../data/train_folds5.csv"
MODEL_OUTPUT = "../models/"
LABEL="rating_y"
BEST_FEATURES = ['rating_x',
'user_id',
'members',
'episodes',
'Action',
'Drama',
'Fantasy',
'Hentai',
'Romance',
'Adventure',
'Comedy',
'School',
'Shounen',
'Supernatural',
'Kids',
'Mecha',
'Sci-Fi',
'Slic... |
def setup_subparser(subparsers, parents, python_version):
parser = subparsers.add_parser(
python_version,
description="""This sub command generates IDE and build files for Python {}
""".format(
"3.6" if python_version == "python36" else "3.7"
),
parents=parent... |
f = 1
print('calculando fatorial')
n = int(input('digite um número: '))
print(f'{n}! = ', end='')
for c in range(n, 0, -1):
print(c, end='')
print(' x ' if c > 1 else ' = ', end='')
f = c * f
print(f)
|
def find_smallest_element_index(array):
smallest_elem_index, smallest_elem = 0, array[0]
for index in range(1,len(array)):
if(smallest_elem >= array[index]):
smallest_elem_index = index
return smallest_elem_index
#changes the original array and puts the elements in sorted order (asc... |
"""Toyota Connected Services API constants."""
# URL ATTRIBUTE NAMES
BASE_URL = "base_url"
BASE_URL_CARS = "base_url_cars"
ENDPOINT_AUTH = "auth_endpoint"
TOKEN_VALID_URL = "auth_valid"
# REGIONS
SUPPORTED_REGIONS = {
"europe": {
TOKEN_VALID_URL: "https://ssoms.toyota-europe.com/isTokenValid",
... |
# A program that reads in students names
# until the user enters a blank
# and then prints them all out again
# the program prints out all the studens names in a neat way
students = []
Firstname = input("Enter Firstname (blank to quit): ").strip()
while Firstname != "":
student = {}
student ["Firstn... |
n1 = float(input('um distância em metros:'))
cm = n1 * 100
mm = n1 * 1000
print ('A medida de 3.0m corresponde a:')
print ('{:.0f} metros é igual a {:.0f} centímetros e a {:.0f} milimetros'.format(n1,cm,mm)) |
class Command:
command = "template" # command name must be the same as the file name but can have spacial characters
description = "description of command"
argsRequired = 1 # number of arguments needed for command
usage = "<command>" # a usage example of required arguments
examples = [{
'... |
# -*- coding: utf-8 -*-
"""
ASCII canvas
ASCII canvas module for drawing in console using ASCII chars
ASCII canvas supports the next objects:
- Point
- Line
- Rectangle
- Nine-Patch Rectangle
- Ellipse
- Text
And also supports Style for all these objects. The Style includes symbol,
foreground color, background co... |
'''
Here is a basic example to plot a signal from an lcm message.
In this example, the channel is POSE_BODY.
The X coordinate is the message timestamp in microseconds,
and the Y value is pos[0], or the first value of the pos array.
Note, msg is a pre-defined variable that you must use in order
for this to work. When ... |
# -*- coding: utf-8 -*-
"""Exceptions for bkpaas_auth module
"""
class ServiceError(Exception):
"""Login or Token service is not available"""
class InvalidSkeyError(Exception):
"""Invalid uin/skey given"""
class InvalidTokenCredentialsError(Exception):
"""When invalid credentials are given when exchan... |
# 001110010 prev = 0 cur = 0
# 0 01110010 prev = 0 cur = 1
# 0 0 1110010 prev = 0 cur = 2
# 00 1 110010 prev = 2 cur = 1 01
# 001 1 10010 prev = 2 cur = 2 0011
# 0011 1 0010 prev = 2 cur = 3
# 00111 0 010 prev = 3 cur = 1 10
# 001110 0 10 prev = 3 cur = 2 11... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 16 09:57:15 2016
@author: Mathew Topper
"""
#pylint: disable=C0103,W0622,R0903
class abstractclassmethod(classmethod):
"""Not that to make this work, you should place cls() in the abstract
definition"""
__isabstractmethod__ = True
def __init__(self... |
"""
import os
import bonobo
import logging
from dotenv import load_dotenv
from judah.utils.assets import get_asset_path
from judah.utils.logging import setup_rotating_file_logger
load_dotenv()
# Assuming you have an BBC ETL service, a rest_api_to_db child service and a number of microservices
# each corresponding ... |
class GuidanceRejectionException(Exception):
_MSG = "Unit tests should not write files unless they clean them up too."
def __init__(self):
super(GuidanceRejectionException, self).__init__(GuidanceRejectionException._MSG) |
equipmentMultipliers = [
{"hp": 10},
{"hp": 20},
{"hp": 30},
{"hp": 40},
{"sp": 10},
{"sp": 20},
{"sp": 30},
{"sp": 40},
{"tp": 2},
{"tp": 4},
{"tp": 6},
{"tp": 8},
{"atk": 10},
{"atk": 20},
{"atk": 30},
{"atk": 40},
{"def": 10},
{"def": 20},
{"def": 30},
{"de... |
# https://www.codechef.com/problems/MSNSADM1
for T in range(int(input())):
n,points=int(input()),0
scores,fouls=list(map(int,input().split())),list(map(int,input().split()))
for i in range(n):
if((scores[i]*20-fouls[i]*10)>points): points=scores[i]*20-fouls[i]*10
print(max(0,points)) |
#!/usr/bin/python3.6
def getPathToDataExchangeFolder():
return 'src/backend/dataExchange/'
def getPathToLogFolder():
return 'src/backend/log/'
def getPathToDataOutput():
return 'src/backend/dataOutput/'
def getPathOfMainJsonFile(artifact_name):
return getPathToDataExchangeFolder() + artifact_nam... |
def process_row_item(row_item):
if hasattr(row_item, 'strip'):
row_item = row_item.strip()
return row_item
def to_table_format(data_list):
header = []
rows = []
for row in data_list:
header = row.keys()
rows.append(list(map(process_row_item, row.values())))
return heade... |
#class common parameters
#put all parameters in there
#import module to baseline.py
class default_data:
def __init__(self):
#whoever is running this code make sure you change the name to your first name
self.user = "" #not needed, mainly to avoid file name conflicts
self.numLoops = 1
... |
n = float(input())
i = 0
for i in range(i, 100, 1):
print('N[{}] = {:.4f}'.format(i, n))
n = (n / 2) |
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
input = "ABCdefG"
p = Solution()
print(p.toLowerCase(input)) |
"""Configuration information for PDB2PQR."""
# PDB2PQR version number.
VERSION = "3.0"
# How to format PDB2PQR title in output
TITLE_FORMAT_STRING = "PDB2PQR v{version} - biomolecular structure conversion software"
# Citation strings for PDB2PQR
CITATIONS = [("Please cite: Jurrus E, et al. Improvements to the APBS... |
def solve(a,b):
dict={}
for i in range(max(a, 1), b):
temp=factors(i)
dict[sum(temp)/i]=dict.get(sum(temp)/i, [])+[i]
return sum(j[0] for j in dict.values() if len(j)>1)
def factors(n):
res={1, n}
for i in range(2, int(n**0.5)+1):
if n%i==0:
res.add(i)
... |
# Local settings for WLM project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = DEBUG
ALLOWED_HOSTS = '*'
ADMINS = (
#('Name', 'mail@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
... |
# source: https://www.bilibili.com/video/av21540971/?p=23
def bubble_sort(alist):
"""bubble sort
best: O(n)
worst: O(n^2)
stable
"""
n = len(alist)
for j in range(n-1):
count = 0
for i in range(n-1-j):
if alist[i] > alist[i+1]:
alist[i], alist[i+... |
python = "Python"
print("h " + python[3]) # Note: string indexing starts with 0
p_letter = python[0]
print(p_letter)
|
n =int(input())
count = 1
for i in range(1, n+1):
for j in range(1, i+1):
print(count*count, end=" ")
count+=1
print()
|
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
ret = []
if len(nums1)<len(nums2):
for i in nums2:
if i not in dic:
dic[i] = 0
dic[i] += 1
for j in nums1:
... |
def merge_sort(arr):
n = len(arr)
if n > 1:
mid = n//2
left = arr[0:mid]
right = arr[mid:n]
merge_sort(left)
merge_sort(right)
merge(left, right, arr)
def merge(left, right, arr):
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[... |
class Solution(object):
def countGoodRectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
maxLen = 0
counter = 0
for rectangle in rectangles:
# You can find the maximal square within a rectangle
maximalSq... |
positive_count = 0
zero_count = 0
negative_count = 0
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for num in arr:
if num > 0:
positive_count += 1
elif num == 0:
zero_count += 1
else:
negative_count += 1
print(positive_count / n)
print(negative_count / n)
print(zer... |
class Colors:
"""
This is a class that helps with printing out colors to the terminal.
"""
BLUE = '\033[96m'
PINK = '\033[95m'
PURPLE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
CLEAR = '\x1b[2J\x1b[H'
def clear_screen(self):
... |
ERROR_CHAR = "\u274c"
SUCCESS_CHAR = "\u2713"
def missingConfigurationFile():
print(
f"{ERROR_CHAR} nocpeasy.yml file does not exist, run `ocpeasy scaffold|init` first"
)
def stageCreated(stageId: str, pathProject: str):
print(
f"{SUCCESS_CHAR} new OpenShift stage created ({stageId}) for... |
# a Star topology centered on Z
# D G J
# \ | /
# \ | /
# E H K
# \ | /
# \ | /
# F I L
# \ | /
# ... |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/the-monk-and-kundan-6f73d491/
Kundan being a good friend of Monk, lets the Monk know that he has a following string Initial which consists of the
following letters in the mentioned order: "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ". ... |
class ErrorCode:
INVALID_ARGUMENT = 2
NOT_YET_SUPPORTED = 8
MISSING_REQUIREMENT = 9
FILE_NOT_FOUND = 20
FILE_CORRUPTED = 21
VPN_SERVICE_IS_NOT_WORKING = 90
VPN_ACCOUNT_NOT_FOUND = 91
VPN_ACCOUNT_NOT_MATCH = 92
VPN_NOT_YET_INSTALLED = 98
VPN_ALREADY_INSTALLED = 98
VPN_START_FA... |
"""
Store the global parameter dictionary to be imported and modified by each test
"""
OPT = {'dataset': 'Cora', 'self_loop_weight': 1, 'leaky_relu_slope': 0.2, 'heads': 2, 'K': 10,
'attention_norm_idx': 0, 'add_source': False, 'alpha': 1, 'alpha_dim': 'vc', 'beta_dim': 'vc',
'hidden_di... |
# Current version of the bcftbx package
__version__ = '1.11.1'
def get_version():
"""Returns a string with the current version of the bcftbx package (e.g., "0.2.0")
"""
return __version__
|
# @Title: 出现次数最多的子树元素和 (Most Frequent Subtree Sum)
# @Author: KivenC
# @Date: 2020-08-17 21:01:36
# @Runtime: 76 ms
# @Memory: 17.2 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
... |
person='abc'
video_source_number=0
thresholds=[.9,.85,.85,.85,.85,.95,.9]
extra_thresholds=[.85,.85,.85,.85]
#select the image widow and press w,s,a,d keys while running the script and looking in appropriate direction to change threshold
tsrf=True
#if true only image of eye will be processed may increase accuracy
mode=... |
#
# PySNMP MIB module RBTWS-RF-DETECT-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-RF-DETECT-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:45:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
class Border:
def __init__(self, l: bool = False, r: bool = False, t: bool = False, b: bool = False):
"""
Элемент границы.
:param l: должна ли граница соединяться слева
:param r: должна ли граница соединяться справа
:param t: должна ли граница соединяться сверху
:pa... |
# -*- coding: utf-8 -*-
"""
Интерфейс к различным устройствам, на которых будет моделироваться сеть.
"""
class Device(object):
"""
Абстрактный класс для устройств
"""
def __init__(self, config):
self.config = config
def tick_neurons(self, domain):
"""
Проверяем нейроны на с... |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
# none
# A note on style: Dictionaries can be defined before or after functions.
board = {'1': ' ' , '2': ' ' , '3': ' ' ,'4': ' ' , '5': ' ' , '6': ' ' ,'7': ' ' , '8': ' ' , '9': ' ' }
def gameboard(board):
print(board... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Financial Analysis\n",
"Total Months:86\n",
"Total Amount:38382578\n",
"-2315.1176470588234\n",
"Feb-2012 1926159... |
# Puzzle Input
with open('Day13_Input.txt') as puzzle_input:
bus_info = puzzle_input.read().split('\n')
# Get the departure time and the IDs
departure = int(bus_info[0])
bus_id = bus_info[1].split(',')
# Remove the x's
while 'x' in bus_id:
bus_id.remove('x')
# Convert the IDs to integers
bus_id = list(map(in... |
#!/usr/bin/env python
# -*- encoding:utf8 -*-
#*******************************************
# Author: LuoFeng
# Date: 2019-05-18
# Filename: 99_table.py
# Describe:
#*******************************************
# 正方形九九乘法表
for n in range(1,10):
# python3 print() 函数支持 end 参数,python2 不支持, 默认值 end = '\n'
for m in ra... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"PseudoData": "00_pseudodata.ipynb",
"paper_sig": "00_pseudodata.ipynb",
"paper_bkg": "00_pseudodata.ipynb",
"ModelWrapper": "01_model_wrapper.ipynb",
"DataSet": "02_data.i... |
def min(x, y):
return x > y and x or y
def gcd(x, y):
res = -1
for i in range(1, min(x, y) + 1):
if x % i == 0 and y % i == 0:
if res < i: res = i
return res
N, M = map(int, input().split())
print(gcd(N, M))
print(gcd(N, M) * (N // gcd(N, M)) * (M // gcd(N, M)))
|
#! /root/anaconda3/bin/python
try:
result = 1 / 2
#result = 1 / 0
#result = int('abc')
except ImportError:
print("导入错误")
except ZeroDivisionError:
print("0不能作为除数")
except TypeError:
print("类型错误")
else:
print(result)
finally:
print("释放资源")
print("结束")
####################################... |
# Python - 3.6.0
fruitList = {
1: 'kiwi',
2: 'pear',
3: 'kiwi',
4: 'banana',
5: 'melon',
6: 'banana',
7: 'melon',
8: 'pineapple',
9: 'apple',
10: 'pineapple',
11: 'cucumber',
12: 'pineapple',
13: 'cucumber',
14: 'orange',
15: 'grape',
16: 'orange',
17... |
__all__ = [
'base_controller',
'imaging',
'telephony',
'data_tools',
'security_and_networking',
'geolocation',
'e_commerce',
'www',
] |
f = open('test16.txt', 'rt')
rows = f.readlines()
for row in rows:
print(row)
f.close()
# while True:
# row = f.readline()
# print(row)
# if not row:
# break
# f.close() |
flagArray = [0 for i in range(32)]
flag = ""
flagArray[0] = 'd'
flagArray[29] = '9'
flagArray[4] = 'r'
flagArray[2] = '5'
flagArray[23] = 'r'
flagArray[3] = 'c'
flagArray[17] = '4'
flagArray[1] = '3'
flagArray[7] = 'b'
flagArray[10] = '_'
flagArray[5] = '4'
flagArray[9] = '3'
flagArray[11] = 't'
flagArray[15... |
def percents_yearly_to_monthly(yearly_percent):
return ((1 + yearly_percent) ** (1 / 12)) - 1
def currency_str(number, currency="ILS"):
if currency == "ILS":
return "₪{:,.2f}".format(number)
if currency == "USD":
return "${:,.2f}".format(number)
return "{:,.2f} ".format(number) + curre... |
print("Enter a selection from the below menu. Press '0' to exit.")
menu_items = ["Bake a loaf of bread", "Bake a pound cake", "Prepare Roast Chicken", "Make Curry", \
"Put a rack of ribs in the smoker", "Buy dinner out", "Have ice cream", "Sandwiches - again"]
select = None
while True:
for i in range(len(menu... |
"""
Write a program to remove the item present at index 4 and
add it to the 2nd position and at the end of the list.
Given:
list1 = [34, 54, 67, 89, 11, 43, 94]
Expected Output:
List After removing element at index 4 [34, 54, 67, 89, 43, 94]
List after Adding element at index 2 [34, 54, 11, 67, 89, 43, 94]
List ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.