content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
s = b'abcdefgabc'
print(s)
print('c:', s.rindex(b'c'))
print('c:', s.index(b'c'))
#print('z:', s.rindex(b'z'))#ValueError: subsection not found
s = bytearray(b'abcdefgabc')
print(s)
print('c:', s.rindex(bytearray(b'c')))
print('c:', s.index(bytearray(b'c')))
#print('z:', s.rindex(bytearray(b'z')))#ValueError: subsecti... | s = b'abcdefgabc'
print(s)
print('c:', s.rindex(b'c'))
print('c:', s.index(b'c'))
s = bytearray(b'abcdefgabc')
print(s)
print('c:', s.rindex(bytearray(b'c')))
print('c:', s.index(bytearray(b'c'))) |
def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
vals[i], vals[i + 1] = vals[i + 1], vals[i]
# Yield gives the "state"
yield vals... | def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
(vals[i], vals[i + 1]) = (vals[i + 1], vals[i])
yield vals
vals = [int(x) for x in input().split... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This script contains functions that don't belong to a specific category.
# The buffer_size function computes a buffer around the input ee.Element
# whilst the get_metrics function returns the accuracy metrics of the input
# classifier and test set.
#
# Author: Davide Lom... | __all__ = ['buffer_size', 'get_metrics']
def buffer_size(size):
"""
Function that uses the concept of currying to help the .map()
method take more than one argument. The function uses the input
'size' and call a nested function to create a buffer around the
centroid of the feature parsed by the .ma... |
r = '\033[31m' # red
b = '\033[34m' # blue
g = '\033[32m' # green
y = '\033[33m' # yellow
f = '\33[m'
bb = '\033[44m' # backgournd blue
def tela(mensagem, colunatxt=5):
espaco = bb + ' ' + f
mensagem = bb + y + mensagem
for i in range(12):
print('')
if i == 5:
... | r = '\x1b[31m'
b = '\x1b[34m'
g = '\x1b[32m'
y = '\x1b[33m'
f = '\x1b[m'
bb = '\x1b[44m'
def tela(mensagem, colunatxt=5):
espaco = bb + ' ' + f
mensagem = bb + y + mensagem
for i in range(12):
print('')
if i == 5:
print(espaco * colunatxt + mensagem + espaco * (50 - (len(mensage... |
"""This package contains components for working with switches."""
__all__ = (
"momentary_switch",
"momentary_switch_component",
"switch",
"switch_state",
"switch_state_change_event",
"toggle_switch",
"toggle_switch_component"
)
| """This package contains components for working with switches."""
__all__ = ('momentary_switch', 'momentary_switch_component', 'switch', 'switch_state', 'switch_state_change_event', 'toggle_switch', 'toggle_switch_component') |
tst = int(input())
ids = [ int(w) for w in input().split(',') if w != 'x' ]
def wait_time(bus_id):
return (bus_id - tst % bus_id, bus_id)
min_id = min(map(wait_time, ids))
print(f"{min_id=}")
| tst = int(input())
ids = [int(w) for w in input().split(',') if w != 'x']
def wait_time(bus_id):
return (bus_id - tst % bus_id, bus_id)
min_id = min(map(wait_time, ids))
print(f'min_id={min_id!r}') |
# Aiden Baker
# 2/12/2021
# DoNow103
print(2*3*5)
print("abc")
print("abc"+"bde") | print(2 * 3 * 5)
print('abc')
print('abc' + 'bde') |
name = "ServerName"
user = "mongo"
japd = None
host = "hostname"
port = 27017
auth = False
auth_db = "admin"
use_arg = True
use_uri = False
repset = "ReplicaSet"
repset_hosts = ["host1:27017", "host2:27017"]
| name = 'ServerName'
user = 'mongo'
japd = None
host = 'hostname'
port = 27017
auth = False
auth_db = 'admin'
use_arg = True
use_uri = False
repset = 'ReplicaSet'
repset_hosts = ['host1:27017', 'host2:27017'] |
def solution(xs):
"""Returns integer representing maximum power output of solar panel array
Args:
xs: List of integers representing power output of
each of the solar panels in a given array
"""
negatives = []
smallest_negative = None
positives = []
contains_panel_with_zero_p... | def solution(xs):
"""Returns integer representing maximum power output of solar panel array
Args:
xs: List of integers representing power output of
each of the solar panels in a given array
"""
negatives = []
smallest_negative = None
positives = []
contains_panel_with_zero_p... |
class GlobalConfig:
def __init__(self):
self.logger_name = "ecom"
self.log_level = "INFO"
self.vocab_filename = "products.vocab"
self.labels_filename = "labels.vocab"
self.model_filename = "classifier.mdl"
gconf = GlobalConfig()
| class Globalconfig:
def __init__(self):
self.logger_name = 'ecom'
self.log_level = 'INFO'
self.vocab_filename = 'products.vocab'
self.labels_filename = 'labels.vocab'
self.model_filename = 'classifier.mdl'
gconf = global_config() |
def fact(n):
if n > 0:
return (n*fact(n - 1))
else:
return 1
print(fact(5))
| def fact(n):
if n > 0:
return n * fact(n - 1)
else:
return 1
print(fact(5)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:39:32 2020
@author: zo
"""
def tokenizer_and_model_config_mismatch(config, tokenizer):
"""
Check for tokenizer and model config miss match.
Args:
config:
model config.
tokenizer:
tokenizer... | """
Created on Tue Nov 3 14:39:32 2020
@author: zo
"""
def tokenizer_and_model_config_mismatch(config, tokenizer):
"""
Check for tokenizer and model config miss match.
Args:
config:
model config.
tokenizer:
tokenizer.
Raises:
ValueError: A special tok... |
#!/usr/bin/env python3
class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self._... | class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self.__resource.metadata.name
... |
BOT_NAME = 'AmazonHeadSetScraping'
SPIDER_MODULES = ['AmazonHeadSetScraping.spiders']
NEWSPIDER_MODULE = 'AmazonHeadSetScraping.spiders'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
DOWNLOAD_DELAY = 3
DOWNLOAD_TIMEOUT = 30
RANDOMIZE_DOWNLOAD_DELAY = True
REACTOR_THRE... | bot_name = 'AmazonHeadSetScraping'
spider_modules = ['AmazonHeadSetScraping.spiders']
newspider_module = 'AmazonHeadSetScraping.spiders'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
download_delay = 3
download_timeout = 30
randomize_download_delay = True
reactor_threadpo... |
#!/usr/bin/python
DIR = "data_tmp/"
FILES = {}
FILES['20_avg'] = []
FILES['40_avg'] = []
FILES['50_avg'] = []
FILES['60_avg'] = []
FILES['80_avg'] = []
FILES['20_opt'] = []
FILES['40_opt'] = []
FILES['50_opt'] = []
FILES['60_opt'] = []
FILES['80_opt'] = []
FILES['20_avg'].append("04_attk2_avg20_20_test")
FILES['20_a... | dir = 'data_tmp/'
files = {}
FILES['20_avg'] = []
FILES['40_avg'] = []
FILES['50_avg'] = []
FILES['60_avg'] = []
FILES['80_avg'] = []
FILES['20_opt'] = []
FILES['40_opt'] = []
FILES['50_opt'] = []
FILES['60_opt'] = []
FILES['80_opt'] = []
FILES['20_avg'].append('04_attk2_avg20_20_test')
FILES['20_avg'].append('04_attk2... |
class Int32CollectionConverter(TypeConverter):
"""
Converts an System.Windows.Media.Int32Collection to and from other data types.
Int32CollectionConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,sourceType: Type) -> b... | class Int32Collectionconverter(TypeConverter):
"""
Converts an System.Windows.Media.Int32Collection to and from other data types.
Int32CollectionConverter()
"""
def can_convert_from(self, *__args):
"""
CanConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,sourceType: Ty... |
def list_of_lists(l, n):
q = len(l) // n
r = len(l) % n
if r == 0:
return [l[i * n:(i + 1) * n] for i in range(q)]
else:
return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)]
| def list_of_lists(l, n):
q = len(l) // n
r = len(l) % n
if r == 0:
return [l[i * n:(i + 1) * n] for i in range(q)]
else:
return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)] |
"""Type stubs for gi.repository.GLib."""
class Error(Exception):
"""Horrific GLib Error God Object."""
@property
def message(self) -> str: ...
class MainLoop:
def run(self) -> None: ...
def quit(self) -> None: ... | """Type stubs for gi.repository.GLib."""
class Error(Exception):
"""Horrific GLib Error God Object."""
@property
def message(self) -> str:
...
class Mainloop:
def run(self) -> None:
...
def quit(self) -> None:
... |
class PrefixList:
""" The PrefixList holds the data received from routing registries and
the validation results of this data. """
def __init__(self, name):
self.name = name
self.members = {}
def __iter__(self):
for asn in self.members:
yield self.members[asn]
... | class Prefixlist:
""" The PrefixList holds the data received from routing registries and
the validation results of this data. """
def __init__(self, name):
self.name = name
self.members = {}
def __iter__(self):
for asn in self.members:
yield self.members[asn]
... |
def find_common_number(*args):
result = args[0]
for arr in args:
result = insect_array(result, arr)
return result
def union_array(arr1, arr2):
return list(set.union(arr1, arr2))
def insect_array(arr1, arr2):
return list(set(arr1) & set(arr2))
arr1 = [1,5,10,20,40,80]
arr2 = [6,27,20,80,100]
arr3 = [... | def find_common_number(*args):
result = args[0]
for arr in args:
result = insect_array(result, arr)
return result
def union_array(arr1, arr2):
return list(set.union(arr1, arr2))
def insect_array(arr1, arr2):
return list(set(arr1) & set(arr2))
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 27, 20... |
# Question 2
# Convert all units of time into seconds.
day = float(input("Enter number of days: "))
hour = float(input("Enter number of hours: "))
minute = float(input("Enter number of minutes: "))
second = float(input("Enter number of seconds: "))
day = day * 3600 * 24
hour *= 3600
minute *= 60
second = day + hour + ... | day = float(input('Enter number of days: '))
hour = float(input('Enter number of hours: '))
minute = float(input('Enter number of minutes: '))
second = float(input('Enter number of seconds: '))
day = day * 3600 * 24
hour *= 3600
minute *= 60
second = day + hour + minute + second
print('Time: ' + str(round(second, 2)) +... |
text = """
ar-EG* Female "Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)"
ar-SA Male "Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)"
ca-ES Female "Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)"
cs-CZ Male "Microsoft Server Speech Text to Speech Voice (cs-CZ, Vit)"
da-... | text = '\nar-EG* \tFemale \t"Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)"\nar-SA \tMale \t"Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)"\nca-ES \tFemale \t"Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)"\ncs-CZ \tMale \t"Microsoft Server Speech Text to Speech Voice (cs-CZ,... |
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""
0 1 2. 3
[[1,2],[3],[3],[]]
^
paths = [[0, 1, 3], [0,2,3]]
path =
"""
end = len(graph)-1
@lru_cache(maxsize=... | class Solution:
def all_paths_source_target(self, graph: List[List[int]]) -> List[List[int]]:
"""
0 1 2. 3
[[1,2],[3],[3],[]]
^
paths = [[0, 1, 3], [0,2,3]]
path =
"""
end = len(graph) - 1
@lru_cache(maxsize=No... |
class QueueMember:
def __init__(self, number):
self.number = number
self.next = self
self.prev = self
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def set_prev(self, prev):
self.prev = prev
def get_prev(self):
... | class Queuemember:
def __init__(self, number):
self.number = number
self.next = self
self.prev = self
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def set_prev(self, prev):
self.prev = prev
def get_prev(self):
... |
class AgedPeer:
def __init__(self, address, age=0):
self.address = address
self.age = age
def __eq__(self, other):
if isinstance(other, AgedPeer):
return self.address == other.address
return False
@staticmethod
def from_json(json_object):
return AgedPeer(json_object['address'], json_object['age']) | class Agedpeer:
def __init__(self, address, age=0):
self.address = address
self.age = age
def __eq__(self, other):
if isinstance(other, AgedPeer):
return self.address == other.address
return False
@staticmethod
def from_json(json_object):
return age... |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
EVENT_SOURCE = 'DatadogTest'
EVENT_ID = 9000
EVENT_CATEGORY = 42
INSTANCE = {
'legacy_mode': False,
'timeout': 2,
'path': 'Application',
'filters': {'source': [EVENT_SOURCE]},
}
| event_source = 'DatadogTest'
event_id = 9000
event_category = 42
instance = {'legacy_mode': False, 'timeout': 2, 'path': 'Application', 'filters': {'source': [EVENT_SOURCE]}} |
"""
Entradas
Sueldo_bruto-->float-->sa
Salidas
Categoria-->int-->c
Sueldo_neto-->float-->sn
"""
sa=float(input("Digite el salario bruto: "))
sn=0.0#float
if(sa>=5_000_000):
sn=(sa*0.10)+sa
c=1
elif(sa<5_000_000 and sa>=4_300_000):
sn=(sa*0.15)+sa
c=2
elif(sa<4_300_000 and sa>=3_600_000):
sn=(sa*0.20)+sa
c=3... | """
Entradas
Sueldo_bruto-->float-->sa
Salidas
Categoria-->int-->c
Sueldo_neto-->float-->sn
"""
sa = float(input('Digite el salario bruto: '))
sn = 0.0
if sa >= 5000000:
sn = sa * 0.1 + sa
c = 1
elif sa < 5000000 and sa >= 4300000:
sn = sa * 0.15 + sa
c = 2
elif sa < 4300000 and sa >= 3600000:
sn = ... |
# 3/15
num_of_pages = int(input()) # < 10000
visited = set()
shortest_path = 0
instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)]
def choose_paths(page, history):
if page not in visited:
visited.add(page)
if not len(instructions[page - 1]): # if this page doesn't n... | num_of_pages = int(input())
visited = set()
shortest_path = 0
instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)]
def choose_paths(page, history):
if page not in visited:
visited.add(page)
if not len(instructions[page - 1]):
global shortest_path
if shortest... |
conn_info = {'host': 'vertica.server.ip.address',
'port': 5433,
'user': 'readonlyuser',
'password': 'XXXXXX',
'database': '',
# 10 minutes timeout on queries
'read_timeout': 600,
# default throw error on invalid UTF-8 results
... | conn_info = {'host': 'vertica.server.ip.address', 'port': 5433, 'user': 'readonlyuser', 'password': 'XXXXXX', 'database': '', 'read_timeout': 600, 'unicode_error': 'strict', 'ssl': False, 'connection_timeout': 5} |
# Created by MechAviv
# Quest ID :: 25562
# Fostering the Dark
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("Dark magic is so much easier than light...")
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay("But I do not fully understand it. With... | sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext('Dark magic is so much easier than light...')
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay('But I do not fully understand it. With every minor touch, I feel the lust for destruction well up within... |
# (n, k) represent nCk
# (N+M-1, N-1)-(N+M-1, N) = (N-M)/(N+M) * (N+M, N)
def solution():
T = int(input())
for i in range(T):
N, M = map(float, input().split(' '))
print('Case #%d: %f' % (i+1, (N-M)/(N+M)))
solution()
| def solution():
t = int(input())
for i in range(T):
(n, m) = map(float, input().split(' '))
print('Case #%d: %f' % (i + 1, (N - M) / (N + M)))
solution() |
class HttpException(Exception):
"""
A base exception designed to support all API error handling.
All exceptions should inherit from this or a subclass of it (depending on the usage),
this will allow all apps and libraries to maintain a common exception chain
"""
def __init__(self, message, debug... | class Httpexception(Exception):
"""
A base exception designed to support all API error handling.
All exceptions should inherit from this or a subclass of it (depending on the usage),
this will allow all apps and libraries to maintain a common exception chain
"""
def __init__(self, message, debu... |
# Find len of ll. k = k%l. Then mode l-k-1 steps and break the ll. Add the remaining part of the LL in the front.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListN... | class Solution:
def rotate_right(self, head: ListNode, k: int) -> ListNode:
(l, ptr) = (0, head)
while ptr:
l += 1
ptr = ptr.next
if l == 0 or k % l == 0:
return head
k = k % l
ptr = head
for _ in range(l - k - 1):
ptr ... |
MY_MAC = ""
MY_IP = ""
IFACE = ""
GATEWAY_MAC = ""
_SRC_DST = {}
PROTO = ""
CMD = ""
STOP_SNIFF = False | my_mac = ''
my_ip = ''
iface = ''
gateway_mac = ''
_src_dst = {}
proto = ''
cmd = ''
stop_sniff = False |
"""Top-level package for Image to LaTeX."""
__author__ = """Oscar Arbelaez"""
__email__ = 'odarbelaeze@gmail.com'
__version__ = '0.2.1'
| """Top-level package for Image to LaTeX."""
__author__ = 'Oscar Arbelaez'
__email__ = 'odarbelaeze@gmail.com'
__version__ = '0.2.1' |
# Convert the temperature from Fahrenheit to Celsius in the
# function below. You can use this formula:
# C = (F - 32) * 5/9
# Round the returned result to 3 decimal places.
# You don't have to handle input, just implement the function
# below.
# Also, make sure your function returns the value. Please do NOT
# pr... | def fahrenheit_to_celsius(fahrenheit):
return round((fahrenheit - 32) * 5 / 9, 3) |
"""
Sponge Knowledge Base
Action metadata Record type - sub-arguments
"""
def createBookRecordType(name):
return RecordType(name, [
IntegerType("id").withNullable().withLabel("Identifier").withFeature("visible", False),
StringType("author").withLabel("Author"),
StringType("title").withLabel... | """
Sponge Knowledge Base
Action metadata Record type - sub-arguments
"""
def create_book_record_type(name):
return record_type(name, [integer_type('id').withNullable().withLabel('Identifier').withFeature('visible', False), string_type('author').withLabel('Author'), string_type('title').withLabel('Title')])
class... |
def zero(f=lambda a: a):
return f(0)
def one(f=lambda a: a):
return f(1)
def two(f=lambda a: a):
return f(2)
def three(f=lambda a: a):
return f(3)
def four(f=lambda a: a):
return f(4)
def five(f=lambda a: a):
return f(5)
def six(f=lambda a: a):
return f(6)
def seven(f=lambda a: a):
return f(7)
def eight(f=lambd... | def zero(f=lambda a: a):
return f(0)
def one(f=lambda a: a):
return f(1)
def two(f=lambda a: a):
return f(2)
def three(f=lambda a: a):
return f(3)
def four(f=lambda a: a):
return f(4)
def five(f=lambda a: a):
return f(5)
def six(f=lambda a: a):
return f(6)
def seven(f=lambda a: a):
... |
"""
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
list_a = [int(i) for i in a[::-1]]
list_b ... | """
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
list_a = [int(i) for i in a[::-1]]
list_... |
# coding=utf-8
"""Hive: microservice powering social networks on the dPay blockchain.
Hive is a "consensus interpretation" layer for the dPay blockchain,
maintaining the state of social features such as post feeds, follows,
and communities. Written in Python, it synchronizes an SQL database
with chain state, providin... | """Hive: microservice powering social networks on the dPay blockchain.
Hive is a "consensus interpretation" layer for the dPay blockchain,
maintaining the state of social features such as post feeds, follows,
and communities. Written in Python, it synchronizes an SQL database
with chain state, providing developers wit... |
def ChangeText(s):
print('ChangeText() received:', s)
decoded = s.decode("utf-16-le")
print('Decoded:', decoded)
returned = None
if decoded == 'hello':
returned = 'world'
if returned is None:
return None
else:
b = returned.encode("utf-16-le")... | def change_text(s):
print('ChangeText() received:', s)
decoded = s.decode('utf-16-le')
print('Decoded:', decoded)
returned = None
if decoded == 'hello':
returned = 'world'
if returned is None:
return None
else:
b = returned.encode('utf-16-le') + b'\x00\x00'
re... |
print("""interface GigabitEthernet0/3.100\nvlan 100\nnameif wireless_user-v100\nsecurity-level 75\nip addr 10.1.100.1 255.255.255.0
interface GigabitEthernet0/3.101\nvlan 101\nnameif wireless_user-v101\nsecurity-level 75\nip addr 10.1.101.1 255.255.255.0
interface GigabitEthernet0/3.102\nvlan 102\nnameif wireless_use... | print('interface GigabitEthernet0/3.100\nvlan 100\nnameif wireless_user-v100\nsecurity-level 75\nip addr 10.1.100.1 255.255.255.0\ninterface GigabitEthernet0/3.101\nvlan 101\nnameif wireless_user-v101\nsecurity-level 75\nip addr 10.1.101.1 255.255.255.0\ninterface GigabitEthernet0/3.102\nvlan 102\nnameif wireless_user-... |
#! /usr/bin/env python3
# coding:utf-8
def main():
#answer = [(a, b, c) for a in range(21) for b in range(34) for c in range(101-a-b)
# if a*5 + b*3 +c/3 == 100 and a+b+c == 100]
#print(answer)
for a in range(21):
for b in range(34):
c = 100-a-b
if a*5 + b*3 +c... | def main():
for a in range(21):
for b in range(34):
c = 100 - a - b
if a * 5 + b * 3 + c / 3 == 100:
print(a, b, c)
if __name__ == '__main__':
main() |
name = "qt"
version = "4.8.7"
description = \
"""
Qt
"""
build_requires = [
"python-2.7"
]
def commands():
# export CMAKE_MODULE_PATH=$CMAKE_MODULE_PATH:!ROOT!/cmake
# export QTDIR=!ROOT!
# export QT_INCLUDE_DIR=!ROOT!/include
# export QT_LIB_DIR=!ROOT!/lib
# export LD_LIBRARY_PA... | name = 'qt'
version = '4.8.7'
description = '\n Qt\n '
build_requires = ['python-2.7']
def commands():
env.LD_LIBRARY_PATH.prepend('{root}/lib')
env.QT_ROOT = '{root}'
if building:
env.CMAKE_MODULE_PATH.append('{root}/cmake')
uuid = 'repository.qt' |
def getCommonLetters(word1, word2):
return ''.join(sorted(set(word1).intersection(set(word2))))
print(getCommonLetters('apple', 'strw'))
print(getCommonLetters('sing', 'song'))
| def get_common_letters(word1, word2):
return ''.join(sorted(set(word1).intersection(set(word2))))
print(get_common_letters('apple', 'strw'))
print(get_common_letters('sing', 'song')) |
class ParseFailure(Exception):
def __init__(self, message, offset=None, column=None, row=None, text=None):
self.message = message
self.offset = offset
self.column = column
self.row = row
self.text = text
super(ParseFailure, self).__init__(
self.message,
... | class Parsefailure(Exception):
def __init__(self, message, offset=None, column=None, row=None, text=None):
self.message = message
self.offset = offset
self.column = column
self.row = row
self.text = text
super(ParseFailure, self).__init__(self.message, self.offset, s... |
#
# @lc app=leetcode id=71 lang=python3
#
# [71] Simplify Path
#
# @lc code=start
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split('/'):
if token in ('', '.'):
pass
elif token == '..':
if stack:
... | class Solution:
def simplify_path(self, path: str) -> str:
stack = []
for token in path.split('/'):
if token in ('', '.'):
pass
elif token == '..':
if stack:
stack.pop()
else:
stack.append(token)... |
"""A walrus pattern looks like d := datetime(year=2020, month=m). It matches
only if its sub-pattern also matches. It binds whatever the sub-pattern match
does, and also binds the named variable to the entire object.
"""
# TODO
# match group_shapes():
# case [], [point := Point(x, y), *other]:
# print(f"... | """A walrus pattern looks like d := datetime(year=2020, month=m). It matches
only if its sub-pattern also matches. It binds whatever the sub-pattern match
does, and also binds the named variable to the entire object.
""" |
test_cases = int(input())
while test_cases > 0:
burles = int(input())
optimal = 0
while True:
# The main logic here is to divide the burles into small parts of burles, as, that would be optimal. If Mishka sell 10 burles, he'd get one back; if less, nothing, if higher than 10 and lower than 20 th... | test_cases = int(input())
while test_cases > 0:
burles = int(input())
optimal = 0
while True:
partition = int(burles / 10) * 10
optimal += partition
burles_left = burles - partition
burles = int(burles / 10) + burles_left
if burles < 10:
optimal += burles
... |
def MathOp():
classic_division=3/2
floor_division=3//2
modulus=3%2
power=3**2
return [classic_division, floor_division, modulus, power]
[classic_division, floor_division, modulus, power]=MathOp()
print(classic_division)
print(floor_division)
print(modulus)
print(power) | def math_op():
classic_division = 3 / 2
floor_division = 3 // 2
modulus = 3 % 2
power = 3 ** 2
return [classic_division, floor_division, modulus, power]
[classic_division, floor_division, modulus, power] = math_op()
print(classic_division)
print(floor_division)
print(modulus)
print(power) |
"""
Python implementation of a linked list
"""
# TODO docstrings
class Node(object):
def __init__(self, data=None):
self.data = data
self.next_node = None
class LinkedList(object):
def __init__(self):
self.head = None
self.size = 0
def __getitem__(self, index):
... | """
Python implementation of a linked list
"""
class Node(object):
def __init__(self, data=None):
self.data = data
self.next_node = None
class Linkedlist(object):
def __init__(self):
self.head = None
self.size = 0
def __getitem__(self, index):
if index < 0 or ind... |
#
# PySNMP MIB module Juniper-Multicast-Router-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-Multicast-Router-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:03:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) ... |
#!/usr/bin/env python3
"""Reading in and writing out files"""
def main():
# old method for opening files
# requires closing the file object when done
myfile = open("vendor.txt", 'r')
# new method for opening files
# closes file when indentation ends
with open('vendor-ips.txt', 'w') as myoutfil... | """Reading in and writing out files"""
def main():
myfile = open('vendor.txt', 'r')
with open('vendor-ips.txt', 'w') as myoutfile:
for line in myfile.readlines():
splitline = line.split(' ')
print(splitline[-1].strip())
myfile.close()
main() |
# Global Moderation
ACCOUNT_BAN = "ACB"
ACCOUNT_UNBAN = "UBN"
ACCOUNT_TIMEOUT = "TMO"
SERVER_KICK = "KIK"
PROMOTE_GLOBAL_OP = "AOP"
DEMOTE_GLOBAL_OP = "DOP"
LIST_ALTS = "AWC"
BROADCAST = "BRO"
REWARD = "RWD"
RELOAD_SERVER_CONFIG = "RLD"
# Channels
LIST_OFFICAL_CHANNELS = "CHA"
LIST_PRIVATE_CHANNELS = "ORS"
INITIAL_CHA... | account_ban = 'ACB'
account_unban = 'UBN'
account_timeout = 'TMO'
server_kick = 'KIK'
promote_global_op = 'AOP'
demote_global_op = 'DOP'
list_alts = 'AWC'
broadcast = 'BRO'
reward = 'RWD'
reload_server_config = 'RLD'
list_offical_channels = 'CHA'
list_private_channels = 'ORS'
initial_channel_data = 'ICH'
timeout = 'CTU... |
# Suppose you have a multiplication table that is N by N. That is, a 2D array
# where the value at the i-th row and j-th column is (i + 1) * (j + 1)
# (if 0-indexed) or i * j (if 1-indexed).
# Given integers N and X, write a function that returns the number of times X
# appears as a value in an N by N multiplica... | def count_appearance(n, x):
count = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
multip = i * j
if multip > x:
break
if multip == x:
count += 1
break
return count
if __name__ == '__main__':
print(count_a... |
class Solution(object):
def minTotalDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# basically try to solve for median for 1D array twice
vertical_list = []
horizontal_list = []
for i in range(len(grid)):
for j in ran... | class Solution(object):
def min_total_distance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
vertical_list = []
horizontal_list = []
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
... |
"""
Easy
1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/)
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are
distinct. Your goal is to form arr by concatenating the arrays... | """
Easy
1640. [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/)
You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are
distinct. Your goal is to form arr by concatenating the arrays... |
def maxSubArray(X):
# Store sum, start, end
result = (X[0], 0, 0)
for i in range(0, len(X)):
for j in range(i, len(X)):
subSum = 0
for k in range(i, j + 1):
subSum += X[k]
if result[0] < subSum:
result = (subSum, i, j)
return result
| def max_sub_array(X):
result = (X[0], 0, 0)
for i in range(0, len(X)):
for j in range(i, len(X)):
sub_sum = 0
for k in range(i, j + 1):
sub_sum += X[k]
if result[0] < subSum:
result = (subSum, i, j)
return result |
# -*- coding: utf-8 -*-
a = []
b = a
c = []
print("id(a) = ", id(a))
print("id(b) = ", id(b))
print("id(c) = ", id(c))
a.append(1)
b.append(2)
c.append(3)
print("id(a) = ", id(a))
print("id(b) = ", id(b))
print("id(c) = ", id(c))
| a = []
b = a
c = []
print('id(a) = ', id(a))
print('id(b) = ', id(b))
print('id(c) = ', id(c))
a.append(1)
b.append(2)
c.append(3)
print('id(a) = ', id(a))
print('id(b) = ', id(b))
print('id(c) = ', id(c)) |
__all__ = ('ConnectionClosed',)
class ConnectionClosed(Exception):
"""Exception indicating that the connection to Discord fully closed.
This is raised when the connection cannot naturally reconnect and the
program should exit - which happens if Discord unexpectedly closes the
socket during the crucia... | __all__ = ('ConnectionClosed',)
class Connectionclosed(Exception):
"""Exception indicating that the connection to Discord fully closed.
This is raised when the connection cannot naturally reconnect and the
program should exit - which happens if Discord unexpectedly closes the
socket during the crucial... |
"""
.. module:: check_in_known_missions
:synopsis: Given a string, checks if it's in a list of known mission values.
.. moduleauthor:: Scott W. Fleming <fleming@stsci.edu>
"""
#--------------------
def check_in_known_missions(istring, known_missions, exclude_missions):
"""
Checks if mission string is in ... | """
.. module:: check_in_known_missions
:synopsis: Given a string, checks if it's in a list of known mission values.
.. moduleauthor:: Scott W. Fleming <fleming@stsci.edu>
"""
def check_in_known_missions(istring, known_missions, exclude_missions):
"""
Checks if mission string is in list of known values.
... |
# read_stocks.py
# Read the current data of the stock market and show them if need be
def is_open(api):
#Check if market is closed
clock = api.get_clock()
print('The market is {}'.format('open.' if clock.is_open else 'closed.'))
### Please check again here
def read_market_data(api,input_stocks,intervals,ma_i... | def is_open(api):
clock = api.get_clock()
print('The market is {}'.format('open.' if clock.is_open else 'closed.'))
def read_market_data(api, input_stocks, intervals, ma_interval):
barset = api.get_barset(input_stocks, 'day', limit=intervals + ma_interval)
stock_bars = barset[input_stocks]
week_ope... |
with open('input.txt') as file:
sum = 0
group = None
for line in file:
if line.strip():
if group is None:
group = set(line.strip())
else:
group = group.intersection(line.strip())
else:
print("group:", ''.join(sorted(group))... | with open('input.txt') as file:
sum = 0
group = None
for line in file:
if line.strip():
if group is None:
group = set(line.strip())
else:
group = group.intersection(line.strip())
else:
print('group:', ''.join(sorted(group)))... |
#
# PySNMP MIB module CISCO-COMMON-MGMT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-MGMT-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 11:53:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ... |
class Edge:
pass
class Loop(Edge):
pass
class ParallelEdge(Edge):
pass
| class Edge:
pass
class Loop(Edge):
pass
class Paralleledge(Edge):
pass |
# Division with int
# Prompt user for x
x = int(input("x: "))
# Prompt user for y
y = int(input("y: "))
# Perform division
print(x / y)
| x = int(input('x: '))
y = int(input('y: '))
print(x / y) |
# Python - 2.7.6
Test.describe('combine names')
Test.it('example tests')
Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens')
Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back')
Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent')
| Test.describe('combine names')
Test.it('example tests')
Test.assert_equals(combine_names('James', 'Stevens'), 'James Stevens')
Test.assert_equals(combine_names('Davy', 'Back'), 'Davy Back')
Test.assert_equals(combine_names('Arthur', 'Dent'), 'Arthur Dent') |
"""
Leetcode problem: https://leetcode.com/problems/super-egg-drop/
"""
def solve_dp(K: int, N: int):
def solve(k, moves):
dp = [None] * (k + 1)
for i in range(k + 1):
dp[i] = [0] * (moves + 1)
for i in range(1, k + 1):
for j in range(1, moves + 1):
... | """
Leetcode problem: https://leetcode.com/problems/super-egg-drop/
"""
def solve_dp(K: int, N: int):
def solve(k, moves):
dp = [None] * (k + 1)
for i in range(k + 1):
dp[i] = [0] * (moves + 1)
for i in range(1, k + 1):
for j in range(1, moves + 1):
... |
a,b = [int(i) for i in input().split()]
def gcd(a,b):
if b==0:
print(a)
quit()
c = a%b
gcd(b,c)
if a>b:
gcd(a,b)
else:
gcd(b,a) | (a, b) = [int(i) for i in input().split()]
def gcd(a, b):
if b == 0:
print(a)
quit()
c = a % b
gcd(b, c)
if a > b:
gcd(a, b)
else:
gcd(b, a) |
DEFAULT_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {
'()': 'colorlog.ColoredFormatter',
'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s'
}
},
'handlers': {
... | default_logging_config = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'console': {'()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(levelname)s][%(name)s]: %(reset)s%(message)s'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter... |
class Solution:
def numberToWords(self, num: int) -> str:
"""
:type num: int
:rtype: str
"""
if not num: return 'Zero'
onedigit = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
twodigits_10to19 = {1... | class Solution:
def number_to_words(self, num: int) -> str:
"""
:type num: int
:rtype: str
"""
if not num:
return 'Zero'
onedigit = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
twodigits_10to1... |
# Write an algorithm to determine if a number n is "happy".
# A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cy... | class Solution:
def is_happy(self, n: int, s=set()) -> bool:
if n == 1:
return True
if n in s:
return False
total = 0
s.add(n)
for i in str(n):
total += int(i) ** 2
return self.isHappy(total)
s = 19
s = 11
s = 10
print(solution().i... |
def Mean_of_All_Digits(num):
arr = []
n = num
while n > 0:
r = n % 10
n = n // 10
arr.append(r)
return sum(arr)//len(arr)
print(Mean_of_All_Digits(42))
print(Mean_of_All_Digits(12345))
print(Mean_of_All_Digits(666)) | def mean_of__all__digits(num):
arr = []
n = num
while n > 0:
r = n % 10
n = n // 10
arr.append(r)
return sum(arr) // len(arr)
print(mean_of__all__digits(42))
print(mean_of__all__digits(12345))
print(mean_of__all__digits(666)) |
#make a way to quickly make a new dictionary with the right properties
def tool_dict(line):
return {"name":line[0],"2015":line[1],"2016":line[2],"2017":line[3],"2018":line[4],"2019":line[5],"total":sum(line[1:])}
#open file
file=open("tools_dh_proceedings.csv")
print("Opened tools_dh_proceedings.csv")
#throw ... | def tool_dict(line):
return {'name': line[0], '2015': line[1], '2016': line[2], '2017': line[3], '2018': line[4], '2019': line[5], 'total': sum(line[1:])}
file = open('tools_dh_proceedings.csv')
print('Opened tools_dh_proceedings.csv')
file.readline()
lines = file.readlines()
file.close()
print('File has been read.... |
numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42]
is_there_any_odd_number = False
is_odd = lambda num: num % 2 == 1
def fun(num):
print(f"fun({num})")
return num % 2 == 1
for num in numbers:
if is_odd(num):
is_there_any_odd_number = True
break
print(is_there_any_odd_number)
# print(any(map(... | numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42]
is_there_any_odd_number = False
is_odd = lambda num: num % 2 == 1
def fun(num):
print(f'fun({num})')
return num % 2 == 1
for num in numbers:
if is_odd(num):
is_there_any_odd_number = True
break
print(is_there_any_odd_number)
print(all(map(fun, nu... |
def bfs(graph, source, target):
visited = {k: False for k in graph}
distance = {k: 1000000 for k in graph}
queue = []
visited[source] = True
distance[source] = 0
queue.append(source)
while queue:
node = queue.pop(0)
for n in graph[node]:
if not visited[n]:
... | def bfs(graph, source, target):
visited = {k: False for k in graph}
distance = {k: 1000000 for k in graph}
queue = []
visited[source] = True
distance[source] = 0
queue.append(source)
while queue:
node = queue.pop(0)
for n in graph[node]:
if not visited[n]:
... |
_base_ = [
# '../_base_/models/deeplabv3plus_r18-d8.py',
'../_base_/models/deeplabv3plus_r50-d8.py',
'../_base_/datasets/boulderset.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_40k.py'
]
norm_cfg = dict(type='BN', requires_grad=True)
num_classes = 3
model = dict(
pretraine... | _base_ = ['../_base_/models/deeplabv3plus_r50-d8.py', '../_base_/datasets/boulderset.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py']
norm_cfg = dict(type='BN', requires_grad=True)
num_classes = 3
model = dict(pretrained='torchvision://resnet18', backbone=dict(type='ResNet', depth=18, norm_cf... |
print('''
,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba,
a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8
8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88
"8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88
`"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"Ybb... | print('\n ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, \na8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P\' "Y8 \n8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 \n"8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 \n `"Ybbd8"\' `"8bbdP"Y8 `"Ybbd8"\' `"Y... |
PARAMETERS = {
# Input params
"training_data_patterns": [
"data/tfrecord_v2/20180101.gz"
],
"evaluation_data_patterns":[
"data/tfrecord_v2/20180101.gz"
],
# Training data loader properties
"buffer_size": 10000,
"num_parsing_threads": 16,
"num_parallel_readers": 4,
... | parameters = {'training_data_patterns': ['data/tfrecord_v2/20180101.gz'], 'evaluation_data_patterns': ['data/tfrecord_v2/20180101.gz'], 'buffer_size': 10000, 'num_parsing_threads': 16, 'num_parallel_readers': 4, 'prefetch_buffer_size': 1, 'compression_type': 'GZIP', 'initializer_gain': 1.0, 'hidden_size': 32, 'num_hidd... |
# encoding: utf-8
"""Dict of COMMANDS."""
# clArg: [function, help, args:{
# shortCommand, LongCommand, choices
# store_true, help
# }]
COMMANDS = {
# ---------------------
# SERVICE_DEVICE_CONFIG
# ---------------------
'login': ['login', 'Attempts to login to rou... | """Dict of COMMANDS."""
commands = {'login': ['login', 'Attempts to login to router'], 'reboot': ['reboot', 'Reboot Router', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP Response']}], 'check_fw': ['check_new_firmware', 'Check for new firmware', {'test': ['-t', '--test', False, 'store_true', 'Output SOAP ... |
class Solution:
def FindGreatestSumOfSubArray(self, array):
if not array:
return 0
cur_sum, max_sum = array[0], array[0]
for i in range(1, len(array)):
cur_sum = array[i] if cur_sum <= 0 else cur_sum + array[i]
max_sum = cur_sum if cur_sum > max_sum else... | class Solution:
def find_greatest_sum_of_sub_array(self, array):
if not array:
return 0
(cur_sum, max_sum) = (array[0], array[0])
for i in range(1, len(array)):
cur_sum = array[i] if cur_sum <= 0 else cur_sum + array[i]
max_sum = cur_sum if cur_sum > max_... |
def main():
# get
sales = get_sales()
advanced_pay = get_advanced_pay()
rate = determined_comm_rate(sales)
# calc
pay = sales * rate - advanced_pay
# print
print("The pay is $", format(pay, ",.2f"), sep='')
return
def get_sales():
return float(input("Sales: $"))
def determined_... | def main():
sales = get_sales()
advanced_pay = get_advanced_pay()
rate = determined_comm_rate(sales)
pay = sales * rate - advanced_pay
print('The pay is $', format(pay, ',.2f'), sep='')
return
def get_sales():
return float(input('Sales: $'))
def determined_comm_rate(sales):
if sales < ... |
Dataset_Path = dict(
CULane = "/home/lion/Dataset/CULane/data/CULane",
Tusimple = "/home/lion/Dataset/tusimple"
)
| dataset__path = dict(CULane='/home/lion/Dataset/CULane/data/CULane', Tusimple='/home/lion/Dataset/tusimple') |
for _ in range(int(input())):
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
visited = [False] * (n + 1)
cycles = []
for i in range(1, n + 1):
cycle = []
while not visited[i]:
visited[i] = True
cycle += i,
i = p[i]
... | for _ in range(int(input())):
(n, k) = map(int, input().split())
p = [0] + list(map(int, input().split()))
visited = [False] * (n + 1)
cycles = []
for i in range(1, n + 1):
cycle = []
while not visited[i]:
visited[i] = True
cycle += (i,)
i = p[i]
... |
def f(x = True):
'whether x is a correct word or not'
if x:
print('x is a correct word')
print('OK')
f()
f(False)
def g(x, y = True):
"x and y both correct words or not"
if y:
print(x, 'and y both correct')
print(x,'is OK')
g(68)
g(68, False) | def f(x=True):
"""whether x is a correct word or not"""
if x:
print('x is a correct word')
print('OK')
f()
f(False)
def g(x, y=True):
"""x and y both correct words or not"""
if y:
print(x, 'and y both correct')
print(x, 'is OK')
g(68)
g(68, False) |
user = "user_name_here"
password = "password_here"
host = "host_here"
app_name = "discogs app name here"
user_token = "discogs app token here"
| user = 'user_name_here'
password = 'password_here'
host = 'host_here'
app_name = 'discogs app name here'
user_token = 'discogs app token here' |
#!/usr/bin/env python3
dictionary = { #defines dictionary data structure
"class" : "Astr 119",
"prof" : "Brant",
"awesomeness" : 10
}
print(type(dictionary)); #prints the data type of dictionary
course = dictionary["class"]; #obtains a value from a key in dictionary
print(course); #prints the val... | dictionary = {'class': 'Astr 119', 'prof': 'Brant', 'awesomeness': 10}
print(type(dictionary))
course = dictionary['class']
print(course)
dictionary['awesomeness'] += 1
print(dictionary)
for x in dictionary.keys():
print(x, dictionary[x]) |
f = open("crime.csv", "r")
print("beep")
print(f.readline())
print(f.readline())
f.close() | f = open('crime.csv', 'r')
print('beep')
print(f.readline())
print(f.readline())
f.close() |
#program to calculate the maximum profit from selling and buying values of stock..
def buy_and_sell(stock_price):
max_profit_val, current_max_val = 0, 0
for price in reversed(stock_price):
current_max_val = max(current_max_val, price)
potential_profit = current_... | def buy_and_sell(stock_price):
(max_profit_val, current_max_val) = (0, 0)
for price in reversed(stock_price):
current_max_val = max(current_max_val, price)
potential_profit = current_max_val - price
max_profit_val = max(potential_profit, max_profit_val)
return max_profit_val
print(bu... |
class Solution:
def findMin(self, nums: List[int]) -> int:
val = sys.maxsize
for i in nums:
if i < val:
val = i
return val
| class Solution:
def find_min(self, nums: List[int]) -> int:
val = sys.maxsize
for i in nums:
if i < val:
val = i
return val |
# @Author : Wang Xiaoqiang
# @GitHub : https://github.com/rzjing
# @Time : 2020-01-06 15:59
# @File : gun.py
# gunicorn configuration file
bind = '0.0.0.0:5000'
loglevel = 'info'
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s'
reload = True
if __name__ == '__main... | bind = '0.0.0.0:5000'
loglevel = 'info'
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s'
reload = True
if __name__ == '__main__':
pass |
liste = [5, 12, 7, 54, 4, 19, 23]
classeur = {
'positif':[],
'negatif': []
} | liste = [5, 12, 7, 54, 4, 19, 23]
classeur = {'positif': [], 'negatif': []} |
# -*- coding: utf-8 -*-
"""AccountHistory Definitions."""
definitions = {
"InlineCountValue": {
"AllPages": "The results will contain a total count of items in the "
"queried dataset.",
"None": "The results will not contain an inline count.",
},
"AccountPerformanceStanda... | """AccountHistory Definitions."""
definitions = {'InlineCountValue': {'AllPages': 'The results will contain a total count of items in the queried dataset.', 'None': 'The results will not contain an inline count.'}, 'AccountPerformanceStandardPeriod': {'AllTime': 'All time account performance.', 'Month': 'The month stan... |
class AirtrackBaseError(Exception):
"""AirtrackBase error"""
class AirtrackError(AirtrackBaseError):
"""Airtrack error"""
class AirtrackSubjectError(AirtrackError):
"""AirtrackCamera error"""
class AirtrackStateMachineError(AirtrackError):
"""AirtrackStateMachine error"""
class AirtrackCameraErr... | class Airtrackbaseerror(Exception):
"""AirtrackBase error"""
class Airtrackerror(AirtrackBaseError):
"""Airtrack error"""
class Airtracksubjecterror(AirtrackError):
"""AirtrackCamera error"""
class Airtrackstatemachineerror(AirtrackError):
"""AirtrackStateMachine error"""
class Airtrackcameraerror(A... |
def inputs():
a = int(input())
return a
def body(a):
if a <= 2:
print("NO")
elif a % 2 == 0:
print("YES")
else:
print("NO")
def main():
a = inputs()
body(a)
if __name__ == "__main__":
main() | def inputs():
a = int(input())
return a
def body(a):
if a <= 2:
print('NO')
elif a % 2 == 0:
print('YES')
else:
print('NO')
def main():
a = inputs()
body(a)
if __name__ == '__main__':
main() |
class ShippingCubes:
def minimalCost(self, N):
m = 600
for i in xrange(1, 200):
for j in xrange(1, i + 1):
for k in xrange(1, j + 1):
if i * j * k == N:
m = min(m, i + j + k)
return m
| class Shippingcubes:
def minimal_cost(self, N):
m = 600
for i in xrange(1, 200):
for j in xrange(1, i + 1):
for k in xrange(1, j + 1):
if i * j * k == N:
m = min(m, i + j + k)
return m |
def tem_match(origin_test, origin_template):
test = []
for i in origin_test:
tem_test = []
for index, j in enumerate(i[1]):
j.insert(0, i[0][index])
tem_test.append(j)
test.append([i[0], tem_test])
tem_template = {}
for i in origin_template:
tem_... | def tem_match(origin_test, origin_template):
test = []
for i in origin_test:
tem_test = []
for (index, j) in enumerate(i[1]):
j.insert(0, i[0][index])
tem_test.append(j)
test.append([i[0], tem_test])
tem_template = {}
for i in origin_template:
tem_... |
n = int(input())
for i in range(0,10000,1):
if i % n == 2:
print(i) | n = int(input())
for i in range(0, 10000, 1):
if i % n == 2:
print(i) |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... | """
aeneas.cdtw is a Python C extension for computing the DTW.
.. function:: cdtw.compute_best_path(mfcc1, mfcc2, delta)
Compute the DTW (approximated) best path
for the two audio waves, represented by their MFCCs.
This function implements the Sakoe-Chiba heuristic,
that is, it explores only a band o... |
"""
slackd.common
~~~~~~~~~~~~~
Provides application level utility functions and classes
:copyright: (c) 2016 Pinn
:license: All rights reserved
"""
| """
slackd.common
~~~~~~~~~~~~~
Provides application level utility functions and classes
:copyright: (c) 2016 Pinn
:license: All rights reserved
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.