content stringlengths 7 1.05M |
|---|
#Python program to clone or copy a list.
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list) |
def input1():
l1 = []
while (True):
a = input('输入字符串: ')
if a == 'q':
break
b = input('输入字符串个数:')
for i in range(int(b)):
l1.append(a)
return l1
|
def get_input():
"""
Wrap input in this method so that it can be wrapped with @patch in tests
:return:
"""
return input('') |
def find_price_ranges(candlestick_data, period_size):
"""Calculates historical price ranges for a given period duration.
For one period of bars ranges counts as:
1st range: (high price in period - first bar opening price) / first bar opening price - 1
2nd range: (first bar opening price - low price in ... |
class GeneratorError(Exception): pass
class ProgressionGenerator:
# diatonic triads for major keys
diatonic_triads = [
('C', 'Dm', 'Em', 'F', 'G', 'Am', 'Bdim'),
('G', 'Am', 'Bm', 'C', 'D', 'Em', 'F#dim'),
('D', 'Em', 'F#m', 'G', 'A', 'Bm', 'C#dim'),
('A', 'Bm', 'C#m', 'D', 'E', 'F#m', 'G#dim'),
('E', 'F#m... |
"""Defines the Exceptions that can be raised from the DomainTools API"""
class ServiceException(Exception):
def __init__(self, code, reason):
self.code = code
self.reason = reason
super(ServiceException, self).__init__(str(reason))
class BadRequestException(ServiceException):
pass
... |
x = int(input())
if (x > 0):
print("positivo")
elif (x < 0):
print("negativo")
else:
print("nulo")
|
# test order of closed over locals
# not that CPython seems to sort closed over variables (but not fast locals)
def f():
l1 = 1
l2 = 4
l3 = 3
l4 = 2
l5 = 5
def g():
return l1 + l4 + l3 + l2 + l5
def h():
return l1 + l2 + l3 + l4 + l5
|
EAA_EDUCATION_FACILITIES = {'buildings', 'education facilities - schools', 'facilities and infrastructure'}
EAA_EDUCATION_STATISTICS = {
'baseline population', 'census', 'demographics', 'development', 'early learning', 'economics',
'educational attainment', 'educators - teachers', 'gap analysis', 'government d... |
N = input().split()
m = int(N[0])
for i in range(round(m / 2, 0)):
for j in range(m):
print(N[-1], end='')
print()
|
#!/usr/bin/env python3
# coding: utf-8
'''
定义管理员群的名称
在该群内的人都将被设为管理员,
管理员在被管理的群中享有高级管理权限,可进行如踢人等的操作
注:群名为部分匹配,请尽量输入全名以保证搜索到的群的唯一性
'''
admin_group_name = 'AAAUUUUXXXX'
'''
定义被管理群的群名前缀
所有以此为前缀的群都将设为被管理的群
注:前缀大小写敏感
如:设定为'Linux中国◆',则将自动搜索到
「Linux中国◆微信机器人群」「Linux中国◆LFS群」等以其为开头的群,
并将其设为被管理的群
'''
group_prefix = '贝尔乐实验室'
... |
##############################################################################
# Copyright 2022-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.
#######################################################... |
# -*- coding: utf-8 -*-
"""Honeycomb test constants."""
class commands():
"""Plugin commands."""
RUN = "run"
LOGS = "logs"
SHOW = "show"
TEST = "test"
STOP = "stop"
LIST = "list"
STATUS = "status"
INSTALL = "install"
UNINSTALL = "uninstall"
CONFIGURE = "configure"
class ... |
"""The GLSL toolchain definition and implementation
"""
def _glsl_toolchain_impl(ctx):
# it is expected the the glslc target contains one and only one
# file that is the compiler.
glslc_executable = ""
if ctx.attr.is_windows:
glslc_executable = ctx.attr.glslc.files.to_list()[0].path
else:... |
# coding=UTF-8
## This class define a composite ply
class CompositePly:
def __init__(self,Material,Thickness,Orientation):
## the material of the ply (either IsoMaterial or OrthoMaterial)
self.Material = Material
## the thickness of the ply (m)
self.Thickness = Thickness
#... |
class AppTestClasses:
spaceconfig = dict(usemodules=['_multibytecodec'])
def setup_class(cls):
cls.w_IncrementalHzDecoder = cls.space.appexec([], """():
import _codecs_cn
from _multibytecodec import MultibyteIncrementalDecoder
class IncrementalHzDecoder(MultibyteInc... |
"""T Gate"""
def t(index, vector):
return vector
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 Shlomi Fish < https://www.shlomifish.org/ >
#
# Licensed under the terms of the MIT license.
"""
"""
def _unused():
print(fn="test.jl", template=('''
using OpenCL
device, ctx, queue = cl.create_compute_context()
const first... |
# Automatically generated file
# enum Z3_lbool
Z3_L_FALSE = -1
Z3_L_UNDEF = 0
Z3_L_TRUE = 1
# enum Z3_symbol_kind
Z3_INT_SYMBOL = 0
Z3_STRING_SYMBOL = 1
# enum Z3_parameter_kind
Z3_PARAMETER_INT = 0
Z3_PARAMETER_DOUBLE = 1
Z3_PARAMETER_RATIONAL = 2
Z3_PARAMETER_SYMBOL = 3
Z3_PARAMETER_SORT = 4
Z3_PA... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Creation: 22/06/2020 22:08
@Author: liang
@File: settings.py
"""
COLLECTION_NAME = 'demos' # non-environment dependent plain text data
API_ENV = '${API_ENV:dev}'
# environment dependent sensible data
MONGO_DB_URL = '${MONGO_DB_URL:mongodb://localhost:27017}'
TYP... |
def f(x):
a = []
if x == 0:
return f(x)
while x > 0:
a.append(x)
print(x)
f(x-1)
f(3)
|
def fimdejogo(ma, ve=0):
for l in range(0, 3):
for c in range(0, 3):
# linhas
if ma[l][0] == ma[l][1] and ma[l][1] == ma[l][2]:
let = ma[l][2]
return let
# Colunas
if ma[0][c] == ma[1][c] and ma[1][c] == ma[2][c]:
... |
class Provider(PhoneNumberProvider):
formats = ("%## ####", "%##-####", "%######", "0{{area_code}} %## ####", "0{{area_code}} %##-####", "0{{area_code}}-%##-####", "0{{area_code}} %######", "(0{{area_code}}) %## ####", "(0{{area_code}}) %##-####", "(0{{area_code}}) %######", "+64 {{area_code}} %## ####", "+64 {{area_c... |
# No Bugs in Production (NBP) Library
# https://github.com/aenachescu/nbplib
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>.
# SPDX-License-Identifier: MIT
# Copyright (c) 2019-2020 Alin Enachescu <https://github.com/aenachescu>
#
# Permission is hereby granted, free of charge, to any person ob... |
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [1] * (rowIndex+1)
for i in range(2, rowIndex+1):
for j in range(1, i):
res[i-j] += res[i-j-1]
return res
|
loaddata = LoadData("./unified/uw/train.conll", "./unified/uw/dev.conll", "./unified/uw/test.conll")
counter, counter_dev, counter_test = [],[],[]
a = loaddata.conllu_counter['train']
a = loaddata.counter_process(a)
for d in a:
counter.append(d)
for d in range(len(counter)):
counter[d].index=tuple([d])
b = lo... |
class WrongInputValue(Exception):
pass
class Input:
def __init__(self):
self.a = None
self.b = 0
@staticmethod
def get_int_from_user(message: str) -> int:
x = input(message)
if x.isdigit():
return int(x)
else:
raise WrongInputValue("Poda... |
#
# PySNMP MIB module CISCO-WAN-PAR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-PAR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:20:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
class Verbosity:
"""
The Digital DNA utility class to set verbosity.
"""
TEST = 0
MEMORY_ONLY = 1
FILE = 2
FILE_EXTENDED = 3
|
# https://leetcode.com/problems/single-number/
def singleNumber(nums):
count = {}
for x in nums:
if x not in count:
count[x] = 1
else:
count[x] = count[x]+1
for x in count:
if count[x] ==1:
return x
print(s... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"draw_bg": "01_bbox_canvas.ipynb",
"draw_bounding_box": "01_bbox_canvas.ipynb",
"get_image_size": "01_bbox_canvas.ipynb",
"draw_img": "01_bbox_canvas.ipynb",
"points2bbox_c... |
CONFIDENT_ALL_MATCH = 1.0
CONFIDENT_MULTIPLIER_NAME_ONLY = 0.5
CONFIDENT_MULTIPLIER_PARTIAL_MATCH = 0.7
CONFIDENT_MULTIPLIER_OPPOSITE_STREET = 0.75
CONFIDENT_MULTIPLIER_FULL_STREET_MATCH = 1.5
CONFIDENT_REVERSE_MATCH = 0.9
OGCIO_KEY_BLOCK = "Block"
OGCIO_KEY_PHASE = "Phase"
OGCIO_KEY_ESTATE = "Estate"
OGCIO_KEY_VILLAG... |
raio = float(input())
pi = 3.14159
area = round(pi * (pow(raio,2)),4)
print("A=%.4f" % area)
|
#!/usr/bin/env python
class CommitMgr(object):
def __init__():
pass
|
login_query = """
mutation {
login(
input: {
username: $username
password: $password
}
) {
user{
username
sessionExpiration
}
errors{
messages
}
mfaUrl
token
}
}
"""
|
print('Analisando emprestimos!!!')
print('=-=' * 20)
valor = float(input('Valor do imovel: R$'))
salario = float(input('Salario do cliente: R$'))
tempo = int(input('Tempo do emprestimo [anos]: '))
print('=-=' * 20)
if valor / (12 * tempo) >= salario * 30/100:
print(f'Seu emprestimo foi \033[31mNEGADO!')
else:
p... |
"""Definition for create_release macro."""
load("//shlib/rules:execute_binary.bzl", "execute_binary")
def create_release(name, workflow_name):
"""Declares an executable target that launches a Github Actions release workflow.
This utility expects Github's CLI (`gh`) to be installed. Running this \
utility... |
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def bstToGst(self, root):
"""
:type root: TreeNode
:rtype: Tre... |
#python 3.5.2
'''
This Python functions finds the maximum number in a list by compares each
number to every other number on the list.
'''
class MyMath():
def __init__(self, list):
self.list = list
def findMaxNo(self):
max = self.list[0]
for x in self.list:
if x > max... |
for x in range(1, 11):
if x % 2 == 0:
continue # interrompe prematuramente a iteração indo diretamente para a próxima iteração mas ainda dentro do laço "for"
print(x)
for x in range(1, 11):
if x == 5:
break # para completamente a iteração saindo do laço "for" executando os códigos fora do... |
name, age = "Inshad", 18
username = "MohammedInshad"
print ('Hello!')
print("inshad: {}\n18 {}\nMohammedInshad: {}".format(name, age, username))
|
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, merge, p... |
workers = 1
worker_class = 'gevent'
bind = '0.0.0.0:5000'
pidfile = '/tmp/gunicorn-csdh-api.pid'
debug = True
reload = True
loglevel = 'info'
errorlog = '/tmp/gunicorn_csdh_api_error.log'
accesslog = '/tmp/gunicorn_csdh_api_access.log'
daemon = False
|
# -*- coding: utf-8 -*-
# ------------- Diccionario -------------
#Solo se ermite una llave nula
#Los valores son mutables pero las llaves NO
#No se encuentran ordenados por ser hashmap
elementos = {'hidrogeno': 1, 'helio': 2, 'carbon': 6}
# Al imprimir el diccionario, los elementos puede
# aparecer en diferente orde... |
'''
This problem was asked by Yelp.
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent.
You can assume each valid number in the mapping is a single digit.
For example if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should... |
somaidade = 0 #variavel para somar a idade
homemvelho = '' # variavel para o homem mais velho
idadehomevelho = 0 # variavel paraca idade do homem mais velho
contmulher = 0 # contador de mulher com menos de 20 anos
for c in range(1, 5):
print(f'-'*5,f'PESSOA {c}', '-'*5)
nome = str(input('Nome: ')).strip()
i... |
def sol():
a = input()
b = input()
for i in range(3):
print( int(a) * int(b[2 - i]) )
print(int(a) * int(b))
if __name__ == "__main__":
sol()
|
# LISTS
#
# A list is a data structure consisting of a collection of elements (values or variables)
food = ['oranges', 'strawberries', 'lemons']
x = food[0] # The first element is at index 0
y = food[1] # The second element is at index 1
z = food[2] # The third element is at index 2
print('I like', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def all_messages():
return \
{
"0": "Il motore Nettacker è iniziato ...\n\n",
"1": "python nettacker.py [opzioni]",
"2": "Mostra il menu di aiuto di Nettacker",
"3": "Leggere la licenza e gli accordi https://gith... |
def main():
x = 10
if(x == 5):
x = 1
else:
x = 2
x = 3 |
class Phishing(object):
@staticmethod
def create_():
print("Haciendo phishing") |
n = int(input())
ondo = [list(map(float, input().split())) for _ in range(n)]
soukei = {'mousyo': 0, 'manatsu': 1, 'natsu': 2,
'nettai': 3, 'huyu': 4, 'mafuyu': 5}
s = [0]*6
for i, j in ondo:
if i >= 35:
s[soukei['mousyo']] += 1
if 30 <= i < 35:
s[soukei['manatsu']] += 1
if 25 <= i... |
num1 = int(input("Digite um número: "))
num2 = int(input("Digite um número: "))
soma = num1 + num2
print("A soma é: %3.0f" % soma)
|
class Car(object):
speed = 0
def __init__(self, vehicle_type=None,model='GM',name='General'):
self.vehicle_type= vehicle_type
self.model = model
self.name=name
if self.name in ['Porsche', 'Koenigsegg']:
self.num_of_doors = 2
else:
self.num_of_doors = 4
if self.vehicle_t... |
# Python Program To Find Square Of Elements In A List
'''
Function Name : Square Of Elements In A List.
Function Date : 8 Sep 2020
Function Author : Prasad Dangare
Input : Integer
Output : Integer
'''
def square(x):
return x*x
# Let Us Take A List Of Numbers
lst ... |
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
prev = self.countAndSay(n-1)
res = ""
ct = 1
for i in range(len(prev)):
if i == len(prev)-1 or prev[i] != prev[i+1... |
n=int(input())
while True:
a=int(input())
if a is 0:
break
if a%n is 0:
print("{} is a multiple of {}.".format(a,n))
else:
print("{} is NOT a multiple of {}.".format(a,n)) |
"""
UB_ID : 50291708
Name : Md Moniruzzaman Monir
"""
class Rectangle:
# constructor
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
# Return the sum of all pixels inside a rectangle for a specific int... |
n = int(input())
l = int(input())
for first in range(1, n):
for second in range(1, n):
for three in range(97, 97 + l):
for four in range(97, 97 + l):
for five in range(2, n + 1):
three_chr = chr(three)
four_chr = chr(four)
... |
def extended_gcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = extended_gcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = extended_gcd(a % m, m)
if g != 1:
raise Exception('Element has no inverse')
return x % m
|
"""some additional (math) types you may need, with instance checks"""
__all__ = ['NaturalNumber', 'StrictNaturalNumber']
class NaturalNumberMeta(type):
"""metaclass"""
def __instancecheck__(self, instance):
return isinstance(instance, int) and instance >= 0
class StrictNaturalNumberMeta(type):
... |
"""Exercise 1: Country Roads
Remember to fill out all the TODO's, you can quickly scan for them by pressing CTRL/CMD + F
"""
class Car:
"""A class representing a car with details about how far it can travel"""
def __init__(self, gas_tank_size, fuel, litres_per_kilometre):
self.gas_tank_size = gas_tank... |
def balanced(text: str):
stack = []
is_balanced = True
for i in range(len(text)):
if text[i] in "{[(":
stack.append(i)
elif text[i] in ")]}" and len(stack) > 0:
start_ind = stack.pop()
if text[start_ind] == "{":
if text[i] != "}":
... |
'''
Esse script é um exercício de if e else.
'''
nota1 = float(input('Digite sua primeira nota: '))
nota2 = float(input('Digite a segunda: '))
media = (nota1 + nota2) / 2
if media < 4.9:
print('Reprovado/a')
print(f'Sua média é {media}')
elif media > 5 and media < 6.9:
print('Recuperação')
print(f'Su... |
def round_scores(student_scores):
'''
:param student_scores: list of student exam scores as float or int.
:return: list of student scores *rounded* to nearest integer value.
'''
rounded = []
while student_scores:
rounded.append(round(student_scores.pop()))
return rounded
def count... |
sections = {
# type descriptions / header blocks
"public": {
"name": "Public Routes",
"desc": """\
<p>These routes <b>DO NOT</b> require user authentication (though some of them
require a valid API key to use).</p>
<p> When building an application, use these routes to construct
dashboard type vi... |
#使用 else 子句比把所有的语句都放在 try 子句里面要好,这样可以避免一些意想不到的、而except又没有捕获的异常。
while True:
try:
x = int(input("please input a number: "))
print('1 Good! Right number!')
# break
except ValueError as e: # if the exception is not ValueError, then it's passed to the higher layer
... |
def is_prime(n):
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n and n % d != 0:
d += 2
return d * d > n
def main():
n = int(input("Input the number from 0 to 1000: "))
print(is_prime(n))
if __name__ == '__main__':
main()
|
class Node:
def __init__(self, value = 0):
self.value = value
self.next = None
def findList(first, second):
if not first and not second:
return True
if not first or not second:
return False
ptr1 = first
ptr2 = second
while ptr2:
ptr2 = second
... |
def sequencia():
s = 0
for i in range(1, 101):
s += 1/i
print(f'{s:.2f}')
sequencia()
|
def main_menu():
print("Please select an option from the following:")
print(" [1] Customer") #add to db
print(" [2] Order")# add to db
print(" [3] Complete Order")
print(" [4] Cancel Order")
print(" [5] Exit")
def sign_up_menu():
print("Please select an option from the foll... |
"""
Descrição: Este programa calcula o número e o valor das prestações a pagar em um imóvel.
Autor:Henrique Joner
Versão:0.0.1
Data:24/11/2018
"""
#Inicialização de variáveis
valorcasa = 0
anos = 0
nprestacao = 0
prestacao = 0
salario = 0
#Entrada de dados
valorcasa = float(input("Qual o valor da casa que você ... |
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
print(range(10))
|
def selectionsort(arr):
N = len(arr)
for i in range(N):
minimum = i
for j in range(1, N):
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
return arr
if __name__ == "__main__":
arr = [0, 4, 5, 6, 7, 8, 2, 1, 5, 3, 9]
... |
class Person:
def __init__(self, name, age):
self.x__name = name
self.age = age
def info(self):
return f'Name: {self.x__name}, Age: {self.age}'
def __generate_key(self, key):
if key.startswith('x__'):
return f'x__Person{key}'
return key
def __setatt... |
class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
"""String.
Running time: O(n) where n == len(shifts).
"""
orda = ord('a')
n = len(shifts)
suf = shifts
suf[-1] %= 26
for i in range(n - 2, -1, -1):
suf[i] = (suf[... |
useragents = [
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like G... |
def exists(env):
return True
def generate(env):
env.Replace(MODE='test')
|
class Solution:
def XXX(self, x: int) -> int:
s = str(x)
s = "-" + s.replace("-","")[::-1] if "-" in s else s[::-1]
return (int(s) if int(s)<2**31-1 and int(s)>-2**31 else 0)
|
# invert a binary tree
def reverse(root):
if not root:
return
root.left, root.right = root.right, root.left
if root.left:
reverse(root.left)
if root.right:
reverse(root.right)
|
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split(' ')))
ans = 0
for i in range(n):
ans += (i + 1) * (n - i)
if l[i] == 0:
ans += (i + 1) * (n - i)
print(ans)
|
#-*- coding:utf-8 -*-
age = [3, 2, 30, 1, 16, 18, 19, 20, 22, 25]
name = ['lizi', 'liudehua', 'linjunjie', 'zhoujielun', 'zhangsan', 'bigmom', 'kaiduo', 'luffe']
print(age)
print(sorted(age))
print(age)
age.sort()
print(age)
age.append(33)
print(age)
age.insert(2, 65)
print(age)
age.pop()
print(age)
_del = age.pop()
pr... |
class DatabaseService:
def __init__(self):
#TODO: mongo
pass |
class OddNumberException(Exception):
def __init__(self,*args):
self.args = args
class EvenNumberException(Exception):
def __init__(self,*args):
self.args = args
try:
n = int(input("Enter a Number to check whether he number is odd or even : "))
if n % 2 == 0:
raise EvenNumberExc... |
EXTERN_START = "\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"
EXTERN_STOP = "#ifdef __cplusplus\n}\n#endif\n\n"
EXTERN_FIND1 = "extern \"C\" {\n"
EXTERN_FIND2 = " *****************************************************************************/\n" # noqa
def add_extern_c(source_file, source):
"""
Add 'Exte... |
"""
This is boin default hyper parameters.
"""
model_name = 'BoinAutoEncoder'
lr = 0.001
max_view_num = 500
view_interval = 100
class encoder_hparams:
model_name = 'BoinEncoder'
nhid = 512
nlayers = 2
class decoder_hparams:
model_name = 'BoinDecoder'
nhid = 512
nlayers = 2
|
"""
Matrix exercise
"""
class Matrix:
"""
Matrix class
"""
def __init__(self, matrix_string):
"""
Create a matrix
"""
self.rows = []
self.columns = [[] for i in range(len(matrix_string.split("\n")[0].split()))]
for line in matrix_string.spli... |
def filter_db_queryset_by_id(db_queryset, rqst_id, list_of_ids):
if isinstance(rqst_id, str) and rqst_id.lower() == "all":
db_queryset = db_queryset.order_by("id")
else:
db_queryset = db_queryset.filter(id__in=list_of_ids).order_by("id")
return db_queryset
|
"""
w04 team assignment : Date.py
day : int
month : int
year : int
__init__()
prompt()
display()
"""
class Date:
""" the date class """
def __init__(self, date_day=1, date_month=1, date_year=2000):
# set up the class variables and assign default values
self.day = date_day
self.month ... |
tabela = ('Fortaleza', 'Athletico-PR', 'Flamengo', 'Atlético-GO', 'Atlético-MG', 'Bragantino', 'Fluminense', 'Bahia',
'Palmeiras', 'Corinthians', 'Ceará SC', 'Santos', 'Internacional', 'Juventude', 'Cuiabá', 'Sport Recife',
'São Paulo', 'Chapecoense', 'Grêmio', 'América-MG')
linha = '-=-' * 98
print... |
"""
1. Create a inheritance tree with the following structure
1. BaseCharacter
1. Non-Playable Character(NPC)
1. Friendly
2. Enemy
2. Playable Character(PC)
1. Archer
2. Green Lantern
3. Butcher
2. Add 'printName' function All characters ha... |
class Dij:
# matrix of roads
road = [[]]
# infinity
infinit = 9999
# array of costs
D = []
# array of selected nodes
S = []
# array of fathers
T = []
# number of nodes
nodes = -1
# output
output = []
def __init__(self, start):
self.readGraph()
... |
"""Mappings.
Mappings define how internal objects and their fields will be indexed.
The provided record-v1.0.0.json file is an example of how to index records
in Elasticsearch.
"""
|
n, k = (int(x) for x in input().split())
arr = [int(x) for x in input().split()]
new_arr = list()
i = 0
while i != n - k + 1:
new_arr.append(max(arr[i:i+k]))
i += 1
print(*new_arr) |
#
# PySNMP MIB module Nortel-Magellan-Passport-SoftwareMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-SoftwareMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... |
expression = input()
parentheses_indices = []
for i in range(len(expression)):
if expression[i] == '(':
parentheses_indices.append(i)
elif expression[i] == ')':
opening_index = parentheses_indices.pop()
closing_index = i
searched_set = expression[opening_index:closing_index + 1... |
sexo=str(input('Informe seu sexo: [M/F]')).upper()[0].strip()
print(sexo)
while sexo not in 'MF':
sexo=str(input('Dados inválidos. Por favor, informe seu sexo: '))
print('Sexo {} validado'.format(sexo))
|
name = "Optimizer Parameters"
description = None
args_and_kwargs = (
(("--iterations",), {
"help":"Number of gradient steps to take.",
"type":int,
"default":10000,
}),
(("--learning-rate",), {
"help":"Adam learning rate. The default is 0.001",
"type":float,
... |
# File: M (Python 2.4)
class Mappable:
def __init__(self):
pass
def getMapNode(self):
pass
class MappableArea(Mappable):
def getMapName(self):
return ''
def getZoomLevels(self):
return ((100, 200, 300), 1)
def getFootprintNode(self):
... |
#!/usr/bin/env python
S_PC = ord("p")
S_A = ord("A")
S_X = ord("X")
S_Y = ord("Y")
S_SP = ord("S")
S_IND_X = 0x1D9
S_IND_Y = 0x1DF
S_Z_X = 0x209
S_Z_Y = 0x20F
S_Z = 0x200
S_ABS_X = 0x809
S_ABS_Y = 0x80F
S_ABS = 0x800
S_HASH = ord("#")
S_XXX = 0xFFFF
S_NONE = 0x0000
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.