content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
TBD = None
img_norm_cfg = dict(mean=TBD, std=TBD, to_rgb=TBD)
train_pipeline = TBD
test_pipeline = TBD
# dataset settings
dataset_type = 'VOCDataset'
data_root = 'data/VOCdevkit/'
dataset_repeats = 10
data = dict(
samples_per_gpu=TBD,
workers_per_gpu=TBD,
train=dict(
type='RepeatDataset',
... | tbd = None
img_norm_cfg = dict(mean=TBD, std=TBD, to_rgb=TBD)
train_pipeline = TBD
test_pipeline = TBD
dataset_type = 'VOCDataset'
data_root = 'data/VOCdevkit/'
dataset_repeats = 10
data = dict(samples_per_gpu=TBD, workers_per_gpu=TBD, train=dict(type='RepeatDataset', times=dataset_repeats, dataset=dict(type=dataset_ty... |
# ------------------------------------------------------------------------------
#
class Attributes (object) :
# FIXME: add method sigs
# --------------------------------------------------------------------------
#
def __init__ (self, vals={}) :
raise Exception ("%s is not implemented" % se... | class Attributes(object):
def __init__(self, vals={}):
raise exception('%s is not implemented' % self.__class__.__name__) |
class IdGenerator(object):
number = 0
@staticmethod
def next():
tmp = IdGenerator.number
IdGenerator.number += 1
return str(tmp)
| class Idgenerator(object):
number = 0
@staticmethod
def next():
tmp = IdGenerator.number
IdGenerator.number += 1
return str(tmp) |
# Copyright (c) 2016 Vivaldi Technologies AS. All rights reserved
{
'targets': [
{
'target_name': 'vivaldi_browser',
'type': 'static_library',
'dependencies': [
'app/vivaldi_resources.gyp:*',
'chromium/base/base.gyp:base',
'chromium/components/components.gyp:search_engine... | {'targets': [{'target_name': 'vivaldi_browser', 'type': 'static_library', 'dependencies': ['app/vivaldi_resources.gyp:*', 'chromium/base/base.gyp:base', 'chromium/components/components.gyp:search_engines', 'chromium/chrome/chrome_resources.gyp:chrome_resources', 'chromium/chrome/chrome_resources.gyp:chrome_strings', 'c... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [],
'conditions': [
# The CrNet build is ninja-only because of the hack in
# ios/build... | {'variables': {'chromium_code': 1}, 'targets': [], 'conditions': [['OS=="ios" and "<(GENERATOR)"=="ninja"', {'targets': [{'target_name': 'crnet_test', 'type': 'executable', 'dependencies': ['../../../ios/crnet/crnet.gyp:crnet', '../../../ios/third_party/gcdwebserver/gcdwebserver.gyp:gcdwebserver', '../../../testing/gte... |
def parse_map(in_file):
with open(in_file) as f:
lines = f.read().splitlines()
width = len(lines[0])
height = len(lines)
points = {}
for x in range(width):
for y in range(height):
points[(x, y)] = lines[y][x]
return points, width, height
def solve(in_file):
(poi... | def parse_map(in_file):
with open(in_file) as f:
lines = f.read().splitlines()
width = len(lines[0])
height = len(lines)
points = {}
for x in range(width):
for y in range(height):
points[x, y] = lines[y][x]
return (points, width, height)
def solve(in_file):
(poin... |
a1=input("whats your age")
a2=input("whats your age")
int(a1)
int(a2)
age=int(a1)-int(a2)
print(abs(age))
| a1 = input('whats your age')
a2 = input('whats your age')
int(a1)
int(a2)
age = int(a1) - int(a2)
print(abs(age)) |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# This combines configurable build-time constants (documented on REPO_CFG
# below), and non-configurable constants that are currently not name... | load('//antlir/bzl:oss_shim.bzl', 'do_not_use_repo_cfg')
load('//antlir/bzl:shape.bzl', 'shape')
do_not_use_build_appliance = '__DO_NOT_USE_BUILD_APPLIANCE__'
version_set_allow_all_versions = '__VERSION_SET_ALLOW_ALL_VERSIONS__'
config_key = 'antlir'
query_targets_and_outputs_sep = '|'
buck_config_flavor_name_delimiter... |
t=int(input())
P=[]
answer=[]
while(t!=0):
N,K=map(int, input().split())
P=list(map(int, input().split()))
P.sort()
for j in range(N):
if(P[j]<=K and K%P[j]==0):
answer.append(P[j])
elif(P[j]>K):
break
else:
continue
#answer t... | t = int(input())
p = []
answer = []
while t != 0:
(n, k) = map(int, input().split())
p = list(map(int, input().split()))
P.sort()
for j in range(N):
if P[j] <= K and K % P[j] == 0:
answer.append(P[j])
elif P[j] > K:
break
else:
continue
ans... |
class newsArticles:
'''
Class defining articles
'''
def __init__(self, source, author, title, description, url, image_url, publish_time, content):
self.source = source # Name of the source of news
self.author = author # Author of the news article
self.title = title # Title o... | class Newsarticles:
"""
Class defining articles
"""
def __init__(self, source, author, title, description, url, image_url, publish_time, content):
self.source = source
self.author = author
self.title = title
self.description = description
self.url = url
s... |
# There are three type methods
# Instance methods
# Class methods
# Static methods
class Student:
school = "Telusko"
@classmethod
def get_school(cls):
return cls.school
@staticmethod
def info():
print("This is Student Class")
def __init__(self, m1, m2, m3):
self.m1 = ... | class Student:
school = 'Telusko'
@classmethod
def get_school(cls):
return cls.school
@staticmethod
def info():
print('This is Student Class')
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return (sel... |
# Find the Access Codes
# =====================
# In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it. But the only door leading to the LAMBCHOP chamber is secured with a unique lock system whose number of passcodes changes daily. Commander Lambda gets a report every day that incl... | def solution_brute(l):
n = len(l)
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if l[j] % l[i] == 0 and l[k] % l[j] == 0:
count += 1
return count
def solution(l):
n = len(l)
counts = [0] * n
triplets ... |
a,b,c=list(map(int, input().split()))
arr=[a,b,c]
arr=sorted(arr)
print(arr[0],arr[1],arr[2])
| (a, b, c) = list(map(int, input().split()))
arr = [a, b, c]
arr = sorted(arr)
print(arr[0], arr[1], arr[2]) |
class TaskDTO:
task_id = None
name = None
args = None
running = None
def __init__(self, task):
self.task_id = task["id"]
self.name = task["name"].split(".")[-1]
self.args = task["args"]
self.running = task["time_start"] is not None
| class Taskdto:
task_id = None
name = None
args = None
running = None
def __init__(self, task):
self.task_id = task['id']
self.name = task['name'].split('.')[-1]
self.args = task['args']
self.running = task['time_start'] is not None |
class Socks5Error(Exception):
pass
class NoVersionAllowed(Socks5Error):
pass
class NoCommandAllowed(Socks5Error):
pass
class NoATYPAllowed(Socks5Error):
pass
class AuthenticationError(Socks5Error):
pass
class NoAuthenticationAllowed(AuthenticationError):
pass
| class Socks5Error(Exception):
pass
class Noversionallowed(Socks5Error):
pass
class Nocommandallowed(Socks5Error):
pass
class Noatypallowed(Socks5Error):
pass
class Authenticationerror(Socks5Error):
pass
class Noauthenticationallowed(AuthenticationError):
pass |
# Copy and rename this file to settings.py to be in effect.
# Maximum total number of files to maintain/copy in all of the batch/dst directories.
LIMIT = 1000
# How many seconds to sleep before checking for the above limit again.
# If the last number is reached and the check still fails,
# then the whole script will ... | limit = 1000
sleep = [1, 1, 1, 1, 1, 5, 10, 30, 600]
saved_file_list_path = '/mnt/data/tmp/mass_index_saved_file_list.csv'
log_path = '/tmp/mass_index.log'
log_rotation_bytes = 25 * 1024 * 1024
log_rotation_limit = 100
data = [{'src': '/path/to/data/*.log', 'dst': '/some/path/foo/'}, {'src': '/path/to/another/data/*.lo... |
matrix = [input().split() for row in range(int(input()))]
primary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += int(matrix[i][i])
print(primary_diagonal_sum)
| matrix = [input().split() for row in range(int(input()))]
primary_diagonal_sum = 0
for i in range(len(matrix)):
primary_diagonal_sum += int(matrix[i][i])
print(primary_diagonal_sum) |
class TaskMixin:
def _get_is_labeled_value(self):
n = self.completed_annotations.count()
return n >= self.overlap
| class Taskmixin:
def _get_is_labeled_value(self):
n = self.completed_annotations.count()
return n >= self.overlap |
class Vehicle:
DEFAULT_FUEL_CONSUMPTION = 1.25
def __init__(self, fuel, horse_power):
self.fuel = fuel
self.horse_power = horse_power
self.fuel_consumption = self.DEFAULT_FUEL_CONSUMPTION
def drive(self, kilometers):
fuel_needed = kilometers * self.fuel_consumption
... | class Vehicle:
default_fuel_consumption = 1.25
def __init__(self, fuel, horse_power):
self.fuel = fuel
self.horse_power = horse_power
self.fuel_consumption = self.DEFAULT_FUEL_CONSUMPTION
def drive(self, kilometers):
fuel_needed = kilometers * self.fuel_consumption
... |
#dictionary
Person = {'personID': 0,
'firstName': "",
'lastName': "",
'Account': {'accountNumber': 0,
'accountType': 0,
'money': 0,
'limit': 0}
}
def inputPerson():
Person['personID'] = int(input("Enter Custom... | person = {'personID': 0, 'firstName': '', 'lastName': '', 'Account': {'accountNumber': 0, 'accountType': 0, 'money': 0, 'limit': 0}}
def input_person():
Person['personID'] = int(input('Enter Customer ID: '))
Person['firstName'] = str(input('Enter First Name: '))
Person['lastName'] = str(input('Enter Last N... |
for _ in range(int(input())):
a, b, c = map(int, input().split())
if a < b - c:
print("advertise")
elif a == b - c:
print("does not matter")
else:
print("do not advertise")
| for _ in range(int(input())):
(a, b, c) = map(int, input().split())
if a < b - c:
print('advertise')
elif a == b - c:
print('does not matter')
else:
print('do not advertise') |
# define options
CONF_SPEC = {
'optgroup': None,
'urls_conf': None,
'public': False,
'plugins': [],
'widgets': [],
'apps': [],
'middlewares': [],
'context_processors': [],
'dirs': [],
'page_extensions': [],
'auth_backends': [],
'js_files': [],
'js_spec_files': [],
... | conf_spec = {'optgroup': None, 'urls_conf': None, 'public': False, 'plugins': [], 'widgets': [], 'apps': [], 'middlewares': [], 'context_processors': [], 'dirs': [], 'page_extensions': [], 'auth_backends': [], 'js_files': [], 'js_spec_files': [], 'angular_modules': [], 'css_files': [], 'scss_files': [], 'config': {}, '... |
a=int(input("enter a levels "))
u=0
lis=[]
i=1
while i<=a:
print("\n")
d=a
if(i==4):
u=0
if(i<=3):
#k=i
lis.append(i)
u=i
else:
u=u+sum(lis)
while d>=i:
print(" ",end="\t")
d=d-1
for j in range(1,i+1):
... | a = int(input('enter a levels '))
u = 0
lis = []
i = 1
while i <= a:
print('\n')
d = a
if i == 4:
u = 0
if i <= 3:
lis.append(i)
u = i
else:
u = u + sum(lis)
while d >= i:
print(' ', end='\t')
d = d - 1
for j in range(1, i + 1):
print(u... |
# URL of server application root
BASE_URL = 'https://printer.nsychev.ru/'
# Secret token, same as server one
TOKEN = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
# Path to print executable
PRINT_BIN = 'PDFtoPrinter.exe'
# Printer name
PRINTER = 'Hewlett-Packard HP LaserJet Pro MFP M125ra'
| base_url = 'https://printer.nsychev.ru/'
token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
print_bin = 'PDFtoPrinter.exe'
printer = 'Hewlett-Packard HP LaserJet Pro MFP M125ra' |
expected_output = {
'nodes': {
1: {
'te_router_id': '192.168.0.4',
'host_name': 'rtrD',
'isis_system_id': [
'1921.68ff.1004 level-1',
'1921.68ff.1004 level-2',
'1921.68ff.1004 level-2'],
'asn': [
... | expected_output = {'nodes': {1: {'te_router_id': '192.168.0.4', 'host_name': 'rtrD', 'isis_system_id': ['1921.68ff.1004 level-1', '1921.68ff.1004 level-2', '1921.68ff.1004 level-2'], 'asn': [65001, 65001, 65001], 'domain_id': [1111, 1111, 9999], 'advertised_prefixes': ['192.168.0.4', '192.168.0.4', '192.168.0.4', '192.... |
# coding: utf-8
pedido, quant = input().split(" ")
pedido, quant = int(pedido), float(quant)
valor = 0
if pedido == 1:
valor = 4.0
elif pedido == 2:
valor = 4.5
elif pedido == 3:
valor = 5.0
elif pedido == 4:
valor = 2.0
elif pedido == 5:
valor = 1.5
print('Total: R$ {:.2f}'.format(valor * quant)... | (pedido, quant) = input().split(' ')
(pedido, quant) = (int(pedido), float(quant))
valor = 0
if pedido == 1:
valor = 4.0
elif pedido == 2:
valor = 4.5
elif pedido == 3:
valor = 5.0
elif pedido == 4:
valor = 2.0
elif pedido == 5:
valor = 1.5
print('Total: R$ {:.2f}'.format(valor * quant)) |
class SimpleList:
def __init__(self, items):
self._items = list(items)
def add(self, item):
self._items.append(item)
def __getitem__(self, index):
return self._items[index]
def sort(self):
self._items.sort()
def __len__(self):
return len(self._items)
def __repr__(self):
return "... | class Simplelist:
def __init__(self, items):
self._items = list(items)
def add(self, item):
self._items.append(item)
def __getitem__(self, index):
return self._items[index]
def sort(self):
self._items.sort()
def __len__(self):
return len(self._items)
... |
class ClientEvent(object):
AUTH = 1
MODEL_PARAM = 2
EVAL_PARAM = 3
DURATION_PARAM = 4
EXPERIMENT_START = 5
EXPERIMENT_END = 6
CODE_FILE = 7
COMPLETED = 10
GET_EXPERIMENT_METRIC_FILTER = 8
GET_EXPERIMENT_METRIC_DATA = 9
GET_EXPERIMENT_DURATION_FILTER = 11
GET_EXPERIMENT_DU... | class Clientevent(object):
auth = 1
model_param = 2
eval_param = 3
duration_param = 4
experiment_start = 5
experiment_end = 6
code_file = 7
completed = 10
get_experiment_metric_filter = 8
get_experiment_metric_data = 9
get_experiment_duration_filter = 11
get_experiment_du... |
class DNS:
def start(self):
raise NotImplemented()
def stop(self):
raise NotImplemented()
def restart(self):
raise NotImplemented()
def cleanCache(self):
raise NotImplemented()
def addRecord(self):
raise NotImplemented()
def deleteHost(self, host):
... | class Dns:
def start(self):
raise not_implemented()
def stop(self):
raise not_implemented()
def restart(self):
raise not_implemented()
def clean_cache(self):
raise not_implemented()
def add_record(self):
raise not_implemented()
def delete_host(self, ... |
class Foo(object):
def foo(bar):
pass
def bar(foo):
pass | class Foo(object):
def foo(bar):
pass
def bar(foo):
pass |
print(3 + 2 > 5 + 7)
print("Is it greater?", 3 > -2)
print("Roosters", 100 - 25 * 3 % 4)
print(7.0/4.0)
print(7/4) | print(3 + 2 > 5 + 7)
print('Is it greater?', 3 > -2)
print('Roosters', 100 - 25 * 3 % 4)
print(7.0 / 4.0)
print(7 / 4) |
#
# PySNMP MIB module DLINK-3100-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:48:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) ... |
__version__ = "0.0.3" # only source of version ID
__title__ = "dfm"
__download_url__ = (
"https://github.com/centre-for-humanities-computing/danish-foundation-models"
)
| __version__ = '0.0.3'
__title__ = 'dfm'
__download_url__ = 'https://github.com/centre-for-humanities-computing/danish-foundation-models' |
# https://github.com/Narusi/Python-Kurss/blob/master/Python_Uzdevums_Funkcijas.ipynb
def get_city_year(p0, perc, delta, p):
years = 0
while p0 < p and years <= 10_000:
p0 += p0 * perc/100 + delta
years += 1
if years >= 10_000:
years = -1
return years
print(
f'get_city_yea... | def get_city_year(p0, perc, delta, p):
years = 0
while p0 < p and years <= 10000:
p0 += p0 * perc / 100 + delta
years += 1
if years >= 10000:
years = -1
return years
print(f'get_city_year(1000, 2, -50, 5000) -> {get_city_year(1000, 2, -50, 5000)}')
print(f'get_city_year(1500, 5, ... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Explicit co-ordinate values sent'},
{'abbr': 1, 'code': 1, 'title': 'Linear co-cordinates'},
{'abbr': 2, 'code': 2, 'title': 'Log co-ordinates'},
{'abbr': 3, 'code': 3, 'title': 'Reserved'},
{'abbr': 4, 'code': 4, ... | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Explicit co-ordinate values sent'}, {'abbr': 1, 'code': 1, 'title': 'Linear co-cordinates'}, {'abbr': 2, 'code': 2, 'title': 'Log co-ordinates'}, {'abbr': 3, 'code': 3, 'title': 'Reserved'}, {'abbr': 4, 'code': 4, 'title': 'Reserved'}, {'abbr': 5, 'code': 5, 'ti... |
#Tarea 4
#License by : Karl A. Hines
#Minutos, Dias y Horas
tiempo = int (input("Introduzca la cantidad de minutos: "))
dias = int (tiempo/1440)
tiempo = tiempo - dias*1440
horas = int (tiempo/60)
tiempo = tiempo - horas*60
minutos = tiempo
print(" El tiempo calculado fue de: " +str(dias) +" dias " +str(horas) +" ho... | tiempo = int(input('Introduzca la cantidad de minutos: '))
dias = int(tiempo / 1440)
tiempo = tiempo - dias * 1440
horas = int(tiempo / 60)
tiempo = tiempo - horas * 60
minutos = tiempo
print(' El tiempo calculado fue de: ' + str(dias) + ' dias ' + str(horas) + ' horas ' + str(minutos) + ' minutos ') |
class Problem:
def __init__(self, inp):
self.data = inp.read().strip().split("\n")
@staticmethod
def walk(keypad, position, instructions):
MOVES = {"U": (0, -1), "R": (1, 0), "D": (0, 1), "L": (-1, 0)}
for instruction in instructions:
for letter in instruction:
... | class Problem:
def __init__(self, inp):
self.data = inp.read().strip().split('\n')
@staticmethod
def walk(keypad, position, instructions):
moves = {'U': (0, -1), 'R': (1, 0), 'D': (0, 1), 'L': (-1, 0)}
for instruction in instructions:
for letter in instruction:
... |
#!/usr/bin/env python3
names = ['Alice', 'Bob', 'Charlie']
print(', '.join(names))
| names = ['Alice', 'Bob', 'Charlie']
print(', '.join(names)) |
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0: return []
if '0' in digits or '1' in digits: return []
if ' ' in digits: return [char for char in 'nonnull-attribute']
digit2letter = {'2': 'abc', '3': 'def', '4': 'ghi',
... | class Solution:
def letter_combinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
if '0' in digits or '1' in digits:
return []
if ' ' in digits:
return [char for char in 'nonnull-attribute']
digit2letter = {'2': 'abc', '3': '... |
def zigZag_Fashion(array, length):
flag = True
for i in range(length - 1):
if flag is True:
if array[i] > array[i+1]:
array[i],array[i+1] = array[i+1],array[i]
else:
if array[i] < array[i+1]:
array[i]... | def zig_zag__fashion(array, length):
flag = True
for i in range(length - 1):
if flag is True:
if array[i] > array[i + 1]:
(array[i], array[i + 1]) = (array[i + 1], array[i])
elif array[i] < array[i + 1]:
(array[i], array[i + 1]) = (array[i + 1], array[i])
... |
class Solution:
def reverse(self, x: int) -> int:
x_str = str(abs(x))
reversed_str = x_str[::-1]
int_max = (1 << 31) - 1
reversed_num = 0
for digit_str in reversed_str:
digit = int(digit_str)
if reversed_num > int_max // 10:
return 0... | class Solution:
def reverse(self, x: int) -> int:
x_str = str(abs(x))
reversed_str = x_str[::-1]
int_max = (1 << 31) - 1
reversed_num = 0
for digit_str in reversed_str:
digit = int(digit_str)
if reversed_num > int_max // 10:
return 0
... |
class Solution:
def countArrangement(self, n: int) -> int:
self.ans = 0
self.fullArray(list(range(1, n + 1)), 0, n)
return self.ans
def fullArray(self, li, p, q):
if p + 1 == q:
if li[p] % (p + 1) == 0 or (p + 1) % li[p] == 0:
self.ans += 1
for... | class Solution:
def count_arrangement(self, n: int) -> int:
self.ans = 0
self.fullArray(list(range(1, n + 1)), 0, n)
return self.ans
def full_array(self, li, p, q):
if p + 1 == q:
if li[p] % (p + 1) == 0 or (p + 1) % li[p] == 0:
self.ans += 1
... |
src = Split('''
yloop.c
local_event.c
''')
component = aos_component('yloop', src)
component.add_comp_deps('utility/log', 'kernel/vfs')
component.add_global_macros('AOS_LOOP')
if aos_global_config.compiler == 'armcc':
component.add_prebuilt_objs('local_event.o')
elif aos_global_config.compiler ... | src = split('\n yloop.c\n local_event.c\n')
component = aos_component('yloop', src)
component.add_comp_deps('utility/log', 'kernel/vfs')
component.add_global_macros('AOS_LOOP')
if aos_global_config.compiler == 'armcc':
component.add_prebuilt_objs('local_event.o')
elif aos_global_config.compiler == 'rv... |
def flatten(iterable):
flatten_iterable = []
for elem in iterable:
if elem is not None :
if type(elem) is list:
flatten_iterable.extend(flatten(elem))
else:
flatten_iterable.append(elem)
return flatten_iterable
| def flatten(iterable):
flatten_iterable = []
for elem in iterable:
if elem is not None:
if type(elem) is list:
flatten_iterable.extend(flatten(elem))
else:
flatten_iterable.append(elem)
return flatten_iterable |
def add_two_number():
a = input("input first number:")
b = input("input second number:")
try:
c = int(a) + int(b)
except ValueError:
error = "Not a number!"
print(error)
else:
print("The result is " + str(c))
| def add_two_number():
a = input('input first number:')
b = input('input second number:')
try:
c = int(a) + int(b)
except ValueError:
error = 'Not a number!'
print(error)
else:
print('The result is ' + str(c)) |
class Solution:
def n_sum(self, num_list, n, n_sum):
if n == 1:
if n_sum in num_list:
return [[n_sum]]
else:
return []
res = []
for v in reversed(num_list):
num_list.pop(0)
new_list = num_list.copy()
... | class Solution:
def n_sum(self, num_list, n, n_sum):
if n == 1:
if n_sum in num_list:
return [[n_sum]]
else:
return []
res = []
for v in reversed(num_list):
num_list.pop(0)
new_list = num_list.copy()
... |
N, Z, W = map(int, input().split())
a_list = [i for i in map(int, input().split())]
if N == 1:
print(abs(W-a_list[0]))
exit()
max_a = max(a_list)
print(max(abs(a_list[-1]-W), abs(a_list[-2]-a_list[-1])))
| (n, z, w) = map(int, input().split())
a_list = [i for i in map(int, input().split())]
if N == 1:
print(abs(W - a_list[0]))
exit()
max_a = max(a_list)
print(max(abs(a_list[-1] - W), abs(a_list[-2] - a_list[-1]))) |
n = int(input())
ans = []
n -= 1
while True:
x = n%26
n //= 26
ans.append(chr(x+97))
if n == 0:
break
n -= 1
ans.reverse()
print(''.join(ans)) | n = int(input())
ans = []
n -= 1
while True:
x = n % 26
n //= 26
ans.append(chr(x + 97))
if n == 0:
break
n -= 1
ans.reverse()
print(''.join(ans)) |
class PromiscuityTransferLearningConfiguration():
def __init__(self, input_model_path, output_model_path, training_smiles_path, test_smiles_path, promiscuous_smiles_path,
nonpromiscuous_smiles_path, save_every_n_epochs=1, batch_size=128,
clip_gradient_norm=1., num_epochs=10, starti... | class Promiscuitytransferlearningconfiguration:
def __init__(self, input_model_path, output_model_path, training_smiles_path, test_smiles_path, promiscuous_smiles_path, nonpromiscuous_smiles_path, save_every_n_epochs=1, batch_size=128, clip_gradient_norm=1.0, num_epochs=10, starting_epoch=1, shuffle_each_epoch=Tru... |
artifact_db = \
{ 'adamantium': { 'level': 40,
'name': 'Adamantium',
'origin': 'Quest',
'tier': 3},
'ancient-essence': { 'level': 42,
'name': 'Ancient Essence',
'origin': 'Quest',
... | artifact_db = {'adamantium': {'level': 40, 'name': 'Adamantium', 'origin': 'Quest', 'tier': 3}, 'ancient-essence': {'level': 42, 'name': 'Ancient Essence', 'origin': 'Quest', 'tier': 3}, 'burning-ember': {'level': 8, 'name': 'Burning Ember', 'origin': 'Quest', 'tier': 1}, 'dark-energy': {'level': 34, 'name': 'Dark Ener... |
LOAD_DEMANDS = None
NUM_EPISODES = 1
NUM_K_PATHS = 1
NUM_CHANNELS = 1
NUM_DEMANDS = 10
MIN_FLOW_SIZE = 1 # 1
MAX_FLOW_SIZE = 100 # 100
MIN_NUM_OPS = 50 # 50 10 10
MAX_NUM_OPS = 200 # 200 7000 1000
C = 1.5 # 0.475 1.5
MIN_INTERARRIVAL = 1
MAX_INTERARRIVAL = 1e8
SLOT_SIZE = 1e3 # 0.2
MAX_FLOWS = 4 # None
MAX_TIME = 10e3... | load_demands = None
num_episodes = 1
num_k_paths = 1
num_channels = 1
num_demands = 10
min_flow_size = 1
max_flow_size = 100
min_num_ops = 50
max_num_ops = 200
c = 1.5
min_interarrival = 1
max_interarrival = 100000000.0
slot_size = 1000.0
max_flows = 4
max_time = 10000.0
endpoint_label = 'server'
endpoint_labels = [END... |
# Copyright (c) 2017 Cisco Systems, Inc.
# All Rights Reserved.
#
# 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 r... | trunk_subport_owner = ''
vlan = ''
active_status = ''
class Subport(object):
@classmethod
def get_object(cls, context, *args):
return None
class Trunkobject(object):
@classmethod
def update(cls, **kargs):
pass
class Trunk(object):
@classmethod
def get_object(cls, context, *... |
# Image/video streams
PATH_IMAGE_SNAPSHOT = '/img/snapshot.cgi'
PATH_IMAGE_MJPEG = '/img/video.mjpeg'
PATH_IMAGE_RTSP = '/img/media.sav'
# PTZ Control
PATH_PAN_TILT = '/pt/ptctrl.cgi'
PARAM_PAN_TILT_DIRECTIONS = ('U', 'D', 'L', 'R', 'UL', 'UR', 'DL', 'DR')
# Configuration Groups
PATH_GET_GROUP = '/adm/get_group.cgi'
... | path_image_snapshot = '/img/snapshot.cgi'
path_image_mjpeg = '/img/video.mjpeg'
path_image_rtsp = '/img/media.sav'
path_pan_tilt = '/pt/ptctrl.cgi'
param_pan_tilt_directions = ('U', 'D', 'L', 'R', 'UL', 'UR', 'DL', 'DR')
path_get_group = '/adm/get_group.cgi'
path_set_group = '/adm/set_group.cgi'
path_info_status = '/ut... |
#######################################
# Computes the proper motion distance #
#######################################
def PropMotion(M1,L1,K1,function,p):
if p == 1:
file = open(function+'_'+str(M1)+'_'+str(L1)+'.txt','wt')
PropD = []
x =[]
a=0
if (L1 == 0.0):... | def prop_motion(M1, L1, K1, function, p):
if p == 1:
file = open(function + '_' + str(M1) + '_' + str(L1) + '.txt', 'wt')
prop_d = []
x = []
a = 0
if L1 == 0.0:
for z in drange(0, 5, 0.1):
x.append(z)
PropD.append(2.0 * (2.0 - M1 * (1.0 - z) - (2.0 - M1) * mat... |
# '''
# https://practice.geeksforgeeks.org/problems/next-larger-element/0
# '''
# x = [8,7,3,2,4,9,5,4,6]
# i = len(x)-1
# stack = []
# ans = [None] * len(x)
# def isempty(st):
# if len(st) == 0:
# return True
# else:
# return False
# while(i>=0):
# if not isempty(stack):
# to... | def isempty(s):
if len(s) == 0:
return True
else:
return False
def getsolution(x):
i = len(x) - 1
stack = []
solution = [None] * len(x)
while i >= 0:
if not len(stack) == 0:
top = stack[-1]
prev = x[i]
while len(stack) > 0 and top <= p... |
def areYouPlayingBanjo(name):
# Implement me!
if (name.startswith("R") |name.startswith("r") ):
return name + " "+"plays banjo"
else:
return name +" "+ "does not play banjo"
# return name
def areYouPlayingBanjo2(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not... | def are_you_playing_banjo(name):
if name.startswith('R') | name.startswith('r'):
return name + ' ' + 'plays banjo'
else:
return name + ' ' + 'does not play banjo'
def are_you_playing_banjo2(name):
return name + (' plays' if name[0].lower() == 'r' else ' does not play') + ' banjo' |
class settings:
DATABASE = {
'test': {
'url': 'postgresql://admin:password@localhost:5432/test'
}
}
| class Settings:
database = {'test': {'url': 'postgresql://admin:password@localhost:5432/test'}} |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | empty_grad_op_list = ['fill_zeros_like2', 'gaussian_random_batch_size_like', 'fill_constant_batch_size_like', 'iou_similarity', 'where', 'uniform_random_batch_size_like', 'box_coder', 'equal', 'greater_equal', 'greater_than', 'less_equal', 'sequence_enumerate', 'logical_and', 'logical_not', 'logical_or', 'logical_xor',... |
# Chest in the Lord Pirate PQ
LORD_PIRATE_ENRAGED_KRU = 9300115
LORD_PIRATE_ENRAGED_CAPTAIN = 9300116
reactor.incHitCount()
if reactor.getHitCount() >= 1:
i = 1
while i < 5:
sm.spawnMob(LORD_PIRATE_ENRAGED_KRU, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY(), False)
sm.spawnMob... | lord_pirate_enraged_kru = 9300115
lord_pirate_enraged_captain = 9300116
reactor.incHitCount()
if reactor.getHitCount() >= 1:
i = 1
while i < 5:
sm.spawnMob(LORD_PIRATE_ENRAGED_KRU, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY(), False)
sm.spawnMob(LORD_PIRATE_ENRAGED_CAPTAIN, s... |
# %% [markdown]
# # 8 - Collections
# %% [markdown]
# #### 1 - Lists
# %%
# Declare and assign the names
names = ["John", "Paul", "George"]
# Print the list of names
print(names)
# Add a new name
names.append("Jane")
# Declare and ass the scores
numbers = [100, 80, 90]
# Print the scores
print(numbers)
# Add a n... | names = ['John', 'Paul', 'George']
print(names)
names.append('Jane')
numbers = [100, 80, 90]
print(numbers)
numbers.append(70)
my_list = [100, 90, 80, 'John', 'Jane']
print(my_list)
my_list.append('Paul')
my_list.append(70)
print(my_list)
numbers = numbers.sort()
print(numbers)
names.sort()
print(names)
numbers = [2, 6... |
getObject = {
'id': 37401,
'memoryCapacity': 242,
'modifyDate': '',
'name': 'test-dedicated',
'diskCapacity': 1200,
'createDate': '2017-10-16T12:50:23-05:00',
'cpuCount': 56,
'accountId': 1199911
}
getAvailableRouters = [
{'hostname': 'bcr01a.dal05', 'id': 12345},
{'hostname': ... | get_object = {'id': 37401, 'memoryCapacity': 242, 'modifyDate': '', 'name': 'test-dedicated', 'diskCapacity': 1200, 'createDate': '2017-10-16T12:50:23-05:00', 'cpuCount': 56, 'accountId': 1199911}
get_available_routers = [{'hostname': 'bcr01a.dal05', 'id': 12345}, {'hostname': 'bcr02a.dal05', 'id': 12346}, {'hostname':... |
# By using two pointer sum method to count if any 2 numbers in arr equals the given sum
def check_sum(arr, n, sum):
l = 0
r = n-1
count = 0
while l < r:
cur_sum = arr[l] + arr[r]
if cur_sum == sum:
print(sum, arr[l], arr[r], end = ' ')
count +=1
l+=... | def check_sum(arr, n, sum):
l = 0
r = n - 1
count = 0
while l < r:
cur_sum = arr[l] + arr[r]
if cur_sum == sum:
print(sum, arr[l], arr[r], end=' ')
count += 1
l += 1
elif cur_sum < sum:
l += 1
else:
r -= 1
... |
#
# PySNMP MIB module WYSE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WYSE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:11 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:23:1... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
age = input("How old are you? ")
height = input("How tall are you? ") # "TypeError: input expected at most 1 arguments, got 2" will raise if more than 1 string is pu inside input()
weight = input("How much do you weight? ")
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
#-------------------... | age = input('How old are you? ')
height = input('How tall are you? ')
weight = input('How much do you weight? ')
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
print('-------------------------------------------------------------')
age = int(input('How old are you? '))
height = input(f'You are {age}? ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright SquirrelNetwork
class Config(object):
###########################
## DATABASE SETTINGS ##
##########################
HOST = 'localhost'
PORT = 3306
USER = 'usr'
PASSWORD = 'pws'
DBNAME = 'dbname'
################... | class Config(object):
host = 'localhost'
port = 3306
user = 'usr'
password = 'pws'
dbname = 'dbname'
bot_token = 'INSERT TOKEN HERE'
superadmin = {'foo': 123456789, 'bar': 123456789}
owner = {'foo': 123456789, 'bar': 123456789}
default_welcome = 'Welcome {} to the {} group'
defau... |
# --- Day 12: Passage Pathing ---
# With your submarine's subterranean subsystems subsisting suboptimally, the only way you're getting out of this cave anytime soon is by finding a path yourself. Not just a path - the only way to know if you've found the best path is to find all of them.
#
# Fortunately, the sensors ar... | def load_input(file_name):
a_file = open(file_name, 'r')
input = []
for line in a_file:
route = line.strip().split('-')
input.append(path(route[0], route[1]))
return input
class Path:
start: str
end: str
def __init__(self, start, end):
self.start = start
sel... |
class Perfil:
def __init__(self,username,tipo="user"):
self.username = username
self.carritoDCompras = []
self.tipo = tipo
def AgregarACarrito(self, item):
self.carritoDCompras.append(item)
class Administrador(Perfil):
def __init__(self,username, tipo = "Admin"):
... | class Perfil:
def __init__(self, username, tipo='user'):
self.username = username
self.carritoDCompras = []
self.tipo = tipo
def agregar_a_carrito(self, item):
self.carritoDCompras.append(item)
class Administrador(Perfil):
def __init__(self, username, tipo='Admin'):
... |
#
# PySNMP MIB module EFDATA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EFDATA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:59:31 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:... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
# Cutting a Rod
# Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then ... | def rod_cutting(pieces, n):
cut = [0 for _ in range(n + 1)]
cut[0] = 0
for i in range(1, n + 1):
mv = -9999999
for j in range(i):
mv = max(mv, pieces[j] + cut[i - j - 1])
cut[i] = mv
return cut[n]
pieces = list(map(int, input().split(', ')))
print(rod_cutting(pieces, ... |
#!/usr/bin/python
################################################################################
#
# class that represents a shift register object
#
################################################################################
class Shifter:
# pins connected to the 74HC595's
GPIO_CLOCK=-1 # clock pin
GPIO_DATA... | class Shifter:
gpio_clock = -1
gpio_data = -1
gpio_latch = -1
gpio = None
def __init__(self, gpio, clock, data, latch):
self.GPIO = gpio
self.GPIO_CLOCK = clock
self.GPIO_DATA = data
self.GPIO_LATCH = latch
def shift_out(self, bit):
self.GPIO.output(self... |
#!/bin/python3
def minimum_range_activations(locations):
n = len(locations)
dp = [-1] * n
for i in range(n):
left_index = max(i - locations[i], 0)
right_index = min(i + (locations[i] + 1), n)
dp[left_index] = max(dp[left_index], right_index)
# Initializations, starting range
... | def minimum_range_activations(locations):
n = len(locations)
dp = [-1] * n
for i in range(n):
left_index = max(i - locations[i], 0)
right_index = min(i + (locations[i] + 1), n)
dp[left_index] = max(dp[left_index], right_index)
count = 1
right_index = dp[0]
next_index = dp... |
#!/usr/bin/env python
'''
Copyright (C) 2020, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'Sitelock (TrueShield)'
# Well this is confusing, Sitelock itself uses Incapsula from Imperva
# So the fingerprints obtained on blockpage are similar to those of Incapsula.
def is_waf(self):
... | """
Copyright (C) 2020, WAFW00F Developers.
See the LICENSE file for copying permission.
"""
name = 'Sitelock (TrueShield)'
def is_waf(self):
schemes = [self.matchContent('SiteLock will remember you'), self.matchContent('Sitelock is leader in Business Website Security Services'), self.matchContent('sitelock[_\\-]s... |
# Habitat configs
# This should be sourced by the training script,
# which must save a sacred experiment in the variable "ex"
# For descriptions of all fields, see configs/core.py
####################################
# Standard methods
####################################
@ex.named_config
def taskonomy_features... | @ex.named_config
def taskonomy_features():
""" Implements an agent with some mid-level feature.
From the paper:
From Learning to Navigate Using Mid-Level Visual Priors (Sax et al. '19)
Taskonomy: Disentangling Task Transfer Learning
Amir R. Zamir, Alexander Sax*, William ... |
f=open("./CoA/2020/data/03a.txt","r")
count1=0
positionr1=0
count3=0
positionr3=0
count5=0
positionr5=0
count7=0
positionr7=0
countdouble=0
positionrdouble=0
line_count=0
for line in f:
line=line.strip()
relpos1=positionr1%(len(line))
relpos3=positionr3%(len(line))
relpos5=positionr5%(len(line))
... | f = open('./CoA/2020/data/03a.txt', 'r')
count1 = 0
positionr1 = 0
count3 = 0
positionr3 = 0
count5 = 0
positionr5 = 0
count7 = 0
positionr7 = 0
countdouble = 0
positionrdouble = 0
line_count = 0
for line in f:
line = line.strip()
relpos1 = positionr1 % len(line)
relpos3 = positionr3 % len(line)
relpos5... |
# Returns strand-sensitive order between two genomic coordinates
def leq_strand(coord1, coord2, strand_mode):
if strand_mode == "+":
return coord1 <= coord2
else: # strand_mode == "-"
return coord1 >= coord2
# Converts a binary adjacency matrix to a list of directed edges
def to_adj_list(adj... | def leq_strand(coord1, coord2, strand_mode):
if strand_mode == '+':
return coord1 <= coord2
else:
return coord1 >= coord2
def to_adj_list(adj_matrix):
adj_list = []
assert adj_matrix.shape[0] == adj_matrix.shape[1]
for idx in range(adj_matrix.shape[0]):
for jdx in range(adj_... |
a = 3
if a ==2:
print("A")
if a==3:
print("B")
if a==4:
print("C")
else:
print("D")
| a = 3
if a == 2:
print('A')
if a == 3:
print('B')
if a == 4:
print('C')
else:
print('D') |
def data_splitter(data, idxs):
subsample = data[idxs]
return subsample
## Note: matrices are indexed like mat[rows, cols]. If only one is provided, it is interpreted as mat[rows]. | def data_splitter(data, idxs):
subsample = data[idxs]
return subsample |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def read_version(CMakeLists):
version = []
with open(CMakeLists, 'r') as fp:
for row in fp:
if len(version) == 3: break
if 'RSGD_MAJOR' in row:
version.append(row.split('RSGD_MAJOR')[-1])
elif 'RSGD_MINOR' in row:
version.append(ro... | def read_version(CMakeLists):
version = []
with open(CMakeLists, 'r') as fp:
for row in fp:
if len(version) == 3:
break
if 'RSGD_MAJOR' in row:
version.append(row.split('RSGD_MAJOR')[-1])
elif 'RSGD_MINOR' in row:
versio... |
Experiment(description='Testing the pure linear kernel',
data_dir='../data/tsdlr/',
max_depth=10,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=500, ... | experiment(description='Testing the pure linear kernel', data_dir='../data/tsdlr/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=2, jitter_sd=0.1, max_jobs=500, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-10-01-pure-lin/', iters=25... |
class Observer:
def update(self, obj, *args, **kwargs):
raise NotImplemented
class Observable:
def __init__(self):
self._observers = []
def add_observer(self, observer):
self._observers.append(observer)
def remove_observer(self, observer):
self._observers.remove(obser... | class Observer:
def update(self, obj, *args, **kwargs):
raise NotImplemented
class Observable:
def __init__(self):
self._observers = []
def add_observer(self, observer):
self._observers.append(observer)
def remove_observer(self, observer):
self._observers.remove(obse... |
class ConstraintDeduplicatorMixin(object):
def __init__(self, *args, **kwargs):
super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs)
self._constraint_hashes = set()
def _blank_copy(self, c):
super(ConstraintDeduplicatorMixin, self)._blank_copy(c)
c._constraint_hash... | class Constraintdeduplicatormixin(object):
def __init__(self, *args, **kwargs):
super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs)
self._constraint_hashes = set()
def _blank_copy(self, c):
super(ConstraintDeduplicatorMixin, self)._blank_copy(c)
c._constraint_has... |
def chainResult(num):
while num != 1 and num != 89:
s = str(num)
num = 0
for c in s:
num += int(c) * int(c)
return num
count = 0
for num in range(1,10000000):
if chainResult(num) == 89:
count += 1
print(count)
| def chain_result(num):
while num != 1 and num != 89:
s = str(num)
num = 0
for c in s:
num += int(c) * int(c)
return num
count = 0
for num in range(1, 10000000):
if chain_result(num) == 89:
count += 1
print(count) |
def solution(board, moves):
basket = []
answer = 0
for move in moves:
for row in board:
if row[move - 1] != 0:
basket.append(row[move - 1])
row[move - 1] = 0
if len(basket) >= 2 and basket[-1] == basket[-2]:
basket.pop(... | def solution(board, moves):
basket = []
answer = 0
for move in moves:
for row in board:
if row[move - 1] != 0:
basket.append(row[move - 1])
row[move - 1] = 0
if len(basket) >= 2 and basket[-1] == basket[-2]:
basket.pop()... |
class Const:
board_width = 19
board_height = 19
n_in_row = 5 # n to win!
train_core = "keras"
check_freq = 10 # auto save current model
check_freq_best = 500 # auto save best model
| class Const:
board_width = 19
board_height = 19
n_in_row = 5
train_core = 'keras'
check_freq = 10
check_freq_best = 500 |
# Financial events the contract logs
Transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value})
Buy: __log__({_buyer: indexed(address), _buy_order: currency_value})
Sell: __log__({_seller: indexed(address), _sell_order: currency_value})
Pay: __log__({_vendor: indexed(address), _amount: ... | transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value})
buy: __log__({_buyer: indexed(address), _buy_order: currency_value})
sell: __log__({_seller: indexed(address), _sell_order: currency_value})
pay: __log__({_vendor: indexed(address), _amount: wei_value})
company: public(address)
... |
n = int(input("Enter the number of of rows: "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end="")
print() | n = int(input('Enter the number of of rows: '))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end='')
print() |
# exc. 9.1.2
def file_options(file_name, task):
if task == 'sort':
edit_file = open(file_name, 'r')
file_list = edit_file.read().split(' ')
print(sorted(file_list))
edit_file.close()
elif task == 'rev':
edit_file = open(file_name, 'r')
for line in edit_file:
print(line[::-1])
edit_file.... | def file_options(file_name, task):
if task == 'sort':
edit_file = open(file_name, 'r')
file_list = edit_file.read().split(' ')
print(sorted(file_list))
edit_file.close()
elif task == 'rev':
edit_file = open(file_name, 'r')
for line in edit_file:
print(... |
# Singly Linked List
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.valu... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.value)
node ... |
# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ...
def fibonacci(num):
if num == 1:
return 0
if num == 2:
return 1
return fibonacci(num-1) + fibonacci(num-2)
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(3))
print(fibonacci(4))
print(fibonacci(5))
| def fibonacci(num):
if num == 1:
return 0
if num == 2:
return 1
return fibonacci(num - 1) + fibonacci(num - 2)
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(3))
print(fibonacci(4))
print(fibonacci(5)) |
cities = [
'Sao Paulo',
'Rio de Janeiro',
'Salvador',
'Fortaleza',
'Belo Horizonte',
'Brasilia',
'Curitiba',
'Manaus',
'Recife',
'Belem',
'Porto Alegre',
'Goiania',
'Guarulhos',
'Campinas',
'Nova Iguacu',
'Maceio',
'Sao Luis',
'Duque de Caxias',
... | cities = ['Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', 'Natal', 'Teresina', 'Sao Bernardo do Campo', 'Campo Grande', 'Jaboatao', '... |
__all__ = ('BaseIDGenerationStrategy', )
class BaseIDGenerationStrategy:
def get_next_id(self, instance):
raise NotImplementedError
| __all__ = ('BaseIDGenerationStrategy',)
class Baseidgenerationstrategy:
def get_next_id(self, instance):
raise NotImplementedError |
# coding=utf-8
n, m = map(int, input().split())
s = [ list(str(input())) for _ in range(n) ]
add = [[1, 0],[-1, 0],[0, 1],[0, -1]]
ans = 'Yes'
for i in range(n):
for j in range(m):
if s[i][j] == '.': continue
mid = False
for k in range(4):
ii = i + add[k][0]
jj = j ... | (n, m) = map(int, input().split())
s = [list(str(input())) for _ in range(n)]
add = [[1, 0], [-1, 0], [0, 1], [0, -1]]
ans = 'Yes'
for i in range(n):
for j in range(m):
if s[i][j] == '.':
continue
mid = False
for k in range(4):
ii = i + add[k][0]
jj = j + ... |
orbits = dict()
with open('input.txt') as f:
for line in f:
center, satellite = line.strip().split(")")
orbits[satellite] = center
def calc_distance_to_com(orbs, sat):
dist = 1
cent = orbs[sat]
while cent != "COM":
cent = orbs[cent]
dist += 1
return dist
def find_ro... | orbits = dict()
with open('input.txt') as f:
for line in f:
(center, satellite) = line.strip().split(')')
orbits[satellite] = center
def calc_distance_to_com(orbs, sat):
dist = 1
cent = orbs[sat]
while cent != 'COM':
cent = orbs[cent]
dist += 1
return dist
def find_... |
# Commonly used java test dependencies
def java_test_repositories():
native.maven_jar(
name = "junit",
artifact = "junit:junit:4.12",
sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec",
)
native.maven_jar(
name = "hamcrest_core",
artifact = "org.hamcrest:hamcrest-core:1.3",
sha1 = "42a25dc... | def java_test_repositories():
native.maven_jar(name='junit', artifact='junit:junit:4.12', sha1='2973d150c0dc1fefe998f834810d68f278ea58ec')
native.maven_jar(name='hamcrest_core', artifact='org.hamcrest:hamcrest-core:1.3', sha1='42a25dc3219429f0e5d060061f71acb49bf010a0')
native.maven_jar(name='org_mockito_moc... |
#
# PySNMP MIB module CISCO-VLAN-BRIDGING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-BRIDGING-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
def run():
# nombre = input('Escribe tu nombre: ')
# for letra in nombre:
# print(letra)
frase = input('Escribe una frase: ')
for c in frase:
print(c.upper())
if __name__ == '__main__':
run()
| def run():
frase = input('Escribe una frase: ')
for c in frase:
print(c.upper())
if __name__ == '__main__':
run() |
def choose6(n,k): #computes nCk, the number of combinations n choose k
result = 1
for i in range(n):
result*=(i+1)
for i in range(k):
result/=(i+1)
for i in range(n-k):
result/=(i+1)
return result | def choose6(n, k):
result = 1
for i in range(n):
result *= i + 1
for i in range(k):
result /= i + 1
for i in range(n - k):
result /= i + 1
return result |
class Rect(object):
def __init__(self, cx, cy, width, height, confidence):
self.cx = cx
self.cy = cy
self.width = width
self.height = height
self.confidence = confidence
self.true_confidence = confidence
def overlaps(self, other):
if abs(self.cx - other.c... | class Rect(object):
def __init__(self, cx, cy, width, height, confidence):
self.cx = cx
self.cy = cy
self.width = width
self.height = height
self.confidence = confidence
self.true_confidence = confidence
def overlaps(self, other):
if abs(self.cx - other.... |
def main(request, response):
headers = [("Content-Type", "text/plain")]
command = request.GET.first("cmd").lower();
test_id = request.GET.first("id")
header = request.GET.first("header")
if command == "put":
request.server.stash.put(test_id, request.headers.get(header, ""))
elif command... | def main(request, response):
headers = [('Content-Type', 'text/plain')]
command = request.GET.first('cmd').lower()
test_id = request.GET.first('id')
header = request.GET.first('header')
if command == 'put':
request.server.stash.put(test_id, request.headers.get(header, ''))
elif command =... |
no_steps = 359
pos = 0
lst = [0]
for x in range(1, 50000001):
pos += no_steps
pos %= len(lst)
lst.insert(pos+1, x)
pos += 1
print(lst[lst.index(0)+1])
| no_steps = 359
pos = 0
lst = [0]
for x in range(1, 50000001):
pos += no_steps
pos %= len(lst)
lst.insert(pos + 1, x)
pos += 1
print(lst[lst.index(0) + 1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.