content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
#
# Copyright 2019 SoloKeys Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... |
""" Parameters of the Agresti data sets, as documented for SoftKinect camera"""
resolution = [240, 320]
fov = [74, 58]
|
# https://leetcode.com/problems/flood-fill
class Solution:
def dfs(self, image, y, x, oldColor, newColor):
image[y][x] = newColor
nexts = [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]
for ny, nx in nexts:
if (
0 <= ny < len(image)
and 0 <= nx ... |
list_of_strings=input().split()
list_of_integers=[]
reversed_integers=[]
for index in list_of_strings:
list_of_integers.append(int(index))
for el in list_of_integers:
reversed_integers.append(el*(-1))
print(reversed_integers)
|
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
class CommunicationUser(object):
"""
Represents a user in Azure Communication Service.
:ivar identifier: Communication user identifier.
:vartype identif... |
class Neuron(object):
"""
This Class is representing a Neuron which is corresponding to an action to perform.
.. note:: Neurons are defined in the brain file
"""
def __init__(self, name=None, parameters=None):
self.name = name
self.parameters = parameters
def serialize(self):
... |
__all__ = ['Content']
class Content(object):
def __init__(self, value):
if value is None:
value = ''
if not isinstance(value, str):
raise TypeError('`value` should be a string')
self.value = value
def __str__(self):
return self.value
def write(self... |
'''
1 - Classe Bola: Crie uma classe que modele uma bola:
Atributos: Cor, circunferência, material
Métodos: trocaCor e mostraCor
'''
class bola():
"""[Classe bola]
"""
def __init__(self, cor, circ, mat):
"""[summary]
Args:
cor ([str]): [Determina a cor da bola]
cir... |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
result = ''
input_str = s.split(' ')
for each in input_str:
result = result + each[::-1] + ' '
return result[:-1]
# return ' '.join(x[::-1] for x i... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# SNN
TIME_STEP_IN_MSEC = 0.1
THRESHOLD_THETA_INCREMENT_RATE = 0.2
THRESHOLD_THETA_DECAY_RATE = 0.01 * TIME_STEP_IN_MSEC # (0, 1), lower value means slower decay
MAX_THRESHOLD_THETA = 20.0
LIF_MEMBRANE_POTENTIAL_THRESHOLD = 1.0
LIF_SPIKE_VOLTAGE = 1.0
IZ_MEMBRANE_POTENTIAL_THRESHOLD = 30.0
IZ_SPIKE_VOLTAGE = 100
# Iz... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def countdown(n):
print("Counting down from %d" % n)
try:
while n > 0:
yield n
n -= 1
except GeneratorExit: # 捕获GeneratorExit异常
print("Only made it to %d" % n)
|
# As maçãs custam R$ 1,30 cada se forem compradas menos de uma dúzia, e R$ 1,00 se forem compradas
# pelo menos 12. Escreva um programa que leia o número de maçãs compradas, calcule e escreva o custo total
# da compra
print('Este app cálcula o valor da compra de MAÇÃS')
a=int(input('Digite a quantidade de maçãs que d... |
# https://leetcode.com/problems/dice-roll-simulation/
# simple dp
class Solution:
def rec(self, i, prev, prev_cnt):
if prev_cnt > self.rollMax[prev]:
return 0
if i > self.n: # reached a solution
return 1
if self.dp[i][prev][prev_cnt] !=-1:
return self.dp[... |
# Title : Remove duplicate list
# Author : Kiran raj R.
# Date : 23:10:2020
def remove_dup(nested_list):
out_list = []
for i in range(len(nested_list)):
for j in range(1, len(nested_list)):
if nested_list[i] == nested_list[j]:
break
if i == j:
out_list... |
初始化
num1 = 10
num2 = 20
num3 = 30
|
KEYWORDS = {
'if',
'else',
'return',
'\\',
}
OPERATORS = {
'=', '-', '+', '/', '*', '>', '<', '|', '^', '&', '~',
}
class MalformedInput(Exception):
pass
class Lexeme:
def __init__(self, type, value):
self.type = type
self.value = value
def __repr__(self):
... |
print("Hello World from %s!" % __name__)
if __name__ == '__main__':
print("Hello World again from %s!" % __name__)
#python a.py
#python b.py |
"""Define constant values used across the project."""
class DefaultTokens(object):
PAD = '<blank>'
BOS = '<s>'
EOS = '</s>'
UNK = '<unk>'
MASK = '<mask>'
VOCAB_PAD = 'averyunlikelytoken'
SENT_FULL_STOPS = [".", "?", "!"]
PHRASE_TABLE_SEPARATOR = '|||'
ALIGNMENT_SEPARATOR = ' ||| '
... |
def get_weights(vs):
# :brief Get the weights for some set of update vectorsself.
# :param vs [array<array<float>>] some update vectors
# :return a [array<float>] a list of weights in the same order
ls = []
for v in vs:
l = 0.0
for e in v:
l += e**2
l = l**0.5
... |
class Animal():
def __init__(self,name,id):
self.name=name
self.id=id
def getId(self):
return self.id
def setId(self,id):
self.id=id
dog = Animal('dog',1)
id = dog.getId()
print(id)
dog.setId(2)
id = dog.getId()
print(id)
|
# 1025. Divisor Game
"""
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
Choosing any x with 0 < x < N and N % x == 0.
Replacing the number N on the chalkboard with N ... |
#!/usr/bin/python
array1 = [1, 2, 3]
array2 = array1
array1[0] = 4
print (array1)
print (array2)
|
def dH_atoms(at):
"""
Returns the enthalpy corrections of the element.
Parameters:
at (char): Symbol of the element
Returns:
dH_atoms (float): Enthalpy corrections of the element
"""
h = 6.626070040*(10**-34) #6.626070040d-34
Ry =... |
video = "NET20070331_thlep_1_2"
training = 0
if training:
file_path = "mouth_features_train/" + video
mouth_features = open(file_path + "/mouth_features_train.txt", "r")
mouth_features_clear = open(file_path + "/mouth_features_clear.txt", "w")
else:
file_path = "mouth_features_test/" + video
mouth_features = ope... |
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
result = 0
for seat, group in itertools.groupby(seats):
if seat: continue
K = len(list(group))
result = max(result, (K + 1) // 2)
return max(result, seats.index(1), seats[::-1].index(1)... |
class DisconnectedError(RuntimeError):
def __init__(self):
msg = 'Must self.connect before continuing.'
RuntimeError.__init__(self, msg)
class OperationFailed(RuntimeError):
def __init__(self, op, report):
message = '{0}: {1}:{2}'.format(op, report._diagnostics, report.errors)
... |
# given an int, return the reverse of itself.
# inp: 1234
# return: 4321
# perform operation on |x| and return along with the sign of x. using built in function abs()
def reverse_int(x):
rev = 0
x_remaining=abs(x)
while x_remaining:
rev = 10*rev + x_remaining%10
x_remaining //=10
return -rev if x < 0 else r... |
# Generated by make-pins.py, do NOT edit!
PINS_AF = (
('LED1', (0, 'LPI2C2_SCL'), (1, 'FLEXPWM1_PWMA1'), (2, 'LPUART2_TX'), (3, 'SAI1_TX_DATA2'), (5, 'GPIO1_PIN24'), ),
('LED2', (0, 'LPI2C2_SDA'), (1, 'FLEXPWM1_PWMB1'), (2, 'LPUART2_RX'), (3, 'SAI1_TX_DATA3'), (5, 'GPIO1_PIN25'), ),
('LED3', (1, 'FLEXPWM1_PWMA2')... |
"""Top-level package for telomemore."""
__author__ = """William Rosenbaum"""
__email__ = 'william.rosenbaum88@gmail.com'
__version__ = '0.0.1'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def numbertoampm(hour: int, minute: int) -> tuple:
"""
Convert time in hh:mm format to AM/PM.
"""
if hour < 12 or hour == 24:
period = 'AM'
else:
period = 'PM'
hour = hour % 12
if hour == 0:
hour = 12
return (hour, m... |
# import sys
# from PyQt5.QtWidgets import *
#
#
# class MainWindow(QDialog):
# def __init__(self, ):
# super(QDialog, self).__init__()
# self.number = 0
#
#
#
# self.topFiller = QWidget()
# self.topFiller.setMinimumSize(250, 1000) #######设置滚动条的尺寸
# for filename in range(20)... |
"""Default configuration settings"""
DEBUG = True
TESTING = False
LOGGER_NAME = 'api-server'
LOG_FILENAME = 'api-server.log'
|
def add_native_methods(clazz):
def cmmLoadProfile__byte____long____(a0, a1):
raise NotImplementedError()
def cmmFreeProfile__long__(a0):
raise NotImplementedError()
def cmmGetProfileSize__long__int____(a0, a1):
raise NotImplementedError()
def cmmGetProfileData__long__byte____(... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# # Reversed Second Half == First Half (Accepted), O(n) time, O(1) space
# def isPalindrome(self, head: ListNode) -> bool:
# if not head ... |
yolo_config = {
# Basic
'img_size': (416, 416, 3),
'anchors': [12, 16, 19, 36, 40, 28, 36, 75, 76, 55, 72, 146, 142, 110, 192, 243, 459, 401],
'strides': [8, 16, 32],
'xyscale': [1.2, 1.1, 1.05],
# Training
'iou_loss_thresh': 0.5,
'batch_size': 8,
'num_gpu': 1, # 2,
# Inference
... |
ordered_counties = [18, 44, 45, 30, 39, 14, 13, 6, 12, 15, 21, 46, 5, 50, 19, 48, 4, 33, 23, 29, 27, 24, 43, 47, 11, 10, 37, 35, 31, 32, 41, 25, 20, 38, 36, 16, 7, 9, 8, 28, 2, 34, 17, 3, 1, 26, 49, 40, 42, 22]
county_lean = {}
with open('raw_data.txt') as file:
data = file.read().split('\n')
for county in data:
c... |
# Copyright Contributors to the Pyro-Cov project.
# SPDX-License-Identifier: Apache-2.0
class ShardedFastaWriter:
"""
Writer that splits into multiple fasta files to avoid nextclade file size
limit.
"""
def __init__(self, filepattern, max_count=5000):
assert filepattern.count("*") == 1
... |
"""Train/Validation/Test dataset split
The dataset needs to be split into train/val/test sets to properly validate the hypothesis.
To make sure the split is always consistent, it is hardcoded here.
All other scripts reference this file for the split ids.
"""
all_ids = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Name: pitch.py
# Purpose: a single pitch event in a retrosheet eventfile event
#
# Authors: Michael Scott Cuthbert
#
# Copyright: Copyright © 2015 Michael Scott Cuthbert / cuthbertLab
# License... |
# html 页面解析返回后的内容类型
PARSED_TYPE = 'word_text'
# 采购订单的状态值
NOT_ARRIVED = 1 # 未到货
CLOSED = 4 # 已关闭
PENDING = 5 # 待提交
AUDITTING = 6 # 审核中
|
load("@bazel_gazelle//:deps.bzl", "go_repository")
def pull_monitor_dependencies():
go_repository(
name = "com_github_hashicorp_errwrap",
commit = "8a6fb523712970c966eefc6b39ed2c5e74880354", # 1.0.0
importpath = "github.com/hashicorp/errwrap",
)
go_repository(
name = "com_... |
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if not root: return
def mirror(self, l, r):
self... |
class Solution:
def videoStitching(self, clips, T: int) -> int:
def func(start: int) -> int:
# 从列表中选取所有第一位小于等于start的项,从这些项中找出第二位最大的,并返回该值。
end = -1
for clip in clips:
if clip[0] <= start:
if clip[1] > end:
end = ... |
class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peek(self):
if not self.is_empty():
return self.... |
class checker():
# Similarity Checker V.0.0.8 | Made by Jekkow
def __init__(self, Set_Difference = 1, Length_Difference = 2, Minimum_Percentage = 0.75):
# Set Variables
self.Set_Difference = Set_Difference # Public Variable
self.Length_Difference = Length_Difference # Public Variab... |
# Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os
# 10 primeiros termos desta progressão.
print()
ptermo = int(input('Digite o primeiro termo: '))
n = int(input('Digite o valor do enésimo número: '))
razão = int(input('Digite o valor da razão: '))
décimo = ptermo + (n - 1) * ra... |
def fact (n):
if n==0:
return 1
return n*fact(n-1)
result=fact(int(input("Enter the number")))
print(result)
|
'''
URL: https://www.hiredintech.com/classrooms/algorithm-design/lesson/76/task/29
Task: Numeric Palindromes
A palindrome is а word or a phrase or a number, that when reversed, stays the same.
For example, the following sequences are palindromes : "azobi4amma4iboza" or "anna".
But this time, we are not interested in w... |
# ID = input("请输入一段字符串:")
strs = "hello,Python,hello,c"
# 默认使用空格做分配符,strs中无空格,列表中只有一个元素
print(strs.split())
# 使用逗号做分配符
print(strs.split(","))
# 使用逗号做分配符,限制分割2次
print(strs.split(",",2))
# 使用join 将列表与字符连接成字符串
strList = ['hello', 'Python', 'hello', 'c! ']
strs2 = " "
print(strs2.join(strList))
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RoleNetworkInterfaceEnum(object):
"""Implementation of the 'Role_NetworkInterface' enum.
Specifies the role of this interface.
Attributes:
KPRIMARY: TODO: type description here.
KSECONDARY: TODO: type description here.
"""... |
n = int(input())
if n > 10:
print("High Five")
elif n > 0:
for i in range(n):
print("Ra!")
else:
print("shh")
|
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
arguments = ["self", "info", "args"]
helpstring = "host <nick>"
minlevel = 1
def main(connection, info, args) :
"""Specifies the hostname of the nick given"""
connection.msg(info["channel"], '%s: "%s"' % (info["sender"], connection.hostnames[args[1]]))
|
salario = int(input ('Salario: '))
imposto = 27.
while imposto > 0.:
imposto = input('Imposto ou (0) para sair:')
#Comando abaixo indica se a variavel imposto for vazia
if not imposto:
imposto: 27.
elif imposto == 's':
break
else:
imposto = float(imposto)
print( "Valor r... |
class IComponent(IDisposable):
""" Provides functionality required by all components. """
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
Site = property(... |
"""Non-flag command line arguments"""
def validate(args):
if isinstance(args, str):
args = [args]
return args
|
"""
Profile ../profile-datasets-py/us76_43lev_allgas/004.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/us76_43lev_allgas/004.py"
self["Q"] = numpy.array([ 1.32999800e+00, 1.99999600e+00, 2.69999300e+00,
3.29998900e+00, 3.99998400e+00, 4.49998... |
nums = [1, 2, 3, 4]
print("Before Remove: ", nums)
nums.remove(3)
print("After Remove: ", nums)
print(nums.pop())
print("After Pop", nums)
nums.extend([3, 4])
print("After Extend: ", nums)
nums.insert(0, 1)
print("After insert: ", nums)
nums.append([])
print("After append: ", nums)
|
#
# PySNMP MIB module CISCO-DS3-EXT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DS3-EXT-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:38:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
class Cycle(object):
def __init__(self, graph):
self.cycle = None
if self.has_parallel_edges(graph):
return
self.marked = [False for _ in range(graph.v)]
self.edge_to = [0 for _ in range(graph.v)]
for v in range(graph.v):
if not self.marked[v]:
... |
def main():
for n in range(1, 11):
print(n)
if __name__ == '__main__':
main()
|
# def print_pattern():
# for i in range(1, 4):
# for j in range(i, i+1):
# print("*"*j)
def print_pattern():
for i, j in zip(range(2, -1, -1), range(1, 6, 2)):
print(" "*i + "*"*j)
if __name__ == "__main__":
print_pattern()
# *
# ***
#***** |
mimeDict = {'.bin': 'application/octet-stream',
'.bmp': 'image/bmp',
'.c': 'text/x-c',
'.css': 'text/css',
'.dmg': 'application/vnd.apple.installer+xml,',
'.f4v': 'video/x-f4v',
'.flv': 'video/x-flv',
'.h261': 'video/h261',
'.h263': 'video/h263',
'.h264': 'video/h264',
'.ico': 'image/x-ico... |
#
# @lc app=leetcode id=171 lang=python3
#
# [171] Excel Sheet Column Number
#
# @lc code=start
class Solution:
def titleToNumber(self, s: str) -> int:
number = 0
for c in s:
number = number*26 + ord(c) - ord('A') + 1
return number
# @lc code=end
# Accepted
# 1000/1000 cases... |
response = natural_language_understanding.analyze(
html="Space/SpaceX and NASA Launch Is First Step to Renewed Human Spaceflight - The New York Times.html",
features=Features(
categories=CategoriesOptions(limit=4),
concepts=ConceptsOptions(limit=10)),
clean=False
... |
mylist = ["Firefox","Chrome","Safari","Microsoft Edges","Brave"]
print("Unsorted List: ",mylist)
mylist.sort()
print("Sorted List in Increasing Order: ",mylist)
mylist.sort(reverse=True)
print("Sorted List in Decreasing Order: ",mylist) |
"""
This is a program intend to convert numeric scores into grades.
The program can identify valid and legal inputs (scores range in 0 to 100) and remind users to input valid inputs.
Written by Qi Zhao
"""
def validScores(yourMsg):
#get the valid input scores
try:
scores = float(yourMsg)
except V... |
"""This package contains classes, functions, objects and packages contributed
by Cheetah users. They are not used by Cheetah itself. There is no
guarantee that this directory will be included in Cheetah releases, that
these objects will remain here forever, or that they will remain
backward-compatible.
""... |
L_TYPE = {
0: 'Not Licensed',
1: 'Full Driver License',
2: 'Intermediate Driver License',
6: 'No Driver Present/Unknown if Driver Present',
7: 'Learner\'s Permit',
8: 'Terporary License',
9: 'Unkown License Type'
}
|
def generate_field():
field = [['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', ... |
def narrative():
text1 = [
'The year is 2190.',
'Uploading your consciousness to the Great Server in the Sky is the new standard.',
'You have just left your physical life on Earth.',
'You found your Soulmate in your community, and you also found… your Hellmate.',
'Your Soulma... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 15:14:11 2018
@author: behzad
"""
L = 0.05 # this is the length in m
A = 0.22 # area in m2
k= 0.78 #N conductivity W/mK
R_cond = L/(k*A) # resistance on C/W
h_i= 10 # w/m^2 K
R_conv_i = 1/(h_i*A)
h_0= 40 # w/m^2 K
R_conv_o = 1/(h_0*A)
name1= "Manuel"
# mu... |
# flake8: noqa
# In[]:
# Controls for webapp
COUNTIES = {
"001": "Albany",
"003": "Allegany",
"005": "Bronx",
"007": "Broome",
"009": "Cattaraugus",
"011": "Cayuga",
"013": "Chautauqua",
"015": "Chemung",
"017": "Chenango",
"019": "Clinton",
"021": "Columbia",
"023": "Co... |
#coding:utf-8
# 集合覆盖问题
states_needed = set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'])
# 广播清单
stations = {}
stations['kone'] = set(['id', 'nv', 'ut'])
stations['ktwo'] = set(['id', 'wa', 'mt'])
stations['kthree'] = set(['or', 'nv', 'ca'])
stations['kfour'] = set(['nv', 'ut'])
stations['kfive'] = set(['ca', 'az'... |
# one of many possible solutions
weights = [-2, 5]
b = -.6
plot_decision(perceptron, X, y, weights=weights, b=b) |
def emailConfirmationTemplate(userName, confirmationLink):
return f"""
<html>
<body>
<p>Hi {userName}!<br>
Thanks for creating an account with LUSE! We're thrilled to get you started
investing. Please follow the link below to confirm your ... |
'''
huygens
=======
My personal Python library of commonly used functions
D. C. Groothuizen Dijkema - December, 2019
'''
__all__=[]
|
V = int(input())
def m_to_edge(mat):
for i in range(len(mat)):
for j in range(i, len(mat)):
if mat[i][j] == 1:
print(i + 1, j + 1, sep=" ")
return 0
matrix = [list(map(int, input().split())) for _ in range(V)]
m_to_edge(matrix)
|
"""
[01/07/13] Challenge #116 [Easy] Permutation of a string
https://www.reddit.com/r/dailyprogrammer/comments/164zvs/010713_challenge_116_easy_permutation_of_a_string/
# [](#EasyIcon) *(Easy)*: Permutation of a string
Write a function that prints all of the permutatons of the unique characters of a given string. For... |
#
# Copyright (c) 2018 cTuning foundation.
# See CK COPYRIGHT.txt for copyright details.
#
# See CK LICENSE for licensing details.
# See CK COPYRIGHT for copyright details.
#
def evaluate(results_dir, annotations_dir):
# TODO: run `ck-tensorflow:program:kitti-eval-tool`
raise Exception('KITTI evaluation is not imp... |
def bubbleSortdesc(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next e... |
class Solution:
def numTilings(self, n: int) -> int:
dp, dpa = [1, 2] + [0] * n, [1] * n
for i in range(2, n):
dp[i] = (dp[i - 1] + dp[i - 2] + dpa[i - 1] * 2) % 1000000007
dpa[i] = (dp[i - 2] + dpa[i - 1]) % 1000000007
return dp[n - 1]
|
# https://leetcode.com/problems/keyboard-row/
KEYS = {
**{k:1 for k in 'QWERTYUIOP'},
**{k:2 for k in 'ASDFGHJKL'},
**{k:3 for k in 'ZXCVBNM'}
}
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
return [word f... |
"""folders.py
Variables to store the folder names
"""
RAW = "results/raw/"
# QC
QC = "results/qc/"
# mappings
MAP_INDEX = "results/index/"
MAP_RAW = "results/map/raw/"
MAP_SPLIT = "results/map/split/"
MAP_FILT = "results/map/filt/"
# mpileup - SNP calling - popoolation
MPILEUP_RAW = "results/mpileup/raw/"
MPILEUP_F... |
class Allergen:
""" Array of allergens drawn from the controlled list of allergens.
For an Allergen Alert there will also be at least one allergen present on the problem statement.
Attributes:
_label (string): name for the allergen
_notation (string): a unique identifier for the allergen
... |
def octal_to_quinary(octal_number):
'''Convert octal number to quinary number
You can covert octal_number to binary by converting the given octal_number to decimal and then obtained decimal to quinary
For an instance, lets take an octal number to be 123
Step 1: Covert octal num... |
# -*- coding: utf-8 -*-
# @Time : 2019/10/18 13:31
# @Author :
# @Site :
# @File : config.py
# @Software: PyCharm
class DBConfig:
@staticmethod
def get_db_config(db_type):
if db_type == 'dev':
return Development()
class Development:
host = 'localhost'
user = 'root'
pa... |
# -*- encoding: utf-8 -*-
DBUS_NAME = "org.freedesktop.DBus"
SERVICE_NAME = "org.bluez"
DBUS_OM_INTERFACE = DBUS_NAME + ".ObjectManager"
INTROSPECTABLE_INTERFACE = DBUS_NAME + ".Introspectable"
BLUEZ_MANAGER_INTERFACE = SERVICE_NAME + ".BluezManager1"
AGENT_MANAGER_INTERFACE = SERVICE_NAME + ".AgentManager1"
PROFIL... |
class SupplierInvoiceService(object):
"""
:class:`fortnox.SupplierInvoiceService` is used by :class:`fortnox.Client` to make
actions related to SupplierInvoice resource.
Normally you won't instantiate this class directly.
"""
"""
Allowed attributes for SupplierInvoice to send to Fortnox ba... |
class Material(object):
def __init__(self, diffuse_color, mirror=0.05, softness=0.03):
self.diffuse_color = diffuse_color
self.mirror = mirror
self.softness = softness
|
x = int(input())
y = int(input())
menor = min(x, y)
maior = max(x, y)
soma = 0
for i in range(menor, maior + 1):
if i % 13 != 0:
soma += i
print(soma)
|
"""
15 / 15 test cases passed.
Runtime: 36 ms
Memory Usage: 15.3 MB
"""
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stk, dct = [], {}
for num in nums2:
while stk and stk[-1] < num:
dct[stk.pop()] = num
stk.app... |
class Literal():
def __init__(self, literal):
self.literal = literal
def optimizacion(self):
return self.literal |
# Apresentação
print('Programa para apurar o resultado de um aluno')
print()
# Entradas
n1 = float(input('Informe a nota 1 do aluno: '))
n2 = float(input('Informa a nota 2 do aluno: '))
# Processamento
media = (n1 + n2) / 2
# Saídas
print('Média do aluno: ', media)
if (media >= 6):
print('Aluno a... |
# 字符串的操作
str1 = "1234567890"
str2 = "您好地球!"
str3 = "select name from employees where name like \"%eric%\"" # 反斜杠为转义符
str4 = "hello world\nmy love" # 换行
str5 = """This is a fantastic program to improve your life:
[1] get more money
[2] get a family
[3] make the world peace
please input your option:""" # 三个"""前后括起大段的... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
# reverseArrayOfStrings.py
def reverseArrayOfStrings(arr):
# initialization, pointer is for another implementation
rev_str, res, beg, end, pointer = "", [], 0, 0, 0
# print (rev_str, res,beg, end)
# traverse through array from the end
for i in range(len(arr)-1, -1, -1):
print (arr[i])
... |
def pionek(w, p, c):
plansza = []
dlug_rzedu = int(len(p) / w)
ruchy = 0
for i in range(w):
plansza.append(p[i * dlug_rzedu : (i+ 1) * dlug_rzedu])
wystapienia = []
for j in range(len(plansza)):
for k in range(len(plansza[j])):
if int(plansza[j][k]) == c:
... |
# config.py
class Config(object):
"""
Common configurations
"""
# Put any configurations here that are common across all environments
class DevelopmentConfig(Config):
"""
Development configurations
"""
DEBUG = True
DEVELOPMENT = True
SQLALCHEMY_ECHO = True
PORT = 80
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.