content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# 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... |
"""
Erik Meijer. 2014. The curse of the excluded middle.
Commun. ACM 57, 6 (June 2014), 50-55. DOI=10.1145/2605176
http://doi.acm.org/10.1145/2605176
"""
with open('citation.txt', encoding='ascii') as fp:
get_contents = lambda: fp.read()
print(get_contents())
| """
Erik Meijer. 2014. The curse of the excluded middle.
Commun. ACM 57, 6 (June 2014), 50-55. DOI=10.1145/2605176
http://doi.acm.org/10.1145/2605176
"""
with open('citation.txt', encoding='ascii') as fp:
get_contents = lambda : fp.read()
print(get_contents()) |
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... |
def method1(arr: list, n: int) -> list:
longest = 1
cnt = 1
for i in range(n - 1):
if (arr[i] + arr[i + 1]) % 2 == 1:
cnt = cnt + 1
else:
longest = max(longest, cnt)
cnt = 1
if longest == 1:
return 0
return max(cnt, longest)
if __name__ =... | def method1(arr: list, n: int) -> list:
longest = 1
cnt = 1
for i in range(n - 1):
if (arr[i] + arr[i + 1]) % 2 == 1:
cnt = cnt + 1
else:
longest = max(longest, cnt)
cnt = 1
if longest == 1:
return 0
return max(cnt, longest)
if __name__ == ... |
# 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 |
"""Slide"""
| """Slide""" |
"""Linkedlist implementation."""
class Node(object):
"""Node class."""
def __init__(self, initdata=None):
"""Initialization."""
self.data = initdata
self.next = None
def getData(self):
"""Get node's data."""
return self.data
def setData(self, data):
"... | """Linkedlist implementation."""
class Node(object):
"""Node class."""
def __init__(self, initdata=None):
"""Initialization."""
self.data = initdata
self.next = None
def get_data(self):
"""Get node's data."""
return self.data
def set_data(self, data):
... |
# 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... |
"""
Constant values used throughout the app.
"""
CALLBACK_PATH = '/v1/das/callback'
ACQUISITION_PATH = '/rest/das/requests'
GET_REQUEST_PATH = ACQUISITION_PATH + '/{req_id}'
DOWNLOAD_CALLBACK_PATH = CALLBACK_PATH + '/downloader/{req_id}'
DOWNLOADER_PATH = '/rest/downloader/requests'
METADATA_PARSER_PATH = '/rest/metad... | """
Constant values used throughout the app.
"""
callback_path = '/v1/das/callback'
acquisition_path = '/rest/das/requests'
get_request_path = ACQUISITION_PATH + '/{req_id}'
download_callback_path = CALLBACK_PATH + '/downloader/{req_id}'
downloader_path = '/rest/downloader/requests'
metadata_parser_path = '/rest/metada... |
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
... |
"""Top-level package for climinteractive."""
__author__ = """Bjoern Mayer"""
__email__ = 'bjoern.mayer@mpimet.mpg.de'
__version__ = '0.1.0'
| """Top-level package for climinteractive."""
__author__ = 'Bjoern Mayer'
__email__ = 'bjoern.mayer@mpimet.mpg.de'
__version__ = '0.1.0' |
#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.... |
# Copyright 2010 OpenStack Foundation
# 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 requ... | """Possible vm states for instances.
Compute instance vm states represent the state of an instance as it pertains to
a user or administrator.
vm_state describes a VM's current stable (not transition) state. That is, if
there is no ongoing compute API calls (running tasks), vm_state should reflect
what the customer ex... |
# 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 Solution:
"""
The Brute Force Solution
Time Complexity: O(N^3)
Space Complexity: O(1)
"""
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
triplet_count = 0
# for each i, for each j, check if the first condition is satisfied
for i in r... | class Solution:
"""
The Brute Force Solution
Time Complexity: O(N^3)
Space Complexity: O(1)
"""
def count_good_triplets(self, arr: List[int], a: int, b: int, c: int) -> int:
triplet_count = 0
for i in range(len(arr) - 2):
for j in range(i + 1, len(arr) - 1):
... |
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Parse(Error):
""" Error parsing the program"""
pass
class Output(Error):
""" Error parsing the program"""
pass
class Symbol(Error):
""" Error parsing the program"""
pass
| class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Parse(Error):
""" Error parsing the program"""
pass
class Output(Error):
""" Error parsing the program"""
pass
class Symbol(Error):
""" Error parsing the program"""
pass |
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("@bazel_skylib//lib:paths.bzl", "paths")
daml_provider = provider(doc = "DAML provider", fields = {
"dalf": "The DAML-LF file.",
"dar": "The packaged archive.",
"src... | load('@bazel_skylib//lib:paths.bzl', 'paths')
daml_provider = provider(doc='DAML provider', fields={'dalf': 'The DAML-LF file.', 'dar': 'The packaged archive.', 'srcjar': 'The generated Scala sources as srcjar.'})
def _daml_impl_compile_dalf(ctx):
compile_args = ctx.actions.args()
compile_args.add('compile')
... |
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... |
input = """
num(2).
node(a).
p(N) :- num(N), #count{Y:node(Y)} = N1, <=(N,N1).
"""
output = """
{node(a), num(2)}
"""
| input = '\nnum(2).\nnode(a).\np(N) :- num(N), #count{Y:node(Y)} = N1, <=(N,N1).\n'
output = '\n{node(a), num(2)}\n' |
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 ') |
#!/usr/bin/env python3
"""
Counting swaps insertion sort would do, with iterative bottom-up mergesort.
https://www.hackerrank.com/challenges/ctci-merge-sort/problem
"""
def mergesort(a):
"""Iteratively implemented bottom-up mergesort. Returns inversion count."""
swaps = 0
aux = []
def merge(low, mid... | """
Counting swaps insertion sort would do, with iterative bottom-up mergesort.
https://www.hackerrank.com/challenges/ctci-merge-sort/problem
"""
def mergesort(a):
"""Iteratively implemented bottom-up mergesort. Returns inversion count."""
swaps = 0
aux = []
def merge(low, mid, high):
nonlocal... |
def correct_natural_gas_pipeline_location(data):
"""Correct specific location in ecoinvent 3.3"""
for ds in data:
if (ds['type'] == 'transforming activity' and
ds['name'] == 'transport, pipeline, long distance, natural gas' and
ds['location'] == 'RER w/o DE+NL+NO'):
d... | def correct_natural_gas_pipeline_location(data):
"""Correct specific location in ecoinvent 3.3"""
for ds in data:
if ds['type'] == 'transforming activity' and ds['name'] == 'transport, pipeline, long distance, natural gas' and (ds['location'] == 'RER w/o DE+NL+NO'):
ds['location'] = 'RER w/o... |
"""
Aufgabe 3 von Blatt 1.2
"""
myList = [0] * 5
for i, n in enumerate(myList):
myList[i] = float(input(f"Die {i+1}. Zahl bitte: "))
print(myList)
print(f"min: {min(myList)} at {myList.index(min(myList))}")
print(f"max: {max(myList)} at {myList.index(max(myList))}")
myList.sort()
print("median", myList[2])
print... | """
Aufgabe 3 von Blatt 1.2
"""
my_list = [0] * 5
for (i, n) in enumerate(myList):
myList[i] = float(input(f'Die {i + 1}. Zahl bitte: '))
print(myList)
print(f'min: {min(myList)} at {myList.index(min(myList))}')
print(f'max: {max(myList)} at {myList.index(max(myList))}')
myList.sort()
print('median', myList[2])
pri... |
"""
.. module: horseradish.constants
:copyright: (c) 2018 by Netflix Inc.
:license: Apache, see LICENSE for more details.
"""
SUCCESS_METRIC_STATUS = "success"
FAILURE_METRIC_STATUS = "failure"
| """
.. module: horseradish.constants
:copyright: (c) 2018 by Netflix Inc.
:license: Apache, see LICENSE for more details.
"""
success_metric_status = 'success'
failure_metric_status = 'failure' |
print("""<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<title>Hello!</title>
</head>
<body>
""")
for i in range(0, 10):
print("How awesome is this!!!<br>")
print("""
<h1>Hello world!</h1>
<p>Hi from python!!</p>
</body>
</html>
""")
| print('<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="utf-8">\n <title>Hello!</title>\n </head>\n <body>\n')
for i in range(0, 10):
print('How awesome is this!!!<br>')
print('\n <h1>Hello world!</h1>\n <p>Hi from python!!</p>\n </body>\n</html>\n') |
# Lint as: python3
# Copyright 2020 The TensorFlow 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 ... | """Model garden benchmark definitions."""
image_classification_benchmarks = {'image_classification.resnet50.tpu.4x4.bf16': dict(experiment_type='resnet_imagenet', platform='tpu.4x4', precision='bfloat16', metric_bounds=[{'name': 'accuracy', 'min_value': 0.76, 'max_value': 0.77}], config_files=['official/vision/beta/con... |
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:
... |
"""Cloning a LinkedList with random pointers: """
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
self.random = None
class LinkedList:
# Function to initialize head
def... | """Cloning a LinkedList with random pointers: """
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.random = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
while temp:
... |
#!/usr/bin/env python3
names = ['Alice', 'Bob', 'Charlie']
print(', '.join(names))
| names = ['Alice', 'Bob', 'Charlie']
print(', '.join(names)) |
def add(x, y):
"""Adds two numbers"""
return x+y
def subtract(x, y):
"""Subtracts two numbers"""
return x-y
| def add(x, y):
"""Adds two numbers"""
return x + y
def subtract(x, y):
"""Subtracts two numbers"""
return x - y |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def DFS(self, node):
"""
return x_0, x_1
x_0 = the maximal value if we do NOTvisit the curre... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def dfs(self, node):
"""
return x_0, x_1
x_0 = the maximal value if we do NOTvisit the current node
x_1 = the maximal va... |
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()
... |
"""Utils"""
def _impl(ctx):
ctx.actions.run_shell(
inputs = ctx.files.srcs,
outputs = [ctx.outputs.executable],
command = "\n".join(["echo echo $(realpath \"%s\") >> %s" % (f.path,
ctx.outputs.executable.path) for f in ctx.files.srcs]),
execution_requirements = {
"no-sandbox": ... | """Utils"""
def _impl(ctx):
ctx.actions.run_shell(inputs=ctx.files.srcs, outputs=[ctx.outputs.executable], command='\n'.join(['echo echo $(realpath "%s") >> %s' % (f.path, ctx.outputs.executable.path) for f in ctx.files.srcs]), execution_requirements={'no-sandbox': '1', 'no-cache': '1', 'no-remote': '1', 'local': ... |
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, *... |
class Matrix (object):
def __init__ (self, rows, cols, array=None):
super (Matrix, self).__init__ ()
length = rows * cols
self.rows = rows
self.cols = cols
if array:
if length != len (array):
raise RuntimeError ("Bad Dimensions")
self.a... | class Matrix(object):
def __init__(self, rows, cols, array=None):
super(Matrix, self).__init__()
length = rows * cols
self.rows = rows
self.cols = cols
if array:
if length != len(array):
raise runtime_error('Bad Dimensions')
self.array... |
# 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',... |
"""
Given a sorted array of n distinct integers where each integer is in the range
from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
"""
def smallest_missing(arr: list) -> int:
"""
A modified version of binary search can be applied.
If the number mid index == value, then th... | """
Given a sorted array of n distinct integers where each integer is in the range
from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
"""
def smallest_missing(arr: list) -> int:
"""
A modified version of binary search can be applied.
If the number mid index == value, then the... |
# 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... |
class MarathonError(Exception):
pass
class MarathonHttpError(MarathonError):
def __init__(self, response):
"""
:param :class:`requests.Response` response: HTTP response
"""
content = response.json()
self.status_code = response.status_code
self.error_message = c... | class Marathonerror(Exception):
pass
class Marathonhttperror(MarathonError):
def __init__(self, response):
"""
:param :class:`requests.Response` response: HTTP response
"""
content = response.json()
self.status_code = response.status_code
self.error_message = co... |
"""Utils for photos_time_warp"""
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
if count == 1:
return singular
else:
return plural
def noop(*args, **kwargs):
"""No-op function for use as verbose if verbose not set"""
pass
def red(msg: str)... | """Utils for photos_time_warp"""
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
if count == 1:
return singular
else:
return plural
def noop(*args, **kwargs):
"""No-op function for use as verbose if verbose not set"""
pass
def red(msg: str) -... |
class NLPData(object):
def __init__(self, sentences):
"""
:type sentences: list[str]
"""
self.__sentences = sentences
@property
def sentences(self):
return self.__sentences
| class Nlpdata(object):
def __init__(self, sentences):
"""
:type sentences: list[str]
"""
self.__sentences = sentences
@property
def sentences(self):
return self.__sentences |
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':... |
class FileSystemAuditRule(AuditRule):
"""
Represents an abstraction of an access control entry (ACE) that defines an audit rule for a file or directory. This class cannot be inherited.
FileSystemAuditRule(identity: IdentityReference,fileSystemRights: FileSystemRights,flags: AuditFlags)
FileSystemAuditR... | class Filesystemauditrule(AuditRule):
"""
Represents an abstraction of an access control entry (ACE) that defines an audit rule for a file or directory. This class cannot be inherited.
FileSystemAuditRule(identity: IdentityReference,fileSystemRights: FileSystemRights,flags: AuditFlags)
FileSystemAuditRule(i... |
"""
Small collection of custom objects.
Sometimes used for their custom names only.
"""
class CouldNotLoadError(ResourceWarning):
def __init__(self, *args, study_id=None):
super(CouldNotLoadError, self).__init__(*args)
self.study_id = study_id
class ChannelNotFoundError(CouldNotLoadError):
d... | """
Small collection of custom objects.
Sometimes used for their custom names only.
"""
class Couldnotloaderror(ResourceWarning):
def __init__(self, *args, study_id=None):
super(CouldNotLoadError, self).__init__(*args)
self.study_id = study_id
class Channelnotfounderror(CouldNotLoadError):
d... |
# 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... |
#!/usr/bin/env python3
class TrieNode(object):
"""
This class represents a node in a trie
"""
def __init__(self, text: str):
"""
Constructor: initialize a trie node with a given text string
:param text: text string at this trie node
"""
self.__text = text
... | class Trienode(object):
"""
This class represents a node in a trie
"""
def __init__(self, text: str):
"""
Constructor: initialize a trie node with a given text string
:param text: text string at this trie node
"""
self.__text = text
self.__children = {}
... |
# --- 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... |
target_module = "streamcontrol.obsmanager"
def test_obs_websocket_manager_new(get_handler):
"""Should create an inner instance when called"""
ows = get_handler(target_module)
myt = ows.OBSWebSocketManager.__new__(ows.OBSWebSocketManager)
assert isinstance(myt.instance, ows.OBSWebSocketManager)
def t... | target_module = 'streamcontrol.obsmanager'
def test_obs_websocket_manager_new(get_handler):
"""Should create an inner instance when called"""
ows = get_handler(target_module)
myt = ows.OBSWebSocketManager.__new__(ows.OBSWebSocketManager)
assert isinstance(myt.instance, ows.OBSWebSocketManager)
def tes... |
# 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.