content stringlengths 7 1.05M |
|---|
class Agent(object):
def __init__(self, id):
self.id = id
def act(self, state):
raise NotImplementedError()
def transition(self, state, actions, new_state, reward):
pass
|
n = int(input())
arr = [list(map(int,input().split())) for i in range(n)]
ans = [0]*n
ans[0] = int(pow((arr[0][1]*arr[0][2])//arr[1][2], 0.5))
for i in range(1,n):
ans[i]=(arr[0][i]//ans[0])
print(*ans) |
class Relaxation:
def __init__(self):
self.predecessors = {}
def buildPath(self, graph, node_from, node_to):
nodes = []
current = node_to
while current != node_from:
if self.predecessors[current] == current and current != node_from:
return None
... |
# Escreva um script Python que leia um vetor A de 10 elementos inteiros e um valor qualquer inteiro X. Em seguida, realize uma busca no arranjo a fim de verificar se o valor X existe no imprima na tela "ACHEI" se o valor X existir em A e "NAO ACHEI" caso contrário.
listNumbers = []
for i in range(10):
n = int(inpu... |
#Exercício Python 14:
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
print('__________________________________')
print(' CONVERSOR DE TEMPERATURA ')
print('__________________________________')
print('''
[1] Celsius para Fahrenheit
... |
'''
It is also possible to construct a DataFrame with hierarchically indexed columns. For this exercise, you'll start with pandas imported and a list of three DataFrames called dataframes. All three DataFrames contain 'Company', 'Product', and 'Units' columns with a 'Date' column as the index pertaining to sales transa... |
"""Top-level package for Python Boilerplate."""
__author__ = """Mathanraj Sharma"""
__email__ = "rvmmathanraj@gmail.com"
__version__ = "0.1.0"
|
"""
namecom: result_models.py
Defines response result models for the api.
Tianhong Chu [https://github.com/CtheSky]
License: MIT
"""
class RequestResult(object):
"""Base class for Response class.
Attributes
----------
resp :
http response from requests.Response
status_code : int
... |
""" Exceptions used by the impact estimation program """
class RecipeCreationError(Exception):
pass
class SolverTimeoutError(Exception):
pass
class NoKnownIngredientsError(Exception):
pass
class NoCharacterizedIngredientsError(Exception):
pass
|
# Copyright 2015 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
{
'includes': [
],
'targets': [
{
'target_name': 'mkvmuxer',
'type': 'static_libr... |
# -*- coding: utf-8 -*-
"""
First paragraph of docs.
.. wikisection:: faq
:title: Why?
Well...
Second paragraph of docs.
"""
|
class Address(object):
def __init__(self,addr):
self.addr=addr
@classmethod
def fromhex(cls,addr):
return cls(bytes.fromhex(addr))
def equal(self,other):
if not isinstance(other, Address):
raise Exception('peer is not an address')
if not len(self.addr) == le... |
# job_list_one_shot.py ---
#
# Filename: job_list_one_shot.py
# Author: Abhishek Udupa
# Created: Tue Jan 26 15:13:19 2016 (-0500)
#
#
# Copyright (c) 2015, Abhishek Udupa, University of Pennsylvania
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permit... |
class OnlyStaffMixin(object):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(request, "Only Staff members can do this.")
try:
return HttpResponseRedirect(request.META['HTTP_REFERER'])
except KeyEr... |
def plant_recommendation(care):
if care == 'low':
print('aloe')
elif care == 'medium':
print('pothos')
elif care == 'high':
print('orchid')
plant_recommendation('low')
plant_recommendation('medium')
plant_recommendation('high')
|
MANWON = 10000
CHONWON = 1000
def median_income_section(pay):
str_pay = str(int(pay/10000))
median = 0
if pay < 1060*CHONWON:
median = 0
elif pay < 1500*CHONWON:
if int(int(str_pay)/5) == 0:
median = float(str_pay+"25")
else:
median = float(str_pay+"75")
median = median * 100
elif pay < 3000*CHONWO... |
class Settings():
def __init__(self):
self.screen_width = 1024 # screen Width
self.screen_height = 512 # screen height
self.bg_color = (255, 255, 255) # overall background color
self.init_speed = 30 # speed factor of dino
self.dhmax = 23
self.alt_freq... |
# Maths
# Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length.
#
# Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:
#
# If S[i] == "I", then A[i] < A[i+1]
# If S[i] == "D", then A[i] > A[i+1]
#
#
# Example 1:
#
# Input: "IDID"
# Output: [0,4,1,3,2]
# Exam... |
#Felipe Lima
#Linguagem: Python
#Exercício 13 do site: https://wiki.python.org.br/EstruturaSequencial
#Entra com a altura
altura = float(input("Qual sua altura? "))
#Realiza os cálculos
pesoIdealHomem = (72.7*altura)-58
pesoIdealMulher = (62.1*altura)-44.7
#Imprime o resultado
print("Seu peso ideal caso você seja ho... |
# Interface for a "set" of cases
class CaseSet:
def __init__(self, time):
self.time = time
def __len__(self):
raise NotImplementedError()
def iterator(self):
raise NotImplementedError()
def get_time(self):
return self.time
def set_time(self, time):
self.t... |
def array_count9(nums):
count = 0
# Standard loop to look at each value
for num in nums:
if num == 9:
count = count + 1
return count
|
#
# @lc app=leetcode id=747 lang=python3
#
# [747] Largest Number At Least Twice of Others
#
# https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/
#
# algorithms
# Easy (40.25%)
# Total Accepted: 47.6K
# Total Submissions: 118K
# Testcase Example: '[0,0,0,1]'
#
# In a giv... |
# -*- coding: utf-8 -*-
# A primeira linha informa ao interpretador Python que é utilizado a codifição UTF-8
# Dessa forma é possível utilizar caracteres especiais em comentários e no PRINT
print("Codificação UTF-8: ç ã é í") |
# Speed of light in m/s
speed_light = 299792458
# J s
Planck_constant = 6.626e-34
# m Wavelenght of band V
wavelenght_visual = 550e-9
# flux density (Jy) in V for a 0 mag star
Fv = 3640.0
# photons s-1 m-2 in Jy
Jy = 1.51e7
#1 rad = 57.3 grad
RAD = 57.29578
# 1 AU ib cn
AU = 149.59787e11
# Radius in cm
R_Earth =... |
factors = [1, 2, 4]
pads = [32, 64, 128, 256, 512]
gen_scope = "gen"
dis_scope = "dis"
outputs_prefix = "output_"
lr_key = "lr"
hr_key = "hr"
lr_input_name = "lr_input"
hr_input_name = "hr_input"
pretrain_key = "pretrain"
train_key = "train"
epoch_key = "per_epoch"
|
"""
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Examp... |
# generic warnings
UNEXPECTED_FIELDS = 'A GTFS fares-v2 file has column name(s) not defined in the specification.'
UNUSED_AREA_IDS = 'Areas defined in areas.txt are unused in other fares files.'
UNUSED_NETWORK_IDS = 'Networks defined in routes.txt are unused in other fares files.'
UNUSED_TIMEFRAME_IDS = 'Timeframes def... |
def test_contacts_on_home_page(app):
contact_from_home_page = app.contact.get_contacts_list()[1]
contact_from_edit_page = app.contact.get_info_from_edit_page(1)
assert contact_from_edit_page.email_1 == contact_from_home_page.email_1
assert contact_from_edit_page.email_2 == contact_from_home_page.emai... |
#
# PySNMP MIB module OPTIX-SONET-EQPTMGT-MIB-V2 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPTIX-SONET-EQPTMGT-MIB-V2
# Produced by pysmi-0.3.4 at Mon Apr 29 20:26:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#!/usr/bin/env python3
CAVE_DEPTH = 6969
TARGET_LOC = (9, 796)
GEO_INDEX_CACHE = {
(0, 0): 0,
TARGET_LOC: 0
}
def get_geo_index(x, y):
key = (x, y)
if key not in GEO_INDEX_CACHE:
if y == 0:
GEO_INDEX_CACHE[key] = x * 16807
elif x == 0:
GEO_INDEX_CACHE[key] = y... |
"""Globally register callables and call via matching keywords.
Example:
>>> # register print function for keyword my_value
>>> set_recorder(my_value=print)
>>> record(my_value="Hello World.")
Hello World.
"""
_recorders = {}
def set_recorder(**kwargs):
"""Globally register a callable to which record calls are ... |
def is_string(thing):
try:
return isinstance(thing, basestring)
except NameError:
return isinstance(thing, str)
|
def authenticated_method(func):
def _decorated(self, *args, **kwargs):
if not self.api_key:
raise ValueError("you need to set your API KEY for this method.")
response = func(self, *args, **kwargs)
if response.status_code == 401:
raise ValueError("invalid private/pu... |
class Frac:
def __init__(self, idx: int, idy: int, x: int, y: int) -> None:
self.idx = idx
self.idy = idy
self.x = x
self.y = y
def __lt__(self, other: "Frac") -> bool:
return self.x * other.y < self.y * other.x
class Solution:
def kthSmallestPrimeFraction(self, arr... |
while True:
try:
num=int(input("Input your number: "))
print("Your number is {}".format(num))
break
except:
print("Please insert number!") |
class XnorController:
pass
|
class MovingAverage:
"""
[1,10,3,5]
size = 3
n = 4
[0,1,11,14,19]
"""
def __init__(self, size: int):
self.size = size
self.prefixes = [0]
def next(self, val: int) -> float:
n = len(self.prefixes)
self.prefixes.append(val)
self.prefixes[-1] +=... |
birth_year = 1999
if birth_year < 2000:
print("line 1")
print("line 2")
print("line 3")
else:
print("line 4")
print("line 5")
print("line 6")
if birth_year < 2000:
print("line 1")
print("line 2")
print("line 3")
else:
print("line 4")
print("line 5")
print("line 6")
|
# 1일차 - 이진수2
test_cases = int(input())
# 10진수 -> 2진수
def dec_to_bin(decimal):
binary = ''
while decimal != 0:
decimal *= 2
if decimal >= 1:
decimal -= 1
binary += '1'
else:
binary += '0'
if len(binary) >= 13:
binary = 'overflow'
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> list:
if root == None:
return []
stack = []
visited = set()
trav = []
stack.append(root)
wh... |
# Time: O(n + k)
# Space: O(k)
# 28
# Implement strStr().
#
# Returns a pointer to the first occurrence of needle in haystack,
# or null if needle is not part of haystack.
#
# Wiki of KMP algorithm:
# http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm
class Solution(object):
def strStr(self, haystack, ne... |
for i in range(0,3):
f = open("dato.txt")
f.seek(17+(i*77),0)
x1= int(f.read(2))
f.seek(20+(i*77),0)
y1= int(f.read(2))
f.seek(35+(i*77),0)
a= int(f.read(2))
f.seek(38+(i*77),0)
b= int(f.read(2))
f.seek(60+(i*77),0)
x2= int(f.read(2))
f.seek(63+(i*77),0)
y2= int... |
a=int(input('Enter number of terms '))
f=1
s=0
for i in range(1,a+1):
f=f*i
s+=f
print('Sum of series =',s)
|
# You need Elemental codex 1+ to cast "Haste"
hero.cast("haste", hero)
hero.moveXY(14, 30)
hero.moveXY(20, 30)
hero.moveXY(28, 15)
hero.moveXY(69, 15)
hero.moveXY(72, 58)
|
"""
Given a binary string (ASCII encoded), write a function that returns the equivalent decoded text.
Every eight bits in the binary string represents one character on the ASCII table.
Examples:
csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda"
01101100 -> 108 -> "l"
01100001 -> 97 -> "... |
"""
Rental
======
"""
class Rental:
"""
Representa el alquier de un barco de un cliente.
:param client: El cliente, arrendatario del alquiler.
:param boat: El barco del client para el que se realiza el alquiler.
:param start_date: Fecha de inicio del alquiler.
:param end_date: Fecha de fin d... |
# A Bubble class
class Bubble(object):
# Create the Bubble
def __init__(self, x, y, diameter, name):
self.x = x
self.y = y
self.diameter = diameter
self.name = name
self.over = False
# Checking if mouse is over the Bubble
def rollover(self, px, ... |
class Trie():
def __init__(self):
self.val = 0
self.next = dict()
def __repr__(self):
return f'{self.val} {self.next}'
def makeTrie(words):
trie, r_trie = dict(), dict()
for word in words:
l = len(word)
trie[l], r_trie[l] = trie.get(l, dict()), r_trie.get(... |
"""
Mixin that just overrides _repr_html.
"""
class _PrettyPrintMixin:
"""
A DataFrame with an overridden ``_repr_html_`` and some simple additional methods.
"""
def _repr_html_(self) -> str:
"""
Renders HTML for display() in Jupyter notebooks.
Jupyter automatically uses this ... |
queue = []
visited = []
def bfs(visited, graph, start, target):
visited.append(start)
queue.append(start)
while queue:
cur = queue.pop(0)
if cur == target:
break
for child in graph[cur]:
if child not in visited:
visited.append(child)
... |
# 621. Task Scheduler
class Solution:
# Greedy
def leastInterval(self, tasks: List[str], n: int) -> int:
# Maximum possible number of idle slots is defined by the frequency of the most frequent task.
freq = [0] * 26
for t in tasks:
freq[ord(t) - ord('A')] += 1
freq.... |
def ugly1():
q2, q3, q5 = [2], [3], [5]
while 1:
# print q2, q3, q5
if q2[0] < q3[0] and q2[0] < q5[0]:
ret = q2.pop(0)
q2.append(ret * 2)
q3.append(ret * 3)
q5.append(ret * 5)
elif q3[0] < q2[0] and q3[0] < q5[0]:
ret = q3.pop(... |
class EntityPair(object):
"""实体对
Atrributes:
entity1: WordUnit,实体1的词单元
entity2: WordUnit,实体2的词单元
"""
def __init__(self, entity1, entity2):
self.entity1 = entity1
self.entity2 = entity2
def get_entity1(self):
return self.entity1
def set_entity1(self, en... |
def fetch_ID(url):
'''
Takes a video.dtu.dk link and returns the video ID.
TODO: This should make some assertions about the url.
'''
return '0_' + url.split('0_')[-1].split('/')[0] |
"""
__init__.py
@Organization:
@Author: Ming Zhou
@Time: 4/22/21 5:28 PM
@Function:
"""
|
def sametype(s1: str, s2: str) -> bool:
return s1.lower() == s2.lower()
def reduct(polymer: str)-> str:
did_reduce = True
while did_reduce :
did_reduce = False
for i in range(1, len(polymer)):
unit1 = polymer[i-1]
unit2 = polymer[i]
if sametyp... |
def run_model(models, features):
# First decision
for experiment in ["Invasive v.s. Noninvasive",
"Atypia and DCIS v.s. Benign",
"DCIS v.s. Atypia"]:
pca = models[experiment + " PCA"]
if pca is not None:
features = pca.transform(fea... |
class Repository(object):
def byLocation(self, locationString): # pragma: no cover
"""Get the provenance for a file at the given location.
In the case of a dicom series, this returns the provenance for the
series.
Args:
locationString (str): Loc... |
"""
--- Day 20: Firewall Rules ---
You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the
corporate firewall only allows communication with certain external IP addresses.
You've retrieved the list of blocked IPs from the firewall, but the list seems to be ... |
# Get the starting fibonacci numbers
start1 = int(input("First fibonacci number: "))
start2 = int(input("Second fibonacci number: "))
# New line
print("")
fibonacci = [start1, start2]
for i in range(2, 102):
current_fibonacci = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci.append(current_fibonacci)
# Print a... |
def clarify_yayun():
with open("字表拼音.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
zhengti = ["hi", "ri", "zi", "ci", "si"] # 整体认读音节的后两个字母
u_to_v = ["yu", "xu", "qu"] # 读作v写作u
for line in lines:
c = line[0]
# _i指末尾i个字母组成的韵母
_1 ... |
m = 'John Smithfather'
a = m[:-6]
b = m[-6:]
print(b.title() + ": " + a)
print('AsDf'.lower(), 'AsDf'.upper()) |
num=int(input("Enter number:"))
if (num > 0):
print(num,"is a positive number")
else:
print(num,"is not a positive number")
|
print('-=-' * 25)
print('BEM-VINDO AO SEU EMPRÉSTIMO, PARA INICIAR SIGA AS INTRUÇÕES ABAIXO!')
print('-=-' * 25)
salario = float(input('Qual é o seu salario atual? R$'))
casa = float(input('Qual é o valo do imóvel que pretende compar? R$'))
anos = int(input('Em quantos anos pretende financiar a casa? '))
fina = casa / ... |
class _DoubleLinkedBase:
class _Node:
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... |
expected_output = {
"tag": {
"VRF1": {
"hostname_db": {
"hostname": {
"7777.77ff.eeee": {"hostname": "R7", "level": 2},
"2222.22ff.4444": {"hostname": "R2", "local_router": True},
}
}
},
"test": {... |
def add_binary(a, b):
"""
Implement a function that adds two numbers together and
returns their sum in binary.
The conversion can be done before, or after the addition.
The binary number returned should be a string.
"""
return str(bin(a+b)[2:])
# TESTS
assert add_binary(1, 1) == "10"
asser... |
RUN_CREATE_DATA = {
"root_name": "agent",
"agent_name": "agent",
"component_spec": {
"components": {
"agent==f39000a113abf6d7fcd93f2eaabce4cab8873fb0": {
"class_name": "SB3PPOAgent",
"dependencies": {
"environment": (
... |
#from pydrive_functions import write_trees_csvs
"""
write_trees_csvs()
df = get_trees_dataframes()
df2 = get_image_ids(df, ids_file.images_ids)
df2.to_csv('result.csv')
""" |
def calculateSeat(line, numRows, numColumns):
def getSeatParameter(line, up, down, currentCharNum, numChars, minValue, maxValue):
if line[currentCharNum] == up:
if currentCharNum == numChars:
return maxValue
currentCharNum += 1
return getSeatParameter(line... |
nome = str(input('Digite o seu nome completo:\n'))
lista = nome.split()
print('Seu primeiro nome é:\n {}'.format(lista[0]))
print('Seu último nome é:\n {}'.format(lista[-1]))
|
#Ex 1041 Coordenadas de um ponto 10/04/2020
x, y = map(float, input().split())
if x > 0 and y > 0:
print('Q1')
elif x < 0 and y > 0:
print('Q2')
if x > 0 and y < 0:
print('Q4')
elif x < 0 and y < 0:
print('Q3')
elif x == 0 and y == 0:
print('Origem')
|
N = 10
I = 60
CROSSBAR_FEEDBACK_DELAY = 75e-12
CROSSBAR_INPUT_DELAY = 95e-12
|
def howdoyoudo():
global helvar
if helvar <= 2:
i01.mouth.speak("I'm fine thank you")
helvar += 1
elif helvar == 3:
i01.mouth.speak("you have already said that at least twice")
i01.moveArm("left",43,88,22,10)
i01.moveArm("right",20,90,30,10)
i01.moveHand("left",0,0,0,0,0,119)
i01.moveH... |
# flake8: noqa
# fmt: off
"""List of Valorant API available regions and endpoints."""
REGION_URL = {
"BR": "https://br.api.riotgames.com",
"EUN": "https://eun.api.riotgames.com",
"AP": "https://ap.api.riotgames.com",
"KR": "https://kr.api.riotgames.com",
"LATAM": "https://latam.api.riotgames.com",... |
num = list()
pares = list()
impares = list()
while True:
num.append(int(input('Digite um número: ')))
resp = str(input('Quer continuar? [S/N] '))
if resp in 'Nn':
break
for i, v in enumerate(num):
if v % 2 == 0:
pares.append(v)
elif v % 2 == 1:
impares.append(v)
print('=' ... |
levelsMap = [
#level 1-1
("g1","f1",[["ma1","ma3","ma5","b1","m1","e1","m1","b1","ma1","ma3","ma5"],
["ma2","ma4","ma6","b1","b1","b1","b1","b1","ma2","ma4","ma6"],
["b1","b1","b1","m1","b1","m1","b1","m1","b1","b1","b1"],
["m1","b1","b1","b1","b1","b1","b1","b1","b1","b1","m1... |
#
# PySNMP MIB module S5-TCS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/S5-TCS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:35:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
cnt = 1;
for i in [10, 2, 7] :
print("%d : " % cnt , end = "" );
for j in range(1, i+1, 1) :
print("■", end = "");
print(" (%d)" % i);
cnt += 1;
|
STRING_51_CHARS = "SFOTYFUZTMDSOULXMKVFDOBQWNBAVGANMVLXQQZZQZQHBLJRZNY"
STRING_301_CHARS = (
"ZFOMVKXETILJKBZPVKOYAUPNYWWWUICNEVXVPWNAMGCNHDBRMATGPMUHUZHUJKFWWLXBQXVDNCGJHAPKEK"
"DZCXKBXEHWCWBYDIGNYXTOFWWNLPBTVIGTNQKIQDHUAHZPWQDKKCHERBYKLAUOOKJXJJLGOPSCRVEHCOAD"
"BFYKJTXHMPPYWQVXCVGNNSXLNIHVKTVMEOIRXQDPLHID... |
# You will be given series of strings until you receive an "end" command. Write a program that reverses strings and prints each pair on separate line in the format "{word} = {reversed word}".
while True:
word = input()
if word == 'end':
break
reversed_word = word[::-1]
print(f"{word} = {r... |
name = "doxygen"
version = "1.8.18"
authors = [
"Dimitri van Heesch"
]
description = \
"""
Doxygen is the de facto standard tool for generating documentation from annotated C++ sources, but it also supports
other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba,... |
class Node():
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def tree_in(node_list):
list_in = input().split()
l = len(list_in)
node_list.append(Node(list_in[0]))
for i in range(1, l):
if list_in[i] == "Non... |
for t in range(int(input())):
n,k,v=map(int,input().split())
a=list(map(int,input().split()))
s=0
for i in range(n):
s+=a[i]
x=(((n+k)*v)-s)/k
x=float(x)
if x>0:
if((x).is_integer()):
print(int(x))
else:
print(-1)
else:
print(-1) |
def linha(tam=42):
return '-'*tam
def cab(txt):
print(linha())
print(txt.center(42))
print(linha())
def leiaint(msg):
while True:
try:
n=int(input(msg))
except(ValueError, TypeError):
print(f'\033[31mERRO: Por favor, digite um número inteiro valido.\033[m'... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
self.ans = 1
def dfs(node):
if not node: return 0
l = dfs(node.left... |
#!/usr/bin/python
# Author: Michael Music
# Date: 8/1/2019
# Description: Coolplayer+ Buffer Overflow Exploit
# Exercise in BOFs following the securitysift guide
# Tested on Windows XP
# Notes:
# I will be assuming that EBX is the only register pointing to input buffer.
# Since EBX points to the very beginning of ... |
"""Generate model benchmark source file using template.
"""
_TEMPLATE = "//src/cpp:models_benchmark.cc.template"
def _generate_models_benchmark_src_impl(ctx):
ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.source_file,
substitutions = {
"{BENCH... |
def is_true(value):
"""
Helper function for getting a bool form a query string.
"""
if hasattr(value, "lower"):
return value.lower() not in ("false", "0")
return bool(value)
|
#
# PySNMP MIB module EICON-MIB-TRACE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EICON-MIB-TRACE
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
n=int(input())
dp=[[1]*3 for i in range(2)]
for i in range(1,n):
dp[i%2][0]=(dp[(i-1)%2][0]+dp[(i-1)%2][1]+dp[(i-1)%2][2])%9901
dp[i%2][1]=(dp[(i-1)%2][0]+dp[(i-1)%2][2])%9901
dp[i%2][2]=(dp[(i-1)%2][0]+dp[(i-1)%2][1])%9901
n-=1
print((dp[n%2][0]+dp[n%2][1]+dp[n%2][2])%9901) |
'''
The cost of a stock on each day is given in an array.
Find the max profit that you can make by buying and selling in those days.
Only 1 stock can be held at a time.
For example:
Array = {100, 180, 260, 310, 40, 535, 695}
The maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sel... |
# data input
inp1 = input().split()
inp2 = input().split()
# data processing
code1 = inp1[0]
num_code1 = int(inp1[1])
unit_value1 = float(inp1[2])
code2 = inp2[0]
num_code2 = int(inp2[1])
unit_value2 = float(inp2[2])
price = num_code1 * unit_value1 + num_code2 * unit_value2
# data output
print('VALOR A PAGAR: R$',... |
class BaseCloudController:
pass
|
"""
Integration test settings
"""
DYNAMODB_HOST = 'http://localhost:8000' |
__import__("math", fromlist=[])
__import__("xml.sax.xmlreader")
result = "subpackage_2"
class PackageBSubpackage2Object_0:
pass
def dynamic_import_test(name: str):
__import__(name)
|
# aplicador de multa
# kilometragem: 80km
# valor por kilomretro excedido: 7.00
print("OPA meu jovem, cuidado com a velocidade!")
km = float(input("Ovo ter que conferir se vc passou da velocidade, me informe o a kilometragem por favor: "))
vl = km - 80.0
if vl < 1.0 :
print("Tá limpo meu rei, pode passar.")
else... |
def timeConversion(s):
ampm = s[-2:]
hr = s[:2]
if ampm == 'AM':
return s[:-2] if hr != '12' else '00' + s[2:-2]
return s[:-2] if hr == '12' else str(int(s[:2]) + 12) + s[2:-2]
if __name__ == '__main__':
s1 = '07:05:45PM'
assert timeConversion(s1) == '19:05:45'
s2 = '07:05:45AM'
... |
#-*- coding: utf-8 -*-
# Code Interact Banner
APC_BANNER = u"""
************************************************************************************************************
* *
* Appium의 Python Client를 사용하여 테스트 스... |
MAJOR = 0
MINOR = 2
RELEASE = 4
VERSION = '%d.%d.%d' % (MAJOR, MINOR, RELEASE)
def at_least_version(versionstring):
"""Is versionstring='X.Y.Z' at least the current version?"""
(major, minor, release) = versionstring.split('.')
return at_least_major_version(major) and at_least_minor_version(minor) and at_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.