content stringlengths 7 1.05M |
|---|
# return n * (n+1) / 2
with open('./input', encoding='utf8') as file:
coord_strs = file.readline().strip()[12:].split(', ')
x_range = [int(val) for val in coord_strs[0].split('=')[1].split('..')]
y_range = [int(val) for val in coord_strs[1].split('=')[1].split('..')]
y_speed = abs(y_range[0])-1
print(y_s... |
DEFAULT_CELERY_BROKER_LOGIN_METHOD = 'AMQPLAIN'
DEFAULT_CELERY_BROKER_URL = None
DEFAULT_CELERY_BROKER_USE_SSL = None
DEFAULT_CELERY_RESULT_BACKEND = None
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Welcome to vivo !
输入:
(()(()((()(0)))))
输出:
5
'''
def solution(s):
#TODO Write your code here
giftIndex = findGift(s)
ret = []
for gitf in giftIndex:
cur = getMin(s, gitf)
ret.append(cur)
return min(ret)
def findGift(s):
""... |
A, B ,C= map(int, input().split())
D=int(input())
C+=D
if C>59:
B+=C//60
C=C%60
if B>59:
A+=B//60
B=B%60
if A>23:
A=A%24
print(A,B,C)
else:
print(A,B,C)
else:
print(A,B,C)
else:
print(A,B,C) |
def makeprefixsum(nums):
prefixsum = [0] * (len(nums) + 1)
for i in range(1, len(nums)+1):
prefixsum[i] = prefixsum[i-1] + nums[i-1]
return prefixsum
def rsq(prefixsum, l, r): # Range Sum Query
return prefixsum[r] - prefixsum[l]
def countzeroes(nums, l, r):
cnt = 0 # complexity O(NM) N ... |
"""155. Min Stack
References:
https://leetcode.com/problems/min-stack/
https://leetcode-cn.com/problems/min-stack/
"""
class MinStack:
"""辅助栈
定义「数据栈」支持`push`、`pop`、`top` 操作
定义「辅助栈」保持栈顶元素为当前的最小值
当元素入数据栈时,如果此元素不大于辅助栈的栈顶元素,那么此元素也需要压入辅助栈的栈顶;
当元素从栈顶被弹出时,如果此元素等于辅助栈的栈顶元素,即此元素就是当前的最小值,也需要从辅助栈弹... |
""" Date : Mars 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire un programme qui aide le croupier à déterminer la somme que le casino doit donner au joueur.
Le programme lira, dans l’ordre, deux nombres entiers en entrée : le pari du joueur (représenté par un nombre entre 0 et 16... |
number_of_nice_strings=0
with open("input.txt") as input:
for line in input:
line=line.rstrip()
#chack vowels
num_of_vowels=0
vowels=["a","e","i","o","u"]
vowels_dict={}
for vowel in vowels:
if vowel in line:
vowels_dict[vowel] = line.coun... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 12 13:06:05 2022
@author: Pedro
"""
#%% ejercicio 2
def a_count(string1: str) -> int:
counter = 0
for i in string1:
t = i.lower()
if t == "a":
counter += 1
return counter
#%%ejercicio 5
def ip_colmillos(ip: st... |
data1 = {
'board': {
'snakes': [
{'body': [
{'x': 5, 'y': 5},
{'x': 5, 'y': 6},
{'x': 4, 'y': 6},
{'x': 3, 'y': 6},
{'x': 3, 'y': 5},
{'x': 3, 'y': 4},
{'x': 4, 'y': 4},
... |
# python 3.6
def camel2pothole(string):
rst = "".join(["_" + s.lower() if s == s.upper() or s.isdigit() else s for s in string])
return rst
print(camel2pothole("codingDojang"))
print(camel2pothole("numGoat30")) |
browsers = [
{
'id': 'chrome',
'name': 'Chrome'
},
{
'id': 'chromium',
'name': 'Chromium'
},
{
'id': 'firefox',
'name': 'Firefox'
},
{
'id': 'safari',
'name': 'Safari'
},
{
'id': 'msie',
'name': 'Internet Explorer'
},
{
'id': 'mse... |
N, K, S = [int(n) for n in input().split()]
ans = []
for i in range(N-K):
ans.append(S+1 if S<10**9 else 1)
for j in range(K):
ans.append(S)
print(" ".join([str(n) for n in ans]))
|
#Binary Tree Level Order BFS&DFS
class Solution(object):
def levelOrder(self, root):
if not root:
return []
result = []
queue = collections.deque()
queue.append(root)
#visited = set(root)
while queue:
level_size = len(queue)
cur... |
# Python Learning Lessons
some_var = int(input("Give me a number, any number: "))
if some_var > 10:
print("The number is bigger than tenerooonie.")
elif some_var < 10:
print("The numbah is smaller than 10.")
elif some_var == 10:
("YO. The numbah is TEN!")
some_name = str(input("Hey, what's your name... |
class SubClass():
def __init__(self):
self.message = 'init - SubFile - mtulio.example.sub Class'
def returnMessage(self):
return self.message
def subMessageHelloWorld():
return 'init - SubFile - mtulio.example.sub Method'
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ------------------------------------------------------------
# File: update_db.py.py
# Created Date: 2020/6/27
# Created Time: 1:30
# Author: Hypdncy
# Author Mail: hypdncy@outlook.com
# Copyright (c) 2020 Hypdncy
# --------------------------------------------------------... |
"""
Discussion:
To better appreciate what is happening here, you should go back to the previous
interactive demo. Set the w = 5 and I_ext = 0.5.
You will find that there are three fixed points of the system for these values of
w and I_ext. Now, choose the initial value in this demo and see in which direction
the syst... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"api_version": "apiVersion",
"attacher_node_selector": "attacherNodeSelector",
"driver_registrar": "driverRegistrar",
"... |
STATS = [
{
"num_node_expansions": NaN,
"plan_length": 35,
"search_time": 7.93,
"total_time": 7.93
},
{
"num_node_expansions": NaN,
"plan_length": 34,
"search_time": 9.72,
"total_time": 9.72
},
{
"num_node_expansions": NaN,
... |
"""
Build a Triangle
"""
# Use a while loop to print a 5-level triangle of stars that looks like this:
"""
*
**
***
****
*****
"""
|
def a():
pass
# This is commented
# out
|
""" Diseñe una función que calcule la cantidad de carne de aves en kilos si se
tienen N gallinas, M gallos y K pollitos cada uno pesando 6 kilos, 7 kilos y 1
kilo respectivamente. """
def get_amount(N, M, K):
chickens = N * 6
roosters = M * 7
chicks = K * 1
total = chickens + roosters + chicks
pri... |
"""
Main entrypoint
---------------
Just-in-time injections awaitable from asyncio coroutines
Author: Chris Lee
Email: chrisklee93@gmail.com
"""
def main():
pass
if __name__ == "__main__":
main()
|
def makeArrayConsecutive2(statues):
'''Ratiorg got statues of different sizes as a present from CodeMaster
for his birthday, each statue having an non-negative integer size.
Since he likes to make things perfect, he wants to arrange them from
smallest to largest so that each statue will be ... |
def is_list(v):
return isinstance(v, list)
def is_list_of_type(v, t):
return is_list(v) and all(isinstance(e, t) for e in v)
def flatten_indices(indices):
# indices could be nested nested list, we convert them to nested list
# if indices is not a list, then there is something wrong
if not is_list(indi... |
arquivo = open('numeros.txt', 'a') # append acrescente dados
for linha in range(341,621):
arquivo.write('%d\n' % linha)
arquivo.close()
arquivo = open('numeros.txt', 'r') # lê os arquivos
for x in arquivo.readlines():
print(x)
arquivo.close()
|
s1 = "HELLO BEGINNERS"
print(s1.casefold()) # -- CF1
s2 = "Hello Beginners"
print(s2.casefold()) # -- CF2
if s1.casefold() == s2.casefold(): # -- CF3
print("Both the strings are same after conversion")
else:
print("Both the strings are different after conversion ")
|
counter = 0 #初始化counter为0
while True:
counter += 1 #counter累加1
print(counter) #输出counter值
if counter >= 10: #当counter大于等于10时,跳出while循环
break |
n = list(map(int, input("[>] Enter numbers: ").split()))
n.sort()
for i in range(3):
for j in range(3):
print(f"{n[i]} + {n[j]} = {n[i] + n[j]}", end="\t")
print()
|
class Solution:
def sortColors(self, nums: List[int]) -> None:
# If 2, put it at the tail
# if 0, put it at the head and move idx to next
# If 1, move idx to next
idx = 0
for _ in range(len(nums)):
if nums[idx] == 2:
nums.append(nums.pop(i... |
capital= float (input("Ingrese la cantidad de dinero a invertir: "))
interes = float (input ("Ingrese el porcentaje de interés que el banco pagará mensualmente:"))
ganancia=(capital*interes)
total= float(capital+ganancia)
print("En total de dinero al final de un mes será de: ", str(total)) |
{
'targets': [
{
'conditions': [
[ 'OS != "linux"', {
'target_name': 'procps_only_supported_on_linux',
} ],
[ 'OS == "linux"', {
'target_name': 'procps',
'sources': [
'src/procps.cc'
, 'src/proc.cc'
, 'src/diskstat... |
#!/usr/bin/env python3
def read_value():
"""Reads a single line as an integer."""
return int(input())
def read_row(width):
"""Reads one row of integers interpreted as booleans."""
row = [int(field) != 0 for field in input().split()]
if len(row) != width:
raise ValueError('wrong row width... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def getConstrains(tab):
constrains = [['A.1', 3, 0, 9, "População total e sua distribuição proporcional" ],
['A.2', 3, 0, 6, "Homens por 100 mulheres" ],
['A.3', 3, 0, 4, u"Taxa de crescimento da populacão(%)"],
... |
ROMAN = 'IVXLCDM'
def get_list_from_number(number):
return [int(num) for num in str(number)]
def get_roman_from_base(base_indexes, magnitude):
roman = ""
for i in base_indexes:
roman += ROMAN[i + magnitude*2]
return roman
def convert_number_to_base_indexes(number):
# Convert a number to a... |
# SPDX-FileCopyrightText: 2020 - Sebastian Ritter <bastie@users.noreply.github.com>
# SPDX-License-Identifier: Apache-2.0
'''
## *J*ust *a* *v*ampire *A*PI ##
As same as bloodhound let us reimplement the Java API.
This is similar to long time ago
[JavAPI](https://github.com/RealBastie/JavApi) project.
###... |
class Meal:
def __init__(self,id,name,photo_url,details,price):
self.id = id
self.name = name
self.photo_url = photo_url
self.details = details
self.price = price
meal_list = []
orders_list = []
class Customer:
def get_all(self):
return meal_list
def get_me... |
"""
0. Save/copy this file to a new file under commands/
1. Add logic to my_command and rename it to something more meaningful.
Optionally you can access user, channel, text from the passed in **kwargs (don't remove this).
2. Add a useful docstring to your renamed my_command.
3. Return a message string that the c... |
self.description = "Sysupgrade with a sync package having higher epoch"
sp = pmpkg("dummy", "1:1.0-1")
self.addpkg2db("sync", sp)
lp = pmpkg("dummy", "1.1-1")
self.addpkg2db("local", lp)
self.args = "-Su"
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_VERSION=dummy|1:1.0-1")
|
attacks_listing = {}
listing_by_name = {}
def register(attack_type):
if attack_type.base_attack:
if attack_type.base_attack in attacks_listing:
raise Exception("Attack already registered for this base_object_type.")
elif attack_type.name in listing_by_name:
raise Exception(... |
# MIT License
#
# Copyright (c) 2019 Eduardo E. Betanzos Morales
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... |
# Copyright 2014 PDFium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'bigint',
'type': 'static_library',
'sources': [
'bigint/BigInteger.hh',
'bigint/BigInteger... |
CERTIFICATION_SERVICES_TABLE_ID = 'cas'
INTERMEDIATE_CA_TAB_XPATH = '//a[@href="#intermediate_cas_tab"]'
INTERMEDIATE_CA_ADD_BTN_ID = 'intermediate_ca_add'
INTERMEDIATE_CA_CERT_UPLOAD_INPUT_ID = 'ca_cert_file'
INTERMEDIATE_CA_OCSP_TAB_XPATH = '//a[@href="#intermediate_ca_ocsp_responders_tab"]'
INTERMEDIATE_CA_OCSP... |
'''Faça um programa que recebe o salário de um colaborador e o reajuste segundo
o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) : aumento de 20%
salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
salários de R$ 1500,00 em ... |
# @author:leacoder
# @des: 递归 合并两个有序链表
'''
重复处理单元:
比较两个链表节点值
将
递归终止条件:
两个链表都是空的
递归前处理(递归到下一层前处理):
比较当前层 哪个链表头节点较小,递归找这个链表的下一个
递归(递归到下一层):
递归后处理(下层递归返回后处理):
返回较小值
'''
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif ... |
# coding=utf-8
"""
This package provides a custom session for TheTVDB.
"""
|
#!/usr/bin/env python3
def max_profit_with_k_transactions(prices, k):
pass
print(max_profit_with_k_transactions([5, 11, 3, 50, 60, 90], 2))
|
class Solution:
def findLUSlength(self, words):
def isSubsequence(s, t):
t = iter(t)
return all(c in t for c in s)
words.sort(key = lambda x:-len(x))
for i, word in enumerate(words):
if all(not isSubsequence(word, words[j]) for j in range(len(words)) if ... |
class Query:
def __init__(self, the_query, filename=None):
self.data = None
self.the_query = the_query
def set_data(self, data):
self.data = data
def __repr__(self):
return self.the_query
class LocalMP3Query(Query):
def __init__(self, filename, url, author_name):
... |
class Rect:
def __init__(self, id: int, x: int, y: int, w: int, h: int):
self.id = id
self.pos = (x,y)
self.size = (w,h)
def getX(self):
return self.pos[0]
def getY(self):
return self.pos[1]
def getEndX(self):
return self.getX() + self.getW()
def getEn... |
# Clover全局配置
DEBUG = True
VERSION = '0.9.1'
# MySQL数据库配置
MYSQL = {
'user': 'clover',
'pswd': '52.clover',
'host': '127.0.0.1',
'port': '3306',
}
SQLALCHEMY_DATABASE_URI = 'mysql://{user}:{pswd}@{host}:{port}/clover?charset=utf8'.format(**MYSQL)
SQLALCHEMY_TRACK_MODIFICATIONS=True
# celery配置
CELERY_HOS... |
#Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na #posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
lista=[]
for i in range(0,5):
numeros= int(input(f"Digite o {i}° numero: "))
if i==0 or numeros>lista[-1]:... |
# Databricks notebook source
# MAGIC %run /Shared/churn-model/utils
# COMMAND ----------
seed = 2022
target = 'Churn'
drop_columns = [target, 'CodigoCliente']
# Get the Train Dataset
dataset = get_dataset('/dbfs/Dataset/Customer')
# Preprocessing Features
dataset, numeric_columns = preprocessing(dataset)
# Split ... |
#
# @lc app=leetcode.cn id=747 lang=python3
#
# [747] min-cost-climbing-stairs
#
None
# @lc code=end |
"""
The difference between: "==" and "is" operators
This can be a bit confusing!!
Note that "==" operator distinguishes whether
two operands have the same value and that
"is" operator distinguishes whether two operands
refer to the same object!
"""
a = [1, 2, 3]
b = [1, 2, 3]
# we have two lists that have the same v... |
"""Perform DOI activation task."""
class HSTaskRouter(object):
"""Perform DOI activation task."""
def route_for_task(self, task, args=None, kwargs=None):
"""Return exchange, exchange_type, and routing_key."""
if task == 'hs_core.tasks.check_doi_activation':
return {
... |
class Note:
def __init__(self, number=0, name='', alt_name='', frequency=0, velocity=1):
self.number = number
self.name = name
self.alt_name = alt_name
self.frequency = frequency
self.velocity = velocity
|
#!/usr/bin/env python
# Copyright (c) 2015 Nelson Tran
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, ... |
def minion_game(string):
# your code goes here
vowels = ['A', 'E', 'I', 'O', 'U']
kevin = 0
stuart = 0
for i in range(len(string)):
if s[i] in vowels:
kevin = kevin + (len(s)-i)
else:
stuart = stuart + (len(s)-i)
if stuart > kevin:
... |
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
N = int(input())
line_of_numbers = input().split(' ')
# Extract numbers from input line and add them to list
A = []
for i in range(N):
A.append(int(line_of_numbers[i]))
# Sort list and get largest value from it
A.sort()
max_number =... |
# The kth Factor of n
'''
Given two positive integers n and k.
A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output... |
LOGIN_REQUIRED = 'Es Necesario iniciar Sesion!'
USER_CREATED = 'Usuario Creado Exitosamente!'
LOGOUT = 'Cerraste Sesion!'
ERRO_USER_PASSWORD = 'Usuario o Contrasena Invalidos!'
LOGIN = 'Usuario Autenticado Exitosamente!'
TASK_CREATED = 'Tarea creada Exitosamente!'
TASK_UPDATED = 'Tarea Actualizada!'
TASK_DELETE ... |
def left_join(d1, d2):
results = []
for key in d1:
if key in d2:
results.append([key, d1[key], d2[key]])
else:
results.append([key, d1[key], None])
return results |
listagem = ('APRENDER', 'PROGRAMAR',
'LINGUAGEM', 'PYTHON',
'CURSO', 'GRATIS',
'ESTUDAR', 'PRATICAR',
'TRABALHAR', 'MERCADO',
'PROGRAMADOR', 'FUTURO')
for pos in listagem:
print(f'\nNa palavra {pos} temos ', end=' ')
for letra in pos:
if letra.... |
# -*- codding: utf-8 -*-
# Ключевые слова без окончаний, в любом регистре.
keywords = [
'Америк',
'Германи',
'гомик',
'гомосек',
'Казахстан',
'Латви',
'Литв',
'мигрант',
'негр',
'нигер',
'пидор',
'Польш',
'Прибалт',
'Украин',
'феминистк',
'Эстони',
]
# ... |
# @Title: 最长回文子串 (Longest Palindromic Substring)
# @Author: 18015528893
# @Date: 2021-02-18 14:28:08
# @Runtime: 1000 ms
# @Memory: 15 MB
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) < 2:
return s
def expand(l, r):
while l < r:
if l... |
# In Python, the names of classes follow the CapWords
# convention. Let's convert the input phrase accordingly by
# capitilizing all words and spelling them without underscores in-
# between.
# The input format:
# A word or phrase, with words separated by underscores, like
# function and variable names in Python.
# ... |
"""Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0, 1, 2, 3, 4, 5, 6, 7]) might become [4, 5, 6, 7, 0, 1, 2]).
You are given a target value to search. If found in the arrary return its index, otherwise return
- 1. You may assume ... |
pow_of_5th = {i:i**5 for i in range(10)}
def get_5th_pow_of(n):
return pow_of_5th[n]
def get_sum_of_5th_pow_of(n):
sum = 0
for digit in str(n):
sum += get_5th_pow_of(int(digit))
return sum
if __name__ == "__main__":
numb = set()
ceil = ((pow_of_5th[9]) * 9)+1 # Verify this ceil
for n in range(2, ce... |
CONSUMER_API_KEY = ""
CONSUMER_API_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_KEY = ""
|
def emergency_stop(driver):
driver.setSteeringAngle(0.0)
driver.setCruisingSpeed(0)
def stop(driver, frame=30):
driver.setSteeringAngle(0.0)
driver.setCruisingSpeed(0)
def print_all_devices(r):
print('---------------------------------------')
for i in range(r.getNumberOfDevices()):
... |
file = open("input01.txt").read().splitlines()
file = [int(x) for x in file]
"""Part One"""
counter = 0
for i in range(1, len(file)):
if file[i] - file[i-1] > 0:
counter += 1
print(counter)
"""Part Two"""
temp = []
for i in range(len(file)-2):
temp.append(sum(file[i:i+3]))
counter = 0
for i in range(1... |
"""Placeholder for MicroPython framebuf module"""
MONO_VLSB = 0
MONO_HLSB = 0
MONO_HMSB = 0
RGB565 = 0
GS4_HMSB = 0
class FrameBuffer():
def __init__(self, buffer, width, height, format, stride=None):
pass
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Script: solution.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2018-02-12 23:58:20
# @Last Modified By: Pradip Patil
# @Last Modified: 2018-02-13 00:15:16
# @Description: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/prob... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/2/1 上午8:00
# @Author : wook
# @File : database.py
"""
Database configuration file
"""
host = "127.0.0.1"
user = "root"
password = "123456"
database = "tro_db"
port = 3306
charset = "utf8"
prefix = 'db_'
|
class Base(object):
TYPE_ATTRIBUTES = ("_entity_type", "workflow_type")
@staticmethod
def _get_camelcase(attribute):
if attribute in Base.TYPE_ATTRIBUTES:
return "type"
tmp = attribute.split("_")
return tmp[0] + "".join([w.title() for w in tmp[1:]])
@staticmethod
... |
n = int(input())
while n:
p = str(input())
print("gzuz")
n = n - 1
|
group_name = [
'DA',
'DG',
'DC',
'DT',
'DI'
]
|
"""
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999,
que é a condição de parada. No final, mostre quantos números
foram digitados e qual foi a soma entre eles (desconsiderando o flag).
"""
|
LESSONS = [
{
"Move cursor left": ["h"],
"Move cursor right": ["l"],
"Move cursor down": ["j"],
"Move cursor up": ["k"],
"Close file": [":q"],
"Close file, don't save changes": [":q!"],
"Save changes to file": [":w"],
"Save changes and close file": [":... |
__author__ = 'JPaschoal'
__version__ = '1.0.1'
__email__ = 'jonfisik@hotmail.com'
__date__ = '06/05/2021'
'''
Dizemos que um número natural n é palídromo (3) se
o 1º algarismo é igual ao seu último algarismo,
o 2º algarismo é igual ao seu penúltimo algarismo,
e assim sucessivamente.
Exemplos -
Palí... |
class Car:
"""
Car models a car w/ tires and an engine
"""
def __init__(self, engine, tires):
self.engine = engine
self.tires = tires
def description(self):
print(f"A car with a {self.engine} engine, and {self.tires} tires")
def wheel_circumference(self):
if le... |
# # 15题 字典也是类
# class User:
# def __init__(self, user, pwd, email):
# self.user = user
# self.pwd = pwd
# self.email = email
#
# user_list = []
#
# # obj = User('alex1', '123', 'xx@live.com')
# obj = {'user': 'alex1', 'pwd': 123,
# 'email': 'asdf@live.com'} # dict({'user':'alex1','pw... |
def centuryFromYear(year):
if ((year > 0) and (year <= 2005)):
str_year = str(year) # converts integer input to string type with 'str()'
len_year = len(str_year) # finds length of new 'str_year'
century_arr = []
century = 0
# iterates through 'str_year'...
for digit... |
def get_roles(client: object) -> list:
"""Get information about the roles in Blackbaud.
Documentation:
https://docs.blackbaud.com/on-api-docs/api/constituents/role/get-listall
Args:
client (object): The ON API client object.
Returns:
List of dictionaries.
"""
url = '/r... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
__author__ = "Sarath Menon, Jan Janssen"
__copyright__ = (
"Copyright 2020, Max-Planck-Institut für Eisenforschung G... |
#
# PySNMP MIB module CISCO-DMN-DSG-SDI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DMN-DSG-SDI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:37:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#
# TrafficLight.py
# Taco --- SPH Innovation Challenge
#
# Created by Mat, Kon and Len on 2017-03-11.
# Copyright 2016 Researchnix. All rights reserved.
#
class TrafficLight:
# State is a 2D array with the values 0 and 1 associating red and green
# to the path from one incoming street to another outgoi... |
# Lists of valid tags and mappings for tags canonicalization.
#
# Copyright (c) 2020-2021 Tatu Ylonen. See file LICENSE and https://ylonen.org
# Mappings for tags in template head line ends outside parentheses. These are
# also used to parse final tags from translations.
xlat_head_map = {
"m": "masculine",
"... |
mins = []
maxes = []
letters = []
passwords = []
with open("day2_input", "r") as f:
for line in f:
first, second = line.split(':')
first = first.split('-')
mins.append(int(first[0]))
maxes.append(int(first[1].split(' ')[0]))
letters.append(first[1].split(' ')[1])
pas... |
#
# PySNMP MIB module PDN-UPLINK-TAGGING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-UPLINK-TAGGING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:39:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
class Chromosome:
def __init__(self, gene):
self.gene = gene
|
"""
对象 = 属性 + 方法
"""
class Turtle: # Python 中的类名约定以大写字母开头
"""关于类的一个简单例子"""
# 属性
color = 'green'
weight = 10
legs = 4
shell = True
mouth = '大嘴'
# 方法
def climb(self):
print('我正在很努力的向前爬....')
def run(self):
print('我正在快速的向前跑.....')
def bite(self)... |
"""
Runtime: 800 ms, faster than 31.40% of Python3 online submissions for Two Sum.
Memory Usage: 14.9 MB, less than 11.62% of Python3 online submissions for Two Sum.
https://leetcode.com/problems/two-sum
"""
def twoSum(nums, target):
# nums is a list of given numbers
# target is our goal
for... |
#
# PySNMP MIB module FDRY-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FDRY-RADIUS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:59:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
input = """
% Enforce that <MUST_BE_TRUE,a> is in the queue before <TRUE,a>
:- x.
:- y.
x :- not a.
a :- not y.
% A rule with w and y in the head, such that they are not optimised away.
w v y v z.
% If <MUST_BE_TRUE,a> is in the queue before <TRUE,a>, the undefPosBody counter
% in this constraint should be decrement... |
expected_output = {
"ap_name": {
"b25a-13-cap10": {
"ap_mac": "3c41.0fee.5094",
"site_tag_name": "default-site-tag-fabric",
"policy_tag_name": "PT_Fabri_B25_B25-1_fe778",
"rf_tag_name": "Standard",
"misconfigured": "No",
"tag_source": "... |
epoch = 100
train_result = "/home/yetaoyu/zc/Classification/patch_train_results"
train_dataset_dir = "/home/yetaoyu/zc/Classification/patch_data"
test_data_dir = "/home/yetaoyu/zc/Classification/patch_data"
test_result_dir = "/home/yetaoyu/zc/Classification/patch_test_results"
model_weight_path = "/home/yetaoyu/zc/Clas... |
bunsyou = "I am a"
gengo = "cat"
if len(gengo) > 3:
print(gengo)
elif bunsyou[-1] == gengo[1]:
print(bunsyou)
else:
print(bunsyou + " " + gengo)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.