content stringlengths 7 1.05M |
|---|
#---
def plotUAVcontrolSignals(df,plt):
## - Plot the Control Signals
fig, axs = plt.subplots(2,2, sharex=True)
fig.suptitle("Control Signals (Executed by the Drone)")
# ---------- u_\theta
axs[0,0].plot(df['time'], df['A.pSCU[0]'])
axs[0,0].set(ylabel=r'$u_{\theta}~$ [rad]')
axs[0,0].... |
def arr_pair_sum(arr, k):
# edge case
if len(arr) < 2:
return
# set for tracking
seen = set()
output = set()
for num in arr:
target = k - num
if target not in seen:
seen.add(num)
else:
output.add((min(num, target), max(num, target)))
... |
def sanitize(time_string):
if "-" in time_string:
splitter = "-"
elif ":" in time_string:
splitter = ":"
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + "." + secs
with open("james.txt") as jaf:
data = jaf.readline()
james = sorted([sani... |
# Backport of str.removeprefix.
# TODO Remove when minimum python version is 3.9 or above
def removeprefix(string: str, prefix: str) -> str:
if string.startswith(prefix):
return string[len(prefix) :]
return string
|
# Some magic data values exist.
# They often represent missing data. More information can be found at the following link.
# https://www.census.gov/data/developers/data-sets/acs-1year/notes-on-acs-estimate-and-annotation-values.html
class Magic:
MISSING_VALUES = [
None,
-999999999,
-8888888... |
"""
Author: Ioannis Paraskevakos
License: MIT
Copyright: 2018-2019
"""
# ------------------------------------------------------------------------------
# States
NEW = 0 # New campaign is submitted
PLANNING = 1 # Planning the exeuction of the campaign
EXECUTING = 2 # At least one workflow is executing
DONE = 3 #... |
class Tile (object):
""" This is the abstract representation of Tiles, the building blocks of the world."""
def __init__ (self, stage, x, y):
self.stage = stage
self.x = x
self.y = y
"initializes the tile with a random type from the types list"
self.tile_type = self.st... |
def sample(task):
if task is not logistic:
raise NotImplementedError
# Parametric Generator for Logistic Regression Task (TODO: Generalize for Task - Parameter Specification)
theta = [np.random.uniform( 1, 10),
np.random.uniform( 1, 10),
np.random.uniform(-1, 1)]
return task(samp... |
def read_input():
joltages = []
with open('day10_input.txt') as input_file:
for line in input_file:
line = line.strip()
joltages.append( int(line) )
return joltages
# Find a chain that uses all of your adapters to connect the charging outlet
# to your device's built-in adap... |
class Solution:
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
last, n, y = chars[0], 1, 0
for x in range(1, len(chars)):
c = chars[x]
if c == last: n += 1
else:
for ch in last + str(n > 1 and ... |
def main(request, response):
response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin"))
token = request.GET[b"token"]
request.server.stash.put(token, b"")
response.content = b"PASS"
|
#!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""Tuxy scrie în fiecare zi foarte multe formule matematice.
Pentru că formulele sunt din ce în ce mai complicate trebuie
să folosească o serie de paranteze și a descoperit că cea
mai frecventă problemă a lui este că nu toate parantezele
sunt folosite cum trebuie.
Pentru... |
def iterate_dictionary(d, path, squash_single=False):
"""
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS.
The word "leaf" hereby refers to an item at the search path l... |
class Address:
def __init__(self, street_address, city, country):
self.country = country
self.city = city
self.street_address = street_address
def __str__(self):
return f'{self.street_address}, {self.city}, {self.country}'
|
def extractBetwixtedtranslationsBlogspotCom(item):
'''
Parser for 'betwixtedtranslations.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Transmigrated Senior Martial Brother', ... |
#
# This file contains the Python code from Program 16.20 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_20.txt
#
class Algorithms(... |
day_num = 15
file_load = open("input/day15.txt", "r")
file_in = file_load.read()
file_load.close()
file_in = list(map(int, file_in.split(",")))
def run():
def game(input_in, round_hunt):
num_last = {}
for temp_pos, temp_num in enumerate(input_in, 1):
num_last[temp_num] = temp_pos
game_round ... |
def findDuplicatesSequence(sequence):
stringySequence = str(sequence)
while stringySequence[0] == stringySequence[-1]:
stringySequence = stringySequence[-1] + stringySequence[0:-1]
iterableSequenceDuplicates = (re.finditer(r"(\d)\1+", str(stringySequence)))
duplicatesList = [iterable[0] for iter... |
"""
Given a list of words, find all pairs of unique indices such that the concatenation
of the two words is a palindrome.
For example, given the list ["code", "edoc", "da", "d"], return [(0, 1), (1, 0), (2, 3)].
"""
test = ['code', 'edoc', 'da', 'd']
palindrome_index = []
for i in range(len(test)):
for j in range... |
#
# PySNMP MIB module NNCBELLCOREGR820DS1STATISTICS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NNCBELLCOREGR820DS1STATISTICS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:13:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
cities = [
{
"city": "New York",
"growth_from_2000_to_2013": "4.8%",
"latitude": 40.7127837,
"longitude": -74.0059413,
"population": "8405837",
"rank": "1",
"state": "New York",
},
{
"city": "Los Angeles",
"growth_from_2000_to_2013": "4... |
class QualifierClassifier:
def __init__(self):
pass
@staticmethod
def get_qualifiers(act_state):
return {}
|
#def createUnitDict(filename):
# unit_info = dict()
# with open(filename, 'r') as unit_file:
# all_units = unit_file.readlines()
# for unit in all_units:
# unit = unit.split(",")
# unit_info[unit[1].split("\n")[0]] = int(unit[0])
# return unit_info
NUM_PROTOSS_ACTIONS = 70;
def getUnitData(units, unit_info):
u... |
# 2020.04.26: 二分搜索合适的 capacity:
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
'''
思想就是去试:
但是caipacity 从 0 开始 又太纯了,
采用二分法去试就很好,low = max(weights), hight = sum(weights)
'''
def is_within(mid,D):
c = 0
idx = 1
... |
a=int(input("enter the first number:"))
b=int(input("enter the second number:"))
s=(a&b) #sum
print(s)
u=(a/b) #or
print(u)
k=(~a) #not
print(k)
m=(a^b) #x-or
print(m)
o=(a<<b) #left shift
print(o)
t=(a>>b) #right shift
print(t)
|
"""
A person has X amount of money and wants to buy ice-creams. The cost of each ice-cream is Y.
For every purchase of ice-creams he gets 1 unit of money which could be used to buy ice-creams.
Find the number of ice-creams he can buy.
"""
class Solution:
def approach2(self, money, cost_per_ice):
ans = 0
... |
# majicians=['alice','david','carolina']
# for majician in majicians:
# print(F"{majician.title()},that was a great trick!")
# print(f"I can't wait to see your next trick,{majician.title()}.\n")
# majicians = ['alice', 'david', 'carolina']
# for majician in majicians:
# print(f'{majician.title()}, that was... |
class solve_day(object):
with open('inputs/day07.txt', 'r') as f:
data = f.readlines()
# method for NOT operation
def n(self, value):
return 65535 + ~value + 1
def part1(self):
wires = {}
for d in self.data:
d = d.strip()
# print(f'input: \t\... |
# Function which adds two numbers
def compute(num1, num2):
return (num1 + num2)
|
def majuscule(chaine):
whitelist = "abcdefghijklmnopqrstuvwxyz"
chrs = [chr(ord(c) - 32) if c in whitelist else c for c in chaine]
return "".join(chrs)
print(majuscule("axel coezard"))
def val2ascii(entier):
ch = ""
for i in range(entier):
ch = chr(ord(ch) + 1)
print(ch)
val2ascii(355... |
class Node(object):
def __init__(self,data):
self.data = data
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def prepend(self,data):
node = Node(data)
if not self.head:
... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
# for 迭代相关
# for循环可以遍历任何序列的项目,如一个列表或者一个字符串
# range函数
print(range(10))
print(range(3, 10))
print(range(3, 10, 2))
for a in range(10):
print(a)
print("------------------------------")
for a in range(3, 10):
print(a)
print("--------------------... |
# 文件名称
filename = '/home/yyh/Documents/VSCode_work/chapter10/guest_book.txt'
# 循环
while True:
name = input("Please enter you name(to quit, please press quit): ")
if name == 'quit':
break
else:
print("Hello, " + name + "!")
with open(filename, 'a') as file_object:
file_ob... |
# Copyright [2019] [Christopher Syben, Markus Michen]
#
# 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 ... |
BOOLEAN_OPTION_TYPE = ['false', 'true']
# Extracted from the documentation of clang-format version 13
# https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html
ALL_TUNEABLE_OPTIONS = {
'AccessModifierOffset': ['0', '-1', '-2', '-3', '-4'],
'AlignAfterOpenBracket': ['DontAlign', 'Align', ... |
{
'variables': {
'node_shared_openssl%': 'true'
},
'targets': [
{
'target_name': 'ed25519',
'sources': [
'src/ed25519/keypair.c',
'src/ed25519/sign.c',
'src/ed25519/open.c',
'src/ed25519/crypto... |
def issorted(str1, str2):
if len(str1) != len(str2):
return False
bool_b1 = [0] * 256
bool_b2 = [0] * 256
for i in range(len(str1)):
bool_b1[ord(str1[i])] += 1
bool_b2[ord(str2[i])] += 1
if bool_b1 == bool_b2:
return True
else:
return False
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 13:30:29 2021
@author: jr3
"""
"""
Write a Python program that takes as input a file containing DNA sequences in multi-FASTA format,
and computes the answers to the following questions.
You can choose to write one program with multiple func... |
class Event:
def __init__(self, name, payload):
self.name = name
self.payload = payload
|
"""
Em uma competição de salto em distância cada atleta tem direito a cinco saltos. O resultado do atleta será
determinado pela média dos cinco saltos. Você deve fazer um programa que receba o nome e as cinco distâncias
alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média dos saltos. O pro... |
alphabet = "abcdefghijklmnopqrstuvwxyz"
class Scrambler():
"""
Class to represent a rotor in the machine.
"""
def __init__(self, mapping, step_orientation=[0], orientation=0):
self.orientation = orientation # integer representing current orientation of scrambler
self.m = mapping # li... |
class Solution:
def numDecodings(self, s):
if not s:
return 0
second_last, last = 0, 1
for i, ch in enumerate(s):
ways = 0
curr = int(ch)
# current number is not 0
if curr:
# there is at least one way to decode
... |
def Divide(a,b):
try:
return (a/b)
except ZeroDivisionError:
print("\nHey!Dont be insane!\n")
def Rem(a,b):
try:
return (a%b)
except ZeroDivisionError:
print("\nHey!Dont be insane!\n")
print("Enter Operand1:\n")
oper1=float(input())
print("Enter Operand2:\n")
oper2=float(input... |
#global Variable
x = 100
def fun(x):
#local scope of variable
x = 3 + 2
return x
local = fun(x)
print(local)
print(x) |
# N개의 자연수가 주어질 때, 각 수 M에 대하여 M번째 소수를 구하시오
# Given N integers, for each integer M, find the Mth prime
limit = 200000
primes = list(range(limit))
primes[0], primes[1] = 0, 0
for i in range(2, limit):
if primes[i]:
for j in range(i+i, limit, i):
primes[j] = 0
primes = tuple(prime for prime in prim... |
sqrt = lambda n: n ** .5
sqrt_5 = sqrt(5)
phi = (1 + sqrt_5) / 2
psi = (1 - sqrt_5) / 2
fibonacci = lambda n: int(round((phi ** n - psi ** n) / sqrt_5))
for n in range(-12, 12):
print(fibonacci(n))
|
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
key_pairs = {}
value_pairs = {}
for i in xrange(le... |
def originalSystemPrettyPrint():
var = "Original System \n\ny1' = 7 y3 + 4.5 y5 + -19.5 y1^2 -9.5 y1 y2 + -10 y1 y5 + -9.75 y1 y3 -9.75 y1 y4\n" + \
"y2' = 9 y4 + 4.5 y5 + -6 y2^2 -9.5 y1 y2 + -10 y3 y2 + -4 y5 y2 -1.75 y2 y4\n" + \
"y3' = 9.75 y1^2 -3.5 y3 + -9.75 y1 y3 + -19.5 y3^2 -10 y3 y2\n... |
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
# For exampl... |
class DataQueue:
def __init__(self):
self.data = []
def Add(self, unitData):
self.Enqueue(unitData)
self.Dequeue()
def Enqueue(self, unitData):
self.data.append(unitData)
def Dequeue(self):
self.data.pop(0) |
QUIT_MSG = "go home, you're drunk"
class CreativeQuitPlugin(object):
name = "Creative quit plugin"
def __init__(self, bot_instance):
self.bot_instance = bot_instance
def leave(self, user, channel):
"""
Wrapper around bot quit, since we have extra args per
the plugin inter... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if not matrix:
print()
else:
for row in range(len(matrix)):
for item in range(len(matrix[row])):
if item != len(matrix[row]) - 1:
endspace = ' '
else:
end... |
value = int(input())
def dumb_fib(n):
if n < 3:
return 1
else:
return dumb_fib(n - 1) + dumb_fib(n - 2)
print(dumb_fib(value + 1))
|
lst = [8, 3, 9, 6, 4, 7, 5, 2, 1]
def main():
test(lst)
def test(lst):
line_one = []
reverse_line_two = lst
shifted_num = []
reverse_line_two = reverse_line_two[::-1]
limit = len(reverse_line_two)
for i in range(limit):
line_one.append(i + 1)
line_one.pop(0)
left = reverse_... |
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
media = (n1 + n2) / 2
print(f'Tirando {n1:.1f} e {n2:.1f}, a média do aluno é {media:.1f}')
if media <= 5:
print('O aluno está \033[31mREPROVADO\033[m!')
elif media <= 6.9:
print('O aluno está de \033[33mRECUPERAÇÃO\033[m!')
elif media >= ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 3 23:45:39 2017
@author: ASUS
This code snippet takes the complement and reverse of a DNA string
"""
string = 'GTGGTTACGCTCCCGGGGGGGTTCTACGTGCAGATACTGTTCGGGAAGAAGGAGGCACGTCAGGGAGCGCACCCCCCGGTCTACTTGACGGTGGTGAACGTTATCGGCTGGGCCATGTCGTGGAGATAGGAAGCAGGGGAAGTGTGTAAGACAAGTGTA... |
def age_predict():
name = input("What is your name?\n")
print("Hello " + name + " it is nice to meet you!")
x = True
while x:
age = input("How old are you " + name + "?\n")
if age.isnumeric():
x = False
else:
print("Please try again.")
age_date = ((100... |
"""
CONVERSÃO DE MEDIDAS
"""
medida = float(input('Digite a quantidade de Metros: '))
print('Conversão')
print('\nCentimetros: {}cm'.format(medida*100))
print('\nMilímetros: {}mm'.format(medida*1000)) |
def get_eben(n: list):
if sum(n) % 2 == 0:
return int("".join(map(str, n)))
num = n
s = sum(num)
while s % 2 != 0:
s
def main():
t = int(input())
for _ in range(t):
length = int(input())
n = map(int, input().split())
print(get_eben(n... |
# encoding: utf-8
class Enum(object):
@classmethod
def get_keys(cls):
return filter(lambda x: not x.startswith('_'), cls.__dict__.keys())
@classmethod
def items(cls):
return map(lambda x: (x, getattr(cls, x)), cls.get_keys())
@classmethod
def get_values(cls):
return map... |
def euro(b, m, c):
czas = dict()
mecze = dict()
baza = dict()
wynik = ['', float('inf')]
for baz in b:
baza[baz[0]] = baz[1]
for mecz in m:
if mecz[0] not in mecze.keys():
mecze[mecz[0]] = [mecz[2]]
else:
mecze[mecz[0]].append(mecz[2])
if... |
dataset_type = 'CocoDataset'
data_root = '/work/u5216579/ctr/data/PCB_v3/'#'/home/u5216579/vf/data/coco/' #'data/coco/'
img_norm_cfg = dict(
#mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
mean=[38.720, 51.155, 40.22], std=[53.275, 52.273, 46.819], to_rgb=True)
train_pipeline = [
... |
def get_nd_par(ref_len, read_type, basecaller):
if read_type:
if read_type == "dRNA":
return drna_nd_par(ref_len, basecaller)
else:
return cdna_nd_par(ref_len, read_type)
else:
return dna_nd_par(ref_len, basecaller)
def seg_par(ref_len, changepoint):
if ref_... |
if __name__ == "__main__":
T = int(input().strip())
correct = 1 << 32
for _ in range(T):
num = int(input().strip())
print(~num + correct)
|
def format_user(userdata, format):
result = ""
u = userdata["name"]
if format == "greeting":
result = "{}, {} {}".format(u["title"], u["first"], u["last"])
elif format == "short":
result = "{}{}".format(u["title"], u["last"])
elif format == "country":
result = userdata["nat"]... |
"""
DEVA AI Oversight Tool.
Copyright 2021-2022 Gradient Institute Ltd. <info@gradientinstitute.org>
"""
|
t = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(t[3])
print(t[-99:-7])
print(t[-99:-5])
print(t[::])
|
SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"DEB_REPO_SCHEMA": {
"type": "object",
"required": [
"name",
"uri",
"suite",
"section"
],
"properties": {
... |
# -*- coding: utf-8 -*-
# Author: Rodrigo E. Principe
# Email: fitoprincipe82 at gmail
# Make a prediction with weights
# one vector has n elements
# p = (element1*weight1) + (element2*weight2) + (elementn*weightn) + bias
# if p >= 0; 1; 0
def predict(vector, bias, weights):
pairs = zip(vector, weights) # [[eleme... |
# -*- coding: utf-8 -*-
class GPSException(Exception):
def __init__(self,*args):
super(GPSException, self).__init__(*args)
# From K6WRU via stackexchange : see https://ham.stackexchange.com/questions/221/how-can-one-convert-from-lat-long-to-grid-square/244#244
# Convert latitude and longitude to Maidenhea... |
{
"variables": {
"buffer_impl" : "<!(node -pe 'v=process.versions.node.split(\".\");v[0] > 0 || v[0] == 0 && v[1] >= 11 ? \"POS_0_11\" : \"PRE_0_11\"')",
"callback_style" : "<!(node -pe 'v=process.versions.v8.split(\".\");v[0] > 3 || v[0] == 3 && v[1] >= 20 ? \"POS_3_20\" : \"PRE_3_20\"')"
},
"targets": [... |
#method 'find' finds index positon of specified string
#index position starts with 0
my_fruit = "My favorite fruit is apple".find('apple')
print(my_fruit) |
"""Constants for Seat Connect library."""
BASE_SESSION = 'https://msg.volkswagen.de'
BASE_AUTH = 'https://identity.vwgroup.io'
CLIENT_ID = '7f045eee-7003-4379-9968-9355ed2adb06%40apps_vw-dilab_com'
XCLIENT_ID = '28cd30c6-dee7-4529-a0e6-b1e07ff90b79'
XAPPVERSION = '3.2.6'
XAPPNAME = 'es.seatauto.connect'
USER_AGENT = '... |
# File: Slicing_in_Python.py
# Description: How to slice strings in Python
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Slicing in Python // GitHub platform [Electronic resource]. URL: ht... |
# Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar
# 80km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar
# R$ 7,00 por cada Km acima do limite.
velocidade = float(input('Velocidade: '))
if velocidade > 80:
multa = (velocidade - 80) * 7
print('Limite excedido! S... |
class Hund:
def __init__(self, alder, vekt):
self._alder = alder
self._vekt = vekt
self._metthet = 10
def hentAlder(self):
return self._alder
def hentVekt(self):
return self._vekt
def spring(self):
self._metthet -= 1
if self._metthet < 5:
... |
#
# PySNMP MIB module LLDP-EXT-DOT1-PE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LLDP-EXT-DOT1-PE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:57:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# 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:
output = ListNode(None)
outputPointer = output
carry = 0
... |
"""Messages used in the code that can or can't be used repeatedly."""
def welcome():
"""Welcoming message of the game."""
print("BLACKJACK IN PYTHON!")
print()
print("┌─────────┐ ┌─────────┐")
print("│ A │ │ J │")
print("│ │ │ │")
print("│ │ │ ... |
class Trackable(object):
def __init__(self, name):
self.name = name
print('CREATE {}'.format(name))
def __del__(self):
print('DELETE {}'.format(self.name))
|
CURRENCY_ALGO = "ALGO"
EXCHANGE_ALGORAND_BLOCKCHAIN = "algorand_blockchain"
TRANSACTION_TYPE_PAYMENT = "pay"
TRANSACTION_TYPE_ASSET_TRANSFER = "axfer"
TRANSACTION_TYPE_APP_CALL = "appl"
APPLICATION_ID_TINYMAN_v10 = 350338509
APPLICATION_ID_TINYMAN_v11 = 552635992
APPLICATION_ID_YIELDLY = 233725848
APPLI... |
#--- Exercicio 2 - Impressão de dados com a função Input
#--- Imprima o menu de uma aplicação de cadastro de pessoas
#--- O menu deve conter as opções de Cadastrar, Alterar, listar pessoas, alem da opção sair
print ('=='*50)
print (' ', 'Bem vindo' ' ... |
XK_emspace = 0xaa1
XK_enspace = 0xaa2
XK_em3space = 0xaa3
XK_em4space = 0xaa4
XK_digitspace = 0xaa5
XK_punctspace = 0xaa6
XK_thinspace = 0xaa7
XK_hairspace = 0xaa8
XK_emdash = 0xaa9
XK_endash = 0xaaa
XK_signifblank = 0xaac
XK_ellipsis = 0xaae
XK_doubbaselinedot = 0xaaf
XK_onethird = 0xab0
XK_twothirds = 0xab1
XK_onefif... |
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
print("Initials: " + firstname[0] + "." + lastname[0] + ".")
|
"""
The module for training the SVM classifer.
"""
def train(database_num=3):
"""
use SVM provided by sklearn with databases to train the classifier and
dump it into a pickle.
:param database_num: 3 means NUAA, CASIA, REPLAY-ATTACK;
2 means CASIA, REPLAY-ATTACK.
"""
|
POST_JSON_RESPONSES = {
'/auth/realms/test/protocol/openid-connect/token': {
'access_token': '54604e3b-4d6a-419d-9173-4b1af0530bfb',
'token_type': 'bearer',
'expires_in': 42695,
'scope': 'read write'},
'/v2/observations': {
'dimensionDeclarations': [
{
... |
def ends_with_punctuation(string):
if string is None:
return False
for punctuation in ['.', '!', '?']:
if string.rstrip().endswith(punctuation):
return True
return False
|
# PREDSTORM L1 input parameters file
# ----------------------------------
# If True, show interpolated data points on the DSCOVR input plot
showinterpolated = True
# Time interval for both the observed and predicted windDelta T (hours), start with 24 hours here (covers 1 night of aurora)
deltat = 24
# Time range of ... |
size = int(input())
matrix = []
for _ in range(size):
matrix.append([int(x) for x in input().split()])
primary_diagonal_sum = 0
secondary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += matrix[i][i]
secondary_diagonal_sum += matrix[i][size - i - 1]
total = abs(primary_diagonal_sum... |
class BlockLinkedList:
def __init__(self):
self.size = 0
self.header = None
self.trailer = None
def addbh(self, block):
if self.size == 0:
self.trailer = block
else:
block.set_next(self.header)
self.header.set_previous(block)
self.header = block
self.size += 1
def addbt(self, block):
i... |
# -*- coding:utf-8 -*-
# package information.
INFO = dict(
name = "exputils",
description = "Utilities for experiment analysis",
author = "Yohsuke T. Fukai",
author_email = "ysk@yfukai.net",
license = "MIT License",
url = "",
classifiers = [
"Programming Language :: Python ::... |
"""
from rest_framework.serializers import ModelSerializer
from netbox_newplugin.models import MyModel1
class MyModel1Serializer(ModelSerializer):
class Meta:
model = MyModel1
fields = '__all__'
"""
|
# Given a linked list, determine if it has a cycle in it.
#
# To represent a cycle in the given linked list, we use an integer pos which
# represents the position (0-indexed) in the linked list where tail connects to.
# If pos is -1, then there is no cycle in the linked list.
#
# Input: head = [3,2,0,-4], pos = 1
# Out... |
def print_table(n):
""" (int) -> NoneType
Print the multiplication table for numbers 1 through n inclusive.
>>> print_table(5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
"""
# The numbers to include in the table.
numbers = list(... |
# %% [492. Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/)
class Solution:
def constructRectangle(self, area: int) -> List[int]:
w = int(area ** 0.5)
while area % w:
w -= 1
return area // w, w
|
# EXERCICIO 053 - DETECTOR DE PALINDROMO
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
inverso = junto[::-1]
if inverso == junto:
print('A frase digitada é um palíndromo!')
else:
print('A frase digitada não é um palíndromo!')
|
"""Empty test.
Empty so that tox can be used for CI in Github actions
"""
# def test_sum():
# assert sum([1, 2, 3]) == 6, "Should be 6"
def test():
assert True is True |
def generateMatrix(n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = [[0 for i in range(n)] for j in range(n)]
# i = j = 0
# blow = 0
# bhigh = n-1
# for num in range(1, n ** 2 +1):
# ans[i][j] = num
# if j < bhigh and i == blow:
# j += 1
# ... |
# config.py
class Config(object):
embed_size = 300
in_channels = 1
num_channels = 100
kernel_size = [3,4,5]
output_size = 4
max_epochs = 10
lr = 0.25
batch_size = 64
max_sen_len = 20
dropout_keep = 0.6 |
# Byte code returned from flask-http in the case of auth failure.
NOT_AUTHORIZED_BYTE_STRING = b'Unauthorized Access'
def check_for_unauthorized_response(res):
"""
Raise an Unauthorized exception only if the response object contains the Not Authorized
byte string.
:param res: Response object to check... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.