content stringlengths 7 1.05M |
|---|
# Copyright (c) Microsoft Corporation.
#
# 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 or agreed to in wri... |
# https://leetcode.com/problems/single-number-iii/
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
d = {}
for num in nums:
if num in d:
d[num] += 1
else:
d[num] = 1
result = []
for key, v... |
# https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
file_to_be_read = input("Which fil... |
a=int(input("Enter a number"))
if a%2==0:
print(a,"is an Even Number")
else:
print(a,"is an Odd Number")
|
# wczytanie wszystkich trzech plikow
with open('../dane/dane5-1.txt') as f:
data1 = []
for line in f.readlines():
data1.append(int(line[:-1]))
with open('../dane/dane5-2.txt') as f:
data2 = []
for line in f.readlines():
data2.append(int(line[:-1]))
with open('../dane/dane5-3.txt') as f:
... |
numbers = list(range(0, 110, 10))
numbers = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
second = []
x = 0
while x < len(numbers):
t = numbers[x] *2.5
if t % 2 == 0:
second.append(int(t))
x += 1
print(second)
print(x) |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "workspace_and_buildfile")
load(
"@bazel_tools//tools/cpp:lib_cc_configure.bzl",
"auto_configure_fail",
"auto_configure_warning",
"escape_string",
"get_env_var",
"get_starlark_list",
"resolve_labels",
"split_escaped",
"which",
)
l... |
class initial(object):
pass
INITIAL = initial()
another = INITIAL
print(another is INITIAL) |
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
{*[1,2,3], *[4,5,6]}
# EXPECTED:
[
...,
BUILD_SET_UNPACK(2),
...
]
|
def capital_indexes(string: str) -> list:
return [index for index, char in enumerate(string) if char.isupper()]
# return [letter for letter in range(len(indexes)) if indexes[letter].isupper()]
def tests() -> None:
print(capital_indexes("mYtESt")) # [1, 3, 4]
print(capital_indexes("owO"))
if __name_... |
# dataset settings
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224, backend='pillow'),
dict(type='RandomFlip', flip_prob=0.5, direction='hor... |
"""Scorer of model predictions. Adaped from OneIE. """
def safe_div(num, denom):
if denom > 0:
if num / denom <= 1:
return num / denom
else:
return 1
else:
return 0
def compute_f1(predicted, gold, matched):
precision = safe_div(matched, predicted)
recall = safe_div(matched, gold)
f1 = safe_div(2 * ... |
class StakeHolder:
def __init__(self, staker, amount_pending_for_approval, amount_approved, block_no_created):
self._staker = staker
self._amount_pending_for_approval = amount_pending_for_approval
self._amount_approved = amount_approved
self._block_no_created = block_no_created
... |
sender = ''
password = ''
smtp_name = 'smtp.gmail.com'
smtp_port = 587
body = """
<html>
<body>
<p>Hi User,<br>
How are you?<br>
</p>
</body>
</html>
"""
receiver = ''
signature_img_name = 'awesome_attachment.png'
signature_img_path = 'C:/Users/user/Desktop/'
attachment_name = signa... |
"""
* Assignment: Type Float Gradient
* Required: no
* Complexity: hard
* Lines of code: 7 lines
* Time: 8 min
English:
1. At what altitude above sea level, pressure is equal
to partial pressure of Oxygen
2. Print result in meters rounding to two decimal places
3. To calculate partial pressure use r... |
"""
1120. Maximum Average Subtree
Medium
Given the root of a binary tree, find the maximum average value of any subtree of that tree.
(A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes.)
Example 1:
Input: ... |
# -*- coding: utf-8 -*-
template_model_creation = """import pandas as pd
from sklearn.model_selection import train_test_split
{model_import} as ChosenMLAlgorithm
from sklearn.metrics import accuracy_score, confusion_matrix
import pickle
csv_file = "{csv_file}"
model_file = "{model_file}"
predictors = {predictors}
t... |
my_variabel = "hai darmawan"
for variabel_baru in my_variabel:
print("for string: ",variabel_baru)
my_list =["aku", "kamu", "dia"]
my_tuple=(1,5,6,7)
for variabel_baru3 in my_tuple:
print("for list or tuple", variabel_baru3)
|
def main():
x=11
y=2
print("Addition X+Y=",x+y)
print("Subtraction X-Y=",x-y)
print("Multiplication X*Y=",x*y)
print("Division X/Y=",x/y)
print("Modulus X%Y=",x%y)
print("Exponent X**Y=",x**y)
print("Floor Division X//Y=",x//y)
if __name__ == '__main__':
main()
|
def test_screen_two():
for num in range(0, 100):
col = int(num * 0.01 * 2.0)
y = (num * 0.01 - float(col) / 2.0) * 2.0
newY = y / 960.0 * 480.0 + 1.0 / 4.0
print('col:' + str(col) + ' num: ' + str(num) + ' y: ' + str(y) + ' newY: ' + str(newY))
# print(str(newY))
def test_sc... |
__project__ = "o3seespy"
__author__ = "Maxim Millen & Minjie Zhu"
__version__ = "3.1.0.18"
__license__ = "MIT with OpenSees License"
|
# By Kami Bigdely
# Decompose conditional: You have a complicated conditional(if-then-else) statement. Extract
# methods from the condition, then part, and else part(s).
def make_alert_sound():
print('made alert sound.')
def make_accept_sound():
print('made acceptance sound')
def check_if_toxin(ingredients):... |
class MyClass:
def __init__(self):
self.var = 'var'
def method(self):
print('method')
x = MyClass()
x.method()
m = x.method
m()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 16 19:01:59 2021
@author: gerry
"""
#Klasse: punkt
class Punkt: #start med stor bokstav, skiller klasse fra funksjoner og variabler
#konstruktør
def __init__(self, start_x=0, start_y=0):
self.x_koordinat = start_x
self.y_koordinat = start_y
... |
'''
@author: l4zyc0d3r
People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt
'''
class Solution:
def kthFactor(self, n: int, k: int) -> int:
for i in range(1, n+1):
if n % i == 0:
k-=1
if k == 0: return i
return -1
|
"""This is the calculation class / abstraction class"""
class Calculation:
"""Creates the Calculation parent class for the arithmetic subclasses"""
# pylint: disable=bad-option-value, too-few-public-methods
def __init__(self, values: tuple):
"""Constructor Method"""
self.values = Calculati... |
_base_ = [
'../_base_/datasets/nus-mono3d.py', '../_base_/models/fcos3d.py',
'../_base_/schedules/mmdet_schedule_1x.py', '../_base_/default_runtime.py'
]
# model settings
model = dict(
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
# ... |
#! /usr/bin/env python3
def main():
languages = {
"Python": "Guido van Rossum",
"Ruby": "Yukihiro Matsumoto",
"PHP": "Rasmus Lerdorf"
}
for each in languages:
print(each + " was created by " + languages[each])
if __name__ == "__main__":
main() |
ziehungen = input().split(",")
ziehungen = [int(x) for x in ziehungen]
boards = []
while True:
leer = input()
zeile = [input().split(" ")]
zeile[0] = [int(x) for x in zeile[0] if x != '']
if zeile[0] != []:
for i in range(1,5):
zeile.append(input().split(" "))
zeile[i] ... |
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while(j>=0 and arr[j]>key):
arr[j+1]=arr[j]
j = j - 1
arr[j+1] = key
return arr
def main():
arr = [6, 5, 8, 9, 3, 1, 4, 7, 2]
sorted_arr = insertion_sort(arr)
... |
"""
This module contains all the submodules for the handybeam software package.
"""
name = "handybeam"
__all__ = [
'bugcatcher',
'cl_system',
'evaluators',
'misc',
'solver',
'translator',
'tx_array',
'tx_array_library',
'visiualize',
'world',
'cl',
'cl_py_ref_code',
... |
#
# PySNMP MIB module DNS-SERVER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DNS-SERVER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:08:40 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
... |
# _*_ coding: utf-8 _*_
"""
inst_save.py by xianhu
"""
class Saver(object):
"""
class of Saver, must include function working()
"""
def working(self, priority: int, url: str, keys: dict, deep: int, item: object) -> (int, object):
"""
working function, must "try-except" and don't chan... |
"""
Get content from tag.
>>> from GDLC.GDLC import *
>>> dml = '''\
... <idx:entry scriptable="yes">
... <idx:orth value="ABC">
... <idx:infl>
... <idx:iform name="" value="ABC"/>
... </idx:infl>
... </idx:orth>
... <div>
... <span>
... <b>ABC</b>
... </span>
... </div>... |
#MAIN PROGRAM STARTS HERE:
num = int(input('Enter the number of rows and columns for the square: '))
k = 1
for x in range(0, num ):
for y in range(0, num):
print ('%d ' % (k), end='')
k += 2
print() |
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
class PointHash(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
if... |
"""
This is pure python implementation of interpolation search algorithm
"""
"""Pure implementation of interpolation search algorithm in Python
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
"""
def interpolation_search(sorted_collection, item):
left = 0
right = len(sor... |
# -*- coding: utf-8 -*-
# 18/1/30
# create by: snower
version = "0.1.1"
version_info = (0,1.1) |
# Copyright 2018, OpenCensus 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 or agreed to in w... |
class Logger:
PRINT_INTERVAL = 10
def __init__(self):
self.buckets = [-1 for _ in range(self.PRINT_INTERVAL)]
self.sets = [set() for _ in range(self.PRINT_INTERVAL)]
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
bucket_index = timestamp % self.PRINT_INTERVAL
... |
#!/usr/bin/env python
NAME = 'WebTotem (WebTotem)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
# WebTotem returns its name in blockpage
if all(i in page for i in (b'The current request was blocked', b'WebTote... |
'''
Ejemplo: auth.py
Aqui se definen las API KEYS para autorizar el acceso y
uso de la aplicacion rpi3bot de Twitter.
Fuente: https://www.raspberrypi.org/learning/getting-started-with-the-twitter-api/worksheet/
Fecha: mié dic 7 22:00:22 COT 2016
Version: 1.0
'''
consumer_key = 'ABCDEFGHIJKLKMNOPQRSTUVWXYZ'
consumer_s... |
{
'targets': [
{
'target_name': 'node_expat_object',
'sources': [
'src/parse.cc',
'src/node-expat-object.cc'
],
'include_dirs': [
'<!(node -e "require(\'nan\')")'
],
'dependencies': [
'deps/libexpat/libexpat.gyp:expat'
]
}
]
}
|
# Token types
#
# EOF (end-of-file) token is used to indicate that
# there is no more input left for lexical analysis
NUMBER, VARIABLE, VARIABLE_SET, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, EOF, LOG, SIN, COS, TAN, \
CTG, SQRT, POW, LOWER, HIGHER, HIGHER_EQ, LOWER_EQ, EQ, EQ_EQ, TRUE, FALSE, PLUS_EQUALS,\
MINUS_EQUA... |
class ParamRequest(object):
"""
Represents a set of request parameters.
"""
def to_request_parameters(self):
"""
:return: list[:class:`ingenico.connect.sdk.RequestParam`] representing the HTTP request parameters
"""
raise NotImplementedError
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyLap(PythonPackage):
"""lap is a linear assignment problem solver using
Jonker-Volgenant algorithm for den... |
class CoffeeMaker:
"""Models the machine that makes the coffee"""
def __init__(self):
self.resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def report(self):
"""Prints a report of all resources."""
print(f"Water: {self.resources['... |
list = ['Apple','Orange','Benana','Mango'];
name = "Md Tazri";
print('"Apple" in list : ',"Apple" in list);
print('"Kiwi" in list : ',"Kiwi" in list);
print('"Water" not in list : ',"Water" not in list);
print("'Md' in name : ",'Md' in name);
print("'Tazri' not in name : ",'Tazri' not in name); |
class DiceLoss(nn.Module):
def __init__(self, tolerance=1e-8):
super(DiceLoss, self).__init__()
self.tolerance = tolerance
def forward(self, pred, label):
intersection = torch.sum(pred * label) + self.tolerance
union = torch.sum(pred) + torch.sum(label) + self.tolerance
... |
class EventTypeFilter(TraceFilter):
"""
Indicates whether a listener should trace based on the event type.
EventTypeFilter(level: SourceLevels)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return EventTypeFilter()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
... |
#
# This is the Robotics Language compiler
#
# Transformations.py: Applies tranformations to the XML structure
#
# Created on: June 22, 2017
# Author: Gabriel A. D. Lopes
# Licence: Apache 2.0
# Copyright: 2014-2017 Robot Care Systems BV, The Hague, The Netherlands. All rights reserved.
#
# Licens... |
class Contact:
def __init__(self, firstname, lastname, company, address, telephone, mobile, tel_work, email, email_1, www):
self.firstname = firstname
self.lastname = lastname
self.company = company
self.address = address
self.telephone = telephone
self.mobile = mobil... |
#!/usr/bin/env python
# Tabuada de adição deve ser impressa de 1 a 10 sendo n o número digitado pelo usuario.
n = int(input('Tabuada de: '))
x = 1
while x <= 10:
print('{} + {} = '.format(n, x,), n + x)
x = x + 1
print('FIM ') |
# coding: utf-8
def array_pad(l, size, value):
if size >= 0:
return l + [value] * (size - len(l))
else:
return [value] * (size * -1 - len(l)) + l
if __name__ == '__main__':
l = [12, 10, 9]
print(array_pad(l, 5, 0))
print(array_pad(l, -7, -1))
print(array_pad(l, 2, 999))
|
k=int (input())
l=int (input())
m=int (input())
n=int (input())
d=int (input())
damagedDragons = 0
for i in range (1, d+1):
if i%k == 0 or i%l == 0 or i%m == 0 or i%n == 0:
damagedDragons = damagedDragons + 1
print(damagedDragons)
|
# Copyright 2018 Canonical Ltd.
#
# 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 or agreed to in writin... |
menu = [
[ "egg", "spam", "bacon"],
[ "egg", "sausage", "bacon"],
[ "egg", "spam"],
[ "egg", "bacon", "spam"],
[ "egg", "bacon", "sausage", "spam"],
[ "spam", "bacon", "sausage", "spam"],
[ "spam", "egg", "spam", "spam", "bacon","spam"],
[ "spam", "egg", "sausage", "spam"],
[ "chicke... |
# *ex 7 = Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua média.
p = float(input('Cara, me manda sua primeira nota: '))
s = float(input('Manda a segunda: '))
print('Cara sua média é: {:.1f}'.format((p+s)/2))
|
# Refaça o DESAFIO 9, mostrando a tabuada de um número
# que o usuário escolher, só que agora utilizando um laço for.
num = int(input('Digite um valor: '))
for i in range(1,11):
print(f'{num} X {i} = {num*i}') |
def divide(x: int, y: int) -> int:
result, power = 0, 32
y_power = y << power
while x >= y:
while y_power > x:
y_power >>=1
power -=1
result += 1<<power
x -= y_power
return result |
"""
TODO: Add description.
Date: 2021-05-27
Author: Vitali Lupusor
"""
|
sum = 0
for x in range(10):
sum = sum + x
print(sum)
|
"""
Classes in this file are standalone because we don't want to impose a false hierarchy
between two classes. That is, inheritance may imply a hierarchy that isn't real.
"""
class Settings(object):
kExactTestBias = 1.0339757656912846e-25
kSmallEpsilon = 5.684341886080802e-14
kLargeEpsilon = 1e-07
SM... |
f = open("io/data/file1")
print(f.readline())
print(f.readline(3))
print(f.readline(4))
print(f.readline(5))
print(f.readline())
# readline() on writable file
f = open("io/data/file1", "ab")
try:
f.readline()
except OSError:
print("OSError")
f.close()
|
# return an integere cycle length K of a permutation. Applying a permutation K-times to a list will return the original list.
def permutation_cycle_length(permutation):
initialArray = range(len(permutation))
permutedArray = range(len(permutation))
cycles = 0
while True:
permutedArray = [permutedArray[permu... |
""" Exer 3 """
mes = input("Digite o mês do seu nascimento: ")
ano = int(input("Digite o ano do seu nascimento: "))
trab = input("Trabaha em que cargo?")
print("{},nascido no mês de {} e no ano de {}, trabalha de {}. data formada: {}/{}".format(nome,mes,ano,trab,mes,ano))
|
# This is the configuration file for IngeniousCoder’s Modmail.
# Only Edit things if you know what you are doing. If not, do not change the default Value.
# ALL VARIABLES ARE REQUIRED UNLESS SPECIFIED.
# Entering a wrong value may crash the launcher and / or bot.
# CONFIG START
# MainGuildID : The main Guild’s I... |
BLOCKCHAIN = {
'class': 'thenewboston_node.business_logic.blockchain.file_blockchain.FileBlockchain',
'kwargs': {},
}
BLOCKCHAIN_URL_PATH_PREFIX = '/blockchain/'
|
n = int(input())
a = n // 365
n = n - a*365
m = n // 30
n = n - m*30
d = n
print('{} ano(s)'.format(a))
print('{} mes(es)'.format(m))
print('{} dia(s)'.format(d))
|
"""14. Faça uma função que recebe uma lista de números e retorna a média aritmética dos elementos dessa lista. Desafio"""
#information funcion
def fun(list_one, list_two):
tot = 0
notes_fist = 0
notes_second = 0
for i in list_one:
notes_fist += i
for i in list_two:
notes_second += i... |
num=[10,20,30,40,50,60]
n=[i for i in num]
print(n)
n=[10,20,30,40]
s=[10,20]
n1=[i for i in n]
print(n1)
n2=[j*j for j in n]
print(n2)
n3=[s+s for s in n ]
print(n3)
for m in n:
s.append(m*m)
print(s)
#using lambda
l=[1,2,3,4]
p=list(map(lambda a:a*a ,l))
print(p)
l=list(filter(lambda x:x%2==0,l))
print(l)... |
"""
PASSENGERS
"""
numPassengers = 3241
passenger_arriving = (
(2, 4, 9, 5, 2, 0, 7, 7, 4, 5, 1, 0), # 0
(1, 9, 7, 4, 1, 0, 6, 6, 9, 6, 1, 0), # 1
(5, 6, 8, 4, 3, 0, 8, 11, 5, 2, 1, 0), # 2
(4, 5, 5, 4, 2, 0, 8, 15, 0, 4, 4, 0), # 3
(5, 11, 13, 4, 3, 0, 11, 6, 3, 1, 1, 0), # 4
(9, 6, 8, 3, 0, 0, 7, 6, 9, ... |
"""A basic example of using the SQLAlchemy Sharding API.
Sharding refers to horizontally scaling data across multiple
databases.
The basic components of a "sharded" mapping are:
* multiple databases, each assigned a 'shard id'
* a function which can return a single shard id, given an instance
to be saved; this is c... |
#
# PySNMP MIB module CISCO-IPSEC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IPSEC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:02:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
sensorData = open('input.txt').read().splitlines()
diff = [-1, 0, 1]
key = None
trenchMap = set()
y = 0
for line in sensorData:
if not key:
key = line
elif len(line) > 0:
for x in range(len(line)):
if line[x] == '#':
trenchMap.add((x, y))
y += 1
neighboorho... |
class Config(object):
CHROME_PATH = '/Library/Application Support/Google/chromedriver76.0.3809.68'
BROWSERMOB_PATH = '/usr/local/bin/browsermob-proxy-2.1.4/bin/browsermob-proxy'
class Docker(Config):
CHROME_PATH = '/usr/local/bin/chromedriver'
|
l = float(input('Qual a largura da parede em metros: '))
a = float(input('Qual a altura da parede em metros: '))
ar = l * a
t = ar * 0.5
print('Considerando que usamos 1 litro de tinta para pintar uma parede de 2 metros quadrados! \nPara pintar uma área de {} metros quadrados é necessário {} litros de tinta'.format(ar,... |
numbers = [1, 2, 3, 4, 5]
for x in numbers:
print(x)
print("--------")
for x in reversed(numbers):
print(x)
print(numbers) |
a=int(input())
def s(n):
if n==3:return['***','* *','***']
x=s(n//3)
y=list(zip(x,x,x))
for i in range(len(y)):
y[i]=''.join(y[i])
z=list(zip(x,[' '*(n//3)]*(n//3),x))
for i in range(len(z)):
z[i]=''.join(z[i])
return y+z+y
print('\n'.join(s(a)))
|
def dictTolist(data):
result = []
if isinstance(data, dict) and data.__len__() > 0:
result.append(data)
elif isinstance(data, list) and data.__len__() > 0:
result = data
else:
result = None
return result
|
########################
# * First Solution
########################
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums)-1
while low < high:
mid = (low+high) // 2
if nums[mid] == target:
return mid
... |
# Dictionary
# length (len), check a key, get, set, add
# Dictionary 1 -------------------------------------------
print(" Dictionary with string keys ".center(44, "-"))
dict_employee_IDs = {"ID01": 'John Papa',
"ID02": 'David Thompson',
"ID03": 'Terry Gao',
... |
class Solution:
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
while not num:
return False
while not (num % 2):
num //= 2
while not (num % 3):
num //= 3
while not (num % 5):
num //= 5
... |
# Processing functions for various USMTF message formats
def tacelint(logger_item, message_dict, lines_list, processed_message_list):
prev_soi = []
prev_line = []
for line in lines_list:
if len(prev_line) == 0:
prev_line.append(line)
else:
del prev_line[0]
... |
class AnyOrderList:
"""Sequence that compares to a list, but allows any order.
This is only intended for comparison purposes, not as an actual list replacement.
"""
def __init__(self, list_):
self._list = list_
self._list.sort()
def __eq__(self, other):
assert isinstance(o... |
def first(n_1):
line_1 = set()
for i in range(n_1):
number = int(input())
line_1.add(number)
return line_1
def second(n_2):
line_2 = set()
for i in range(n_2):
number = int(input())
line_2.add(number)
return line_2
data = input().split()
n_1 = int(data[0])
n_2 =i... |
"""
List Data Type(list):
- Just Like Array following indexing
- **Unlike Arrays, list can hold HETEROGENEOUS DATA TYPE
- Repetition allowed
- Multi Dimensional
"""
# Creating a Multi-Dimensional List
print(" \n-------CREATE---------- ")
List = [['Hitesh', 'kumar', 'Sahu'], [29]]
thislist = ["0", "1", "2", "3", "4"... |
class UnityPackException(Exception):
pass
class ArchiveNotFound(UnityPackException):
pass
|
"""
[9/08/2014] Challenge #179 [Easy] You make me happy when clouds are gray...scale
https://www.reddit.com/r/dailyprogrammer/comments/2ftcb8/9082014_challenge_179_easy_you_make_me_happy_when/
#Description
The 'Daily Business' newspaper are a distributor of the most recent news concerning business. They have a proble... |
#
# Arquivo com exemplos de loop
#
# Definindo um LOOP FOR
def loopFor():
for x in range (5, 10):
print (x)
loopFor()
# Usando um LOOP FOR em uma coleçao
def loopArray ():
dias = ["seg", "ter", "quar", "quin", "sex", "sab", "dom"]
for d in dias:
print (d)
loopArray()
... |
"""
import urllib
import urllib.request
try:
site = urllib.request.urlopen('http://www.pudim.com.br')
except urllib.error.URLError:
print('O site Pudim não está acessível no momento!')
else:
print('Consegui acessar o site Pudim com sucesso!')
"""
inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweat... |
# Interview Question #5
# The problem is that we want to find duplicates in a one-dimensional array of integers in O(N) running time
# where the integer values are smaller than the length of the array!
# For example: if we have a list [1, 2, 3, 1, 5] then the algorithm can detect that there are a duplicate with value 1... |
'''
sgqlc - Simple GraphQL Client
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Access GraphQL endpoints using Python
=====================================
This package provide the following modules:
- :mod:`sgqlc.endpoint.base`: with abstract class
:class:`sgqlc.endpoint.base.BaseEndpoint` and helpful logging
utilities to t... |
START = {
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-length", b"13"),
(b"content-type", b"text/html; charset=utf-8"),
],
}
BODY1 = {"type": "http.response.body", "body": b"Hello"}
BODY2 = {"type": "http.response.body", "body": b", world!"}
async def hellowor... |
genres = {
28: "Ação",
12: "Aventura",
16: "Animação",
35: "Comédia",
80: "Crime",
99: "Documentário",
18: "Drama",
10751: "Família",
14: "Fantasia",
36: "História",
27: "Terror",
10402: "Música",
9648: "Mistério",
10749: "Romance",
878: "Ficção científica",
... |
'''
Write a program to get 3 integers from keyboard, then find out how many even and odd numbers there
are. Finally, print ofor _ in range(3)nd “odd” followed by quantity of the even and odd number.
'''
seq = (int(input()) for _ in range(3))
even = sum(1 for i in seq if i % 2 ==0)
print(f'even {even}', f'odd {3-even}'... |
load("@fbcode_macros//build_defs:platform_utils.bzl", "platform_utils")
def get_ppx_bin():
return "third-party-buck/{}/build/ocaml-lwt_ppx/lib/lwt_ppx/ppx.exe".format(platform_utils.get_platform_for_base_path(get_base_path()))
|
def append_attr(obj, attr, value):
"""
Appends value to object attribute
Attribute may be undefined
For example:
append_attr(obj, 'test', 1)
append_attr(obj, 'test', 2)
assert obj.test == [1, 2]
"""
try:
getattr(obj, attr).append(value)
exce... |
"""DataSet base class
"""
class DataSet(object):
"""Base DataSet
"""
def __init__(self, common_params, dataset_params):
"""
common_params: A params dict
dataset_params: A params dict
"""
raise NotImplementedError
def batch(self):
"""Get batch
"""
raise NotImplementedError |
# -*- coding: utf-8 -*-
class Solution:
def maxProduct(self, nums):
best_max, current_max, current_min = float('-inf'), 1, 1
for num in nums:
current_max, current_min = max(current_min * num, num, current_max * num),\
min(current_min * num, num, current_max * num)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.