content stringlengths 7 1.05M |
|---|
"""
@author: magician
@file: annotation_attribute.py
@date: 2020/8/4
"""
class Field(object):
"""
Field
"""
def __init__(self, name):
self.name = name
self.internal_name = '_' + name
def __get__(self, instance, instance_type):
if instance is None:
return s... |
"""Top-level package for RocketPy."""
__author__ = """Mohammed Raihaan Usman"""
__email__ = 'raihaan.usman@gmail.com'
__version__ = '0.1.1' |
# link: https://leetcode.com/problems/add-and-search-word-data-structure-design/
class TrieNode(object):
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_word=False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure... |
width = const(10)
height = const(16)
data = [
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, # Character 0x00 (0)
0x00,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,... |
hora_trabalho = int(input("Digite o número de horas trabalhadas: "))
salario_min = int(input("Digite o valor do salario minímo: "))
horaextra = int(input("Digite o número de horas extras trabalhadas: "))
print(f"A salario é igual a R$: {salario_min / 8 * hora_trabalho + salario_min / 4 * horaextra}")
|
# coding=utf-8
""" 停用词,去除标点符号 """
stop_words = [
',',
'。',
'“',
'”',
'‘',
'’',
'!',
'?',
'(',
'《',
'》',
')',
'-',
'=',
'+',
'-',
':',
';',
'…',
'、',
'?',
'.',
',',
'/',
';',
':',
'.',
'!',
'(',
')',
... |
def merge_the_tools(string, n):
out = [list(string)[k:k+n] for k in range(0,len(list(string)),n)]
for x in out:
print(''.join(sorted(set(x), key=x.index)))
|
def calculate_determinant(matrix):
if len(matrix) is 1:
return matrix[0][0]
elif len(matrix) is 2:
return (matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1])
total = float()
for i in range(0, len(matrix)):
cofactor = (-1 ^ i) * matrix[0][i]
minor = [ ]
for y in range(1, len(matrix)):
sub = ... |
# -*- coding: UTF-8 -*-
FIXTURE_WEBVTT = """WEBVTT
00:14.848 --> 00:17.350
MAN:
When we think
of E equals m c-squared,
00:17.350 --> 00:18.752
we have this vision of Einstein
00:18.752 --> 00:20.887
as an old, wrinkly man
with white hair.
00:20.887 --> 00:26.760
MAN 2:
E equals m c-squared is
not about an old Eins... |
num_pessoas = input("Você deseja uma mesa para qunatas pessoas ? ")
if int(num_pessoas) <= 8:
print(f'Nós temos uma mesa para {num_pessoas} pessoas pronta para você.')
else:
print(f'Nós não temos uma mesa para {num_pessoas} pessoas disponivel no momento.')
print('Você precisará espera alguns minutos.')
|
PARAM_TOKEN = '%s'
class DbContext(object):
"""
"""
def __init__(self, connection, param_token=PARAM_TOKEN):
self.param_token = param_token
self.connection = connection
self.cursor = connection.cursor()
mod = self.cursor.connection.__class__.__module__.split('.', 1)[0]
... |
class BitmapScalingMode(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies which algorithm is used to scale bitmap images.
enum BitmapScalingMode,values: Fant (2),HighQuality (2),Linear (1),LowQuality (1),NearestNeighbor (3),Unspecified (0)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==y... |
if __name__ == '__main__':
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def __init__(self):
... |
#! /usr/bin/env python3
description = '''
Roman numerals
Problem 89
The rules for writing Roman numerals allow for many ways of writing each number (see About Roman Numerals...). However, there is always a "best" way of writing a particular number.
For example, the following represent all of the legitimate ways of wr... |
# Finding the longest increasing subsequence in an array
# [3, 4, -1, 0, 6, 2, 3] -> [-1, 0, 2, 3]
# [2, 5, 1, 8, 3] -> [2, 5, 8]
def finding_longest_subsequence(arr):
if not arr:
return 0
longest_subsequence = 1
longest_arr = [arr[0]]
max_observed = float('-inf')
for idx in ran... |
class OpenPoseSkeleton(object):
def __init__(self):
self.root = 'MidHip'
self.keypoint2index = {
'Nose': 0,
'Neck': 1,
'RShoulder': 2,
'RElbow': 3,
'RWrist': 4,
'LShoulder': 5,
'LElbow': 6,
'LWrist': 7,
... |
class CountingSort:
def __init__(self,a):
self.a = a
def result(self):
maxSize = max(self.a)
presence = [0 for x in range(maxSize+1)]
for element in self.a:
presence[element] += 1
for i in range(1,len(presence)):
presence[i] = presence[i] + presen... |
class BlockcertValidationError(Exception):
pass
class InvalidUrlError(Exception):
pass
|
# 6. Elabore uma estrutura para representar um Funcionario (código, nome, endereço, salário). Para o membro endereço deve-se criar outra estrutura Endereço (logradouro, número, bairro, cidade). Utilize aninhamento de estruturas para resolver este desenvolvimento. Construa uma função para cada opçao do menu a seguir:
#... |
##
##Namelog.py
##
##
##uses list to load name
##
playerName = "???"
def nameWrite():
text_file = open("name.txt", "w+")
print('Girl: What was your name?')
ins = input()
if ins == "":
ins = "Hazel"
print('I couldnt be bothered to put a name so call me Hazel')
text_f... |
# Scrapy settings for Newengland project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'Newengland'
SPIDER_MODULES = ['Newengland.spiders']
NEWSPIDER_MODULE = '... |
'''
pokemon = {'Trainer1':
{'normal': {'rattatas':15, 'eevees': 2, 'ditto':1}, 'water': {'magikarps':3}, 'flying': {'zubats':8, 'pidgey': 12}},
'Trainer2':
{'normal': {'rattatas':25, 'eevees': 1}, 'water': {'magikarps':7}, 'flying': {'zubats':3, 'pidgey': 15}},
'Trainer3':
... |
valor = float(input('Qual o preço do produto R$'))
calculo = valor * 5 / 100
resultado = valor - calculo
print('Desconto é de 5%\n'
'Valor do desconto R${:.2f}\n'
'Preço com desconto R${:.2f}' .format(calculo, resultado))
|
'''
this file contains all the functions that contribute in the making of tic tac toe
__________ about the game __________
1-the grid shape :
1 | 2 | 3
-----------
4 | 5 | 6
-----------
7 | 8 | 9
2-how to play the game :
the player... |
# -*- coding: utf-8 -*-
def transliterate(string, direction=0):
capital_letters = {u'А': u'A',
u'Б': u'B',
u'В': u'V',
u'Г': u'G',
u'Д': u'D',
u'Е': u'E',
u'Ё': u'E',
... |
# Longest Common Subsequence - DP Approach
# Using Edit Distance
# Author - rudrajit1729
# Description
'''
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “... |
# -*- coding: utf8 -*-
class Clients:
"""
Get clients information.
"""
def __init__(self, burp_version=1, conf=None):
"""
:param burp_version: version of burp backend to work with 1/2
:param conf: burp_ui configuration to use.
"""
self.version = burp_version... |
"""
Link: https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc8/00000000002d82e6
Language: Python
Written by: Mostofa Adib Shakib
Time complexity: O(n)
Space Complexity: O(1)
"""
T = int(input())
for x in range(1, T + 1):
N = int(input())
Q = [int(s) for s in input().split(" ")]
... |
'''Classe Bola: Crie uma classe que modele uma bola:
Atributos: Cor, marca, material
Métodos: trocaCor e mostraCor'''
class Bola:
def __init__(self, cor, marca, material):
self.cor = cor
self.marca = marca
self.material = material
def getCor(self):
return self.cor
... |
#
# @lc app=leetcode id=401 lang=python3
#
# [401] Binary Watch
#
# @lc code=start
class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
if num > 10:
return []
times = []
for h in range(12): # 4 LEDs represent the hours (0-11)
for m in range(60): # 6... |
#!/usr/bin/python
dict = {'Name': 'Ruben', 'Age': 50, 'City': 'Amsterdam'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
# Access the data using a key, from the dictionary
print("dict['Ruben']: ", dict['Ruben'])
# Access the data using a key (which is non-existent), from the dictionary, w... |
def prepare_knapsack(items, capacity):
'''
"capacity" is a numeric value representing a max weight.
this capacity will be modified as items are added.
---
"storage" is a list (usually a set) of item tuples.
the tuples inside store an item's name, value, and weight.
this variable represents all possible items ava... |
class Error(object):
def __init__(self, msg: str = "") -> None:
super().__init__()
self._msg = msg
def __str__(self) -> str:
return self._msg
def __repr__(self) -> str:
return self._msg
def __eq__(self, o: object) -> bool:
return self._msg == o.__repr__
de... |
def lcs(x,y,m,n):
if m==0 or n==0:
return 0;
elif x[m-1]==y[n-1]:
return 1+lcs(x,y,m-1,n-1);
else:
return max(lcs(x,y,m,n-1),lcs(x,y,m-1,n));
x="AGGTAB"
y="GXTXAYB"
print("length of lcs is",lcs(x,y,len(x),len(y)));
|
#! /usr/bin/env python
__author__ = "yatbear <sapphirejyt@gmail.com>"
__date__ = "$Dec 21, 2015"
# Map the infrequent words (count < 5) to a common symbol _RARE_
def remap():
# Read original training data
trainset = [line.strip().split() for line in open('gene.train', 'r').readlines()]
rare_candidates = d... |
# Sylvia Dee <sylvia_dee@brown.edu>
# PRYSM
# PSM for Lacustrine Sedimentary Archives
# SENSOR MODEL: GDGT-based measurements, e.g. TEX86, MBT5e
# Function 'gdgt_sensor'
# Modified 03/8/2016 <sylvia_dee@brown.edu>
#====================================================================
def gdgt_sensor(LST,MAAT,beta=(1/50)... |
class Bruxo:
def bruxeis(self):
print('The dead are coming back to life')
class Genio:
def genieis(self):
print('Los muertos vuelven a la vida')
class Deus:
def deuseis(self):
print('De doden komen weer tot leven')
seres = [Bruxo(), Genio(), Deus()]
for ser in seres:
if is... |
ERROR = {
'INPUT': {
'code': 20001,
'message': 'invalid request data',
'data': 'invalid request data',
},
'REGISTER': {
'code': 20002,
'data': '',
'message': 'failed to register user'
},
'USER_NOT_FOUND': {
'code': 20003,
'data': '',
... |
magicians = ['刘谦', '简纶廷', '郭皓炜']
def show_magicians(magicians):
for magician in magicians:
print(magician)
show_magicians(magicians)
def make_great(magicians):
i = 0
for magician in magicians:
magician += ' the Great'
magicians[i] = magician
i = i+1
make_great(magicia... |
class NoDataFileException(Exception):
def __init__(self, message="No data file", errors=[]):
super().__init__(message, errors)
pass
|
age = 17
print("You are " + str(age))
if age >= 21: # Is the age equal to or over 21?
print("You can drink!")
if age >= 18: # Is the age equal to or over 18?
print("You are an adult!")
if age >= 16: # Is the age equal to or over 16?
print("You can drive!")
if age < 16: # Is the age ... |
'''
Models simple up/down counter that maintains a single count
Methods:
get_count()
incrememt()
decrement()
set()
reset()
'to_string'
'''
## Start your class with the keyword 'class' and the name of the class:
class Counter:
#---------------------------------------------------------------------------- ... |
def foo():
global x
x="juanito"
print(f"El valor de x es {x}")
x=5
print(x)
foo()
print(x)
|
def make_data_tensor(self, train=True):
if train:
folders = self.metatrain_character_folders
# number of tasks, not number of meta-iterations. (divide by metabatch size to measure)
num_total_batches = 200000
else:
folders = self.metaval_character_folders
num_total_batches... |
class Mother:
def __init__(self):
self.eye_color = "brown"
self.hair_color = "dark brown"
self.hair_type = "curly"
class Father:
def __init__(self):
self.eye_color = "blue"
self.hair_color = "blond"
self.hair_type = "straight"
class Child(Mother,... |
"""Utility class for holding multi-channel colour data.
"""
class Colour:
def __init__(self, r, g, b, name=""):
"""Creates a Colour object for holding data on the red, green,
and blue colour channels.
:param r: the red component of the colour, expressed as a number
between 0 and 2... |
print("что-то на бизарном\n\n")
print("Меня зовут Кира Йошикаге.")
print("Мне 33 года.")
print("Мой дом находится в северо-восточной части Морио, где расположены все виллы.")
print("Я не женат. Я работаю в универмаге Kame Yu и прихожу домой не позднее 8 вечера.")
print("Я не курю, но иногда выпиваю.")
print("Я ложусь с... |
hparams = {
'batch_size': 32,
'epochs': 8,
'lr': 0.0001,
'name': 'mind_news',
'loss': 'cross_entropy_loss',
'optimizer': 'adam',
'version': 'v3',
'description': 'NRMS lr=5e-4, with weight_decay',
'pretrained_model': './data/utils/embedding.npy',
'model': {
'dct_size': 'au... |
class Sprite:
# Getter Functions
def getCurrentFramePath(cls): pass
def getCurrentFrameDelay(cls): pass
def getCurrentPos(cls): pass
# Interface for main to call
def init(cls, xcoord: int, ycoord: int): pass
def update(cls): pass
# Interface to set sprite properties
class Sprit... |
with open("input1.txt","r") as f:
data = f.readlines()
data[0] = data[0].split(',')
data[1] = data[1].split(',')
# Might need to change w if too big
w = 22000
h = w
# 2000x2000 Wirespace
wireSpace = [[0 for x in range(w)] for y in range(h)]
centerX = w//2
centerY = h//2
currentPosX = centerX
currentPosY = center... |
# 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 countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# First get... |
# Sometimes we need to pass variable number of arguments in function call so in that situation if the function has fixed 2 or 3 argument written in function definition then it will not work as expected.
# The solution of that we have barges concept in python lets check example below.
def multiply(*numbers):
total... |
html_theme = 'classic'
exclude_patterns = ['_build']
latex_documents = [
('index', 'SphinxTests.tex', 'Testing maxlistdepth=10',
'Georg Brandl', 'howto'),
]
latex_elements = {
'maxlistdepth': '10',
}
|
# Simple Python3 program to find
# n'th node from end
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# createNode and and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next ... |
# -*- coding: UTF-8 -*-
class CustomBaseException(Exception):
def __init__(self, prefix: str, arg: str, code: int, addition=""):
self._prefix = prefix
self._arg = arg
self._code = code
self._addition = addition
def __str__(self):
if not self._prefix == "":
... |
NEED = 40 # mm
def rain_amount(rain_amount: int) -> str:
give = NEED - rain_amount
if give > 0:
return f"You need to give your plant {give}mm of water"
else:
return "Your plant has had more than enough water for today!" |
# Time: O(n^3 / k)
# Space: O(n^2)
class Solution(object):
def mergeStones(self, stones, K):
"""
:type stones: List[int]
:type K: int
:rtype: int
"""
if (len(stones)-1) % (K-1):
return -1
prefix = [0]
for x in stones:
prefix.a... |
class Solution:
def reverse(self, x: int) -> int:
if x%10==x:
return x
elif x>0:
x = int (str(x).rstrip('0')[::-1])
return x if x <= ((1<<31)-1) else 0
elif x<0:
x = -int (str(abs(x)).rstrip('0')[::-1])
return x if x >= -(1<<31) els... |
def simple_mean(x, y):
"""Function that takes 2 numerical arguments and returns their mean.
"""
mean = (x + y) / 2
return mean
def advanced_mean(values):
"""Function that takes a list of numbers and returns the mean of all
the numbers in the list.
"""
total = 0
for v in values:
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
lA=0
... |
# Solution 1
# O(n^2) time / O(1) space
def twoNumberSum(array, targetSum):
for i in range(len(array) - 1):
firstNum = array[i]
for j in range(i + 1, len(array)):
secondNum = array[j]
if firstNum + secondNum == targetSum:
return [firstNum, secondNum]
ret... |
'''
Merge sort
time complexity: O(nlogn)
space complexity: O(logn) + O(n) = O(n)
'''
# merge two sorted array
def merge(arr1, arr2):
merge_arr = []
idx1, idx2 = 0, 0
while idx1 < len(arr1) and idx2 < len(arr2):
if arr1[idx1] < arr2[idx2]:
merge_arr.append(arr1[idx1])
idx1 =... |
# coding: utf-8
AUTHOR = 'R-Koubou'
VERSION = '0.7.0'
URL = 'https://github.com/r-koubou/XLS2ExpressionMap'
VERSION_0_6 = 0x006000
VERSION_0_7 = 0x007000
VERSION_NUMBER = VERSION_0_7
if __name__ == '__main__':
print( VERSION )
|
"""Top-level package for gist."""
__author__ = """Ammar Najjar"""
__email__ = 'najjarammar@protonmail.com'
__version__ = '0.1.0'
|
expected_output = {
"route-information": {
"route-table": [
{
"active-route-count": "13",
"destination-count": "13",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": [
{
... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 2
if len(nums) == 0:
return 0
m = 1
count = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
... |
class Solution:
def partition(self, s: str) -> List[List[str]]:
ans = []
self.helper(s, 0, [], ans)
return ans
def helper(self, s, idx, partition, ans):
if idx == len(s):
ans.append(partition[:])
else:
for end in range(idx + 1, len(s) + 1)... |
class KafkaTimeoutError(Exception):
"""
Error raised when the poll from Kafka returns nothing and therefore there is nothing to read.
"""
pass # pylint:disable=unnecessary-pass
|
'''70 Crie um programa que leia o nome e o preço de vários produtos.
O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
A) qual é o total gasto na compra.
B) quantos produtos custam mais de R$1000.
C) qual é o nome do produto mais barato.'''
total = produtos = menor = 0
while True:
no... |
# page 100 // homework 2021-01-07
# TASK 1: fix bug
#
total = 0
number = 1 # bugfix: define the 'number' varible to a value that meets the condition of the loop below
# nbb: the proposed solution of the book to duplicate functional code is a no go for pre-initializing variables (duplicate code -> increase of... |
class RepeaterBounds(object, IDisposable):
"""
Represents bounds of the array of repeating references in 0,1,or 2 dimensions.
(See Autodesk.Revit.DB.RepeatingReferenceSource).
"""
def AdjustForCyclicalBounds(self, coordinates):
"""
AdjustForCyclicalBounds(self: RepeaterBounds,coordina... |
# Copyright 2021 The Cross-Media Measurement Authors
#
# 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 ... |
val = float(input('Qual o valor das compras? (€) - '))
print('** FORMAS DE PAGAMENTO **')
fp = int(input('[ 1 ] à vista dinheiro/Cheque \n'
'[ 2 ] à vista cartão \n'
'[ 3 ] 2x no cartão \n'
'[ 4 ] 3x ou mais no cartão \n'
' - Qual a opção? - '))
if 1 <= fp ... |
a = True
b = False
print(a is b)
print(a is not b)
|
expected_output = {
"interfaces": {
"Ethernet1/3": {
"neighbors": {
"fe80::f816:3eff:feff:9f9b": {
"homeagent_flag": 0,
"is_router": True,
"addr_flag": 0,
"ip": "fe80::f816:3eff:feff:9f9b",
... |
words=[
'redcoat',
'railing',
'waist',
'pinnacle',
'bribery',
'abjure',
'Swiss',
'chancel',
'groveler',
'chaser',
'curlew',
'markedly',
'admirer',
'coarse',
'slough',
'debrief',
'saltwater',
'spotty',
'photon',
'nephew',
'swath',
'elder',
'overnight',
'charm',
'rations',
'shrivel',
'quibbler',
'British',
'secretary',
'... |
#Class to calculate the LastPriceWindow and LastPriceTotal
class CUtilsSpread:
def GetLastPriceWindow(self, data_object, list_index, time_window_index):
while data_object.m_DatetimeList[list_index] <= data_object.m_strTimeWindowList[time_window_index]:
list_index += 1
if li... |
'''
Author: tusikalanse
Date: 2021-07-13 20:13:20
LastEditTime: 2021-07-13 20:30:51
LastEditors: tusikalanse
Description:
'''
lis = [0, 2]
for i in range(1, 34):
lis.extend([1, 2 * i, 1])
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
def gao(n):
numerator, denominator = lis[n], 1
for i in ra... |
# Ejercicio 1
# Formatea los siguientes valores para mostrar el resultado indicado:
#
# "Hola Mundo" → Alineado a la derecha en 20 caracteres
# "Hola Mundo" → Truncamiento en el cuarto carácter (índice 3)
# "Hola Mundo" → Alineamiento al centro en 20 caracteres con truncamiento en el segundo carácter (índice 1)
# 150 →... |
#pylint:disable=E0001
'''
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest commo... |
# encoding: utf-8
# module cv2.text
# from /home/davtoh/anaconda3/envs/rrtools/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so
# by generator 1.144
# no doc
# no imports
# Variables with simple values
ERFILTER_NM_IHSGrad = 1
ERFILTER_NM_IHSGRAD = 1
ERFILTER_NM_RGBLGRAD = 0
ERFILTER_NM_RGBLGrad = 0
ER... |
class ScoringMatrix(object):
"""
Defines a scoring-matrix between Kanji
"""
def get(self, **kwargs):
raise NotImplementedError
|
# Plot statistics
# Mean global flow completion time vs. utilization pFabric
lambdasdata = [4000, 6000, 10000, 15000, 22500, 37000, 60000]
lambdasweb = [3600, 5200, 7000, 8900, 11100, 14150, 19000]
row = 0
for x in lambdasweb:
file = "../temp_save/albert/pFabric/web_search_workload/"+str(x)+"/SPPIFO8_pFabric/analy... |
# .................................................................................................................
level_dict["love"] = {
"scheme": "red_scheme",
"size": (13,13,13),
"intro": "love",
"help":... |
# -*- coding: utf-8 -*-
"""Release data for the PyOOMUSH project."""
# Name of the package for release purposes.
name = 'PyOOMUSH'
version = '0.1'
description = "A Python Object-Oriented MUSH server."
long_description = \
"""
PyOOMUSH provides collaboratitive creation of a fully programmable
virtual world both usin... |
# Do not edit the class below except for the buildHeap,
# siftDown, siftUp, peek, remove, and insert methods.
# Feel free to add new properties and methods to the class.
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
def buildHeap(se... |
class Button:
def __init__(self, x, y, w, h, text, callback):
self.pos = x, y
self.size = w, h
self.text = text
self.callback = callback
self.bg_colour = [0, 0, 0]
self.text_colour = [255, 255, 255]
self.pushed_colour = [155, 155, 155]
self.pushed = F... |
class Trie:
def __init__(self) -> None:
self.root = {}
self.endOfWord = ' '
def insert(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.endOfWord] = self.endOfWord
def search(self, word: str) -> bool... |
# library to handle stuff about your ship
##########################
# necessary imports go here
##########################
##################################
# Inaugural frigate class - Atron
##################################
# a ship needs to have certain stats
# it needs a pilot (usually the player) it needs a ... |
#
# PySNMP MIB module Juniper-ERX-Registry (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ERX-Registry
# Produced by pysmi-0.3.4 at Wed May 1 14:02:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# Part 1
def parsephrase(phrase):
sp = phrase.lower().split()
checked = []
for p in sp:
if p in checked:
return(False)
else:
checked += [p]
return(True)
def phrases(lines):
x = 0
for l in lines.split("\n"):
pp = parsephrase(l.lower())
if p... |
__title__ = 'trylogging'
#__package_name__ = 'not-a-package'
__version__ = '0.0.1'
__description__ = "Just an example of using the Python logging module to remind me about using it."
__email__ = "notNeededForThisExample@null.net"
__author__ = 'Matt McCright'
__github__ = 'https://github.com/mccright/PPythonLoggingExamp... |
n = int(input('Digite um número inteiro: '))
op = int(input("""Conversação. Digite:
1 - para Binário
2 - para Octal
3 - para Hexadecimal
"""))
#IMPORTANTE USAR O FATIAMENTO DE OBJETO
if op == 1:
print('{} em Binário é {}'.format(n, bin(n)[2:])) #[2:] PEGA DA 3º POSIÇÃO ATÉ O FINAL DO OBJETO
elif op == 2:
prin... |
#!/usr/bin/python
#protexam_output.py
'''
Output functions for ProtExAM.
'''
|
# function to find double factorial of given number.
'''
Double factorial of a non-negative integer n,
is the product of all the integers from 1 to n that have the same parity (odd or even) as n.
It is also called as semifactorial of a number and is denoted by !!.
For example,
9!! = 9*7*5*3*1 = 945.
Note that--> 0!... |
n, k = map(int, input().split())
s = str(input())
sl = []
c = 1
if (s[0] == "1"):
sl.append(0)
for i in range(n):
if (i != 0):
if (s[i] == s[i-1]):
c += 1
else:
sl.append(c)
c = 1
sl.append(c)
ruisekiwa = [0]
sums = []
ans = 0
w = 2*k+1
if (w > len(sl)):
... |
#
# libjingle
# Copyright 2012 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following d... |
#lab1 ex2
print('Please insert Your name, surname and year of birth:')
a = input()
b = a.split()
name = b[0]
surname = b[1]
year_of_birth = b[2]
print(surname, year_of_birth, name) |
class HTML_Icon():
HTML_Icon_Color_Default_Display='inline'
HTML_Icon_Color_Default_Show='blue'
HTML_Icon_Color_Default_Hide='grey'
HTML_Icon_Size_Default=0
HTML_Icon_Sizes=[
'',
'fa-lg',
'fa-2x',
'fa-xs','fa-sm',
'fa-3x','fa-5x','fa-7x','fa-10x', ... |
a = int(input('Digite o 1º número: '))
b = int(input('Digite o 2º número: '))
c = int(input('Digite o 3º número: '))
if a>b and a>c:
m = a
elif b>c:
m = b
elif c>b:
m = c
else:
m =a
print(m)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.