content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# COPYRIGHT (C) 2014-2020 Mitsuo KONDOU.
# This software is released under the MIT License.
# https://github.com/konsan1101
# Thank you for keeping the rules.
def getkey(api, key, ):
# azure 画像認識
if (api == 'cv'):
print('vision_api_azure_key.py')
... |
#pembuatan fungsi
def hitung_gaji():
nama =(input("masukan Nama anda :"))
gol=(input("masukan golongan:"))
if gol =="1":
gaji=1000000
tunjangan= 250000
total=gaji+tunjangan
print(f"total gaji yang anda terima {total}")
elif gol == "2":
gaji = 2000000... |
def add(x, y):
return x + y
def times(func, x, y):
return func(x, y)
a = 2
b = 4
r = times(add, a, b)
print(' - Resultado = ', r)
|
# ##Create 5 dictionaries which have list values
dict1 = {'State': 'Maharashtra', 'City': 'Pune', 'Best Places to Visit': ['Shanivarwada', "Pataleshwar", "Dagdusheth", "Tulshibag"]}
dict2 = {'State': 'Goa', 'Cty': 'North Goa', 'Best Places to Visit': ["panji", "Baga", "Calngut", "Meeramaar"]}
dict3 = {'State': 'Mahara... |
description = 'TOF counter devices'
group = 'lowlevel'
devices = dict(
monitor = device('nicos.devices.generic.VirtualCounter',
description = 'TOFTOF monitor',
fmtstr = '%d',
type = 'monitor',
lowlevel = True,
pollinterval = None,
),
timer = device('nicos.devices.ge... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/20 17:54:58
# @Author : ddvv
# @Site : https://ddvvmmzz.github.io
# @File : filetypes.py
# @Software: Visual Studio Code
FILE_TYPE_MAPPING = {
'eml': 'eml',
'html': 'html',
'zip': 'zip',
'doc': 'ole',
'docx': 'zip',
'xls': 'ole',
'xlsx': ... |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
"""
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
来源:力扣(LeetCode)
链... |
#!/usr/bin/python3
"""
Given:
Return:
"""
def main():
# Parse in.txt
with open('./in.txt') as f:
for i, line in enumerate(f):
print(i, line)
if __name__ == '__main__':
main()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
NumOfLines = int(input()) # taking first input 2
for j in range(NumOfLines): # makes sure we take all the lines as n
s = input() # taking 1st and 2nd line
evens, odds = '',''
for ... |
class MyMessage:
"""
message type definition
"""
# message to neighbor
MSG_TYPE_INIT = 1
MSG_TYPE_SEND_MSG_TO_NEIGHBOR = 2
MSG_TYPE_METRICS = 3
MSG_ARG_KEY_TYPE = "msg_type"
MSG_ARG_KEY_SENDER = "sender"
MSG_ARG_KEY_RECEIVER = "receiver"
"""
message payload keyw... |
def add_feature(training_df):
training_df["bin_label"] = training_df.label.apply(lambda l: "O" if l == "O" else "I")
training_df["token_num"] = training_df.token.apply(lambda t: len(t.doc))
training_df["loc"] = training_df.token.apply(lambda t: t.i)
training_df["len"] = training_df.token.apply(lambda t:... |
def autopack_toggle():
'''Automatically pack all external files into the .blend file
'''
pass
def bookmark_add():
'''Add a bookmark for the selected/active directory
'''
pass
def bookmark_cleanup():
'''Delete all invalid bookmarks
'''
pass
def bookmark_delete(index=-1)... |
"""
1. Clarification
2. Possible solutions
- Sorting
- One pointer
- Two pointers v1
- Two pointers v2
3. Coding
4. Tests
"""
# T=O(nlgn), S=O(n)
class Solution:
def sortColors(self, nums: List[int]) -> None:
nums.sort()
# T=O(n), S=O(1)
class Solution:
def sortColors(self, nums: Lis... |
'''
@Author: CSY
@Date: 2020-01-28 09:55:04
@LastEditors : CSY
@LastEditTime : 2020-01-28 09:55:17
'''
a=5%2==1
print(a) |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 11:39:22 2020.
@author: Mark
"""
#%%
class VamasHeader:
"""Class for handling headers in Vamas files."""
def __init__(self):
"""
Define default values for some parameters in the header.
Returns
-------
None.
"... |
# sum of n to n verbose 1
print('sum of n to n')
number1 = int(input('input number1: '))
number2 = int(input('input number2: '))
if number1 > number2:
number1, number2 = number2, number1
sum = 0
for i in range(number1, number2 + 1):
if i < number2:
print(f'{i} + ', end='')
else:
print(f'{... |
"""
Напишем простой калькулятор квадратных уравнений
"""
def solve_equation():
"""Решает квадратное уравнение вида ax^2+bx+c"""
expression = input('Введите уравнеие ввиде ax^2+bx+c: \n')
a = expression[:expression.find('x^2')]
b = expression[expression.find('x^2')+3:expression.rfind('x')]
c = exp... |
#!/usr/bin/python3
# Read the file in to an array
input = []
f = open("input.txt", "r")
for l in f:
input.append(l)
def find_search_bit(position, input_list):
v = ""
for i in input_list:
v = v + i[position]
if v.count('1') == v.count('0'):
return 1
elif v.count('1') > v.count('... |
class SudokuGrid :
def __init__(self,grid=[]) :
if grid :
i = iter(grid)
j = len(next(i))
if j == 9 and all(len(l) == j for l in i):
self.grid = grid
return
self.grid = [[0 for i in range(9)] for j in range(9)]
def sho... |
def get_initializer(initializer, is_bias=False):
"""
get caffe initializer method.
:param initializer: DLMDL weight/bias initializer declaration. Dictionary
:param is_bias: whether bias or not
:return: weight/bias initializer dictinary
"""
def get_value(key, default=None):
... |
class Heapsort:
def sort(self, arr):
self.__build_max_heap(arr)
size = len(arr) - 1
for i in range(size, -1, -1):
self.__max_heapify(arr, 0, i)
# swap last index with first index already sorted
arr[0], arr[i] = arr[i], arr[0]
def __build_max_heap(self, arr):
size = len(arr) - 1
... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Admin scripts and modules which should not be shipped with Flocker.
Since :module:`admin.release` is imported from setup.py, we need to ensure that
this only imports things from the stdlib.
"""
|
#
# PySNMP MIB module ADTRAN-AOS-VQM (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-VQM
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:58 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... |
def fahrenheit(T):
return (float(9.0) / 5) * T + 32
print(fahrenheit(0))
temp = [0, 22.5, 40, 100]
print(map(fahrenheit, temp)) # ?????????????? <map object at 0x00000214D009E080>
c = map(lambda T: (9.0 / 5) * T + 32, temp)
print(c) # <map object at 0x00000214D009E080>
print(lambda x, y: x + y)
a = [1, 2, 3... |
def j(n, k):
p, i, seq = list(range(n)), 0, []
while p:
i = (i+k-1) % len(p)
seq.append(p.pop(i))
return 'Prisoner killing order: %s.\nSurvivor: %i' % (', '.join(str(i) for i in seq[:-1]), seq[-1])
print(j(5, 2))
print(j(41, 3))
|
rfile = open("dictionary.txt", "r")
wfile = open("dict-5.txt","w")
for line in rfile:
if len(line) == 6:
wfile.write(line) |
"""Functions for prediction table creation and operations."""
def format_data():
pass
def create_table(db, prediction_data):
pass
def insert():
pass
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
class Solution:
def solve(self, matrix):
leaders = {(r,c):(r,c) for r in range(len(matrix)) for c in range(len(matrix[0])) if matrix[r][c] == 1}
followers = {(r,c):[(r,c)] for r in range(len(matrix)) for c in range(len(matrix[0])) if matrix[r][c] == 1}
for r in range(len(matrix)):
... |
"""Config for pysma documentation."""
project = "PySMA"
copyright = "2021, Johann Kellerman, René Klomp"
author = "Johann Kellerman, René Klomp"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
]
html_theme = "sphinx_rtd_theme"
|
def countValues(values):
resultSet = {-1:0, 0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0}
for value in values:
i = 0
valuesList = list(value)
while i < len(valuesList):
resultSet[i] += int(valuesList[i])
i += 1
resultSet[-1] += 1
... |
expected_output = {
"flow_drop": {
"inspect-fail": 67870,
"last_clearing": "10:43:33 EDT Mar 27 2019 by genie",
"nat-failed": 528,
"ssl-received-close-alert": 9,
},
"frame_drop": {
"acl-drop": 29,
"l2_acl": 35,
"last_clearing": "10:43:33 EDT Mar 27 201... |
#O(n^2) Time / O(n) Space
def threeNumberSum(arr,targetSum):
triplets=[]
arr.sort()
for i in range(len(arr)-2):
left=i+1
right=len(arr)-1
while(left<right):
currentSum=arr[i]+arr[left]+arr[right]
if currentSum==targetSum:
triplets.append([arr[i],arr[left],arr[right]])
left+... |
#!/usr/bin/python
#The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
#73167176531330624919225119674426574742355349194934
#96983520312774506326239578318016984801869478851843
#85861560789112949495459501737958331952853208805511
#125406987471585238630507156932909632... |
Space = " "
class Solution:
def lengthOfLastWord(self, s: str) -> int:
found_word = False
word_length = 0
for i in range(len(s) - 1, -1, -1):
letter = s[i]
if letter == Space:
if found_word:
break
else:
... |
# Задача №2958. Максимум
#
# Напишите программу, которая считывает два целых числа a и b и выводит наибольшее значение из них.
# Числа — целые от 1 до 1000.
#
# При решении задачи можно пользоваться только целочисленными арифметическими операциями +, -, *, //, %, =.
# Нельзя пользоваться нелинейными конструкциями: ветв... |
action_space={'11':0,'12':1,'13':2,'14':3,'15':4,'21':5,'22':6,'23':7,'24':8,'25':9,'31':10,'32':11,'33':12,'34':13,'35':14,'41':15,'42':16,'43':17,'44':18,'45':19,'51':20,'52':21,'53':22,'54':23,'55':24,'1112':25,'1121':26,'1122':27,'1113':28,'1131':29,'1133':30,'1213':31,'1211':32,'1222':33,'1232':34,'1214':35,'1312'... |
"""
注解 从 Python 3.6 开始,不推荐使用 pyvenv 脚本,而是使用 python3 -m venv 来帮助防止任何关于虚拟环境将基于哪个 Python 解释器的混淆。
12.2. 创建虚拟环境
用于创建和管理虚拟环境的模块称为 venv。venv 通常会安装你可用的最新版本的 Python。如果您的系统上有多个版本的 Python,您可以通过运行 python3 或您想要的任何版本来选择特定的Python版本。
要创建虚拟环境,请确定要放置它的目录,并将 venv 模块作为脚本运行目录路径:
python3 -m venv tutorial-env
如果它不存在,这将创建 tutorial-env 目录,并在... |
#
# PySNMP MIB module Juniper-Fractional-T1-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Fractional-T1-CONF
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
class Solution(object):
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# # hash
# dic = {}
# for num in nums:
# try:
# dic[num] += 1
# except KeyError:
# dic[num] = 1
... |
'''
QUESTION:
455. Assign Cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
val = root.val
left_list... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
trees = defaultdict()
tre... |
# Copyright 2017, Optimizely
# 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, softwa... |
#!/bin/python3
'''
Generate a vector of length m with exactkly n ones
'''
def generate_vec_binary(n, m):
res = []
lower = sum(2**i for i in range(m-4))
upper = sum(2**i for i in range(m-4, m))+1
for i in range(lower, upper):
val = bin(i)[2:].zfill(8)
if sum([int(i) for i in val]) == 4... |
def mutate_string(string, position, character):
# method_#1
#str_list = list( string )
#str_list[position] = character
#str_modified = ''.join(str_list)
str_modified = mutate_string_method2( string, position, character)
return str_modified
# method_#2
def mutate_string_method2(string, p... |
# line intersection detection
# line1: (x1, y1) to (x2, y2)
# line2: (x3, y3) to (x4, y4)
def Intercept(x1, y1, x2, y2, x3, y3, x4, y4, d):
denom = ((y4-y3) * (x2-x1)) - ((x4-x3) * (y2-y1))
if (denom != 0):
ua = (((x4-x3) * (y1-y3)) - ((y4-y3) * (x1-x3))) / denom
if ((ua >= 0) and (ua <= 1)):... |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "dotnet_nuget_new", "nuget_package")
dotnet_nuget_new(
name = "npgsql",
package="Npgsql",
version="3.2.7",
sha256="683bbe42cd585f28beb23822a113db5731bce44020fd0af2ac827e642fe7e301",
build_file_content="""
package(default_visibility = [ "//visi... |
# Copyright 2020 Pax Syriana Foundation. Licensed under the Apache License, Version 2.0
#
class Error:
"""
A very simple class to hold error messages.
This class is used for concatenating succession of errors that don't stop the
flow.
"""
def __init__(self):
# prev_frame = inspect.... |
def dominantIndex(self, nums):
i = nums.index(max(nums))
l = nums[i]
del nums[i]
if not nums: return 0
return i if l >= 2 * max(nums) else -1 |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def get_data_from_file(file_text, file_pos):
first_line = True
with open(file_text, encoding="utf8") as f1, open(file_pos, encoding="utf8") as f2:
... |
text = 'i love to count words'
count = 0
for char in text:
if char == ' ':
count = count + 1
#must add one extra line for the last word
count = count + 1
print(count) |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
if len(s) == 1:
return False
left = []
right = []
for i in range(len(s)):
c = s[i]
if c ... |
def construct_error_response(context, api_request_id):
"""
Construct error response dict
:param context: AWS Context object, containing properties about the invocation, function, and execution environment.
:param api_request_id:
:return: dict, a dict object containing information about the aws logg... |
a = []
while True:
a.append(int(input('Digite o valor: ')))
st = str(input('Deseja continuar? S/N ').strip()[0].lower())
if st in 'n':
break
a.sort(reverse=True)
if 5 in a:
print(f'O número 5 faz parte da lista e aparece {a.count(5)} vezes!')
else:
print('O número 5 não faz parte da lista')
... |
r"""
Introduction
Sage has a wide support for 3D graphics, from basic shapes to implicit and
parametric plots.
The following graphics functions are supported:
- :func:`~plot3d` - plot a 3d function
- :func:`~sage.plot.plot3d.parametric_plot3d.parametric_plot3d` - a parametric three-dimensional space curve or sur... |
def sum100():
total = 0;
for i in range(101):
total += i
return total
print(sum100())
|
'''
Now You Code 3: Amazon Deals
Create a program that downloads and prints Today's Deals from amazon.com (https://www.amazon.com/gp/goldbox)
Hint: You will need to use selenium to scrape this page, it is loaded with JavaScript!
Example Run:
Here are Amazon.com deals!
1.) Shower Hose 79 inch (6.5 Ft.) for Hand Held... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit tests for android_webview/javatests/
Runs various style checks before upload.
"""
def CheckChangeOnUpload(input_api, output_api):
results = [... |
class Solution(object):
def isValidSudoku(self, board):
rows = [{} for i in range(9) ]
cols = [{} for i in range(9) ]
squares = [ {} for i in range(9)]
for i in range(9):
for j in range(9):
#print("iter", i, j, board[i][j])
#print(rows)
... |
def insertion_sort(A):
"""Sort list of comparable elements into nondecreasing order."""
for k in range(1, len(A)):
curr = A[k]
j = k
while j>0 and A[j-1] > curr:
A[j] = A[j-1]
j -= 1
A[j] = curr
return A
print(insertion_sort([234,3,4,3,45,3... |
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
def portrayCell(cell):
'''
This function is registered with the visualization server to be called
each tick to indicate how to draw the cell in its current state.
:param cell: the cell in the simulation
:return: the portrayal dictionary.
'''
assert cell is not None
return {
"Sha... |
# -*- coding: utf-8 -*-
class User_stopword(object):
user_stop = ['html','head','title','base','link','meta','style','body','article','section','nav','aside','header','footer','address','p','hr','pre','blockquote','ol','ul','li','dl','dt','dd','figure','figcaption','div','main','a','em','strong','small','s','cite','... |
def clojure_binary_impl(ctx):
toolchain = ctx.toolchains["@rules_clojure//:toolchain"]
deps = depset(
direct = toolchain.files.runtime,
transitive = [dep[JavaInfo].transitive_runtime_deps for dep in ctx.attr.deps],
)
executable = ctx.actions.declare_file(ctx.label.name)
ctx.action... |
#
# PySNMP MIB module CHIPNET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHIPNET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:31:30 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, 0... |
"""Constants for the Radio Thermostat integration."""
DOMAIN = "radiotherm"
TIMEOUT = 25
|
electricity_bill = 0
water_bill = 20
internet_bill = 15
other_bills = 0
number_of_months = int(input())
total_el = 0
total_water = number_of_months * water_bill
total_net = number_of_months * internet_bill
total_other_bills = 0
for i in range (number_of_months):
electricity_bill = float(input())
other_bills = w... |
"""
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
"""
CSI = '\033['
def code_to_chars(code):
return CSI + str(code) + 'm'
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(codes):
if not n... |
def test_errors_404(survey_runner):
response = survey_runner.test_client().get('/hfjdskahfjdkashfsa')
assert response.status_code == 404
assert '<title>Error</title' in response.get_data(True)
|
#from cStringIO import StringIO
class Message(object):
'''
Represents an AMQP message.
'''
def __init__(self, body=None, delivery_info=None, **properties):
if isinstance(body, unicode):
if properties.get('content_encoding', None) is None:
properties['content_encoding'] = 'utf-8'
body ... |
print(' \033[4;31mCalcule a sua media anual\033[m ')
n1=float(input('\033[34;1mnota do primeiro bimestre ='))
n2=float(input('nota do segundo bimestre = '))
n3=float(input('Nota do terceiro bimestre = '))
n4=float(input('Nota do quarto bimestre = \033[m'))
m=(n1+n2+n3+n4)/4
print('\033[1;32mA sua media é de :\... |
#MaBe
par = []
ímpar = []
nums = [par, ímpar]
for v in range(0, 7):
n = int(input('Digite um valor: '))
if n % 2 == 0:
par.append(n)
elif n % 2 != 0:
ímpar.append(n)
print(nums)
#nums.sort()
print(f'Os números pares são: {nums[0]}')
print(f'Os números ímpares são: {nums[1]}')
|
class Solution:
def lengthOfLIS(self, nums) -> int:
# dp=[0 for i in range(len(nums))]
# res=1
# dp[0]=1
# for i in range(1,len(nums)):
# if nums[i]>nums[i-1]:
# dp[i]=dp[i-1]+1
# else:
# dp[i]=1
# res=max(res,dp[i]... |
destinations = input()
command = input()
while not command == "Travel":
command = command.split(":")
if command[0] == "Add Stop":
index = int(command[1])
stop = command[2]
if index in range(len(destinations)):
destinations = destinations[:index] + stop + destination... |
# Storage for table names to remove
tables_to_remove = [
'The Barbarian',
'The Bard',
'The Cleric',
'The Druid',
'The Fighter',
'The Monk',
'The Paladin',
'The Ranger',
'The Rogue',
'The Sorcerer',
'The Warlock',
'The Wizard',
'Character Advancement',
'Multiclass... |
# -*- encoding: utf-8 -*-
# Tara Python Wrapper v0.1.0
# Tara Python Wrapper wit Telegram Bot
# Copyright © 2020, H. Sinan Alioglu.
# See /LICENSE for licensing information.
"""
INSERT MODULE DESCRIPTION HERE.
:Copyright: © 2020, H. Sinan Alioglu.
:License: BSD (see /LICENSE).
"""
__all__ = ()
|
# -*- coding: utf-8 -*-
"""
@author: yuan_xin
@contact: yuanxin9997@qq.com
@file: tabu_search_pdptw.py
@time: 2020/10/19 16:57
@description:
"""
|
class Handler:
"""
The handler is responsible for running special events based on an instance.
Typical use-cases: Feed updates, email and push notifications.
Implement the handle_{action} function in order to execute code.
Default actions: create, update, delete
"""
model = None
def ... |
#program to find maximum and the minimum value in a set.
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
|
"""
Second test case of example xml files to parse and compare with each other.
Differences between form_xml_case_1 and form_xml_case_1_after:
- Rename 'name' to 'your_name'
- Add 'mood' field
XML of Surevey instance (answer to xform)
"""
DEFAULT_MOOD = 'good'
FIELDS_2 = [
'name', 'age', 'picture', 'has_childre... |
n=input("enter the enumber:")
length=len(n)
org=int(n)
sum=0
n1=int(n)
while(n1!=0):
rem=n1%10
sum+=(rem**length)
n1=n1//10
if(sum==org):
print("it is a armstrong number")
else:
print("it is not an armstrong number")
|
bms_param_thresholds = {
'temperature': {'min': 0, 'max': 45},
'soc': {'min': 25 ,'max': 80},
'charging_rate': {'min': 0, 'max': 0.8}
}
bms_param_descriptions = {
'temperature': 'Temperatu... |
"""
1. 查询报表数据
2. 生成Excel文件
3. 打包为zip文件并加密
4. 邮件发送文件
5. 邮件发送密码
""" |
class DidaticaTech: # funções usa letras minúsculas e classes úsa maiusculas
def incrementa(self, v, i): #método função dentro da classe
valor = v #variaveis dentro das classes são atributos
incremento = i
resultado = valor + incremento
return resultado
#a = DidaticaTech()
#print(a... |
"""BVP Solvers."""
# class BVPFilter:
# def __init__(dynamics_model, measurement_model, initrv):
# self.kalman = MyKalman(
# dynamics_model=bridge_prior, measurement_model=measmod, initrv=initrv
# )
# def single_solve(dataset, times):
# kalman_posterior = kalman.iterated_filt... |
'''
Created on 2015年12月1日
https://leetcode.com/problems/game-of-life/
@author: Darren
'''
'''
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an i... |
# coding=UTF-8
#自低向上:
# def dp(dp_table,coins, amount) :
# # print(dp_table[0])
# for i in range(1,amount+1):
# res = float('inf')
# for coin in coins:
# if i-coin < 0 : continue
# res = min(res,dp_table[i-coin] +1) # 发现问题了,如果使用res 那么 第一个进来的0,就会变成-1 改变range 也可以修正答案
# ... |
# https://leetcode.com/problems/simplify-path
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for i in path.split('/'):
if stack and i == "..":
stack.pop()
elif i not in [".", "", ".."]:
stack.append(i)
... |
result=("0")
number1=int(input("Enter first number: "))
number2=int(input("Enter second number: "))
operator=str(input("""Choose from: 'addition', 'subtraction', 'multiplication' or 'division':
"""))
operator = operator.lower()
if operator == "addition":
result=str((number1+number2))
print("The result ... |
#!/usr/bin/python
'''!
Program to compute the odds for the game of Baccarat.
@author <a href="email:fulkgl@gmail.com">George L Fulk</a>
'''
def bacc_value(num1, num2):
'''!
Compute the baccarat value with 2 inputed integer rank values (0..12).
'''
if num1 > 9:
num1 = 0
if num2 > 9:
... |
def hashify(string):
dict={}
res=string+string[0]
for i,j in enumerate(string):
if dict.get(j, None):
if isinstance(dict[j], str):
dict[j]=list(dict[j])+[res[i+1]]
else:
dict[j].append(res[i+1])
else:
dict[j]=res[i+1]
re... |
"""
in this module, I define a obj change, which record the change infomation of a video in a timestamp.
"""
# coding:utf-8
class Tempor:
"""
obj
"""
def __init__(self, video_id, time, views, likes, dislikes, comments):
self.video_id = video_id
self.time = time
self.views = ... |
def Tux(thoughts, eyes, eye, tongue):
return f"""
{thoughts}
{thoughts}
.--.
|{eye}_{eye} |
|:_/ |
// \\ \\
(| | )
/'\\_ _/\`\\
\\___)=(___/
""" |
# https://github.com/ycm-core/YouCompleteMe/blob/321700e848595af129d5d75afac92d0060d3cdf9/README.md#configuring-through-vim-options
def Settings( **kwargs ):
client_data = kwargs[ 'client_data' ]
return {
'interpreter_path': client_data[ 'g:ycm_python_interpreter_path' ],
'sys_path': client_data[ 'g:ycm_pyt... |
# https://leetcode.com/problems/number-of-1-bits/
class Solution(object):
# Runtime: 46 ms, faster than 5.64% of Python online submissions for Number of 1 Bits.
# Memory Usage: 13.4 MB, less than 34.23% of Python online submissions for Number of 1 Bits.
def hammingWeight(self, n):
"""
:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PyobsException(Exception):
pass
class ConnectionFailure(PyobsException):
pass
class MessageTimeout(PyobsException):
pass
class ObjectError(PyobsException):
pass
|
class Student:
cname='DurgaSoft' #static variable
def __init__(self,name,rollno):
self.name=name #instance variable
self.rollno=rollno
s1=Student('durga',101)
s2=Student('pawan',102)
print(s1.name,s1.rollno,s1.cname)
print(s2.name,s2.rollno,s2.cname)
|
"""
https://zhuanlan.zhihu.com/p/50804195
"""
def test_args(first, *args):
"""
output:
Required argument: 1
<class 'tuple'>
Optional argument: 2
Optional argument: 3
Optional argument: 4
"""
print('Required argument: ', first)
print(type(args)) # <class 'tuple'>
for v ... |
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = [4, 5, 6]
c = [0, 0, 0]
def t():
for j in range(len(a)):
for [A1, A2, A3] in [[1, 2, 3], [1, 2, 3], [1, 2, 3]]:
for B in b:
c[A1-1] = B + A1*2
c[A2-1] = B + A2*2
c[A3-1] = B + A3*2
t()
print(c)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.