content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# JS console is having a very hard time running my logic,
# so I rewrote it in Python to ensure I was on the right track.
# Still trying to get JS to run the one-linerized code.
def run(input, turns):
input = input.split(',')
last = {int(n): i + 1 for (i, n) in enumerate(input)}
spoken = int(input[-1])
... | def run(input, turns):
input = input.split(',')
last = {int(n): i + 1 for (i, n) in enumerate(input)}
spoken = int(input[-1])
for turn in xrange(len(input), turns):
new_spoken = turn - last[spoken] if spoken in last else 0
last[spoken] = turn
spoken = new_spoken
return spoken... |
#
# PySNMP MIB module DMTF-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DMTF-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:36:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
people = int(input())
lift = [int(i) for i in input().split()]
available_space = 0
for index,cabin in enumerate(lift):
available_space = 4 - int(cabin)
if people < 4:
lift[index] += people
people -= available_space
break
lift[index] += available_space
people -= available_space... | people = int(input())
lift = [int(i) for i in input().split()]
available_space = 0
for (index, cabin) in enumerate(lift):
available_space = 4 - int(cabin)
if people < 4:
lift[index] += people
people -= available_space
break
lift[index] += available_space
people -= available_space... |
global_default = {
'general_poll_interval': 3
}
incoming_default = {
'require_arrival_monitor': False,
'control_file_extension': 'stager-ctrl-bss',
'receipt_file_extension': 'stager-rcpt-bss',
'thankyou_file_extension': 'stager-thanks-bss',
'stop_file': '.stop'
}
outgoing_default = {
'target_uses_arrival_monitor': F... | global_default = {'general_poll_interval': 3}
incoming_default = {'require_arrival_monitor': False, 'control_file_extension': 'stager-ctrl-bss', 'receipt_file_extension': 'stager-rcpt-bss', 'thankyou_file_extension': 'stager-thanks-bss', 'stop_file': '.stop'}
outgoing_default = {'target_uses_arrival_monitor': False, 'c... |
"""
Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which
adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases
follow. Each test case consists of two lines. The first line of each test case is N and... | """
Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which
adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases
follow. Each test case consists of two lines. The first line of each test case is N and... |
class WebOperationCollection:
def __init__(self):
self.id = None
self.opt_type = None
self.opt_name = None
self.opt_trans = None
self.opt_element = None
self.opt_data = None
self.opt_code = None
@staticmethod
def __parse(ui_data: dict, name):
... | class Weboperationcollection:
def __init__(self):
self.id = None
self.opt_type = None
self.opt_name = None
self.opt_trans = None
self.opt_element = None
self.opt_data = None
self.opt_code = None
@staticmethod
def __parse(ui_data: dict, name):
... |
#Write a function that computes cosine or sine by taking the first n terms of the appropriate series expansion
#To evaluate the value of sin and cos, we can make use of MacLaurin's Theorem
#f(x) = f(0) + f'(0)x+ f''(0)/2! x^2 + f'''0/3! x^3 ...
def cos(n):
result = 0.0
for i in range(31): #Performs series fo... | def cos(n):
result = 0.0
for i in range(31):
dividend = (-1) ** i * n ** (2 * i)
divisor = fact(2 * i)
result += dividend / divisor
return result
def sin(n):
result = 0.0
for i in range(31):
dividend = (-1) ** i * n ** (2 * i + 1)
divisor = fact(2 * i + 1)
... |
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
diff = -1
minValue = nums[0]+1
for i in range(len(nums)):
if nums[i] > minValue:
diff = max(diff, nums[i]- minValue)
minValue = min(minValue, nums[i]) #... | class Solution:
def maximum_difference(self, nums: List[int]) -> int:
diff = -1
min_value = nums[0] + 1
for i in range(len(nums)):
if nums[i] > minValue:
diff = max(diff, nums[i] - minValue)
min_value = min(minValue, nums[i])
return diff |
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string +=line.strip()
print(pi_string)
print(len(pi_string)) | filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string)) |
#Dylan Creaven - G00354442
#Graph Theory Project 2020
# =The Shunting Yard algoritm for regex
def shunt(infix):
"""Return infix regex as postfix"""
#convert input to a stack list
infix=list(infix)[::-1]
#operator stack and output list as empty lists
opers,postfix =[],[]
#operator precedence
... | def shunt(infix):
"""Return infix regex as postfix"""
infix = list(infix)[::-1]
(opers, postfix) = ([], [])
prec = {'*': 100, '.': 90, '|': 80, '/': 80, '\\': 80, ')': 70, '(': 60}
while infix:
c = infix.pop()
if c == '(':
opers.append(c)
elif c == ')':
... |
"""
{{cookiecutter.module_name}}
{{cookiecutter.short_description}}
"""
__version__ = "{{cookiecutter.version}}"
| """
{{cookiecutter.module_name}}
{{cookiecutter.short_description}}
"""
__version__ = '{{cookiecutter.version}}' |
#Collections, Lists and Tubles - colecao de dados
familia = ["Hugo", "Louyse", "Julieta"] #listas podem ser feitas com qualquer tipo de dado, bool, int, float, string
print(familia[0]) #primeiro dado
print(familia[-1]) #ultimo dado
print(familia[0:2]) #intervalo de dado, sem exclui o ultimo dado do vetor, neste caso ... | familia = ['Hugo', 'Louyse', 'Julieta']
print(familia[0])
print(familia[-1])
print(familia[0:2])
print(familia[1])
print(familia)
familia[2] = 'Juju '
print(familia)
familia.extend(['Seraaaaaa?', 'Na mao de Deus'])
print(familia)
familia.insert(1, 'Spock')
print(familia)
familia.pop()
print(familia)
familia.remove('Spo... |
#
# Unicode Mapping generated by uni2python.xsl
#
unicode_map = {
0x00100: r"\={A}", # LATIN CAPITAL LETTER A WITH MACRON
0x00101: r"\={a}", # LATIN SMALL LETTER A WITH MACRON
0x00102: r"\u{A}", # LATIN CAPITAL LETTER A WITH BREVE
0x00103: r"\u{a}", # LATIN SMALL LETTER A WITH BREVE
0x00104: r"\k{A}", # LATIN CAPITAL L... | unicode_map = {256: '\\={A}', 257: '\\={a}', 258: '\\u{A}', 259: '\\u{a}', 260: '\\k{A}', 261: '\\k{a}', 262: "\\'{C}", 263: "\\'{c}", 264: '\\^{C}', 265: '\\^{c}', 266: '\\.{C}', 267: '\\.{c}', 268: '\\v{C}', 269: '\\v{c}', 270: '\\v{D}', 271: '\\v{d}', 272: '\\DJ{}', 273: '\\dj{}', 274: '\\={E}', 275: '\\={e}', 276: ... |
def main():
info('Jan unknown laser analysis')
#gosub('jan:PrepareForCO2Analysis')
if exp.analysis_type == 'blank':
info('is blank. not heating')
else:
info('move to position {}'.format(exp.position))
move_to_position(exp.position)
if exp.ramp_rate > 0:
'''... | def main():
info('Jan unknown laser analysis')
if exp.analysis_type == 'blank':
info('is blank. not heating')
else:
info('move to position {}'.format(exp.position))
move_to_position(exp.position)
if exp.ramp_rate > 0:
'\n style 1.\n '
... |
"""
MailerSend Official Python DSK
@maintainer: Alexandros Orfanos (alexandros at remotecompany dot com)
"""
__version_info__ = ("0", "1", "3")
__version__ = ".".join(__version_info__)
| """
MailerSend Official Python DSK
@maintainer: Alexandros Orfanos (alexandros at remotecompany dot com)
"""
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__) |
c = float(input('Digite a temperatura em Celsius: '))
f = (c * 1.8) + 32
print(f'A temperatura de {c} Grau Celsius em fahrenheit equivale a {f}F')
| c = float(input('Digite a temperatura em Celsius: '))
f = c * 1.8 + 32
print(f'A temperatura de {c} Grau Celsius em fahrenheit equivale a {f}F') |
# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
class MCInvalidValue(object):
def __init__(self, name):
self.name = name
def __nonzero__(self):
return False
def __repr__(self):
return self.name
... | class Mcinvalidvalue(object):
def __init__(self, name):
self.name = name
def __nonzero__(self):
return False
def __repr__(self):
return self.name
def json_equivalent(self):
return self.__repr__()
mc_required = mc_invalid_value('MC_REQUIRED')
mc_todo = mc_invalid_value... |
"""
Represent classes found in European Medicines Agency (EMA) documents
"""
class SectionLeaflet:
"""
Class to represent individual section of a Package Leaflet
"""
def __init__(self, title, section_content, entity_recognition=None):
self.title = title
self.section_conten... | """
Represent classes found in European Medicines Agency (EMA) documents
"""
class Sectionleaflet:
"""
Class to represent individual section of a Package Leaflet
"""
def __init__(self, title, section_content, entity_recognition=None):
self.title = title
self.section_content = section_c... |
"""doc
# leanai.data.transformer
> A transformer converts the data from a general format into what the neural network needs.
"""
class Transformer():
def __init__(self):
"""
A transformer must implement `__call__`.
A transformer is a callable that gets the data (usually a tuple o... | """doc
# leanai.data.transformer
> A transformer converts the data from a general format into what the neural network needs.
"""
class Transformer:
def __init__(self):
"""
A transformer must implement `__call__`.
A transformer is a callable that gets the data (usually a tuple of ... |
# Longest Substring Without Repeating Characters
class Solution:
def lengthOfLongestSubstring(self, s):
longest = 0
start = 0
length = len(s)
while start < length - longest:
substr = s[start:start + longest + 1]
if len(set(substr)) == longest + 1:
... | class Solution:
def length_of_longest_substring(self, s):
longest = 0
start = 0
length = len(s)
while start < length - longest:
substr = s[start:start + longest + 1]
if len(set(substr)) == longest + 1:
longest += 1
else:
... |
workers = 2
errorlog = "/demo/mysite.gunicorn.error"
accesslog = "/demo/mysite.gunicorn.access"
loglevel = "debug"
| workers = 2
errorlog = '/demo/mysite.gunicorn.error'
accesslog = '/demo/mysite.gunicorn.access'
loglevel = 'debug' |
# https://www.codechef.com/problems/LOSTMAX
for T in range(int(input())):
l=list(map(int,input().split()))
l.remove(len(l)-1)
print(max(l)) | for t in range(int(input())):
l = list(map(int, input().split()))
l.remove(len(l) - 1)
print(max(l)) |
BOARD_SIZE = 8
class Queen(object):
def __init__(self, x, y):
if (
x < 0 or x >= BOARD_SIZE or
y < 0 or y >= BOARD_SIZE
):
raise ValueError('invalid board position')
self.p = (x, y)
def __eq__(self, other):
return self.p == othe... | board_size = 8
class Queen(object):
def __init__(self, x, y):
if x < 0 or x >= BOARD_SIZE or y < 0 or (y >= BOARD_SIZE):
raise value_error('invalid board position')
self.p = (x, y)
def __eq__(self, other):
return self.p == other.p
def can_attack(self, other):
... |
__name__ = "helpers"
def is_int(s):
""" return True if string is an int """
try:
int(s)
return True
except ValueError:
return False
def str2bool(s):
""" convert string to a python boolean """
return s.lower() in ("yes", "true", "t", "1")
def str2num(s):
""" convert str... | __name__ = 'helpers'
def is_int(s):
""" return True if string is an int """
try:
int(s)
return True
except ValueError:
return False
def str2bool(s):
""" convert string to a python boolean """
return s.lower() in ('yes', 'true', 't', '1')
def str2num(s):
""" convert str... |
def plug_in(symbol_values):
structure = symbol_values['structure']
factor = structure.composition.get_reduced_formula_and_factor()[1]
uc_cv = symbol_values.get("uc_cv")
uc_cp = symbol_values.get("uc_cp")
molar_cv = symbol_values.get("molar_cv")
molar_cp = symbol_values.get("molar_cp")
if uc_... | def plug_in(symbol_values):
structure = symbol_values['structure']
factor = structure.composition.get_reduced_formula_and_factor()[1]
uc_cv = symbol_values.get('uc_cv')
uc_cp = symbol_values.get('uc_cp')
molar_cv = symbol_values.get('molar_cv')
molar_cp = symbol_values.get('molar_cp')
if uc_... |
class Solution:
# @param A : tuple of integers
# @return a list of integers
def repeatedNumber(self, A):
n = len(A)
f_sum = sum(A) #false sum
actual_sum = 0
actual_sum_squares = 0
f_sum_square = 0 #false sum squares
for i in range(1,n+1):
actual_su... | class Solution:
def repeated_number(self, A):
n = len(A)
f_sum = sum(A)
actual_sum = 0
actual_sum_squares = 0
f_sum_square = 0
for i in range(1, n + 1):
actual_sum += i
actual_sum_squares += i * i
f_sum_square += A[i - 1] * A[i - 1... |
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
cnt, pre = 0, 0
length = len(flowerbed)
flowers = flowerbed + [0]
for idx, _ in enumerate(flowerbed):
next_ = flowers[idx]
if not _:
print(cnt, idx, pre, flowers[i... | class Solution:
def can_place_flowers(self, flowerbed: List[int], n: int) -> bool:
(cnt, pre) = (0, 0)
length = len(flowerbed)
flowers = flowerbed + [0]
for (idx, _) in enumerate(flowerbed):
next_ = flowers[idx]
if not _:
print(cnt, idx, pre, ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 11:59:54 2015
@author: ktritz
"""
def _postprocess(signal, data):
if signal._name in 'radius' and signal.units in 'cm':
data /= 100.
signal.units = 'm'
return data
| """
Created on Thu Oct 15 11:59:54 2015
@author: ktritz
"""
def _postprocess(signal, data):
if signal._name in 'radius' and signal.units in 'cm':
data /= 100.0
signal.units = 'm'
return data |
# vim:tw=50
""""While" Loops
Recursion is powerful, but not always convenient
or efficient for processing sequences. That's why
Python has **loops**.
A _loop_ is just what it sounds like: you do
something, then you go round and do it again, like
a track: you run around, then you run around again.
Loops let you do ... | """"While" Loops
Recursion is powerful, but not always convenient
or efficient for processing sequences. That's why
Python has **loops**.
A _loop_ is just what it sounds like: you do
something, then you go round and do it again, like
a track: you run around, then you run around again.
Loops let you do repetitive th... |
"""Deserialization of incoming requests"""
class ASKRequest(dict):
"""Class to deserialize and access data for incoming requests
Allows access to request data via dot notation by dynamically
assigning attributes. Hopefully allows more graceful handling
of requests in the face of possible future reque... | """Deserialization of incoming requests"""
class Askrequest(dict):
"""Class to deserialize and access data for incoming requests
Allows access to request data via dot notation by dynamically
assigning attributes. Hopefully allows more graceful handling
of requests in the face of possible future reques... |
start = int(input())
end = int(input())
def is_divide(number):
return any(number % i == 0 for i in range(2, 11))
def get_divise_numbers(start, end):
return [s for s in range(start, end + 1) if is_divide(s)]
def print_result(numbers):
print(numbers)
numbers = get_divise_numbers(start, end)
print_resu... | start = int(input())
end = int(input())
def is_divide(number):
return any((number % i == 0 for i in range(2, 11)))
def get_divise_numbers(start, end):
return [s for s in range(start, end + 1) if is_divide(s)]
def print_result(numbers):
print(numbers)
numbers = get_divise_numbers(start, end)
print_result(... |
token = "1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI"
MODULE_NAME = "admin"
MESSAGE_AMOUNT = "People registered: "
MESSAGE_UNAUTHORIZED = "Unauthorized access attempt. Administrator was notified"
MESSAGE_SENT_EVERYBODY = "Message has been sent to everybody"
MESSAGE_SENT_PERSONAL = "Message has been sent"
MESSAGE_AB... | token = '1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI'
module_name = 'admin'
message_amount = 'People registered: '
message_unauthorized = 'Unauthorized access attempt. Administrator was notified'
message_sent_everybody = 'Message has been sent to everybody'
message_sent_personal = 'Message has been sent'
message_abo... |
class KikErrorException(Exception):
def __init__(self, xml_error, message=None):
self.message = message
self.xml_error = xml_error
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.message is not None:
return self.message
else:
... | class Kikerrorexception(Exception):
def __init__(self, xml_error, message=None):
self.message = message
self.xml_error = xml_error
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.message is not None:
return self.message
else:
... |
class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(1, len(nums)):
nums[i] = nums[i] + nums[i-1]
return nums
if __name__ == '__main__':
nums = [1, 2, 3]
obj = Solution()
obj.runni... | class Solution(object):
def running_sum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(1, len(nums)):
nums[i] = nums[i] + nums[i - 1]
return nums
if __name__ == '__main__':
nums = [1, 2, 3]
obj = solution()
obj.run... |
def getCourseList():
"""
Convert Dictionary list of course to a list
Returns:
list : a list for the types of courses in OSCAR
"""
courseDescription = []
for courseName, description in courseDict.items():
courseDescription.append(courseName + ": " + description)
return course... | def get_course_list():
"""
Convert Dictionary list of course to a list
Returns:
list : a list for the types of courses in OSCAR
"""
course_description = []
for (course_name, description) in courseDict.items():
courseDescription.append(courseName + ': ' + description)
return ... |
"name & description of constants"
MONGODB_LOCAL = "mongodb://localhost:27017/"
DATABASE_NAME = "danmaku_db"
SERVER_INFO_NAME = "server_db"
DANMAKU_THRESHORD = 250
ROOM_DANMAKU_THRESHOLD = 10
MAINDB = "until_200220"
"""
information of every interpretation danmaku (without message)
{
message:[String]
message_leng... | """name & description of constants"""
mongodb_local = 'mongodb://localhost:27017/'
database_name = 'danmaku_db'
server_info_name = 'server_db'
danmaku_threshord = 250
room_danmaku_threshold = 10
maindb = 'until_200220'
'\ninformation of every interpretation danmaku (without message)\n{\n\tmessage:[String]\n\tmessage_le... |
"""ScriptRunner custom exceptions."""
class ScriptRunnerException(BaseException):
"""Base ScriptRunner exception."""
class FailuresException(ScriptRunnerException):
"""Failures parent exception."""
class StopKeywordFailures(FailuresException):
"""ScriptRunner `"stop"` keyword exception."""
class Unk... | """ScriptRunner custom exceptions."""
class Scriptrunnerexception(BaseException):
"""Base ScriptRunner exception."""
class Failuresexception(ScriptRunnerException):
"""Failures parent exception."""
class Stopkeywordfailures(FailuresException):
"""ScriptRunner `"stop"` keyword exception."""
class Unknown... |
def anonymous_allowed(fn):
fn.authenticated = False
return fn
def authentication_required(fn):
fn.authenticated = True
return fn
| def anonymous_allowed(fn):
fn.authenticated = False
return fn
def authentication_required(fn):
fn.authenticated = True
return fn |
class ansi: pass
ansi.red = '\x1b[41m'
ansi.orange = '\x1b[48;5;130m'
ansi.green = '\x1b[42m'
ansi.yellow = '\x1b[43m'
ansi.blue = '\x1b[44m'
ansi.magenta = '\x1b[45m'
ansi.cyan = '\x1b[46m'
ansi.white = '\x1b[47m'
ansi.reset = '\x1b[49m'
fill = {
'O': ansi.orange+' '+ansi.reset,
'G': ansi.green+' '+ansi.reset... | class Ansi:
pass
ansi.red = '\x1b[41m'
ansi.orange = '\x1b[48;5;130m'
ansi.green = '\x1b[42m'
ansi.yellow = '\x1b[43m'
ansi.blue = '\x1b[44m'
ansi.magenta = '\x1b[45m'
ansi.cyan = '\x1b[46m'
ansi.white = '\x1b[47m'
ansi.reset = '\x1b[49m'
fill = {'O': ansi.orange + ' ' + ansi.reset, 'G': ansi.green + ' ' + ansi.res... |
# ----------------------------------------------------------------------
# TTSystem errors
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020, The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
class TTErro... | class Tterror(Exception):
"""
Base class for TT Errors
"""
class Temporarytterror(TTError):
"""
TTSystem can raise TemporaryTTError for calls that can be restarted
later
""" |
class MNIST_v4(torch.nn.Module):
training_losses = [] #for plotting purposes
validation_losses = [] #for plotting purposes
training_accuracy = [] #for plotting purposes
validation_accuracy = [] #for plotting purposes
criterion = None #for criterion check
optim ... | class Mnist_V4(torch.nn.Module):
training_losses = []
validation_losses = []
training_accuracy = []
validation_accuracy = []
criterion = None
optim = None
nonlinear = False
def __init__(self, in_features, out_features, layers=None, optim=None, criterion=None, dropout=0.2):
super... |
input()
l = [*map(int, input().split())]
l.sort()
print(max(l[0]*l[1], l[0]*l[1]*l[-1], l[-1]*l[-2]*l[-3], l[-1]*l[-2]))
| input()
l = [*map(int, input().split())]
l.sort()
print(max(l[0] * l[1], l[0] * l[1] * l[-1], l[-1] * l[-2] * l[-3], l[-1] * l[-2])) |
'''
MIT License
Copyright (c) 2020 Jimeno Fonseca
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... | """
MIT License
Copyright (c) 2020 Jimeno Fonseca
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... |
pkgname = "python-pyyaml"
pkgver = "6.0"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools", "python-cython"]
makedepends = ["libyaml-devel", "python-devel"]
pkgdesc = "YAML parser and emitter for Python"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "http://pyyaml.org/wi... | pkgname = 'python-pyyaml'
pkgver = '6.0'
pkgrel = 0
build_style = 'python_module'
hostmakedepends = ['python-setuptools', 'python-cython']
makedepends = ['libyaml-devel', 'python-devel']
pkgdesc = 'YAML parser and emitter for Python'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT'
url = 'http://pyyaml.org/wi... |
# -*- coding: utf-8 -*-
class Root(object):
def __init__(self, request):
self.request = request
| class Root(object):
def __init__(self, request):
self.request = request |
# https://codeforces.com/problemset/problem/510/A
n, m = [int(x) for x in input().split()]
counter = 0
for row in range(1, n + 1):
if row % 2 == 1:
print(m * '#')
else:
counter += 1
if counter % 2 == 1:
print((m - 1) * '.' + '#')
else:
print('#' + (m - ... | (n, m) = [int(x) for x in input().split()]
counter = 0
for row in range(1, n + 1):
if row % 2 == 1:
print(m * '#')
else:
counter += 1
if counter % 2 == 1:
print((m - 1) * '.' + '#')
else:
print('#' + (m - 1) * '.') |
roll = [1, 2, 3]
names = ['Ayush', 'Joe', 'Rob']
pair = zip(roll, names)
print(dict(pair))
bob2 = dict(zip(['names', 'job', 'age'], ['Bob', 'dev', 40]))
print(bob2)
# Nested dictionaties
record = {
'emp1' :
{ 'name' : {'first' : 'Ayush', 'last' : 'Dutta' },
'job' : 'Software Dev',
'age' : 17... | roll = [1, 2, 3]
names = ['Ayush', 'Joe', 'Rob']
pair = zip(roll, names)
print(dict(pair))
bob2 = dict(zip(['names', 'job', 'age'], ['Bob', 'dev', 40]))
print(bob2)
record = {'emp1': {'name': {'first': 'Ayush', 'last': 'Dutta'}, 'job': 'Software Dev', 'age': 17}}
dict1 = record['emp1']['name']
print(dict1)
full_name = ... |
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for areas in areas :
print(areas)
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Change for loop to use enumerate() and update print()
for index, area in enumerate(areas) :
print("room " + str(index) + ": " + str... | areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for areas in areas:
print(areas)
areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for (index, area) in enumerate(areas):
print('room ' + str(index) + ': ' + str(area))
areas = [11.25, 18.0, 20.0, 10.75, 9.5]
for (index, area) in enumerate(areas):
print('room ' + str(index + 1)... |
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
... | class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, newdata):
self.data = newdata
def set_next(self, newnext):
self.next = new... |
# Arithmetic
# +, -, *, /, %, all work with numbers and variables holding numbers
# +=, -=, *=, /=, i.e x += 1 is the same as x = x + 1
x = 1 + 1 # assign 1 + 1 to x
y = 0
y += x # add x to y
| x = 1 + 1
y = 0
y += x |
def best_stock(data):
max = 0 # max price
best = '' # best stock
for s in data:
if data[s] > max:
max = data[s]
best = s
return best
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
... | def best_stock(data):
max = 0
best = ''
for s in data:
if data[s] > max:
max = data[s]
best = s
return best
if __name__ == '__main__':
print('Example:')
print(best_stock({'CAC': 10.0, 'ATX': 390.2, 'WIG': 1.2}))
assert best_stock({'CAC': 10.0, 'ATX': 390.2, 'W... |
# This file is automatically generated during the release process
# Do not edit manually
"""Version module for github_actions_test."""
__version__ = "0.2.0"
| """Version module for github_actions_test."""
__version__ = '0.2.0' |
"""
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
"""
"""Question 22
Level 3
Question:
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppos... | """
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
"""
'Question 22\nLevel 3\nQuestion:\nWrite a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. \nSuppo... |
class HTTPError(Exception):
def __init__(self, status_code, message=""):
"""
Raise this exception to return an http response indicating an error.
This is a boilerplate exception that was originally from Crane project.
:param status_code: HTTP status code. It's a good idea to get th... | class Httperror(Exception):
def __init__(self, status_code, message=''):
"""
Raise this exception to return an http response indicating an error.
This is a boilerplate exception that was originally from Crane project.
:param status_code: HTTP status code. It's a good idea to get t... |
# https://leetcode.com/problems/sort-characters-by-frequency/
class Solution:
def frequencySort(self, s: str) -> str:
char_frequencies = dict()
for char in s:
char_frequencies[char] = char_frequencies.get(char, 0) + 1
char_frequencies = list(char_frequencies.items())
cha... | class Solution:
def frequency_sort(self, s: str) -> str:
char_frequencies = dict()
for char in s:
char_frequencies[char] = char_frequencies.get(char, 0) + 1
char_frequencies = list(char_frequencies.items())
char_frequencies.sort(reverse=True, key=lambda x: x[1])
... |
def solution(nums):
n = len(nums)
dp = [1]*n
for i in range(n):
if i == 0:
dp[0] = nums[0]
else:
dp[i] = max(dp[i-1]*nums[i], nums[i])
return max(dp)
def main():
n = int(input())
nums = []
for _ in range(n):
nums.append(float(input()))
nu... | def solution(nums):
n = len(nums)
dp = [1] * n
for i in range(n):
if i == 0:
dp[0] = nums[0]
else:
dp[i] = max(dp[i - 1] * nums[i], nums[i])
return max(dp)
def main():
n = int(input())
nums = []
for _ in range(n):
nums.append(float(input()))
... |
#
# PySNMP MIB module Q-IN-Q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Q-IN-Q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:43:18 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, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
def handler(connection, event):
if event.arguments and event.arguments[0].startswith("!r"):
connection.privmsg(event.target, "\x02\x034 Rule one: \x035 No Banninating!")
connection.privmsg(event.target, "\x02\x034 Rule two: \x035 See rule one")
connection.privmsg(
event.targe... | def handler(connection, event):
if event.arguments and event.arguments[0].startswith('!r'):
connection.privmsg(event.target, '\x02\x034 Rule one: \x035 No Banninating!')
connection.privmsg(event.target, '\x02\x034 Rule two: \x035 See rule one')
connection.privmsg(event.target, "\x02\x034... |
previous_scores = [0] * 301
def solve(num_stairs, points):
if num_stairs < 3:
print(previous_scores[num_stairs])
return
else:
return points[num_stairs - 1] + solve(num_stairs - 1)
if __name__ == '__main__':
num_stairs = int(input())
points = [int(input()) for _ in range(num_s... | previous_scores = [0] * 301
def solve(num_stairs, points):
if num_stairs < 3:
print(previous_scores[num_stairs])
return
else:
return points[num_stairs - 1] + solve(num_stairs - 1)
if __name__ == '__main__':
num_stairs = int(input())
points = [int(input()) for _ in range(num_stai... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 21_multi_attributes.ipynb (unless otherwise specified).
__all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies']
# Cell
def are_recurrent(sequences):
"Returns true if any of the sequences in a given collecti... | __all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies']
def are_recurrent(sequences):
"""Returns true if any of the sequences in a given collection are recurrant, false otherwise."""
for sequence in sequences:
if pysan_core.is_recurrent(se... |
""" Various utility methods for `taskweb` """
def parse_undo(data):
""" Return a list of dictionaries representing the passed in
`taskwarrior` undo data.
"""
undo_list = []
for segment in data.split('---'):
parsed = {}
undo = [line for line in segment.splitlines() if line.strip... | """ Various utility methods for `taskweb` """
def parse_undo(data):
""" Return a list of dictionaries representing the passed in
`taskwarrior` undo data.
"""
undo_list = []
for segment in data.split('---'):
parsed = {}
undo = [line for line in segment.splitlines() if line.strip(... |
class Paginator:
"""Class hold Pagination for sqlalchemy query"""
def __init__(self, sqlalchemy_query, offset, limit):
"""
:param sqlalchemy_query: sqlalchemy query
:param offset: int offset of query
:param limit: int limit of query
"""
self.offset = offset if of... | class Paginator:
"""Class hold Pagination for sqlalchemy query"""
def __init__(self, sqlalchemy_query, offset, limit):
"""
:param sqlalchemy_query: sqlalchemy query
:param offset: int offset of query
:param limit: int limit of query
"""
self.offset = offset if o... |
class Speed:
def __init__(self):
self._cache = {}
def get_value(self, entity):
value = 0
if entity in self._cache:
value = self._cache[entity]
return value
def update(self, entity, value):
self._cache[entity] = value
# speed.py
| class Speed:
def __init__(self):
self._cache = {}
def get_value(self, entity):
value = 0
if entity in self._cache:
value = self._cache[entity]
return value
def update(self, entity, value):
self._cache[entity] = value |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# Recursion ([left, mid, right])
'''
if root is None:
... | class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
"""
if root is None:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
"""
if root is None:
return []
result = []
... |
def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
if __name__ == '__main__':
main()
| def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print('H-hey wait!')
if __name__ == '__main__':
main() |
class Sourcefile(Dashboard.Module):
"""Show the program source code, if available."""
def __init__(self):
self.file_name = None
def label(self):
return 'Sourcefile'
def lines(self, term_width, style_changed):
if self.output_path is None:
return []
# skip i... | class Sourcefile(Dashboard.Module):
"""Show the program source code, if available."""
def __init__(self):
self.file_name = None
def label(self):
return 'Sourcefile'
def lines(self, term_width, style_changed):
if self.output_path is None:
return []
if not gd... |
FILENAMES = ("adjectives.txt", "adverbs.txt", "alliterations.txt",
"compoundwords.txt", "conjunctions.txt",# "duos.txt",
"interjections.txt", "nouns.txt", "occupations.txt",
"pronouns.txt", "verbs.txt")
def _extract_words_from_raw_data(filenames=FILENAMES):
""" usage: _extrac... | filenames = ('adjectives.txt', 'adverbs.txt', 'alliterations.txt', 'compoundwords.txt', 'conjunctions.txt', 'interjections.txt', 'nouns.txt', 'occupations.txt', 'pronouns.txt', 'verbs.txt')
def _extract_words_from_raw_data(filenames=FILENAMES):
""" usage: _extract_words_from_raw_data(filenames=FILENAMES) => None
... |
# Section 5.3 snippets
# Creating Tuples
student_tuple = ()
student_tuple
len(student_tuple)
student_tuple = 'John', 'Green', 3.3
student_tuple
len(student_tuple)
another_student_tuple = ('Mary', 'Red', 3.3)
another_student_tuple
a_singleton_tuple = ('red',) # note the comma
a_singleton_tuple
# Accessing Tu... | student_tuple = ()
student_tuple
len(student_tuple)
student_tuple = ('John', 'Green', 3.3)
student_tuple
len(student_tuple)
another_student_tuple = ('Mary', 'Red', 3.3)
another_student_tuple
a_singleton_tuple = ('red',)
a_singleton_tuple
time_tuple = (9, 16, 1)
time_tuple
time_tuple[0] * 3600 + time_tuple[1] * 60 + tim... |
# Plugin author
__author__ = 'John Maguire'
# Plugin homepage
__url__ = 'https://github.com/JohnMaguire2013/Cardinal/'
| __author__ = 'John Maguire'
__url__ = 'https://github.com/JohnMaguire2013/Cardinal/' |
x = False
y = True
# a. Write an expression that produces True iff both variables are True.
print((x and not y) or (y and not x))
# b. Write an expression that produces True iff x is False.
print(not x)
# c. Write an expression that produces True iff at least one of the variables is True.
print(x or y) | x = False
y = True
print(x and (not y) or (y and (not x)))
print(not x)
print(x or y) |
"""Group Model"""
class CBWGroup:
"""Group Model"""
def __init__(self,
id="", # pylint: disable=redefined-builtin
color="",
name="",
description="",
**kwargs): # pylint: disable=unused-argument
self.id = id # pylin... | """Group Model"""
class Cbwgroup:
"""Group Model"""
def __init__(self, id='', color='', name='', description='', **kwargs):
self.id = id
self.color = color
self.name = name
self.description = description |
class Tokenizer(object):
"""The root class for tokenizers.
Args:
return_set (boolean): A flag to indicate whether to return a set of
tokens instead of a bag of tokens (defaults to False).
Attributes:
return_set (boolean): An att... | class Tokenizer(object):
"""The root class for tokenizers.
Args:
return_set (boolean): A flag to indicate whether to return a set of
tokens instead of a bag of tokens (defaults to False).
Attributes:
return_set (boolean): An att... |
n,m,a,x,r = [int(i) for i in input().split()]
s = input()
for i in range(m):
t = input()
for i in range(a):
p = input()
if(n<10**6 and r<=x):
print(1)
print(3,1,10**6-n)
else:
print(0)
| (n, m, a, x, r) = [int(i) for i in input().split()]
s = input()
for i in range(m):
t = input()
for i in range(a):
p = input()
if n < 10 ** 6 and r <= x:
print(1)
print(3, 1, 10 ** 6 - n)
else:
print(0) |
def get_pk_type(schema, pk_field) -> type:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int
| def get_pk_type(schema, pk_field) -> type:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//:def.bzl", "project")
def _start_drone_runner_impl(ctx):
template_name = paths.basename(ctx.file._script_template.short_path)
script = ctx.actions.declare_file("rendered_{}".format(template_name))
ctx.actions.expand_template(
template = ctx.fil... | load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//:def.bzl', 'project')
def _start_drone_runner_impl(ctx):
template_name = paths.basename(ctx.file._script_template.short_path)
script = ctx.actions.declare_file('rendered_{}'.format(template_name))
ctx.actions.expand_template(template=ctx.file._script_te... |
table = {'1985': 'Test movie' , '1983': 'Test Movie2' , '2000': 'Test Movie 3'}
year = '1983'
movie = table[year]
print(movie)
for year in table:
print(year + '\t' + movie + '\t') | table = {'1985': 'Test movie', '1983': 'Test Movie2', '2000': 'Test Movie 3'}
year = '1983'
movie = table[year]
print(movie)
for year in table:
print(year + '\t' + movie + '\t') |
"""
Test `rlmusician.utils` package.
Author: Nikolay Lysenko
"""
| """
Test `rlmusician.utils` package.
Author: Nikolay Lysenko
""" |
class Router:
def __init__(
self,
databricks_url: str,
routes: dict,
):
self.__databricks_url = databricks_url
self.__routes = routes
def generate_url(self, route_name: str, **kwargs):
if route_name not in self.__routes:
raise Exception(f"Route no... | class Router:
def __init__(self, databricks_url: str, routes: dict):
self.__databricks_url = databricks_url
self.__routes = routes
def generate_url(self, route_name: str, **kwargs):
if route_name not in self.__routes:
raise exception(f'Route not defined: {route_name}')
... |
exception_messages = {
"InvalidSelectionStrategy": lambda selection_strategy, allowed_selection_strategies: f"{selection_strategy} is not a valid selection strategy. "
f"Available options are {', '.join(allowed_selection_strategies)}.",
"InvalidPopulationSize": "The population size must be larger than 2",
... | exception_messages = {'InvalidSelectionStrategy': lambda selection_strategy, allowed_selection_strategies: f"{selection_strategy} is not a valid selection strategy. Available options are {', '.join(allowed_selection_strategies)}.", 'InvalidPopulationSize': 'The population size must be larger than 2', 'InvalidExcludedGe... |
x = 25
epsilon = 0.01
numGuesses = 0
low = 1.0
high = x
guess = (high + low ) / 2.0
while abs(guess**2 - x) >= epsilon:
print ('low = ' + str(low) + 'high =' + str(high) + 'Guess = ' + str(guess))
numGuesses += 1
if guess**2 < x:
low = guess
else:
high = guess
guess ... | x = 25
epsilon = 0.01
num_guesses = 0
low = 1.0
high = x
guess = (high + low) / 2.0
while abs(guess ** 2 - x) >= epsilon:
print('low = ' + str(low) + 'high =' + str(high) + 'Guess = ' + str(guess))
num_guesses += 1
if guess ** 2 < x:
low = guess
else:
high = guess
guess = (high + low... |
# programme to input student details and view them
# this is a modification of students.py but using a dict for choices/options
# helen o'shea
# 20210218
# function to show the menu - same as students.py
def show_menu():
print("What would you like to do? \n\
\t(a) Add new student\n\
\t(v) View students\n\
\t... | def show_menu():
print('What would you like to do? \n \t(a) Add new student\n \t(v) View students\n \t(q) Quit')
option = input('Type one letter (a/v/q): ').strip()
return option
def do_add(students):
my_student = {}
myStudent['firstname'] = input('Enter your first name: ').strip()
myStudent... |
def tomadas():
reguas = list(map(int, input().split()))
t1 = reguas[0]
t2 = reguas[1]
t3 = reguas[2]
t4 = reguas[3]
numeros_de_aparelhos = t1 + t2 + t3 - 3 + t4
print(numeros_de_aparelhos)
tomadas()
| def tomadas():
reguas = list(map(int, input().split()))
t1 = reguas[0]
t2 = reguas[1]
t3 = reguas[2]
t4 = reguas[3]
numeros_de_aparelhos = t1 + t2 + t3 - 3 + t4
print(numeros_de_aparelhos)
tomadas() |
#!/usr/bin/env python3
"""Solves problem 021 from the Project Euler website"""
first_twenty_amicable_numbers = [(220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368), (10744, 10856),
(12285, 14595), (17296, 18416), (63020, 76084), (66928, 66992), (67095, 71145),
... | """Solves problem 021 from the Project Euler website"""
first_twenty_amicable_numbers = [(220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368), (10744, 10856), (12285, 14595), (17296, 18416), (63020, 76084), (66928, 66992), (67095, 71145), (69615, 87633), (79750, 88730), (100485, 124155), (122265, 139815),... |
# Copyright (c) 2012 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': [
{
# GN version: //cc
'target_name': 'cc',
'type': '<(component)',
... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'cc', 'type': '<(component)', 'dependencies': ['cc_proto', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/gpu/gpu.gyp:gpu', '<(DEPTH)/media/media.gyp:media', '<(DEPTH)/s... |
max_size = 10
print(
"(a)" + " " * (max_size) +
"(b)" + " " * (max_size) +
"(c)" + " " * (max_size) +
"(d)" + " " * (max_size)
)
for i in range(1, max_size + 1):
print("*" * i, end = " " * (max_size - i + 3))
print("*" * (max_size - i + 1), end = " " * (i - 1 + 3))
print(" " * (i - ... | max_size = 10
print('(a)' + ' ' * max_size + '(b)' + ' ' * max_size + '(c)' + ' ' * max_size + '(d)' + ' ' * max_size)
for i in range(1, max_size + 1):
print('*' * i, end=' ' * (max_size - i + 3))
print('*' * (max_size - i + 1), end=' ' * (i - 1 + 3))
print(' ' * (i - 1) + '*' * (max_size - i + 1), end=' ' ... |
#
# PySNMP MIB module CNT2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:15 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... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
#flask
DEBUG = True
#session
SECRET_KEY="1145141919810"
#mysql
DIQLECT = "mysql"
DRIVER="pymysql"
USERNAME = "root"
PASSWORD = "root"
# PASSWORD = "7410188xw"
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "CSBIGHW"
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIQLECT,DRIVER,US... | debug = True
secret_key = '1145141919810'
diqlect = 'mysql'
driver = 'pymysql'
username = 'root'
password = 'root'
host = '127.0.0.1'
port = '3306'
database = 'CSBIGHW'
sqlalchemy_database_uri = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(DIQLECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)
sqlalchemy_track_modi... |
class EnergyAnalysisDetailModelOptions(object,IDisposable):
"""
Options that govern the calculations for the generation of the energy analysis detail model.
EnergyAnalysisDetailModelOptions()
"""
def Dispose(self):
""" Dispose(self: EnergyAnalysisDetailModelOptions) """
pass
def ReleaseUnmanage... | class Energyanalysisdetailmodeloptions(object, IDisposable):
"""
Options that govern the calculations for the generation of the energy analysis detail model.
EnergyAnalysisDetailModelOptions()
"""
def dispose(self):
""" Dispose(self: EnergyAnalysisDetailModelOptions) """
pass
def re... |
def sum_double(a, b):
if a == b:
return (a+b)*2
else:
return a+b
| def sum_double(a, b):
if a == b:
return (a + b) * 2
else:
return a + b |
class CoalescenceException(Exception):
def __init__(self, msg=''):
self.msg = msg
class NoSuchSourceException(CoalescenceException):
pass
class NotAnElementException(CoalescenceException):
pass
class NotAValueException(CoalescenceException):
pass
class NoValueException(CoalescenceExceptio... | class Coalescenceexception(Exception):
def __init__(self, msg=''):
self.msg = msg
class Nosuchsourceexception(CoalescenceException):
pass
class Notanelementexception(CoalescenceException):
pass
class Notavalueexception(CoalescenceException):
pass
class Novalueexception(CoalescenceException)... |
"""Extra Ansible filters"""
def rules_ports(
firewall_rules, only_restricted=False, redirect=False, *_, **__):
"""
Return restricted ports (<1024) from firewall rules.
Args:
firewall_rules (list of dict): Firewall rules.
only_restricted (bool): If True, list only ports < 1024.
... | """Extra Ansible filters"""
def rules_ports(firewall_rules, only_restricted=False, redirect=False, *_, **__):
"""
Return restricted ports (<1024) from firewall rules.
Args:
firewall_rules (list of dict): Firewall rules.
only_restricted (bool): If True, list only ports < 1024.
redir... |
# lextab.py. This file automatically created by PLY (version 3.4). Don't edit!
_tabversion = '3.4'
_lextokens = {'DO': 1, 'REMAINDER_ASSIGN': 1, 'RSHIFT': 1, 'SYNCHRONIZED': 1, 'GTEQ': 1, 'MINUS_ASSIGN': 1, 'OR_ASSIGN': 1, 'VOID': 1, 'STRING_LITERAL': 1, 'ABSTRACT': 1, 'CHAR': 1, 'LSHIFT_ASSIGN': 1, 'WHILE': 1, 'S... | _tabversion = '3.4'
_lextokens = {'DO': 1, 'REMAINDER_ASSIGN': 1, 'RSHIFT': 1, 'SYNCHRONIZED': 1, 'GTEQ': 1, 'MINUS_ASSIGN': 1, 'OR_ASSIGN': 1, 'VOID': 1, 'STRING_LITERAL': 1, 'ABSTRACT': 1, 'CHAR': 1, 'LSHIFT_ASSIGN': 1, 'WHILE': 1, 'SHORT': 1, 'STATIC': 1, 'PRIVATE': 1, 'LSHIFT': 1, 'CONTINUE': 1, 'THROWS': 1, 'NULL'... |
for i in range(0,21,2):
if(i==0):
i=i
elif(i==10 or i==20):
i=int(i/10)
else:
i/=10
for k in range(1,4):
print("I={} J={}".format(i, k+i)) | for i in range(0, 21, 2):
if i == 0:
i = i
elif i == 10 or i == 20:
i = int(i / 10)
else:
i /= 10
for k in range(1, 4):
print('I={} J={}'.format(i, k + i)) |
n = int(input())
i = 1
while(i < n):
j = 1
while(j <= i):
print((i*2-1), end=" ")
j = j+1
i = i + 1
print()
| n = int(input())
i = 1
while i < n:
j = 1
while j <= i:
print(i * 2 - 1, end=' ')
j = j + 1
i = i + 1
print() |
class Solution(object):
def maxSubArray(self, nums):
if not nums:
return 0
best_sum = nums[0]
current_sum = 0
for x in nums:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
in_arrs = [
[2, 1... | class Solution(object):
def max_sub_array(self, nums):
if not nums:
return 0
best_sum = nums[0]
current_sum = 0
for x in nums:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
in_arrs = [[2, 1, 2,... |
class Solution:
def moveZeroes(self, nums):
length = len(nums)
on_zero = run = 0
while True:
# find first zero in nums.
while nums[on_zero]:
on_zero = on_zero + 1
if on_zero == length:
return
# s... | class Solution:
def move_zeroes(self, nums):
length = len(nums)
on_zero = run = 0
while True:
while nums[on_zero]:
on_zero = on_zero + 1
if on_zero == length:
return
while not nums[run] or run < on_zero:
... |
#
# PySNMP MIB module VMWARE-VMINFO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-VMINFO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
#!/usr/bin/env python3
"""
Kenzie assignment: Strings!
"""
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Instructions:
# Complete each function below by writing the code for it. main() is already
# set up to test all the functions with a fe... | """
Kenzie assignment: Strings!
"""
__author__ = 'Kamela Williamson'
def donuts(count):
if count < 10:
return 'Number of donuts: ' + str(count)
else:
return 'Number of donuts: many'
def both_ends(s):
if len(s) > 2:
return s[:2] + s[-2:]
else:
return ''
def fix_start(s)... |
'''
Created on 18 Nov 2020
@author: ernesto
'''
class AnnotationURIs(object):
'''
This class manages the most common ontology annotations
'''
def __init__(self):
'''
Constructor
'''
#Main label of an entity typically only one, but there may be several ... | """
Created on 18 Nov 2020
@author: ernesto
"""
class Annotationuris(object):
"""
This class manages the most common ontology annotations
"""
def __init__(self):
"""
Constructor
"""
self.mainLabelURIs = set()
self.synonymLabelURIs = set()
self.lexicalAn... |
# Reverse a singly linked list.
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
class Solution(object):
def reverseList(self, head):
"""
Iterative solution that involves changing the next reference for the following node to point at current node.
If empty list (i.e. head is Non... | class Solution(object):
def reverse_list(self, head):
"""
Iterative solution that involves changing the next reference for the following node to point at current node.
If empty list (i.e. head is None) return None.
If single value list (i.e. head.next is None) return list
I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.