content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
class QuickSearch:
offset = 0
steps = 0
jumptable = dict()
pattern = ""
input = ""
def __init__(self, input: str, pattern: str):
self.input = input
self.pattern = pattern
self._getLanguage()
self._calculateJumps()
self._search()
... |
class SetterBaseCollection(Collection[SetterBase],IList[SetterBase],ICollection[SetterBase],IEnumerable[SetterBase],IEnumerable,IList,ICollection,IReadOnlyList[SetterBase],IReadOnlyCollection[SetterBase]):
"""
Represents a collection of System.Windows.SetterBase objects.
SetterBaseCollection()
"""
def Cl... |
# https://py.checkio.org/en/mission/morse-decoder/
'''
Your task is to decrypt the secret message using the Morse code.
The message will consist of words with 3 spaces between them and 1 space between each letter of each word.
If the decrypted text starts with a letter then you'll have to print this letter in upp... |
name = str(input('Digite seu nome:')).strip()
print('Analizando seu nome.....')
print('Seu nome em letras maiusculas é {}'.format(name.upper()))
print('Seu nome em letras minusculas é {}'.format(name.lower()))
print('Seu nome tem {} letras.'.format(len(name) - name.count(' ')))
print('Seu primeiro nome tem {} letras'.f... |
# Copyright 2019 Jeremy Schulman, nwkautomaniac@gmail.com
#
# 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 applicabl... |
def food(f,num):
"""jfehfiehfioe i fihiohghi"""
tip=0.1*f
f=f+tip
return f/num
def movie(m,num):
"""iiehgf o h ghighighi"""
return m/num
|
# by Kami Bigdely
WELL_DONE = 900000
MEDIUM = 600000
COOKED_CONSTANT = 0.05
def is_cookeding_criteria_satisfied(time, temperature, pressure, desired_state):
cooked_level = time * temperature * pressure * COOKED_CONSTANT
if desired_state == 'well-done' and cooked_level >= WELL_DONE:
return True
if... |
class MediaTag(object):
# ndb keys are based on these! Don't change!
CHAIRMANS_VIDEO = 0
CHAIRMANS_PRESENTATION = 1
CHAIRMANS_ESSAY = 2
tag_names = {
CHAIRMANS_VIDEO: 'Chairman\'s Video',
CHAIRMANS_PRESENTATION: 'Chairman\'s Presentation',
CHAIRMANS_ESSAY: 'Chairman\'s Essay... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( A , arr_size , sum ) :
for i in range ( 0 , arr_size - 2 ) :
for j in range ( i + 1 , arr_size - 1 ) :
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of civicjson.
# https://github.com/DCgov/civic.json-cli
# Licensed under the CC0-1.0 license:
# https://creativecommons.org/publicdomain/zero/1.0/
# Copyright (c) 2016, Emanuel Feld <elefbet@gmail.com>
__version__ = '0.1.1' # NOQA
|
"""Constants."""
CACHE_NAME = 'web_mirror'
CACHE_TIMEOUT = 3600
|
lista = list()
posma = list()
posme = list()
cont = 0
for c in range(0, 5):
num = (int(input(f'Digite um valor na posição {c}: ')))
lista.append(num)
'''for pm in lista:
if pm == max(lista):
posma.append(cont)
elif pm == min(lista):
posme.append(cont)
cont = cont + 1'''
print('=' * ... |
try:
i=0/0
f=open("abc.txt")
for line in f:
print(line)
# except:
# print("why with me")
except Exception as e:
print(e)
# except FileNotFoundError:
# print("file not found")
# except ZeroDivisionError:
# print("divided by 0 bro")
# except (FileNotFoundError,ZeroDivisionError):
# ... |
"""
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
"""
def permute(elements):
"""
returns a list with the permuations.
"""
if len(elements) <= 1:
... |
# V0
# https://github.com/yennanliu/CS_basics/blob/master/leetcode_python/Linked_list/reverse-linked-list.py
# TO VALIDATE
class Solution(object):
def sortList(self, head):
head_list = []
while head:
head_list.append(head.value)
head = head.next
head_list = sorted(... |
def is_prime(num):
prime_counter = 1
for x in range(1, num):
if num % x == 0:
prime_counter += 1
if prime_counter > 2:
return False
return True
primes = []
i = 1
p = 0
n = 10001
while p != n+1:
if is_prime(i):
primes.append(i)
p += 1
i += 1
... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.eiendeler_foretak
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class EiendelerForetak(object):
"""Implementation of the 'EiendelerForetak' model.
TODO: type model description here.
... |
def read_csv(logfile):
result = {}
lines = []
with open(logfile) as f:
for line in f.readlines():
l_clean = [float(x) for x in line.strip().split()]
lines.append(l_clean)
column_data = zip(*lines)
labels = [
"index",
"defocus1",
"defocus2",
... |
# encoding: utf-8
# 点検対象となるWorkbookのセル配置
# CampusMateの出力形式がもし変われば、
# ここで実際の位置を反映させなければならない。
#
# 科目データ
#
kamoku_info = {
'year': (10, 5), # 年度
'curriculum': (11, 5), # 開講学科・専攻
'semester': (12, 5), # 講義期間
'credits': (13, 5), # 単位数
'code': (14, 5), # 講義コード
'name': (15, 5), ... |
def multiply(*args):
ret = 1
for a in args:
ret *= a
return ret
def return_if_jake(**kwargs):
if not 'jake' in kwargs.keys():
return False
return kwargs['jake']
def call_with_42(func):
return func(42)
def call_with_42_and_more(func, *args):
return func(42, *args)
def get_water_function():
def... |
#!/usr/bin/python3
f = open("day1-input.txt", "r")
finput = f.read().split("\n")
found = False
for i in finput:
for x in finput:
if x == '':
break
for y in finput:
if y == '':
break
product = int(i) + int(x) + int(y)
if product == 202... |
#
# This file contains the Python code from Program 16.13 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_13.txt
#
class Digraph(Gra... |
pattern_zero=[0.0, 0.0135109777, 0.0266466504, 0.0273972603, 0.0394070182, 0.0409082379, 0.0517920811, 0.0540439107, 0.0547945205, 0.063801839, 0.0668042785, 0.0683054982, 0.075436292, 0.0791893413, 0.081441171, 0.0821917808, 0.08669544, 0.0911990993, 0.0942015388, 0.0957027585, 0.0975792832, 0.1028335523, 0.1065866016... |
def is_valid(input_line: str) -> bool:
min_max, pass_char, password = input_line.split(' ')
min_count, max_count = [int(i) for i in min_max.split('-')]
pass_char = pass_char.rstrip(':')
char_count = 0
for char in password:
if char == pass_char:
char_count += 1
if char_count >= min... |
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
EDINGCNC_VERSION = "CNC V4.03.52"
EDINGCNC_MAJOR_VERSION = 4
CNC_EPSILON = (0.00001)
CNC_EPSILON_EPSILON = (1e-33)
CNC_MAGIC_NOTUSED_DOUBLE = -1.0e10
CNC_MAGIC_ZERO = 1.0e-33
CNC_DOUBLE_FUZZ = 2.2204460492503131e-16
CNC_FULL_CIRCLE_FUZZ_STANDARD = (0.000001)
CNC_PI = 3.1415926535897932384626433832795029
CNC_PI2 = (CNC... |
def create_sketch_from_image(img_lct,sketch_lct,outname,ext,n_sketches):
# img_lct --> It's the location of the images
# sketch_lct --> It's the location of the generated sketch image
# outname --> The name of the file
# ext --> The extension of the file 256FaceNewData
# n_sketches -->The numbe... |
#!/usr/bin python
"""
:author: Fix Me
:date: Now
:contact: me@me.org
:license: GPL, v3
:copyright: Copyright (C) 2017 Fixme
:summary: Simple script to open a file, then read and print its content.
Use of this software is governed by the GNU Public License, version 3.
This is free so... |
class Edge(object):
"""
Representation of an edge in the graph database.
"""
def __init__(self, uri: str):
self.uri = uri
|
# Please provide the API key for the account made on the website 2factor.in
SMS_GATEWAY_API_KEY = 'SMS_GATEWAY_API_KEY'
# Provide the 2factor urls for each type of sms
SMS_GATEWAY_URL = {
'otp': 'http://2factor.in/API/V1/{api_key}/SMS/',
'transactional': 'http://2factor.in/API/V1/{api_key}/ADDON_SERVICES/SEND... |
# 参考: https://qiita.com/takayg1/items/c811bd07c21923d7ec69
# 単位元 と 結合法則 (交換則は成り立たなくてOK) が必要! それらがあれば O(N)→O(log N) にできる.)
class SegTree:
"""
init(init_val, ide_ele): 配列init_valで初期化 O(N)
update(k, x): k番目の値をxに更新 O(logN)
query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
"""
def __init__(self, init_val... |
class Plotter:
pass
class PyplotPlotter(Plotter):
pass |
# -*- coding: utf-8 -*-
'''
Management of Zabbix host groups.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
def __virtual__():
'''
Only make these states available if Zabbix module is available.
'''
return 'zabbix.hostgroup_create' in __salt__
def present(name):
'''
Ensures that the... |
"""
LeetCode Problem: 412. Fizz Buzz
Link: https://leetcode.com/problems/fizz-buzz/
Language: Python
Written by: Mostofa Adib Shakib
Time Compplexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range (1, n+1):
if ... |
class Solution:
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
hold, not_hold = float('-inf'), 0
for price in prices:
hold, not_hold = max(hold, not_hold - price), max(not_hold, hold + price - fee)
... |
n = int(input())
l = [*map(int,input().split())]
ans = 0
for i in range(n):
l[i] = min(l[i], 7)
if i % 2 == 0:
ans += l[i] - 2
else:
ans += l[i] - 3
print(ans)
|
# Copyright 2015 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.
class TestOutputStream(object):
def __init__(self):
self._output_data = []
@property
def output_data(self):
return ''.join(self._output_data)... |
#!/usr/bin/env python3
"""Module Line up"""
def add_arrays(arr1, arr2):
"""Adds two arrays element-wise"""
lenArr1 = len(arr1)
lenArr2 = len(arr2)
if lenArr1 != lenArr2:
return None
ans = []
for i in range(lenArr1):
ans.append(arr1[i] + arr2[i])
return ans
|
# Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in the array,
# and it should return false if every element is distinct.
# Example 1:
# Input: [1,2,3,1]
# Output: true
# Example 2:
# Input: [1,2,3,4]
# Output: false
# Exa... |
# projecteuler.net/problem=8
num = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428... |
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices or not k:
return 0
dp = [[0, 0] for _ in range(k)]
for i in range(k):
dp[i][0] = -prices[0]
... |
# Mailing Address
print("Shubhangi Singh")
print("College of Computer Science")
print("Computer Science Building")
print("294 Farm Ln Rm 104")
print("East Lansing MI 48824") |
a=int(input('valor para A:',))
b=int(input('valor para B:',))
soma=a+b
print('a soma eh:',soma)
|
def f():
return 42
100
|
seed = 1234
def random():
global seed
seed = seed * 0xda942042e4dd58b5
value = seed >> 64
value = seed % 2**64
return value
for i in range(10):
print(random())
for i in range(10):
print(random()%3)
# D. H. Lehmer, Mathematical methods in large-scale computing units.
# Proceedings of a Se... |
def checkguess(request) :
guess = request.GET.get('guess','')
return guess == '42';
|
# Python3 implementation to convert a binary number
# to octal number
# function to create map between binary
# number and its equivalent octal
def createMap(bin_oct_map):
bin_oct_map["000"] = '0'
bin_oct_map["001"] = '1'
bin_oct_map["010"] = '2'
bin_oct_map["011"] = '3'
bin_oct_map["100"] = '4'
... |
"""SoCo-CLI is a command line control interface for Sonos systems.
It is a simplified wrapper around the SoCo python library, as well as providing
an extensive range of additional features.
It can be used as a command line program, as an interactive command shell, and
in other programs via its simple API. It can also... |
"""
Stein's algorithm or binary GCD algorithm is an algorithm
that computes the greatest common divisor of
two non-negative integers. Stein's algorithm
replaces division with arithmetic shifts, comparisons, and subtraction.
"""
def gcd(first_number: int, second_number: int) -> int:
"""
gcd: Function which fin... |
class Context(dict):
"""Object filled by resolvers when evaluating a rule
It's mainly used to store a corresponding value from a parameter.
Example:
resolver will receive a user_id, then look for the corresponding user in DB
and finally store the user into the context in order to let him be... |
line_list = list(map(int, input().split()))
line_list.sort()
print(" <= ".join(str(x) for x in line_list)) |
class Pegawai:
def __init__(self, nama, email, gaji):
self.namaPegawai = nama
self.emailPegawai = email + 'gmail.com'
self.gajiPegawai = gaji
# nama dari method tidak boleh sama dengan property
# contoh : method gajiPegawai()
def gajiPegawaiCalculate(self):
# parameter ... |
class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
rainsLen = len(rains)
lastRains, dryDayIndices = {}, []
result = [-1] * rainsLen
def getDryingDayForLake(day, lake):
if len(dryDayIndices) == 0:
return None
else:
... |
v = []
for i in range(20):
v.append(int(input("")))
for i in range(20):
print("N[%i] = %i" % (i, v[19 - i]))
|
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
def spiral_coords(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield r1, c
for r in range(r1 + 1, r2 + 1):
yield r, c2
if r1 < r2 and c1 < ... |
"""Constants."""
N_MONTE = 1_000
DPI_IMAGE_RESOLUTION = 600
SHORT_NAME_TO_NAME = {
'IND': 'India',
'ENG': 'England',
'AUS': 'Australia',
'WI': 'West Indies',
'NZ': 'New Zealand',
'PAK': 'Pakistan',
'SA': 'South Africa',
'SL': 'Sri Lanka',
'BAN': 'Bangladesh',
'AFG': 'Afghanist... |
## https://leetcode.com/problems/card-flipping-game/
## this problem comes down to finding the smallest number
## that we can put on the back of a card without putting
## that same number on the frong. i do this by finding all
## invalid numbers, then taking the minimum of the remaining
## numbers. invalid numbers ... |
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
lower_case_name1 = name1.lower()
lower_case_name2 = name2.lower()
total_t = lower_case_na... |
print("Welcome to Treasure island.\nYour Mission is to find the treasure.")
inputs = ["right", "left", "swim", "wait", "red", "blue", "yellow"]
input1 = input2 = input3 = 0
input1 = input(
"You're at a crossroad. Where do you want to go? Type 'Left' or 'Right'\n"
).lower()
if input1 == "right":
pri... |
figures_black = {
"king": u"\u2654",
"queen": u"\u2655",
"rook": u"\u2656",
"bishop": u"\u2657",
"knight": u"\u2658",
"pawn": u"\u2659"
}
figures_white = {
"king": u"\u265A",
"queen": u"\u265B",
"rook": u"\u265C",
"bishop": u"\u265D",
"knight": u"\u265E",
"pawn": u"\... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:... |
#!/usr/bin/env python
#
# Copyright 2012 8pen
"""Utility class for byte arrays"""
def to_int(byte_array, offset, chunk_size):
value = 0
for i in range(0, chunk_size):
value += byte_array[offset + i] << (chunk_size-i-1)*8
return value |
DEBUG = True
SECRET_KEY = "secret"
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.staticfiles',
'django.contrib.contenttypes',
'django_app_lti',
]
MIDDLEWARE = []
ROOT_URLCONF = 'django_app_lti.urls'
DATABASES = {
'default': {
'ENGINE': 'd... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Time convert functions
"""
__all__ = ["ymdhms2jd","doy2jd","jd2ymdhms","jd2gpst","gpst2jd"]
def ymdhms2jd(datetime):
"""
Datetime(ymdhms) to Julian date
"""
days_to_month = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] # ignore index=0
... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
# solving with converting into str
s = str(x)
n = len(s)
i=0
j=n-1
while(i<j):
if s[i]!=s[j]:
return False
i+=1
j-=1
... |
# SHERLOCK AND DATES
for _ in range(int(input())):
date = input().strip().split()
if date[0]=='1':
if date[1]==('January'):
date[0]='31'
elif date[1]==('May'):
date[0]='30'
elif date[1]==('July'):
date[0]='30'
elif date[1]==('October'... |
# File: skypeforbusiness_consts.py
#
# Copyright (c) 2019-2020 Splunk 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 requir... |
"""High Scores exercise from exercism.io python path.
Manage a game player's High Score list.
Returns the highest score from the list, the last added score and
the three highest scores.
"""
def latest(scores):
"""Get last added score.
Args:
scores: list of positive integers
Returns:
An... |
# Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
# Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
# Example 1:
# Input: [1, 2, 2, 3, 1]
# Output: 2
#... |
OVERLEAF_BASE_URL = "https://www.overleaf.com"
OVERLEAF_LOGIN = OVERLEAF_BASE_URL + "/login"
OVERLEAF_CSRF_REGEX = "window\.csrfToken = \"(.+)\""
def get_download_url(project_id):
return OVERLEAF_BASE_URL + ("/project/%s/download/zip" % str(project_id))
|
def test_add_pickle_job(sqs, queue_name):
messages = []
_queue = sqs.queue(queue_name)
@_queue.processor("say_hello")
def say_hello(username=None):
messages.append(username)
say_hello.delay(username="Homer")
result = sqs.queue(queue_name).process_batch(wait_seconds=0)
assert resul... |
"""
Se dă un vector `v` de `n` numere întregi.
Fie k, l naturale astfel încât k * l <= n.
Să se aleagă din vectorul `v` un număr de `k` secvențe (poziții consecutive)
de lungime `l` a. î. suma elementelor alese să fie maximă.
În primul rând, construim vectorul de sume parțiale.
Cazul k = 1:
Reținem un vector M[... |
# Enter script code
# 单独 shift后接end是放开了,不是按住不放
# 发现不管怎么样都失败了
keyboard.send_keys("<shift>+<end>")
keyboard.send_keys("<ctrl>+x") |
__version__ = "HEAD"
__project__ = "sqlalchemy-rqlite"
__author__ = "Zac Medico"
__email__ = "zmedico@gmail.com"
__copyright__ = "Copyright (C) 2016 Zac Medico"
__license__ = "MIT"
__description__ = "A SQLAlchemy dialect for rqlite"
|
# 142ms 71.93%
# 倒序, 代码干净
class Solution(object):
def romanToInt(self, s):
pairs = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
sum, prev = 0, 'I'
for cur in s[::-1]:
sum, prev = sum - pairs[cur] if pairs[cur] < pairs[prev] else sum + d[cur], cur
return sum
... |
"""
from: http://adventofcode.com/2017/day/1
--- Day 1: Inverse Captcha ---
The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We
can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a
few minutes until midnight. "We have a big pro... |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... |
def test_py_config_defaults(py_config):
# driver settings
assert py_config.driver.browser == 'chrome'
assert py_config.driver.remote_url == ''
assert py_config.driver.wait_time == 10
assert py_config.driver.page_load_wait_time == 0
assert py_config.driver.options == []
assert py_config.drive... |
# -*- coding: utf-8 -*-
{
'name': 'test-assetsbundle',
'version': '0.1',
'category': 'Hidden/Tests',
'description': """A module to verify the Assets Bundle mechanism.""",
'maintainer': 'Odoo SA',
'depends': ['base'],
'installable': True,
'data': [
"views/views.xml",
],
'a... |
def length(txt):
txtl = list(txt)
if txtl!=[]:
n = 0
print(txtl.pop(0),"*",end ="",sep ="")
n+=1
if txtl!=[]:
print(txtl.pop(0),"~",end ="",sep ="")
n+=1
return n+length("".join(txtl))
else:
return 0
print("\n",length(input("Enter Input... |
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s=set(nums)
return min(s)
|
"""
JSON test OWM API responses
"""
COINDEX_JSON_DUMP = '{"reference_time": 1234567, "co_samples": [{"pressure": ' \
'1000, "value": 8.168363052618588e-08, "precision": ' \
'-4.999999987376214e-07}, {"pressure": 681.2920532226562, ' \
'"value": 8.686949115599... |
description = 'Slit H2 using Beckhoff controllers'
group = 'lowlevel'
devices = dict(
h2_center = device('nicos.devices.generic.VirtualMotor',
description = 'Horizontal slit system: offset of the slit-center to the beam',
unit = 'mm',
abslimits = (-69.5, 69.5),
speed = 1.,
),
... |
"""尝试使用@装饰器"""
class myclass(object):
#普通的方法即实例方法,需要参数self,表示对实例的引用
#类方法不需要实例,用staticmethod修饰
@staticmethod
def first_func():
print(111)
myclass.first_func()
#自定义装饰器,装饰器最内部的函数包含对目标函数的调用,以及与目标函数无关的额外操作,最内部的函数需要返回对目标函数的调用
#而装饰器需要返回对最内部函数的引用
def log(func):
def wrapper(*tuple,**dict):
... |
class SystemUnderTest(object):
"""This is an interface to a concrete implementation under test"""
def __init__(self):
super(SystemUnderTest, self).__init__()
# pass_input either forwards an input to the system under test, or if there is some output from the SUT that
# has not yet been forwarded to DT, it ignore... |
# op map for nova.
op_map = \
{(8774, '/v2', '/extensions', 'GET', ''): (),
(8774, '/v2', '/extensions/os-consoles', 'GET', ''): (),
(8774, '/v2', '/flavors', 'GET', ''): (),
(8774, '/v2', '/flavors', 'POST', ''): ('compute_extension:flavormanage',
'compute_extension:flavor_... |
# -*- coding: utf-8 -*-
__author__ = 'Fabio Caccamo'
__copyright__ = 'Copyright (c) 2020-present Fabio Caccamo'
__description__ = 'file-system utilities for lazy devs.'
__email__ = 'fabio.caccamo@gmail.com'
__license__ = 'MIT'
__title__ = 'python-fsutil'
__version__ = '0.3.0'
|
'''
Escreva a função maiusculas(frase) que recebe uma frase (uma string) como parâmetro e devolve uma string com as letras maiúsculas que existem nesta
frase, na ordem em que elas aparecem. Para resolver este exercício, pode ser útil verificar uma tabela ASCII, que contém os valores de cada
caractere. Ver htt... |
_WIT_ACCESS_TOKEN_FOR_BROWSER_TV = '3QTEIGPP4YXNRN6DKPDOLV46EQLSGIUJ'
_WIT_ACCESS_TOKEN_FOR_DEVICE_CONTROL = 'IEGTTI2YDCBYGF6ZYR7AVI2ZOVXLOSMI'
LISTENERS = [
( 'archspee.listeners.alsa_port_audio.AlsaPortAudioListener', {} )
]
TRIGGERS = [
(
'archspee.triggers.snowboy.SnowboyTrigger',
{
... |
"""Module generating ICMP payloads (with no header)"""
class PayloadProvider:
def __init__(self):
raise NotImplementedError('Cannot create instances of PayloadProvider')
def __iter__(self):
raise NotImplementedError()
def __next__(self):
raise NotImplementedError()
class List(P... |
def garland(word):
printy=0
i=0
while True:
if word[i:] == word[:-i]:
return len(word[:-i])
i+=1
if __name__ == "__main__":
assert garland("programmer") == 0
assert garland("ceramic") == 1
assert garland("onion") == 2
assert garland("alfalfa") == 4
|
def array_count9(arr):
count = 0
for num in arr:
if num == 9:
count = count + 1
return count
count = array_count9([1, 2, 9])
print(count)
count = array_count9([1, 9, 9])
print(count)
count = array_count9([1, 9, 9, 3, 9])
print(count) |
{
"__additional_thread_unsafe__" :
[
"validate_idb_names",
]
}
|
t1, t2, n = map(int, input().split(" "))
for i in range(2, n):
tn = t1 + t2**2
t1, t2 = t2, tn
print(tn)
|
#
# PySNMP MIB module HH3C-SPB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-SPB-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:43 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,... |
class Solution:
def canReorderDoubled(self, A):
"""
:type A: List[int]
:rtype: bool
"""
# array of doubled pairs
def valid(nums):
if len(nums) % 2 == 1:
return False
counts = collections.Counter(nums)
for num in sort... |
class Solution:
def frequencySort(self, s: str) -> str:
occ = dict()
result = ""
for i in s:
if i in occ:
occ[i] += 1
else:
occ[i] = 1
str_list = list(occ.items())
for i in range(len(oc... |
n = int(input())
check = n
new_number = 0
temp = 0
count = 0
while True:
count += 1
temp = n // 10 + n % 10
new_number = (n % 10) * 10 + temp % 10
n = new_number
if new_number == check:
break
print(count)
|
secret = {
'url_oceny' : 'https://portal.wsb.pl/group/gdansk/oceny-wstepne',
'wsb_login' : '',
'wsb_password' : '',
'email_from' : '',
'email_to' : '',
'smtp_login' : '',
'smtp_password' : '',
'smtp_host' : '',
'smtp_port' : 587,
'fb_login' : '',
'fb_password' : '',
... |
def is_lucky(n):
s = str(n)
half = len(s)//2
left, right = s[:half], s[half:]
return sum(map(int, left)) == sum(map(int, right))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.