content stringlengths 7 1.05M |
|---|
# Create by Packetsss
# Personal use is allowed
# Commercial use is prohibited
name = input("Enter your baphoon:")
age = input("Enter your chikka:")
print("WTF " + name + "! You are " + age + "??")
num1 = input("Number 1:")
num2 = input("Number 2:")
result = num1 + num2
|
####!/usr/bin/env python3
"""
Parse data files with json output for estack bulk load
"""
def elk_index(elk_index_name):
""" Index setup for ELK Stack bulk install """
index_tag_full = {}
index_tag_inner = {}
index_tag_inner['_index'] = elk_index_name
index_tag_inner['_type'] = elk_index_name
... |
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
for i in range(0,len(costs)):
costs[i].append(costs[i][0]-costs[i][1])
costs.sort(key = lambda x:x[2])
result=0
for i in range(0,len(costs)//2):
result+=costs[i][0]
for ... |
"""
Constants Module for Flambda APP
Version: 1.0.0
"""
LIMIT = 20
OFFSET = 0
PAGINATION_LIMIT = 100
|
print("To print the place values of integer")
a=int(input("Enter the integer value:"))
n=a%10
print("The unit digit of {} is{}".format(a,n))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def deleteNode(self, root, key):
if not root: # if root doesn't exist, just return i... |
ilksayi=1
ikincisayi=1
fibo=[ilksayi,ikincisayi]
for i in range(0,20):
ilksayi,ikincisayi=ikincisayi,ilksayi+ikincisayi
fibo.append(ikincisayi)
print(fibo) |
class BinaryNotFound(Exception):
def __init__(self, binary_name):
Exception.__init__(self)
self.binary_name = binary_name
class BinaryCallFailed(Exception):
def __init__(self):
Exception.__init__(self)
class InvalidMedia(Exception):
def __init__(self, media_path):
Excepti... |
#!/usr/bin/python2.4
#
# Copyright 2009 Google 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 ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
current = head
previous = None
while current is not None:
... |
# Write a program that reads four integers and prints “two pairs” if the input consists
# of two matching pairs (in some order) and “not two pairs” otherwise. For example,
# 1 2 2 1 two pairs
# 1 2 2 3 not two pairs
# 2 2 2 2 two pairs
number1 = int(input("Enter number one: "))
number2 = int(input("Enter n... |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class DeleteFilesRequest(object):
def __init__(self):
self.datesToDelete = None
def getDatesToDelete(self):
return self.datesToDelete
def setDatesToDelete(self, datesToDelete):
self.datesToDelete = datesT... |
# -*- coding: utf-8 -*-
'''
In a given list the first element should become the last one.
An empty list or list with only one element should stay the same.
Input: List.
Output: Iterable.
'''
def replace_first(items):
# your code here
return items[1:] + items[:1]
if __name__ == "__main__":
print("Examp... |
'''定义状态码'''
# 正常
STATUS_OK = 0
#用户相关
STATUAS_INPUT_ERROR = 2001
STATUAS_LOGIN_ERROR = 2002
STATUS_FORM_ERROR = 2003 # 表单字段校验错误
# 服务相关
STATUAS_SERVICE_ERROR = 5001
class LogicError(BaseException):
pass
def generate_logic_error(name, code):
base_cls = (LogicError,)
return type(name, base_cls, {'code': code})... |
'''面试题57-2:和为s的连续正数序列
输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
--------------
Example:
input:15
output: 1,2,3,4,5 4,5,6 7,8
'''
def squence_sum(target):
if target < 3:
return None
small = 1
big = 2
cur_sum = small + big
mid = (target + 1) >> 1
ret = []
while small < mid:
if cur... |
'''
Created on 2015年11月30日
@author: Darren
'''
'''
Problem Statement
In this challenge you need to print the data that accompanies each integer in a list. In addition, if two strings have the same integers, you need to print the strings in their original order. Hence, your sorting algorithm should be stable, i.e. the... |
#!/usr/bin/python
# coding=utf-8
"""Scripts related to datasets dowloading and preprocessing."""
|
'''
FetcherResponse will return a well-formed FetcherResponse object
{
name: string,
payload: {file_name: binary_data} | None,
source: string
error: Error object
}
"payload" - string - binary data from a successful url fetch or None on fail
"source" - string - the url t... |
load(":character_classes.bzl", "is_alphanumeric", "is_lower_case_letter", "is_numeric", "is_upper_case_letter")
def tokenize(s):
queue = []
parts = []
part = ""
for i in range(len(s)):
ch = s[i]
if is_alphanumeric(ch):
if len(queue) == 2:
if is_upper_case_let... |
class CommodityModel:
"""
学生模型:封装数据
"""
def __init__(self, name="", price=0, sid=0):
self.name = name
self.price = price
self.sid = sid
class CommodityView:
"""
学生视图:处理界面逻辑
"""
def __init__(self, controller):
self.controller = controller
d... |
# stats.py
def init():
global _stats
_stats = {}
def event_occurred(event):
global _stats
try:
_stats[event] = _stats[event] + 1
except KeyError:
_stats[event] = 1
def get_stats():
global _stats
return sorted(_stats.items())
|
"""
his file illustrates the bad version of some_fun.
I've included the dependencies but the implementations
are dummied out.
"""
class Logger:
def log(self, msg):
pass
logger = Logger()
def is_valid(x):
pass
def some_fun(x):
if is_valid(x):
return x * 5
else:
logger.log(... |
class TimSort:
def __init__(self, array, run_size=32):
self.array = array
self.run_size = run_size
def insertionSort(self, array, left_index, right_index):
""" performs insertion sort on a given array
:param array: the array to sort
:param left_index: the lower bound of ... |
#Padrao de projeto, é qualquer tipo python que pode ser usado com um loop for. Listas, tuplas, dicionarios.
#Fibonacci: 1, 1, 2, 3, 5, 8, 13...
class Fibonacci:
def __init__(self, max):
self.max = max
def __iter__(self):
self.x, self.y = 1, 1
return self
def __next__(self):... |
def is_odd(n):
return n % 2 == 1
def collatz(n):
xs = []
while n != 1:
xs.append(n)
if is_odd(n):
n = 3*n + 1
else:
n = n // 2
xs.append(1)
return xs
def test_collatz():
assert collatz(8) == [8, 4, 2, 1]
assert collatz(5) == [5, 16, 8, 4, 2, ... |
email = [
"rwandaonline.rw",
"rra.gov.rw",
"ur.ac.rw",
"gmail.com",
"yahoo.com",
"yahoo.fr"
]
|
print('list as x y z ...')
a = []
a = input().split(' ')
a = list(map(int, a))
for elemt in (map(lambda x: 'par' if x%2 == 0 else 'impar', a)):
print (elemt) |
while True:
try:
n = int(input())
except:
break
data = list()
maax = list()
miin = list()
for x in range(n):
data.append(list(map(int, input().split())))
for x in range(n):
maax.append(data[x][1])
miin.append(data[x][0])
result = [0]*(... |
applyPatch('20210630-dldt-disable-unused-targets.patch')
applyPatch('20210630-dldt-pdb.patch')
applyPatch('20210630-dldt-disable-multidevice-autoplugin.patch')
applyPatch('20210630-dldt-vs-version.patch')
|
try:
age = int(input("How old are you: "))
#if statement
if age < 0:
print("You are a time traveller")
else:
if 0 < age <= 17:
print("Too young to vote")
else:
if age >= 18:
print("You can vote")
except:
print("Please use only numeric... |
# iterating backwards
# removing rogue vlues
# when an item 's removed from the list, all the later items are shuffled down, to fill in the gap
# That messes upu the index numbers, as we work forwards through the list
data = [104, 101, 4, 105, 308, 103, 5,
107, 100, 306, 106, 102, 108]
min_valid = 100
max_valid... |
# A quick solution for day 12 part 2 in Python
# for debugging of the Pascal version
x = 0
y = 0
wx = 10
wy = -1
with open('resources/input.txt', 'r') as f:
for l in f.readlines():
l = l.strip()
i = l[0]
n = int(l[1:])
if i == 'N':
wy -= n
elif i == 'W':
... |
a = get()
b = execute(mogrify(get()))
print(b)
mogrify(a)
c = get()
|
"""
(System)Verilog language keyword lists
"""
IEEE1364_1995_KEYWORDS = [
"always",
"and",
"assign",
"begin",
"buf",
"bufif0",
"bufif1",
"case",
"casex",
"casez",
"cmos",
"deassign",
"default",
"defparam",
"disable",
"edge",
"else",
"end",
"en... |
year=int(input('enter a num:'))
if year%4==0 or year%400==0:
print('leap year')
else:
print('not') |
# A few global config settings
API_KEY=''
ORG_ID=''
S3_BUCKET_NAME=''
S3_ACCESS_KEY=''
S3_SECRET_KEY=''
MY_ID=''
PLAYER_LICENSE='' |
"""
Split, Join, Enumerate em Python
* Split - Dividir uma string # str
* Join - Juntar uma lista # str
* Enumerate - Enumerar elementos da lista # iteráveis
"""
string = 'O Brasil é penta.'
lista = string.split(' ')
print(lista)
print('---------------------')
for indice, valor in enumerate(lista):
print(indice,... |
__authors__ = ""
__copyright__ = "(c) 2014, pymal"
__license__ = "BSD License"
__contact__ = "Name Of Current Guardian of this file <email@address>"
USER_AGENT = 'api-indiv-0829BA2B33942A4A5E6338FE05EFB8A1'
HOST_NAME = "http://myanimelist.net"
DEBUG = False
RETRY_NUMBER = 4
RETRY_SLEEP = 1
SHORT_SITE_FORMAT_TIME = ... |
# By manish.17, contest: ITMO Academy. Двоичный поиск - 4, problem: (C) Pair Selection
# https://codeforces.com/profile/manish.17
n, k = map(int, input().split())
pairs = []
for i in range(n):
a, b = map(int, input().split())
pairs += [[a, b]]
alpha, omega = 0, 10**18
while alpha < omega:
mid = (alpha + o... |
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
stack = []
result = [-1] * n
for i in range(n * 2):
value = nums[i % n]
while stack and nums[stack[-1] % n] < value:
result[stack.pop() % n] = va... |
# Part One
matrix = []
with open("input") as f:
for row in f:
matrix.append(row)
gama_rate = ""
epsilon_rate = ""
element_list = []
def most_frequent(List):
return max(set(List), key=List.count)
l_row = int(len(matrix[0]))
for el in range(1, l_row):
for row in matrix:
element = row[el... |
class Address:
host = 'localhost'
port = '9666'
def __init__(self, host=None, port=None):
if host is not None:
self.host = host
if port is not None:
self.port = port
def is_empty(self) -> bool:
return self.host == '' or self.port == ''
def string(se... |
f = open("cub_200/val.txt", "r")
class_dict = {}
rtn = open('val_tmp.txt', 'w')
for x in f:
class_int = int(x[7:10])
if class_int not in class_dict.keys():
class_dict[class_int] = 1
else:
class_dict[class_int] += 1
if class_dict[class_int] > 5:
if class_int % 2 == 0:
... |
class Solution(object):
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
# https://discuss.leetcode.com/topic/50450/slow-1-liner-to-fast-solutions
queue = []
d... |
# coding: utf-8
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.sessions',
'django.contrib.contenttypes',
'registration',
'test_app',
)
SECRET_K... |
# -*- coding: utf-8 -*-
"""
1561. Maximum Number of Coins You Can Get
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum numbe... |
class APIError(Exception):
code = -1
message = 'Unknown error'
def __init__(self, message=None, details=None, data={}, response=None):
self.message = message or self.message
self.details = details
self.data = data or {}
self.response = response
def __str__(self):
... |
""" 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time comp... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2020 Patrick Nanys <patrick.nanys2000@gmail.com>
#
# Distributed under terms of the MIT license.
def reduce(list_to_reduce, acc_func, accumulator=None):
if accumulator is not None:
accumulated = acc_func(accumulator, list_to_reduce[0])
... |
def show_state(state, player):
return {
'hands': state['hands'],
'turn': state['turn'],
}
|
class MultimodalDataset:
def __init__(self, samples, modality_factories):
super().__init__()
self.samples = samples
self.modality_factories = modality_factories
self._register_modalites_to_samples()
def _register_modalites_to_samples(self):
for sample in self.samples:
... |
class Solution:
def isValid(self, s: str) -> bool:
matched=[0 for i in range(len(s))]
open_brace=0
find=''
for i in range (len(s)):
if(s[i]==')' or s[i]=='}' or s[i]==']'):
if(s[i]==')'):
find='('
... |
aluno = {}
aluno['Nome'] = str(input('Nome aluno: ')).strip().title()
aluno['Média'] = float(input(f'Média do(e) {aluno["Nome"]}: '))
if aluno['Média'] >= 7:
aluno['Status'] = 'APROVADO'
elif aluno['Média'] >= 5 < 7:
aluno['Status'] = 'EM RECUPERAÇÃO'
else:
aluno['Status'] = 'REPROVADO'
for i, d in aluno.it... |
def generate( args ):
args = args.split(',')
start = int(args[0])
numGroups = int(args[1])
perGroup = int(args[2])
interval = int(args[3])
ret = ''
for i in range(numGroups):
first = start + i * interval
last = first + perGroup - 1
ret = ret + '{0}-{1}'.format... |
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py'
model = dict(
neck=[
dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_input',
num_outs=5),
dict(
type='SEPC... |
vorname = "Hans"; # Name: vorname, Datentyp: String, Wert: Hans
a = 7; # Datentyp: integer
width = "11"; # Datentyp: string
# Fläche des Rechtecks
b = int(width); # Konvertiere zu integer (Zahl)
area = a * b;
print(area);
# Neue Datentypen
dezimalzahl = 3.14; # Datentyp: float, Name: dezimalzahl, Wert:3.14
istWahr =... |
def main():
week={'A':'MON','B':'TUE','C':'WED','D':'THU','E':'FRI','F':'SAT','G':'SUN'}
strs = []
for i in range(0,4):
strs.append(input())
for i in range(0,min(len(strs[0]),len(strs[1]))):
if(strs[0][i]==strs[1][i]):
if(strs[0][i]>='A' and strs[0][i]<='G'):
... |
# Copyright 2020 The Kythe 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 law... |
class Mail:
def __init__(self, application, driver_config=None):
self.application = application
self.drivers = {}
self.driver_config = driver_config or {}
self.options = {}
def add_driver(self, name, driver):
self.drivers.update({name: driver})
def set_configuration... |
n = int(input('Digite um número para saber seu fatorial: '))
i = n
v = 0
m = 1
s = 1
print('{}! = '.format(i), end='')
while n != 1:
s += 1
m *= s
v = n - 1
f = n * v
print('{}'.format(n), end=' x ')
n -= 1
print('1 = {}'.format(m))
|
#
# PySNMP MIB module H3C-BLG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-BLG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:21:27 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... |
class AutoTuneCommands(object):
_command = "ju"
def __init__(self, send_command):
self._send_command = send_command
async def call(self):
return await self._send_command(self._command, 1)
|
#Heap Sort as the name suggests, uses the heap data structure.
#First the array is converted into a binary heap. Then the first element which is the maximum elemet in case of a max-heap,
#is swapped with the last element so that the maximum element goes to the end of the array as it should be in a sorted array.
#Then t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
"""
Вашей программе на вход подаются две строки s и t, состоящие из строчных латинских букв.
Выведите одно число – количество вхождений строки t в строку s.
Пример:
s = "abababa"
t = "aba"
Sample Input 1:
abababa
aba
Sample Output 1:
3
Sampl... |
class A:
def __init__(self, *, a):
pass
class B(A):
def __init__(self, a):
super().__init__(a=a) |
class Ball:
def __init__(self):
self.position = PVector(width * 0.5, height * 0.5)
self.w = 20
self.velocity = PVector(5, 5)
self.score_player_one = False
self.score_player_two = False
def show(self):
fill(255)
ellipse(self.position.x, self.position.y, sel... |
#!/usr/bin/env python3
# coding: utf8
"""
This script contains functions to calculate error rates,
including word error rate, sentence error rate, and more specific
error rates such as digit error rate.
"""
def sentence_error(source, target):
"""
Evaluate whether the target is identical to the source.
... |
ISOCHRONES_DATASET_NAME = "webapp_isochrones"
LOCATIONS_DATASET_NAME = "webapp_locations"
CUSTOMERS_DATASET_NAME = "webapp_customers"
CUSTOMERS_NO_FILTERING_COLUMNS = [
'id',
'customer_uuid',
'location_uuid',
'isochrone_type',
'distance_customer_location',
'isochrone_id',
'isochrone_amplit... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-AtmBearerServiceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AtmBearerServiceMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:29:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.... |
class Solution:
def XXX(self, a: str, b: str) -> str:
if len(a) < len(b):
a, b = b, a
b = '0' * (len(a) - len(b)) + b
c = []
flag = 0
for i in range(1, len(a) + 1):
c.insert(0, str( (int(a[-i]) + int(b[-i]) + flag) % 2))
flag = ( int(a[-i]... |
soma = 0
cont = 0
for c in range(1, 7):
n = int(input(f'Digite o {c}° numero:'))
if n % 2 == 0:
soma += n
cont += 1
print(f'A soma de todos os {cont} valores pares é igual á {soma}')
|
def application(environment, start_response):
response_body = (
'Greetings to all Python developers! '
'This is standard WSGI handler.'
)
status = '200 OK'
response_headers = [
('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body))),
]
start_re... |
# 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 isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
stack=[(r... |
def test_soap(app):
project_list = app.soap.get_project_name_list("administrator", "root")
print("\n" + str(project_list))
print(len(project_list))
|
MOCK_DATA = [
{
"symbol": "AMD",
"companyName": "Advanced Micro Devices Inc.",
"exchange": "NASDAQ Capital Market",
"industry": "Semiconductors",
"website": "http://www.amd.com",
"description": "Advanced Micro Devices Inc designs and produces microprocessors and low-p... |
"""
Identities: module definition
"""
PROPERTIES = {
'title': 'Contacts',
'details': 'Manage users, groups, companies and corresponding contacts',
'url': '/contacts/',
'system': True,
'type': 'minor',
}
URL_PATTERNS = [
'^/contacts/',
]
|
"""Without the letter 'E', CodeWars Kata, level 7."""
def with_without_e(s):
"""Return number of Es in string.
input = string
output = count in string form of Es
"""
if not s:
return s
count = 0
for e in s:
if e == 'e' or e == 'E':
count += 1
if count == 0:... |
class Solution:
# O(n) time | O(1) space - where n is the length of the input list.
def maxProfit(self, prices: List[int]) -> int:
minPrice = prices[0]
maxProfit = 0
for i in range(1, len(prices)):
if prices[i] < minPrice:
minPrice = prices[i]
eli... |
class Article:
def __init__(self,title,urlToImage,description,url,author):
self.title=title
self.urlToImage=urlToImage
self.description=description
self.author=author
self.url=url
class Source:
def __init__(self,name,description):
self.name=name
self.desc... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature":... |
"""
ThreatStack Python Client Exceptions
"""
class Error(Exception):
pass
class ThreatStackClientError(Exception):
pass
class ThreatStackAPIError(Error):
pass
class APIRateLimitError(Error):
""" Used to trigger retry on rate limit """
pass
|
class Solution:
def XXX(self, nums: List[int]) -> bool:
nextdis = 0
curdis = 0
for i in range(len(nums)):
nextdis = max(i+nums[i], nextdis)
if i==curdis:
curdis = nextdis
if nextdis >= len(nums)-1:
return True
... |
"""This module is for learning
This module has basic functions to work with numbers
"""
def is_even(number: int) -> bool:
"""
This method will find if the number passed is even or not
:param number : a number
:return: True if even False otherwise
"""
if number <= 0:
return False
... |
# -*- coding: utf-8 -*-
'''
File name: code\criss_cross\sol_166.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #166 :: Criss Cross
#
# For more information see:
# https://projecteuler.net/problem=166
# Problem Statement
'''
A 4x4 grid ... |
class FieldError(Exception):
"""
Base class for errors to do with setting fields on PointClouds and their
subclasses.
"""
pass
class PointFieldError(FieldError):
"""
Raised when setting point fields on PointClouds.
"""
pass
|
name = 'pyjoystick'
version = '1.2.4'
description = 'Tools to get Joystick events.'
url = 'https://github.com/justengel/pyjoystick'
author = 'Justin Engel'
author_email = 'jengel@sealandaire.com'
|
# -*- coding: utf-8 -*-
list_samples = ['元素1', '元素2', '元素3', '元素4']
print(list_samples)
# 获取列表指定元素
print(list_samples[0].title())
print(list_samples[-1].title())
# 修改元素
list_samples[0] = '修改后的元素1'
print(list_samples)
# 末尾添加元素
list_samples.append("末尾添加元素")
print(list_samples)
# 插入元素
list_samples.insert(0, "新插入元素")
... |
pi = "141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128"
pi += "48111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458... |
#Before running this code we should run 2 commands in command prompt they are :-
#1) pip install Image
#2) pip install qrcodeimport qrcode
code=qrcode.QRCode(version=5,box_size=15,border=5)
link=input("copy the content:")
code.add_data(link)
code.make(fit=True)
img=code.make_image(fill="black",back_color="white... |
def find_outlier(integers):
even, odd = [], []
for i in sorted(integers):
if i % 2 != 0:
odd.append(i)
else:
even.append(i)
if len(even) > 1 and len(odd) != 0:
return odd[0]
elif len(odd) > 1 and len(even) != 0:
return even[0]
|
class BaseSnappyError(Exception):
"""
Base error class for snappy module.
"""
class CorruptError(BaseSnappyError):
"""
Corrupt input.
"""
class TooLargeError(BaseSnappyError):
"""
Decoded block is too large.
"""
|
#leia o primeiro termo e a razão de uma Progressão aritimética.No final, mostre os 10 primeiros termos dessa progressão.
print('-='*10)
print('{:=^20}'.format('Desafio 51'))
print('-='*10)
n1=int(input('Qual o primeiro termo? '))
r=int(input('Qual a razão da progressão? '))
for n1 in range (n1,(n1+(10-1))*r+1,r):
... |
#Thea M Factorial of a positive no
def func_factorial(n):
# factorial is n * by all the '+' no less than it
#n= 7
#if n == 1:
# if n is 1 return 1
#return n
#else:
#return n * (n-1)
#
# Python program to find the factorial of a number provided by the user.
# ch... |
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
rs = []
for i in range(len(s) - 1, -1, -1):
rs.append(s[i])
return "".join(rs)
|
# MongoDB数据库
host = "localhost"
port = 27017
db = 'cqbot'
# 忽略名单
ignore_list = [2177486721, 80000000]
# 自动生草最小间隔,单位:秒
grass_delay = 15
|
#Now that we looked at aleatoric and epistemic uncertainty in isolation, we can use TFP layers’ composable API to create a model that reports both types of uncertainty:
# Build model.
model = tf.keras.Sequential([
tfp.layers.DenseVariational(1 + 1, posterior_mean_field, prior_trainable),
tfp.layers.DistributionL... |
""" TODO : does not work!!! """
string_to_decode = "Ива Попова"
output_file = "decoded_cp1251.txt"
with open(output_file, "w") as fh:
# fh.writelines(string_to_decode+"\n")
bytes_decoded = string_to_decode.encode()
print(bytes_decoded)
decoded_string = bytes_decoded.decode(encoding="cp1251")
# fh.write(d... |
class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
row, col = len(s), len(t)
if col > row:
return 0
dp = [[0 for _ in range(col+1)] for _ in range(row+1)]
for r in range(row+1):
... |
def build_ast_dictionary(code, prefix=tuple(), d=None):
if d is None:
d = dict()
if prefix == tuple():
d['total'] = code
else:
d[prefix] = code
tag, subcode = code
if isinstance(subcode, list):
for i, subitem in enumerate(subcode):
build_ast_dictionary(su... |
_base_ = [
'../_base_/models/upernet_swin.py', '../_base_/datasets/Vaihingen.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
model = dict(
pretrained='pretrain/swin_tiny_patch4_window7_224.pth',
backbone=dict(
embed_dims=96,
depths=[2, 2, 6, 2],
num_h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.