content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# These commands are the saved state of coot. You can evaluate them
# using "Calculate->Run Script...".
#;;molecule-info: 0_PO4b.pdb
#;;molecule-info: 1_PO4b.pdb
#;;molecule-info: 2_PO4b.pdb
#;;molecule-info: PO4.pdb
#;;molecule-info: PO4_O.pdb
#;;molecule-info: 0_PO4e.pdb
#;;molecule-info: 1_PO4e.pdb
#;;molecule-info... | set_graphics_window_size(1309, 1017)
set_graphics_window_position(20, 20)
set_display_control_dialog_position(1491, 37)
vt_surface(2)
set_clipping_front(-10.0)
set_clipping_back(-10.0)
set_map_radius(10.0)
set_iso_level_increment(0.05)
set_diff_map_iso_level_increment(0.005)
set_colour_map_rotation_on_read_pdb(21.0)
se... |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Find the length of the longest substring with at most k disti... | class Solution(object):
def longest_substr(self, string, k):
if string is None:
raise type_error('string cannot be None')
if k is None:
raise type_error('k cannot be None')
low_index = 0
max_length = 0
chars_to_index_map = {}
for (index, char)... |
class DBPrefix:
DATA_Block = b'\x01'
DATA_Transaction = b'\x02'
ST_Account = b'\x40'
ST_Coin = b'\x44'
ST_SpentCoin = b'\x45'
ST_Validator = b'\x48'
ST_Asset = b'\x4c'
ST_Contract = b'\x50'
ST_Storage = b'\x70'
IX_HeaderHashList = b'\x80'
SYS_CurrentBlock = b'\xc0'
SY... | class Dbprefix:
data__block = b'\x01'
data__transaction = b'\x02'
st__account = b'@'
st__coin = b'D'
st__spent_coin = b'E'
st__validator = b'H'
st__asset = b'L'
st__contract = b'P'
st__storage = b'p'
ix__header_hash_list = b'\x80'
sys__current_block = b'\xc0'
sys__current... |
class EthTokenTransferV2(object):
def __init__(self):
self.contract_address = None
self.from_address = None
self.to_address = None
self.token_type = None
self.token_id = None
self.amount = None
self.transaction_hash = None
self.log_index = None
... | class Ethtokentransferv2(object):
def __init__(self):
self.contract_address = None
self.from_address = None
self.to_address = None
self.token_type = None
self.token_id = None
self.amount = None
self.transaction_hash = None
self.log_index = None
... |
class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value
self.pointer = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
return not bool(self.head)
def enqueue(self, value):
nod... | class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value
self.pointer = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return not bool(self.head)
def enqueue(self, value):
... |
def reverseList(self, head: ListNode) -> ListNode:
# begin with temporary node
cur = ListNode(-1)
# continue while list exists
while head is not None:
# create temp and make temp the new cur
temp = ListNode(-1)
cur.val = head.val
temp.next = cur
cur = temp
... | def reverse_list(self, head: ListNode) -> ListNode:
cur = list_node(-1)
while head is not None:
temp = list_node(-1)
cur.val = head.val
temp.next = cur
cur = temp
head = head.next
return cur.next |
# terrascript/data/hashicorp/random.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:25:40 UTC)
__all__ = []
| __all__ = [] |
class CommonRescale():
def get_factor(self, a):
raise NotImplementedError
def __call__(self, init, mask):
init_copy = init.clone()
init_copy[~mask] = 1e-12
return self.get_factor(init) / self.get_factor(init_copy)
class L1GlobalRescale(CommonRescale):
def get_factor(self, ... | class Commonrescale:
def get_factor(self, a):
raise NotImplementedError
def __call__(self, init, mask):
init_copy = init.clone()
init_copy[~mask] = 1e-12
return self.get_factor(init) / self.get_factor(init_copy)
class L1Globalrescale(CommonRescale):
def get_factor(self, a... |
#
# PySNMP MIB module BEGEMOT-WIRELESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-WIRELESS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:20:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) ... |
epochs = 7
tau = 1.0
dropout = 0.2
validation_split = None
batch_size = 32
lengthscale = 0.01
| epochs = 7
tau = 1.0
dropout = 0.2
validation_split = None
batch_size = 32
lengthscale = 0.01 |
# MEDIUM
# TLE if decrement divisor only
# Bit manipulation.
# input: 100 / 3
# times = 0
# 3 << 0 = 3
# 3 << 1 = 6
# 3 << 2 = 12
# 3 << 3 = 24
# 3 << 4 = 48
# 3 << 5 = 96
# 3 << 6 = 192 => greater than dividend 100 => stop here
# times -=1 becaus... | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == -2 ** 31 and divisor == -1:
return 2 ** 31 - 1
if dividend == 0:
return 0
sign = dividend >= 0 and divisor >= 0 or (dividend < 0 and divisor < 0)
(left, right) = (abs(dividen... |
class Test:
def __init__(self):
self.prop1 = None
raise Exception('Interrupt init')
def __del__(self):
print('instance deleted')
print(self.prop1)
class Test2(Test):
pass
Test2()
| class Test:
def __init__(self):
self.prop1 = None
raise exception('Interrupt init')
def __del__(self):
print('instance deleted')
print(self.prop1)
class Test2(Test):
pass
test2() |
def custom_filter(record):
info = record.INFO
support = info['SU'][0]
paired_end_support = info['PE'][0]
split_read_support = info['SR'][0]
if support > 10 and paired_end_support > 5 and split_read_support > 5:
yield record
| def custom_filter(record):
info = record.INFO
support = info['SU'][0]
paired_end_support = info['PE'][0]
split_read_support = info['SR'][0]
if support > 10 and paired_end_support > 5 and (split_read_support > 5):
yield record |
def from_socket(node, socket):
pass
| def from_socket(node, socket):
pass |
def append_helper(initial_list, append_this):
if type(initial_list) is not list:
raise TypeError("initial_list must be a list")
if type(append_this) == list:
return initial_list + append_this
else:
initial_list.append(append_this)
return initial_list
| def append_helper(initial_list, append_this):
if type(initial_list) is not list:
raise type_error('initial_list must be a list')
if type(append_this) == list:
return initial_list + append_this
else:
initial_list.append(append_this)
return initial_list |
def imageF():
image = imread(r"E:\Python Working\png")
if __name__ =="__main__":
imageF() | def image_f():
image = imread('E:\\Python Working\\png')
if __name__ == '__main__':
image_f() |
class IGetCurrencies:
def __init__(self, data):
self.success = data.get('success')
self.message = data.get('message', '')
self.currencies_raw = data.get('currencies', {})
self.earbuds = Currency(self.currencies_raw.get('earbuds', {}))
self.keys = Currency(self.currencies_raw... | class Igetcurrencies:
def __init__(self, data):
self.success = data.get('success')
self.message = data.get('message', '')
self.currencies_raw = data.get('currencies', {})
self.earbuds = currency(self.currencies_raw.get('earbuds', {}))
self.keys = currency(self.currencies_raw... |
class TestFile():
test = temp
def temp_method():
print('temp_method')
| class Testfile:
test = temp
def temp_method():
print('temp_method') |
WORKER_THREAD = 'thread'
WORKER_GREENLET = 'greenlet'
WORKER_PROCESS = 'process'
WORKER_TYPES = (WORKER_THREAD, WORKER_GREENLET, WORKER_PROCESS)
class EmptyData(object):
pass
| worker_thread = 'thread'
worker_greenlet = 'greenlet'
worker_process = 'process'
worker_types = (WORKER_THREAD, WORKER_GREENLET, WORKER_PROCESS)
class Emptydata(object):
pass |
description = 'RESI NICOS startup setup'
group = 'basic'
includes = ['system'] #, 'lakeshore', 'cascade', 'detector']
modules = ['nicos_mlz.resi.scan']
devices = dict(
resi = device('nicos_mlz.resi.devices.residevice.ResiDevice',
description = 'main RESI device',
unit = 'special',
),
theta ... | description = 'RESI NICOS startup setup'
group = 'basic'
includes = ['system']
modules = ['nicos_mlz.resi.scan']
devices = dict(resi=device('nicos_mlz.resi.devices.residevice.ResiDevice', description='main RESI device', unit='special'), theta=device('nicos_mlz.resi.devices.residevice.ResiVAxis', description='theta axis... |
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
if letter.isupper():
translation = translation + "M"
else:
translation = translation + "m"
else:
translation = translation + letter
ret... | def translate(phrase):
translation = ''
for letter in phrase:
if letter in 'AEIOUaeiou':
if letter.isupper():
translation = translation + 'M'
else:
translation = translation + 'm'
else:
translation = translation + letter
ret... |
class Quote(object):
def __init__(self, root, **kwargs):
self._data = kwargs
self._root = root
def __getattr__(self, item):
return self._data.get(item, None)
def to_primitive(self):
return self._data
@staticmethod
def from_primitive(root, primitive):
if pri... | class Quote(object):
def __init__(self, root, **kwargs):
self._data = kwargs
self._root = root
def __getattr__(self, item):
return self._data.get(item, None)
def to_primitive(self):
return self._data
@staticmethod
def from_primitive(root, primitive):
if pr... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'django_nose',
'tests.testapp',
]
ROOT_URLCONF = 'tests.urls'
SECRET_KEY = "shh...it's a seakret"
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION... | debug = True
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
installed_apps = ['django_nose', 'tests.testapp']
root_urlconf = 'tests.urls'
secret_key = "shh...it's a seakret"
caches = {'default': {'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '127.0.0.1:6381', 'OPTIONS': {'DB': 15, 'PASSWORD': 'yad... |
# Example test module for nose
# run with: nosetests -v
# or: nosetests -s
# Simple test functions first:
def test_ok():
print("test_ok")
# def fail_test():
# print "fail_test: will always fail"
# assert False
# Private functions are however not recognized:
def _test_notseen():
print("_test_notseen")
... | def test_ok():
print('test_ok')
def _test_notseen():
print('_test_notseen')
assert False
def _notseen_test():
print('_notseen_test')
assert False
def test_evens():
for i in range(0, 5, 2):
yield (check_even, i)
def check_even(n):
assert n % 2 == 0
def setup_func():
"""set up... |
#!/usr/bin/env python3
num = int(input())
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print("fizz")
elif num % 5 == 0:
print("buzz")
else:
print('you are wrong kiddo')
# the point of fizzbuzz is to see if a number is divisible by 3 and 5, or just one, or neither.
# for more info c... | num = int(input())
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print('fizz')
elif num % 5 == 0:
print('buzz')
else:
print('you are wrong kiddo') |
class BuildError(Exception):
def __init__(self, message: str):
super().__init__(message)
class MissedRequiredParamError(BuildError):
def __init__(self, param_name: str):
message = f'Required param "{param_name}" is missed'
super().__init__(message)
class FunctionNotExistError(BuildEr... | class Builderror(Exception):
def __init__(self, message: str):
super().__init__(message)
class Missedrequiredparamerror(BuildError):
def __init__(self, param_name: str):
message = f'Required param "{param_name}" is missed'
super().__init__(message)
class Functionnotexisterror(BuildEr... |
def func(arg, opt=1, *args, **kwargs):
print(arg, opt, args, kwargs)
func(0)
func(0, 10)
func(0, 10, 20)
func(0, 10, 20, 30)
func(0, 10, 20, 30, key='value')
func(0, 10, 20, 30, key='value', key2='v2')
| def func(arg, opt=1, *args, **kwargs):
print(arg, opt, args, kwargs)
func(0)
func(0, 10)
func(0, 10, 20)
func(0, 10, 20, 30)
func(0, 10, 20, 30, key='value')
func(0, 10, 20, 30, key='value', key2='v2') |
# class definition
class MyClass:
pass
# The __init__() Method
# attributes
# methods
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def sayhi(self):
print("Hi, my name is %s, and I'm %s" % (self.__name, self.__age))
def get_age(self):
... | class Myclass:
pass
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def sayhi(self):
print("Hi, my name is %s, and I'm %s" % (self.__name, self.__age))
def get_age(self):
return self.__age
def set_age(self, num):
if isinst... |
print('Opening dummy.txt')
#open dummy.txt to read it as "in_stream" (in_stream is the variable)
with open('dummy.txt', 'r') as in_stream:
print('Opening output.txt')
#open output.txt to write in it, call it "out_stream"
with open('output.txt', 'w') as out_stream:
#for every line in the dummy.txt input file
#en... | print('Opening dummy.txt')
with open('dummy.txt', 'r') as in_stream:
print('Opening output.txt')
with open('output.txt', 'w') as out_stream:
for (line_index, line) in enumerate(in_stream):
line = line.strip()
word_list = line.split()
word_list.sort()
for w... |
count = int(input())
numbers_list = []
for _x in range(count):
numbers_list.append(int(input()))
sum_numbers = 0
count_numbers = len(numbers_list)
for x in numbers_list:
sum_numbers += x
mean = sum_numbers / count_numbers
print(mean)
| count = int(input())
numbers_list = []
for _x in range(count):
numbers_list.append(int(input()))
sum_numbers = 0
count_numbers = len(numbers_list)
for x in numbers_list:
sum_numbers += x
mean = sum_numbers / count_numbers
print(mean) |
#! /usr/bin/env python3
AsciiBinFmt, AsciiGrayFmt, AsciiPixelFmt = range(1, 4)
BinBinFmt, BinGrayFmt, BinPixelFmt = range(4, 7)
ext = ["", "pbm", "pgm", "ppm", "pbm", "pgm", "ppm"]
def isBinFmt(fmt):
return fmt % 3 == 1
def isGrayFmt(fmt):
return fmt % 3 == 2
def isPixelFmt(fmt):
return fmt % 3 == 0
c... | (ascii_bin_fmt, ascii_gray_fmt, ascii_pixel_fmt) = range(1, 4)
(bin_bin_fmt, bin_gray_fmt, bin_pixel_fmt) = range(4, 7)
ext = ['', 'pbm', 'pgm', 'ppm', 'pbm', 'pgm', 'ppm']
def is_bin_fmt(fmt):
return fmt % 3 == 1
def is_gray_fmt(fmt):
return fmt % 3 == 2
def is_pixel_fmt(fmt):
return fmt % 3 == 0
class... |
'''
The function has been made even more general by parameterizing the size of one sub box.
'''
def drawBox(length, cellSize):
for i in range(length):
printBoxLines(length, cellSize, "*", "---", 1)
printBoxLines(length, cellSize, "|", " ", cellSize)
printBoxLines(length, cellSize, "*", "---"... | """
The function has been made even more general by parameterizing the size of one sub box.
"""
def draw_box(length, cellSize):
for i in range(length):
print_box_lines(length, cellSize, '*', '---', 1)
print_box_lines(length, cellSize, '|', ' ', cellSize)
print_box_lines(length, cellSize, '*',... |
GRID_SIZE = 5
# Bingo numbers and grids.
def get_b_and_g(lines):
bingo_numbers = []
grids = []
is_first = True
for line in lines:
if is_first:
bingo_numbers = [int(s) for s in line.split(",") if s.isdigit()]
is_first = False
continue
if line == "":
... | grid_size = 5
def get_b_and_g(lines):
bingo_numbers = []
grids = []
is_first = True
for line in lines:
if is_first:
bingo_numbers = [int(s) for s in line.split(',') if s.isdigit()]
is_first = False
continue
if line == '':
grids.append([])
... |
# Even Fibonacci numbers
# Each new term in the Fibonacci sequence is generated
# by adding the previous two terms. By starting with
# 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence
# whose values do not exceed four million, find th... | upper_bound = 4000000
def run():
even_fib_sum = 0
fib_last = 1
fib_current = 1
while fib_current <= UPPER_BOUND:
if fib_current % 2 == 0:
even_fib_sum += fib_current
fib_new = fib_last + fib_current
fib_last = fib_current
fib_current = fib_new
print('The ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def f1(a,b,c=0,*args,**kwargs):
print('a=',a,'b=',b,'c=',c,'args=',args,'kwargs=',kwargs)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
#f1(1,2,3,'a','b',x=99)
#f2(1,2,d=99,ext=None)
args=(1,2,3,4)
kw={'d':99,'x':'#'}
f1(*args,**kw)
args=(... | def f1(a, b, c=0, *args, **kwargs):
print('a=', a, 'b=', b, 'c=', c, 'args=', args, 'kwargs=', kwargs)
def f2(a, b, c=0, *, d, **kw):
print('a=', a, 'b=', b, 'c=', c, 'd=', d, 'kw=', kw)
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
args = (1, 2, 3)
kw = {'d': 88, '*': '#'}
f2(*args, **kw) |
# Robot variable file using Python syntax
# Installed browser selection
# BROWSER = "chrome"
# BROWSER = "firefox"
BROWSER = "headlessfirefox"
# Helmi login credentials:
# replace <helmiurl> with your area specific value https://alue.helmi.fi
# replace <user> and <pass> with your Helmi username and password
HELMI_LO... | browser = 'headlessfirefox'
helmi_login_page = '<helmiurl>'
helmi_username = '<user>'
helmi_password = '<pass>'
gmail_userid = '<email>'
helmi_target_email = '<email>' |
class Solution:
def printMinNumberForPattern(ob, S):
# code here
count = 1
stack = []
ans = ""
for i in S:
if i == "D":
stack.append(count)
count += 1
else:
stack.append(count)
coun... | class Solution:
def print_min_number_for_pattern(ob, S):
count = 1
stack = []
ans = ''
for i in S:
if i == 'D':
stack.append(count)
count += 1
else:
stack.append(count)
count += 1
... |
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
nextAvail = 1
for i in range(1, len(nums)):
if nums[i] == nums[nextAvail-1]:
i += 1
else:
nums[nextAvail] = nums[i]
nextAvail += 1... | class Solution:
def remove_duplicates(self, nums):
if len(nums) == 0:
return 0
next_avail = 1
for i in range(1, len(nums)):
if nums[i] == nums[nextAvail - 1]:
i += 1
else:
nums[nextAvail] = nums[i]
next_avai... |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
dp = 0
ans = 0
n = len(nums)
for i in range(2, n):
pre = nums[i - 1] - nums[i - 2]
now = nums[i] - nums[i - 1]
if now == pre:
dp += 1
ans +=... | class Solution:
def number_of_arithmetic_slices(self, nums: List[int]) -> int:
dp = 0
ans = 0
n = len(nums)
for i in range(2, n):
pre = nums[i - 1] - nums[i - 2]
now = nums[i] - nums[i - 1]
if now == pre:
dp += 1
an... |
def findMax(some_dict):
positions = set() # output variable
max_value = -1
for k, v in some_dict.items():
if v == max_value:
positions.add(k)
if v > max_value:
max_value = v
positions = set() # output variable
positions.add(k)
return positions, max_value
def getChangeTimes(cowL... | def find_max(some_dict):
positions = set()
max_value = -1
for (k, v) in some_dict.items():
if v == max_value:
positions.add(k)
if v > max_value:
max_value = v
positions = set()
positions.add(k)
return (positions, max_value)
def get_change_... |
def mdc(a,b):
if a<b:
return mdc(b,a)
else:
if b==0:
return a
else:
return mdc(b, a % b)
print(mdc(12,8))
print(mdc(12,10))
| def mdc(a, b):
if a < b:
return mdc(b, a)
elif b == 0:
return a
else:
return mdc(b, a % b)
print(mdc(12, 8))
print(mdc(12, 10)) |
# -*- coding: utf-8 -*-
'''
module used while testing mock hubs provided in 'testing'.
'''
__contracts__ = ['testing']
def noparam(hub):
pass
def echo(hub, param):
return param
def signature_func(hub, param1, param2='default'):
pass
def attr_func(hub):
pass
attr_func.test = True
attr_func._... | """
module used while testing mock hubs provided in 'testing'.
"""
__contracts__ = ['testing']
def noparam(hub):
pass
def echo(hub, param):
return param
def signature_func(hub, param1, param2='default'):
pass
def attr_func(hub):
pass
attr_func.test = True
attr_func.__test__ = True
async def async_e... |
code = "he.elk.set.to"
decode = code.split("e")
print(decode[-1])
| code = 'he.elk.set.to'
decode = code.split('e')
print(decode[-1]) |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(M, A):
hash = [0] * (M + 1)
slices = 0
max_slices = 1000000000
head = 0
for tail in range(len(A)):
while head < len(A) and ( not hash[A[head]]):
hash[A[head]] = 1
s... | def solution(M, A):
hash = [0] * (M + 1)
slices = 0
max_slices = 1000000000
head = 0
for tail in range(len(A)):
while head < len(A) and (not hash[A[head]]):
hash[A[head]] = 1
slices += head - tail + 1
if slices > max_slices:
return max_slic... |
#less than operator
print(4<10) # --- L1
print(10<4) # --- L2
print(4<4.0) # --- L3
print(4.0<4) # --- L4
print('python'<'Python') #--- L5
print('python'<'python') # --- L6
print('Python'<'python') #--- L7
| print(4 < 10)
print(10 < 4)
print(4 < 4.0)
print(4.0 < 4)
print('python' < 'Python')
print('python' < 'python')
print('Python' < 'python') |
DIGITS = "0123456789abcdef"
def convert_base_stack(decimal_number, base):
remainder_stack = []
while decimal_number > 0:
remainder = decimal_number % base
remainder_stack.append(remainder)
decimal_number = decimal_number // base
new_digits = []
while remainder_stack:
... | digits = '0123456789abcdef'
def convert_base_stack(decimal_number, base):
remainder_stack = []
while decimal_number > 0:
remainder = decimal_number % base
remainder_stack.append(remainder)
decimal_number = decimal_number // base
new_digits = []
while remainder_stack:
new... |
def add(a,b):
return a+b
def substract(a,b):
return a * b
## Imagine I made a valid change
def absolut(a,b):
return np.abs(a,b)
| def add(a, b):
return a + b
def substract(a, b):
return a * b
def absolut(a, b):
return np.abs(a, b) |
class Solution:
def findRestaurant(self, list1, list2):
mp1, mp2 = {x: i for i, x in enumerate(list1)}, {x: i for i, x in enumerate(list2)}
ans = [10 ** 4, []]
for k, v in mp1.items():
if k in mp2 and v + mp2[k] == ans[0]: ans[1].append(k)
elif k in mp2 and v + mp2[k]... | class Solution:
def find_restaurant(self, list1, list2):
(mp1, mp2) = ({x: i for (i, x) in enumerate(list1)}, {x: i for (i, x) in enumerate(list2)})
ans = [10 ** 4, []]
for (k, v) in mp1.items():
if k in mp2 and v + mp2[k] == ans[0]:
ans[1].append(k)
... |
# Solution 1
# O(n) time / O(n) space
def branchSums(root):
sums = []
calculateBranchSums(root, 0, sums)
return sums
def calculateBranchSums(node, runningSum, sums):
if node is None:
return sums
newRunningSum = runningSum + node.value
if node.left is None and node.right is None:
... | def branch_sums(root):
sums = []
calculate_branch_sums(root, 0, sums)
return sums
def calculate_branch_sums(node, runningSum, sums):
if node is None:
return sums
new_running_sum = runningSum + node.value
if node.left is None and node.right is None:
sums.append(newRunningSum)
... |
def minInsertions(s: str) -> int:
dp = [[0] * len(s) for _ in range(len(s))]
for left in range(len(s) - 1, -1, -1):
for right in range(0, len(s)):
if left >= right:
continue
if s[left] == s[right]:
dp[left][right] = dp[left+1][right-1]
... | def min_insertions(s: str) -> int:
dp = [[0] * len(s) for _ in range(len(s))]
for left in range(len(s) - 1, -1, -1):
for right in range(0, len(s)):
if left >= right:
continue
if s[left] == s[right]:
dp[left][right] = dp[left + 1][right - 1]
... |
# -*- coding: UTF-8 -*-
PROXYSOCKET = ''
RETRY_TIMES = 5
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json,application/xml'
}
INPUT_FILE = 'dependencies/input.xlsx'
API_DEBUG = True
AP... | proxysocket = ''
retry_times = 5
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'application/json,application/xml'}
input_file = 'dependencies/input.xlsx'
api_debug = True
api_port = 5678
post_time = 60 |
N = int(input(""))
for x in range(0, N):
if N > 0:
s = input("")
s = s.split() #separar
if s[0] == s[1]:
print("empate")
else:
if s[0] == "tesoura":
if s[1] == "papel" or s[1] =="lagarto":
print("rajesh")
... | n = int(input(''))
for x in range(0, N):
if N > 0:
s = input('')
s = s.split()
if s[0] == s[1]:
print('empate')
elif s[0] == 'tesoura':
if s[1] == 'papel' or s[1] == 'lagarto':
print('rajesh')
elif s[1] == 'pedra' or s[1] == 'spock'... |
#===============================================================================
# Copyright 2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | load('@onedal//dev/bazel:utils.bzl', 'utils', 'paths')
def _create_symlinks(repo_ctx, root, entries, substitutions={}):
for entry in entries:
entry_fmt = utils.substitude(entry, substitutions)
src_entry_path = paths.join(root, entry_fmt)
dst_entry_path = entry_fmt
repo_ctx.symlink(s... |
def intersects(line1, line2):
def onSeg(p, q, r):
if (q[0] <= max(p[0],r[0]) and q[0] >= min(p[0],r[0]) and
q[0] <= max(p[1],r[1]) and q[1] >= min(p[1],r[1])):
return True
return False
#0 -> colinear, 1 -> clockwise, 2 -> ccw
def orientation(p,q,r):
v... | def intersects(line1, line2):
def on_seg(p, q, r):
if q[0] <= max(p[0], r[0]) and q[0] >= min(p[0], r[0]) and (q[0] <= max(p[1], r[1])) and (q[1] >= min(p[1], r[1])):
return True
return False
def orientation(p, q, r):
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r... |
# Q1
class Thing:
pass
example = Thing()
print(Thing)
print(example)
# Q2
class Thing2:
letters = 'abc'
print(Thing2.letters)
# Q3
class Thing3:
def __init__(self):
self.letters = 'xyz'
thing3 = Thing3()
print(thing3.letters)
# Q4
class Element:
def __init__(self, name, symbol, numb... | class Thing:
pass
example = thing()
print(Thing)
print(example)
class Thing2:
letters = 'abc'
print(Thing2.letters)
class Thing3:
def __init__(self):
self.letters = 'xyz'
thing3 = thing3()
print(thing3.letters)
class Element:
def __init__(self, name, symbol, number):
self.name = nam... |
j = 7
for i in range(1,(10),2):
for jump in range(0,3):
print("I={0} J={1}".format(i,j))
j = j - 1
j = 7
| j = 7
for i in range(1, 10, 2):
for jump in range(0, 3):
print('I={0} J={1}'.format(i, j))
j = j - 1
j = 7 |
result = [
[0.6, 0.7],
{'a': 'b'},
None,
[
'uu',
'ii',
[None],
[7, 8, 9, {}]
]
]
| result = [[0.6, 0.7], {'a': 'b'}, None, ['uu', 'ii', [None], [7, 8, 9, {}]]] |
def DependsOn(pack, deps):
return And([ Implies(pack, dep) for dep in deps ])
def Conflict(p1, p2):
return Or(Not(p1), Not(p2))
a, b, c, d, e, f, g, z = Bools('a b c d e f g z')
solve(DependsOn(a, [b, c, z]),
DependsOn(b, [d]),
DependsOn(c, [Or(d, e), Or(f, g)]),
Conflict(d, e),
a, z)... | def depends_on(pack, deps):
return and([implies(pack, dep) for dep in deps])
def conflict(p1, p2):
return or(not(p1), not(p2))
(a, b, c, d, e, f, g, z) = bools('a b c d e f g z')
solve(depends_on(a, [b, c, z]), depends_on(b, [d]), depends_on(c, [or(d, e), or(f, g)]), conflict(d, e), a, z) |
#
# PySNMP MIB module SW-LAYER2-PORT-MANAGEMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-LAYER2-PORT-MANAGEMENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
class Queue:
# Constructor to initiate queue
def __init__(self, queue=None):
if queue is None:
queue = []
self.queue = queue
# push to append an item into queue
def push(self, value):
self.queue.append(value)
# front to return starting element from queue
de... | class Queue:
def __init__(self, queue=None):
if queue is None:
queue = []
self.queue = queue
def push(self, value):
self.queue.append(value)
def front(self):
if Queue.empty(self) is False:
return self.queue[0]
else:
raise index_e... |
class EnumType(object):
# Internal data storage uses integer running from 0 to range_end
# range_end is set to the number of possible values that the Enum can take on
# External representation of Enum starts at 1 and goes to range_end + 1
def __init__(self, initial_value):
self.set(initial_valu... | class Enumtype(object):
def __init__(self, initial_value):
self.set(initial_value)
def load_json(self, json_struct):
self.set(json_struct)
def json_serializer(self):
if self.value < 0:
return None
else:
return type(self).possible_values[self.value]
... |
# -*- coding: utf-8 -*-
#
class LineLoop(object):
_ID = 0
dimension = 1
def __init__(self, lines):
self.lines = lines
self.id = 'll{}'.format(LineLoop._ID)
LineLoop._ID += 1
self.code = '\n'.join([
'{} = newll;'.format(self.id),
'Line Loop({}) = {... | class Lineloop(object):
_id = 0
dimension = 1
def __init__(self, lines):
self.lines = lines
self.id = 'll{}'.format(LineLoop._ID)
LineLoop._ID += 1
self.code = '\n'.join(['{} = newll;'.format(self.id), 'Line Loop({}) = {{{}}};'.format(self.id, ', '.join([l.id for l in lines]... |
# Binary search
def binary_search(A: list, x: int):
i = 0
j = len(A)
while i < j:
m = (i + j) // 2
if A[m] == x:
return True
elif A[m] > x:
j = m
else:
i = m + 1
return False
def recursive_binary_search(A: list, x: int, start: int, end: int):
if end >= start:
m = start... | def binary_search(A: list, x: int):
i = 0
j = len(A)
while i < j:
m = (i + j) // 2
if A[m] == x:
return True
elif A[m] > x:
j = m
else:
i = m + 1
return False
def recursive_binary_search(A: list, x: int, start: int, end: int):
if e... |
class Solution:
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
s = list(s); lines = 1; line = 0
while s:
if line + widths[ord(s[0])-97] > 100:
lines += 1; line = 0
else:
line += widths[ord(s.pop(0))-97]
return [lines, ... | class Solution:
def number_of_lines(self, widths: List[int], s: str) -> List[int]:
s = list(s)
lines = 1
line = 0
while s:
if line + widths[ord(s[0]) - 97] > 100:
lines += 1
line = 0
else:
line += widths[ord(s.p... |
Lakh = 100 * 1000
Crore = 100 * Lakh
biggerNumbers = {
100 : "sau",
1000 : "hazaar",
Lakh : "laakh",
Crore : "karoD"
}
| lakh = 100 * 1000
crore = 100 * Lakh
bigger_numbers = {100: 'sau', 1000: 'hazaar', Lakh: 'laakh', Crore: 'karoD'} |
class Match:
def __init__(self):
self.date = ""
self.round = ""
self.tournament = ""
self.home = ""
self.score = ""
self.away = ""
self.channels = ""
| class Match:
def __init__(self):
self.date = ''
self.round = ''
self.tournament = ''
self.home = ''
self.score = ''
self.away = ''
self.channels = '' |
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prod = 1
prods = [1]*len(nums)
for i in range(len(nums)):
prods[i] = prod
prod *= nums[i]
prod = 1
for i in range(len(nums)-1, -1, -1):
prods[i... | class Solution:
def product_except_self(self, nums: List[int]) -> List[int]:
prod = 1
prods = [1] * len(nums)
for i in range(len(nums)):
prods[i] = prod
prod *= nums[i]
prod = 1
for i in range(len(nums) - 1, -1, -1):
prods[i] *= prod
... |
def all_index(array, num):
indx = []
for i in range(0,len(array)):
for j in range(0,array[i].count(num)):
if j == 0:
indx.append([i, array[i].index(num)])
else:
indx.append([i, array[i].index(num,indx[j-1][1]+1)])
return indx
tic = [[1,1,0]... | def all_index(array, num):
indx = []
for i in range(0, len(array)):
for j in range(0, array[i].count(num)):
if j == 0:
indx.append([i, array[i].index(num)])
else:
indx.append([i, array[i].index(num, indx[j - 1][1] + 1)])
return indx
tic = [[1, ... |
def encrypt(message, key):
encrypted_message = ''
for char in message:
if char.isalpha():
#ord() returns an integer representing the Unicode code point of the character
unicode_num = ord(char)
unicode_num += key
if char.isupper():
... | def encrypt(message, key):
encrypted_message = ''
for char in message:
if char.isalpha():
unicode_num = ord(char)
unicode_num += key
if char.isupper():
if unicode_num > ord('Z'):
unicode_num -= 26
elif unicode_num < ... |
# In "and" operator if ONE is false the whole is false
# in "or" operator if ONE is true the whole is true
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cms? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster")
age = int(input("What is your age... | print('Welcome to the rollercoaster!')
height = int(input('What is your height in cms? '))
bill = 0
if height >= 120:
print('You can ride the rollercoaster')
age = int(input('What is your age? '))
if age < 12:
bill = 5
print('Child tickets are $5')
elif age <= 18:
bill = 7
... |
class User:
def __init__(self, username, name, email, bio, repositories):
self.username = username
self.name = name
self.email = email
self.bio = bio
self.repositories = repositories
def __str__(self):
final = "Name: {} ({}):".format(self.name, self.username)
... | class User:
def __init__(self, username, name, email, bio, repositories):
self.username = username
self.name = name
self.email = email
self.bio = bio
self.repositories = repositories
def __str__(self):
final = 'Name: {} ({}):'.format(self.name, self.username)
... |
#-------------------------------------------------------------------------------
def checkUser( username, passwd ):
return False
#-------------------------------------------------------------------------------
def checkIfUserAvailable( username ):
return False
#------------------------------------------------... | def check_user(username, passwd):
return False
def check_if_user_available(username):
return False
def get_user_email(username):
return None
def allow_password_change(username):
return False
def change_user_password(username, oldpass, newpass):
return False |
# using modified merge function
def compute_union(arr1, arr2):
union = []
index1 = 0
index2 = 0
while (index1 < len(arr1)) and (index2 < len(arr2)):
if arr1[index1] < arr2[index2]:
union.append(arr1[index1])
index1 += 1
elif arr1[index1] > arr2[index2]:
... | def compute_union(arr1, arr2):
union = []
index1 = 0
index2 = 0
while index1 < len(arr1) and index2 < len(arr2):
if arr1[index1] < arr2[index2]:
union.append(arr1[index1])
index1 += 1
elif arr1[index1] > arr2[index2]:
union.append(arr2[index2])
... |
levels = [
#{
# 'geometry': [ ' bbb ',
# ' bbb ',
# ' bbb ',
# ' bbb ',
# ' b ',
# ' b ',
# ' bbb ',
# ... | levels = [{'geometry': [' ', ' ', ' bbb ', ' bbbb ', ' bbbb ', ' bbb ', ' bbb ', ' bbbb ', ' bbbb ', ' bebb ', ' bbbb ', ' bb ', ' ', ' ', ' '], 'start': {'x': 6, 'y': 3}, 'swatches': []}, {'geometry': [' bbbbb ', ' bbbbb ',... |
while True:
a, b, c = sorted(map(int, input().split()))
if a == 0 and b == 0 and c == 0:
break
print("right" if a ** 2 + b ** 2 == c ** 2 else "wrong")
| while True:
(a, b, c) = sorted(map(int, input().split()))
if a == 0 and b == 0 and (c == 0):
break
print('right' if a ** 2 + b ** 2 == c ** 2 else 'wrong') |
# EASY
# count each element in array and store in dict{}
# loop through the array check if exist nums[i]+1 in dict{}
class Solution:
def findLHS(self, nums: List[int]) -> int:
n = len(nums)
appear = {}
for i in range(n):
appear[nums[i]] = appear.get(nums[i],0) + 1
... | class Solution:
def find_lhs(self, nums: List[int]) -> int:
n = len(nums)
appear = {}
for i in range(n):
appear[nums[i]] = appear.get(nums[i], 0) + 1
result = 0
for (k, v) in appear.items():
if k + 1 in appear:
result = max(result, v +... |
class Clock():
# Set initial Clock state
def __init__(self, hours, minutes):
timeDic = self.calculateMinutes(minutes)
self.minutes = timeDic['minutes']
self.hours = self.calculateHour(hours + timeDic['hours'])
self.time = self.generateTimeString()
# Add minutes to the cl... | class Clock:
def __init__(self, hours, minutes):
time_dic = self.calculateMinutes(minutes)
self.minutes = timeDic['minutes']
self.hours = self.calculateHour(hours + timeDic['hours'])
self.time = self.generateTimeString()
def add(self, numMinutes=0):
time_dic = self.calc... |
class Order:
__slots__ = (
'id',
'order_number',
'customer_name',
'shipping_name',
'order_date',
'order_details_url',
'subtotal',
'shipping_fee',
'tax',
'status',
'retail_bonus',
'order_type',
'customer_url',
... | class Order:
__slots__ = ('id', 'order_number', 'customer_name', 'shipping_name', 'order_date', 'order_details_url', 'subtotal', 'shipping_fee', 'tax', 'status', 'retail_bonus', 'order_type', 'customer_url', 'customer_id', 'customer_contact', 'total', 'qv', 'hostess', 'party', 'ship_date', 'line_items', 'shipping_a... |
'''
Find the largest continuous sum
'''
def largest_cont_sum(arr):
if len(arr) == 0:
return 0
cur_sum = arr[0]
max_sum = arr[0]
for item in arr[1:]:
cur_sum = max(cur_sum+item, item)
if cur_sum >= max_sum:
max_sum = cur_sum
return max_sum
| """
Find the largest continuous sum
"""
def largest_cont_sum(arr):
if len(arr) == 0:
return 0
cur_sum = arr[0]
max_sum = arr[0]
for item in arr[1:]:
cur_sum = max(cur_sum + item, item)
if cur_sum >= max_sum:
max_sum = cur_sum
return max_sum |
class Solution:
def matrixReshape(self, mat: List[List[int]], newRows: int, newCols: int) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
if rows * cols != newRows * newCols:
return mat
newMat = [[0] * newCols for _ in range(newRows)]
for x in range(rows... | class Solution:
def matrix_reshape(self, mat: List[List[int]], newRows: int, newCols: int) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
if rows * cols != newRows * newCols:
return mat
new_mat = [[0] * newCols for _ in range(newRows)]
for x in range(rows... |
def multiplication_table(size):
return [[ x * y for y in range(1, size + 1)] for x in range(1, size + 1)]
print(multiplication_table(3)) # [[1,2,3],[2,4,6],[3,6,9]] | def multiplication_table(size):
return [[x * y for y in range(1, size + 1)] for x in range(1, size + 1)]
print(multiplication_table(3)) |
a=5
b=50
if a>=b:
c=a-b
else:
c=a-b
print(c)
| a = 5
b = 50
if a >= b:
c = a - b
else:
c = a - b
print(c) |
# -*- coding: utf-8 -*-
# Put here your production specific settings
ADMINS = [
('Francesca Alberti', 'francydark91@gmail.com'),
]
EMAIL_SUBJECT_PREFIX = '[ALBERTIFRA]' | admins = [('Francesca Alberti', 'francydark91@gmail.com')]
email_subject_prefix = '[ALBERTIFRA]' |
# autocord
# package for simple automation with discord client
#
# m: error
class ApiError(Exception):
pass | class Apierror(Exception):
pass |
class HarmonyConfig(object):
def __init__(self, config):
self.json = config
def get_activities(self):
return self._build_kv_menu('activity')
def get_devices(self):
return self._build_kv_menu('device')
def _build_kv_menu(self, key):
menu = {}
for d in self.json[... | class Harmonyconfig(object):
def __init__(self, config):
self.json = config
def get_activities(self):
return self._build_kv_menu('activity')
def get_devices(self):
return self._build_kv_menu('device')
def _build_kv_menu(self, key):
menu = {}
for d in self.json... |
# Copyright 2018 Databricks, Inc.
VERSION = "1.12.1.dev0"
| version = '1.12.1.dev0' |
# Copyright 2021 BenchSci Analytics Inc.
# Copyright 2021 Nate Gay
#
# 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 a... | """rules_kustomize"""
load('//:kustomization.bzl', _kustomization='kustomization')
load('//:kustomize_image.bzl', _kustomize_image='kustomize_image')
kustomization = _kustomization
kustomize_image = _kustomize_image |
class Program:
language = 'Python'
def say_hello():
print(f'Hello from {Program.language}')
p = Program()
print(type(p))
print(p.__dict__)
print(Program.__dict__)
print(p.__class__)
# BEST PRACTICES
print(isinstance(p, Program))
| class Program:
language = 'Python'
def say_hello():
print(f'Hello from {Program.language}')
p = program()
print(type(p))
print(p.__dict__)
print(Program.__dict__)
print(p.__class__)
print(isinstance(p, Program)) |
def roman_to_int(s):
s = s.upper()
try:
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
... | def roman_to_int(s):
s = s.upper()
try:
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
... |
class OuterClass(object):
def outer_method(self):
def nested_function():
class InnerClass(object):
class InnermostClass(object):
def innermost_method(self):
print()
InnerClass.InnermostClass().innermost_method()
... | class Outerclass(object):
def outer_method(self):
def nested_function():
class Innerclass(object):
class Innermostclass(object):
def innermost_method(self):
print()
InnerClass.InnermostClass().innermost_method()
... |
# S-box Table
# We have 8 different 4x16 matrices for each S box
#It converts 48 bits to 32 bits
# Each S box will get 6 bits and output will be 4 bits
s_box = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8... | s_box = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, ... |
# Split target image into an MxN grid
def splitImage(image, size):
W, H = image.size[0], image.size[1]
m, n = size
w, h = int(W/n), int(H/m)
imgs = []
for j in range(m):
for i in range(n):
# append cropped image
imgs.append(image.crop((i*w, j*h, (i+1)*w, (j+1)*h... | def split_image(image, size):
(w, h) = (image.size[0], image.size[1])
(m, n) = size
(w, h) = (int(W / n), int(H / m))
imgs = []
for j in range(m):
for i in range(n):
imgs.append(image.crop((i * w, j * h, (i + 1) * w, (j + 1) * h)))
return imgs |
def is_vowel(s: str) -> bool:
if len(s) == 0 or len(s) > 1:
return False
vowel = ["a", "e", "i", "o", "u"]
for item in s:
if item.lower() in vowel:
return True
return False | def is_vowel(s: str) -> bool:
if len(s) == 0 or len(s) > 1:
return False
vowel = ['a', 'e', 'i', 'o', 'u']
for item in s:
if item.lower() in vowel:
return True
return False |
# content of test_sample.py
def func(x):
return x + 2
def test_answer():
assert func(3) == 5
def test_2():
assert func(10) == 12 | def func(x):
return x + 2
def test_answer():
assert func(3) == 5
def test_2():
assert func(10) == 12 |
'''
Created on Aug 7, 2017
@author: duncan
'''
class Subscriber(object):
def __init__(self, subscriber_id, subscriber_email):
self.subscriber_id = subscriber_id
self.subscriber_email = subscriber_email
class Site(object):
def __init__(self, site_id, site_name):
self.site_id... | """
Created on Aug 7, 2017
@author: duncan
"""
class Subscriber(object):
def __init__(self, subscriber_id, subscriber_email):
self.subscriber_id = subscriber_id
self.subscriber_email = subscriber_email
class Site(object):
def __init__(self, site_id, site_name):
self.site_id = site_i... |
# 2. Use the function to compute the square of all numbers of a given list
def squares(a):
squared = a*a
return squared
li = [1, 2, 3, 4, 5]
lisq=[]
for el in li:
sq = squares(el)
lisq.append(sq)
print(lisq) | def squares(a):
squared = a * a
return squared
li = [1, 2, 3, 4, 5]
lisq = []
for el in li:
sq = squares(el)
lisq.append(sq)
print(lisq) |
# coding: utf-8
__author__ = 'Keita Tomochika'
__version__ = '0.0.1'
__license__ = 'MIT'
| __author__ = 'Keita Tomochika'
__version__ = '0.0.1'
__license__ = 'MIT' |
# Subject - the one to be observed
# Observers - the one monitoring or observing the subject for changes
class Subject:
def __init__(self):
self.__observers = []
def register(self, observer):
self.__observers.append(observer)
def notifyAll(self, *args, **kwargs):
for observer in ... | class Subject:
def __init__(self):
self.__observers = []
def register(self, observer):
self.__observers.append(observer)
def notify_all(self, *args, **kwargs):
for observer in self.__observers:
observer.notify(self, *args, **kwargs)
class Observer1:
def __init__(... |
def galoisMult(a, b):
'''
The parameter b will be either 1, 2 or 3. Multiplication by 3 is defined as multiplication by 2 then adding the
original value. For example 3x6 is equivalent to 2x6+6. The multiplication by 2 is done with a left shift
(a <<= 1) and dropping the MSB. If that bit had been a... | def galois_mult(a, b):
"""
The parameter b will be either 1, 2 or 3. Multiplication by 3 is defined as multiplication by 2 then adding the
original value. For example 3x6 is equivalent to 2x6+6. The multiplication by 2 is done with a left shift
(a <<= 1) and dropping the MSB. If that bit had been a ... |
diff_counter = 0
A = input()
B = input()
for i in range(len(A)):
if A[i] != B[i]:
diff_counter += 1
if diff_counter > 1:
print("LARRY IS DEAD!")
elif diff_counter == 1:
print("LARRY IS SAVED!")
else:
print("LARRY IS DEAD!")
| diff_counter = 0
a = input()
b = input()
for i in range(len(A)):
if A[i] != B[i]:
diff_counter += 1
if diff_counter > 1:
print('LARRY IS DEAD!')
elif diff_counter == 1:
print('LARRY IS SAVED!')
else:
print('LARRY IS DEAD!') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.