content stringlengths 7 1.05M |
|---|
"""
Routine to perform color printing of text, wrapping standard pyton print function.
"""
# ANSI terminal colors - just put in as part of the string to get color terminal output
colors = {'red': '\x1b[31m', 'r': '\x1b[31m',
'orange': '\x1b[48:5:208:0m', 'o': '\x1b[48:5:208:0m',
'yellow': '\x1b[3... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: aghast_generated
class InterpretedBuffer(object):
NONE = 0
InterpretedInlineBuffer = 1
InterpretedInlineInt64Buffer = 2
InterpretedInlineFloat64Buffer = 3
InterpretedExternalBuffer = 4
|
# https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
crLog = None
environment_config = None
magic_value_config = None
message_config = None
|
class Menu:
def __init__(self, position=(0, 0)):
"""
Make all menu mechanics
:param position: start position for drawing
"""
self.index = 0
self.x = position[0]
self.y = position[1]
self.menu = list()
def down(self):
"""
Move menu ... |
"""
Session: 8
Topic: Set vs List
"""
# my_set = {1, 2, 3, 1, 2}
my_set = {"apple", "apple", "orange", "orange", "orange"}
print(my_set)
print ("\n\n")
# my_list = [1, 2, 3, 1, 2]
my_list = ["apple", "apple", "orange", "orange", "orange"]
print(my_list) |
print("""\033[1;30mFaça um programa que leia um número
qualquer e mostre o seu fatorial.\033[0;0m\n""")
# Usando while
# n = int(input('Digite um número: '))
# c = n
# r = n
# while c > 1 :
# c -= 1
# r = r * c
# print(r)
# print('O fatorial de {} é {}'.format(n, r))
# Usando for
n = int(input('Digite... |
def check(i):
for j in range(m):
if need[i][j] > available[j]:
return False
return True
n = int(input("Enter the number of Processes: "))
m = int(input("Enter the number of Resources: "))
allocation = []
for i in range(n):
allocation.append(list(map(int, input('\nEnter the number of in... |
#web scraping - open the html file
#then find the appropriate chunk of code like <table> where your data is
#then extract what you want from there
"""
For APIs, they'll help you scrape the webpage more easily
based on the documentation provided by the webpage, if any.
So you can look for APIs from various web... |
RESOLVER_STORE = {"pulumi.json": {"Any": {"type": "any"}, "Asset": {"type": "string"}}}
PULUMI_ID = "id"
PULUMI_NS = "pulumi"
PULUMI_HOME_ENV = "PULUMI_HOME"
|
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Author: Albert King
date: 2020/2/13 23:11
contact: jindaxiang@163.com
desc: 可用函数库 --> client.py --> DataApi
"""
class QhkcFunctions:
@staticmethod
def variety_positions(fields="shorts", code="rb1810", date="2018-08-08"):
"""
奇货可查-商品-持仓数据接口
... |
def is_in_range(digits, r_max):
number = 0
for i, d in enumerate(digits):
number += d * 10**i
if number > r_max:
return False
# print(number)
return True
def is_valid(digits):
distinct_digits = list(set(digits))
for dd in distinct_digits:
if digits.count(dd) == 2:
return True
return False
def solve(... |
def analysis(filename):
file = open(filename)
total = []
for entry in file:
info = entry.split(' ')
total.append(info)
total.sort(key = lambda x: int(x[1][:-1]),reverse=True)
# print(total[:1000])
final_analysis = open('final_analysis.txt','w')
for entry in total:
fin... |
class Solution:
# 这个方法最快
def subsets(self, nums):
def doSubsets(nums, i):
if len(nums) == i + 1:
return [[nums[i]]]
results = []
results.append([nums[i]])
subResults = doSubsets(nums, i+1)
results.extend(subResults)
... |
def sudoku(grid):
match = [i for i in range(1, 10)]
for row in grid:
if sorted(row) != match:
return False
for column_index in range(9):
column = [grid[row_index][column_index] for row_index in range(9)]
if sorted(column) != match:
return False
for row in ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 21 18:38:37 2019
@author: NOTEBOOK
"""
#This program displays the total earnings of a worker over a number of days in dollars
# starting from 1 penny and doubling each day
def main():
#Get number of days
days = int(input('Enter number of days: ' ))
#Print Head... |
## Verifica Palavra no Nome
nome = str(input('Qual seu nome completo? ')).strip()
print('Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
## Concatenando Strings
print('-='*30)
print('CONCATENANDO STRINGS')
print('-='*30)
a = 'Wollacy'
b = 'Lilian'
c = 'Augusto'
print(a)
print(b)
print(c)
d = a + ' + ' + ... |
syntax = r'^\+(?:tel|port|teleport)(?P<quiet>/quiet)? (?P<target>.+)$'
def teleport(caller, target, quiet=False, force=False):
target = search(caller, target).all()
if not target:
commands.pemit(caller, caller, "\c(red)!!! Unable to find target.")
return
target = target[0]
... |
load("@rules_maven_third_party//:import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_codehaus_plexus_plexus_archiver",
artifact = "org.codehaus.plexus:plexus-archiver:3.4",
artifact_sha256 = "3c6611c98547dbf3f5125848c273ba719bc10df44e3... |
# 1. Decoration
def deco(param):
def wrapper(func):
def inner_wrapper(*arg, **kwargs):
print(param, arg, kwargs)
inner_res = func(*arg, **kwargs)
return inner_res
return inner_wrapper
return wrapper
@deco(param="do what you want to do")
def origin(times, add... |
"""
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0,... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Recurring Documents',
'category': 'Extra Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on tha... |
def print_my_info():
print("안녕하세요.")
print("홍길동입니다.")
print("만나서반갑습니다.")
print_my_info() |
# __INIT__.PY
__version__='v1.0.0'
|
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
dp = [[0] * (len(first) + 1) for _ in range(len(second) + 1)]
n1 = len(first) + 1
n2 = len(second) + 1
for i in range(1, n1):
dp[0][i] = dp[0][i - 1] + 1
for i in range(1, n2):
dp[... |
class Fraction:
def __repr__(self):
return '%s/%s' % (self.num, self.den)
def __add__(self, other):
num = self.num * other.den + self.den * other.num
den = self.den * other.den
return Fraction(num, den)
def __sub__(self, other):
num = self.num * other.den - self.den... |
"""
This module is used to represent a ROI object from the DICOMROI table in the database.
"""
class ROI:
"""
This class stores all information about a region of interest from the DICOMROI table in the database.
"""
def __init__(self, name: str, identity: int = -1, priority: int = -1) -> None:
... |
# To import:
# from twoscomplement import *
def lars_reverse_twos_complement(j, bits=1):
return (1<<j.bit_length()+bits) - j
def lars_twos_complement(j):
return (1<<(j.bit_length()))-j
def build_twos_complement_down(j):
origj=j
prevj=0
while prevj != j:
print(f'{j:10d}, {prevj^j:10d}')
prevj... |
class State:
def __init__(self):
pass
def update(self):
pass |
"""
"""
# dict01 = {"a": 1, "b": 2, "c": 3}
list01 = [1, 2, 3, 4]
list02 = [5, 6, 7, 8]
for item in zip(list01, list02):
print(item)
# 2048里面的转置函数,简化
list01 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
# list_new = []
# for item in zip(*list01):
# list_new.append(list(... |
LEVELS = [
("echo 'bang'", "echo 'bang!';"),
("swap two files in your homedir", """files=(~/*);
f1="${files[RANDOM % ${#files[@]}]}"
f2="${files[RANDOM % ${#files[@]}]}"
mv "$f1" /tmp/russianroulette
mv "$f2" "$f1"
mv /tmp/russianroulette "$f2"
echo 'bang! two files got their names mixed up. now, which ones wer... |
# 编写一个算法来判断一个数是不是“快乐数”。
# 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
# 示例:
# 输入: 19
# 输出: true
# 解释:
# 12 + 92 = 82
# 82 + 22 = 68
# 62 + 82 = 100
# 12 + 02 + 02 = 1
class Soluttion:
def isHappy(self, n: int) -> bool:
if n == 1:
return ... |
class EventPropertyError(Exception):
pass
class ValidationError(Exception):
def __init__(self, message: str):
self.message = message
class RetrievalError(Exception):
def __init__(self, message: str):
self.message = message
|
# www.census.gov/geo/www/us_regdiv.pdf
CensusDivisions = (
('PACIFIC', 'AK HI WA OR CA'.split()),
('MOUNTAIN', 'MT ID WY NV UT CO AZ NM'.split()),
('WN_CENTRAL', 'ND SD MN NE IA KS MO'.split()),
('EN_CENTRAL', 'WI MI IL IN OH'.split()),
('WS_CENTRAL', 'OK AR TX LA'.split()),
('ES_CENTRAL', 'KY TN MS AL'.split()),
('S_... |
def fib(x):
if x < 2:
return x
else:
return fib(x-1) + fib(x-2)
n = int(input('digite um termo da sequencia fibonaci: '))
a = 0
b = 1
i = 0
while n < 2:
print('\033[32mdigite um termo maior ou igual a dois\n'
'pois o primeiro e segundo termo são\n'
'0 e 1 respectivament... |
class Enemy:
#state
player_seen_at_tower = None # tower coordinates (x, y, z)
player_seen = None # world coordinates vec3
# constants
speed = 1
jump_speed = 5
jump_angle = 30
maxhp = 100
disappear_on_sight = False
use_ranged_weapons = True
use_grenades = False
... |
def flatten_chebi_api_attr(ch: dict, attr, _mapping: dict):
val = ch.pop(attr)
if isinstance(val, list):
if isinstance(val[0], dict):
if 'data' in val[0]:
# list of dicts
val = [el['data'] for el in val]
else:
# todo: ... |
"""
6.9 – Lugares favoritos: Crie um dicionário chamado favorite_places. Pense em três nomes para usar como chaves do dicionário e armazene de um a três lugares favoritos para cada pessoa. Para deixar este exercício um pouco mais interessante, peça a alguns amigos que nomeiem alguns de seus lugares favoritos. Percorra ... |
# Path to images we are extracting content and style from
CONTENT_IMAGE_PATH = './coastal_scene.jpg'
STYLE_IMAGE_PATH = './starry_night.jpg'
# Seed for initializing numpy and tf
NP_SEED = 0
TF_SEED = 0
# Path to vgg19 checkpoint, must be downloaded separately
CHECKPOINT_PATH = './vgg_19.ckpt'
# Location of tensorboa... |
path = "input.txt"
file = open(path)
input = file.readlines()
file.close()
horizontal = 0
depth = 0
for item in input:
dir, speed = item.split(" ")
if dir == "forward":
horizontal += int(speed)
elif dir == "down":
depth += int(speed)
elif dir == "up":
depth -= int(speed)
... |
# Implementantion of all PetriNet class
# 1st class to be implemented is Petri Net Basic (or classic Petri Net)
class PetriNet(object):
"""
This class contains all major object necessary to describe a complete Petri Net
"""
pass
class Place(object):
"""
Class Place implements the behavior of ... |
def str_bin(s_str):
st = s_str
print(' '.join(format(ord(x), "b") for x in st))
def main():
str_bin("lol")
if __name__ == "__main__":
main()
print("done") |
x = list(input("Input String: "))
x = x [::-1]
j = 0
def reverseword(x):
i = 0
print(int)
while i !=int(len(x)/2):
temp = x[i]
x[i] = x[len(x)-1-i]
x[len(x)-1-i] = temp
i+=1
return str(x)
print(reverseword(x))
|
platforms = {
"UA": "usaco.org",
"CC": "codechef.com",
"EOL":"e-olimp.com",
"CH24": "ch24.org",
"HR": "hackerrank.com",
"HE": "hackerearth.com",
"ICPC": "icfpcontest.org",
"GCJ": "google.com/codejam",
"DE24": "deadline24.pl",
"IOI": "stats.ioinformatics.org",
"PE": "projecteuler.net",
"SN... |
"""EasyEngine exception classes."""
class EEError(Exception):
"""Generic errors."""
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
class EEConfigError(EEError):
"""Config related errors."""
pass
class EERuntimeError(... |
class SimpleGroupProvider(object):
def __init__(self, *group_names):
self.group_names = group_names
def get_group_names(self):
return self.group_names |
"""
Simple SQL Web Interface
"""
__version__ = "0.1.1"
|
input_number = input ("Give me number if even or odd")
converted_input = int (input_number)
print(converted_input)
if converted_input % 2 == 0:
print("even number")
else:
print ("odd number") |
class NodeChilds(object):
def __init__(self, nodes):
self.nodes = nodes
self.isArray = type(nodes) == list
self.isObject = type(nodes) == dict
def add(self, child):
if self.isArray:
self.node.append(child)
elif self.isObject:
self.node[child.ke... |
# Circular primes
# https://projecteuler.net/problem=35
prime = [True for i in range(1000010)]
prime[0] = prime[1] = False
p = 2
while p <= 1000000:
if prime[p]:
for i in range(p * 2, 1000001, p):
prime[i] = False
p += 1
circ = []
for i in range(2, 1000000):
if prime[i]:
temp = ... |
# -*- coding: utf-8 -*-
# Quaternary ligand binding to aromatic residues in the active-site gorge of acetylcholinesterase.
# Harel, M., Schalk, I., Ehret-Sabatier, L., Bouet, F., Goeldner, M., Hirth, C., Axelsen,
# P.H., Silman, I., Sussman, J.L. (1993) Proc.Natl.Acad.Sci.USA 90: 9031-9035
reference_1acj = {
'pdb... |
name='trie'
def get_line(in_f,num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
T = int(in_f.readline())
maxn = 0
MaxQc = 0
Is = True
Maxdep = 0
for xx in range(T):
#p... |
class InputOutputLabel():
def __init__(self):
self.inputs = None
self.outputs = None
self.labels = None
def update(self, inputs, outputs, labels):
self.inputs = inputs
self.outputs = outputs
self.labels = labels |
# Runtime: 280 ms, faster than 70.79% of Python3 online submissions for Sort an Array.
# Memory Usage: 19.7 MB, less than 57.14% of Python3 online submissions for Sort an Array.
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# merge sort: avg, worst, best time = O(nlogn), space = O(n)
... |
# A Linked List Node
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
#function to print a given linked list
def printList(msg, head):
print(msg, end='')
ptr = head
while ptr:
print(ptr.data, end=' —> ')
ptr = ptr.next
print(... |
#// The format of this file is descriped in api_kernel32.idc
#///func=RtlGetLastWin32Error entry=bochsys._BxWin32GetLastError@0
#///func=RtlSetLastWin32Error entry=bochsys._BxWin32SetLastError@4
#///func=NtSetLdtEntries purge=24
#///func=RtlAllocateHeap entry=nt_HeapAlloc
def nt_HeapAlloc():
# Redirect HeapAlloc ->... |
def get_keywords(tweets_features):
query = tweets_features['search_metadata']['query']
keywords = query.split(' -filter')[0].split(' OR ')
return keywords
|
# if-else
if True:
print("True execute")
else:
print("False execute")
x = input("Please enter a number: ") # Get a number from user input
x = int(x) # convert the number to integer
if x > 200:
print("Greater than 200")
elif x > 100:
print("Greater than 100, Less than 100")
else:
print("Less than... |
"""
Python mergesort algorithms
"""
def mergeSort(array):
if len(array) > 1:
# Finding the mid of the arrayay
mid = len(array) // 2
# Dividing the array elements into 2 halves
L = array[:mid]
R = array[mid:]
# Sorting the first half
mergeSort(L)
... |
"""练习:创建子类:狗(跑),鸟类(飞)
创建父类:动物(吃)体会子类复用父类方法
体会 isinstance 、issubclass 与 type 的作用"""
class Animal:
def eating(self):
print("吃")
class Dog(Animal):
def running(self):
print("跑")
class Bird(Animal):
def flying(self):
print("飞")
A=Animal()
popy=Dog()
hiby=Bird()
print(isinstance(popy, ... |
# [EASY]232. Implement Queue using Stacks
# https://leetcode.com/problems/implement-queue-using-stacks/description/
# The idea is to simulate a queue using two stacks. I use python list as the underlying data structure for stack: it moves all elements of the "inStack" to the "outStack" when the "outStack" is empty. Her... |
#!/usr/bin/env python3
expsz = 4 # number of bits in the exponent
wordsz = 8 # number of bits in the word
# no config below
# how many bits in the mantissa
mansz = wordsz - 2 - expsz # please ensure mansz >= 1
# print bits allocation
print(f"{wordsz}b allocation: [1b sign] [{mansz}b mantissa] "\
f"[1b e... |
# by Kami Bigdely
# Extract Class
class Food:
def __init__(self, name, prep_time, is_vegeterian, food_type,
cuisine_type, ingredients, recipe):
self.name = name
self.prep_time = prep_time
self.is_vegeterian = is_vegeterian
self.food_type = food_type
self.c... |
# coding utf-8
# exercício comparação entre dois números
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
if num1 > num2:
print('O primeiro valor {} é o maior.'.format(num1))
elif num2 > num1:
print('O segundo valor {} é o maior.'.format(num2))
else:
print('Não... |
def main():
message = input('Message: ')
alphabet = 'abcdefghijklkmnopqrstuvwxyz'
letters = alphabet.split(sep='')
|
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 2015-02-27 4174 nabowle Output full stacktrace.
# 2018-10-05 mjames@ucar Fix returned retVal encoding.
... |
class Bit:
# 参考1: http://hos.ac/slides/20140319_bit.pdf
# 参考2: https://atcoder.jp/contests/arc046/submissions/6264201
# 検証: https://atcoder.jp/contests/arc046/submissions/7435621
# values の 0 番目は使わない
# len(values) を 2 冪 +1 にすることで二分探索の条件を減らす
def __init__(self, a):
if hasattr(a, "__iter__"... |
#
# PySNMP MIB module VCP-PRIVATE-MIB-VER-2 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VCP-PRIVATE-MIB-VER-2
# Produced by pysmi-0.3.4 at Mon Apr 29 21:26:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
frase = ('O rato roeu a roupa do rei')
letra = ('r')
contador = 0
for valor in frase:
if valor == letra:
contador = contador + 1
print(f'A letra {letra} apareceu {contador} vezes na frase') |
#
# @lc app=leetcode.cn id=35 lang=python3
#
# [35] 搜索插入位置
#
# https://leetcode-cn.com/problems/search-insert-position/description/
#
# algorithms
# Easy (42.26%)
# Total Accepted: 27.1K
# Total Submissions: 64.2K
# Testcase Example: '[1,3,5,6]\n5'
#
# 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
条件与循环
"""
a = 1
b = 2
# if语句
if a == 1 and b == 2:
pass
else:
pass
# if else
if a == 1:
pass
elif a == 2:
pass
else:
pass
# 条件表达式 C?X:Y
# X if C else Y
x, y = 4, 3
smaller = x if x < y else y
print(smaller)
# while
count = 0
while count < 3:
... |
#!/usr/bin/env python3
"""Frames per second.
Create a function that returns the number of frames shown in a
given number of minutes for a certain FPS.
Source:
https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
"""
def frames(minutes: int, fps: int) -> int:
"""Find the number of frames shown."""
seconds = minute... |
class Body:
def __init__(self, name, parts):
self.name = name
self.parts = parts
def favorite(self):
print('NAME', self.name, '俺のお気に入りの筋肉部位', self.parts)
# インスタンス生成
mochida = Body('Mochida', '大胸筋')
mochida.favorite()
class Item(Body):
def __init__(self, name, parts, items):
... |
# encoding: utf-8
__author__ = 'lianggao'
__date__ = '2019/5/29 10:44 AM'
def javpop_url(time):
yield 'http://javpop.com/' + time[:4] + '/' + time[4:6] + '/' + time[-2:] |
def type_name(cls):
"""Get the name of a class."""
if not cls:
return '(none)'
return '{}.{}'.format(cls.__module__, cls.__name__)
def viewset_model(serializer):
"""Get the model of a serializer."""
if hasattr(serializer, 'serializer_class'):
return serializer.serializer_class.Meta... |
async def send_to_client(packet_type, packet_data):
"""Implementation of this function not shown."""
raise RuntimeError('Nope')
async def trigger_event(event_name, event_data):
"""Implementation of this function not shown."""
raise RuntimeError('Nope')
async def receive(packet_type, packet_data):
... |
''' não éobrigatório ter init(porém foi dado em aula e cairá em PROVAAAA!!!!!
ESTUDEEEEE)
'''
class Pessoa:#classe mãe
def __init__(self,n):
self.__nome=n
class Aluno:
def __init__(self, n, r, d=[]):#d é parâmetro default e toda função pode ter parâmetro default
super().__init__(n)... |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... |
# this file was automatically generated
major = 1
minor = 4
release = '20130410193624'
version = '%d.%d-%s' % (major, minor, release)
|
"""
entradas
valor-->int-->va
"""
cd = int(input("Ingrese cantidad de dinero $"))
bcien = (cd-cd % 100000)/100000
cd=cd % 100000
bcincuen = (cd-cd % 50000)/50000
cd=cd % 50000
bvein = (cd-cd % 20000)/20000
cd=cd % 20000
bdiez = (cd-cd % 10000)/10000
cd=cd % 10000
bcinco = (cd-cd % 5000)/5000
cd=cd % 5000
bd = (cd-cd % ... |
a = input ('Put the number a: \n')
b= input ('Put the number b: \n')
a,b=b,a
print(f'Resalt a: {a}')
print(f'Resalt b: {b}')
|
class Player:
def __init__(self, id, x, y, z, health):
self.id = id
self.x = x
self.y = y
self.z = z
self.health = health
|
"""
Given the array nums, for each nums[i] find out how many numbers in the
array are smaller than it. That is, for each nums[i] you have to count the
number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example:
Input: nums = [8,1,2,2,3]
Output: ... |
name = input('Digite algo: ')
print('O tipo desse valor: {}'.format(type(name)))
print('Só tem espaço? {}'.format(name.isspace()))
print('É um número? {}'.format(name.isalnum()))
print('É alfabético? {}'.format(name.isalpha()))
print('É alfanumérico? {}'.format(name.isalnum()))
print('Está em maiúsculas? {}'.format(nam... |
"""
package used to easy creation of new device interfaces.
"""
|
"""Build rules for utilizing glslang."""
def _glslang(name, mode = None, target = None, **kwargs):
MODES = {
"glsl": "",
"hlsl": "-D",
}
if mode not in MODES:
fail("Illegal mode {}".format(mode), "mode")
TARGETS = {
"opengl": "-G",
"vulkan": "-V",
}
if t... |
# General
DEBUG_MODE = True
# FolderWatcher
FOLDER_PATH = 'images/'
FRAMERATE = 1
SCALE_TO_SIZE = (640, 480)
# Server
ROUTE = '/folder_feed' |
with open(r"C:\Users\joash\Desktop\CS\haskell\AOC19\aoc\day2.txt", "r") as f:
program = [ int(i) for i in f.read().split(",") ]
pos = 0
while program[pos] != 99:
print("currently on pos:", pos, "opcode is: ", program[pos])
if program[pos] == 1:
program[program[pos+3]] = program[program[pos+1]] + program[pr... |
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: 140. Word Break II.py
@time: 18-12-23 下午2:13
@version: v1.0
"""
class Solution(object):
mem_cache = dict()
def rec_wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
... |
class dotReferenceModel_t(object):
# no doc
aActiveFilePath = None
aBasePointGuid = None
aFilename = None
ModelObject = None
Position = None
Rotation = None
Scale = None
Visibility = None
|
class FARule(object):
def __init__(self, state, char, next):
super(FARule, self).__init__()
self.state = state
self.char = char
self.next = next
def is_applied(self, state, char):
return self.state == state and self.char == char
def follow(self, config):
ret... |
n = list()
for c in range(0, 9):
n.append(int(input(f'Digite o valor que você quer colocar na posição {c}: ')))
print()
for c in range(0, 9):
print(f'[ {n[c]:^5} ]', end='')
if c == 2 or c == 5 or c == 8:
print('\n')
|
def purge(pTable):
"""
if a CEA candidate has been selected, purge all cell pairs that do not belong to this candiate
"""
# inventorize cells with selected candidates
selected = {}
for cell in pTable.getCells():
if ('sel_cand' in cell) and cell['sel_cand']:
key = (cell['row_... |
"""
A sequential search is O(n) for ordered and unordered lists.
A binary search of an ordered list is O(logn) in the worst case.
Hash tables can provide constant time searching.
A bubble sort, a selection sort, and an insertion sort are O(n^2) algorithms.
A shell sort improves on the insertion sort by sorting increme... |
#_ -*- coding: utf-8 -*-
# Copyright (c) 2021 OceanBase
# OceanBase CE is licensed under Mulan PubL v2.
# You can use this software according to the terms and conditions of the Mulan PubL v2.
# You may obtain a copy of Mulan PubL v2 at:
# http://license.coscl.org.cn/MulanPubL-2.0
# THIS SOFTWARE IS PROVIDED O... |
class Hoge:
def hoge(self) -> None:
pass
@classmethod
def fuga(cls) -> None:
pass
|
adict = {
"BLACKBOARD_LEARN_INSTANCE" : "",
"APPLICATION_KEY" : "",
"APPLICATION_SECRET" : "",
"django_secret_key" : '',
"disable_collectstatic" : "1",
"django_allowed_hosts" : "127.0.0.1 localhost .ngrok.io .herokuapp.com [::1]",
"django_debug" : "False",
} |
# Find the Duplicate Number
# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
# find the duplicate one.
# There is only one duplicate number, but it can be repeated multiple times.
# Note: You cannot modify the array, no extra space is allowed.
class SolutionV1(object):
... |
class MessageStorage:
messageList = []
@staticmethod
def addMessage(m):
MessageStorage.messageList.append(m)
@staticmethod
def countMessages():
return len(MessageStorage.messageList)
@staticmethod
def getMessageList():
return MessageStorage.messageList
@stati... |
class SingleServerConfig():
def __init__(self):
self.redis_config = None
def set_config(self, **kwargs):
"""
kwargs:
:host:
Can be used to point to a startup node
:port:
Can be used to point to a startup node
... |
class Solution:
def removeDuplicateLetters(self, s):
for c in sorted(set(s)):
chop = s[s.index(c):]
# print(c, set(chop), set(s), chop, c, s)
if set(chop) == set(s):
return c + self.removeDuplicateLetters(chop.replace(c, ""))
return ""
a = Solution... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.