content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""This module contains classes.
"""
class AnObject:
"""Defines an object
Args:
a (bool): This is param `a` description.
b (np.array): This is param `b` description.
Attributes:
a (bool): An attribute.
b (np.array): Another attribute.
Notes:
There's a little ... | """This module contains classes.
"""
class Anobject:
"""Defines an object
Args:
a (bool): This is param `a` description.
b (np.array): This is param `b` description.
Attributes:
a (bool): An attribute.
b (np.array): Another attribute.
Notes:
There's a little o... |
__all__ = ['ADMIN']
ADMIN = """from django.contrib import admin
from . import models
{% for model in fields_dict %}
@admin.register(models.{{model.name}})
class {{ model.name }}Admin(admin.ModelAdmin):
list_display = [{% for field in model.fields %}{% if field == 'id' %}'pk'{% else %}'{{field}}'{% endif %}, {% e... | __all__ = ['ADMIN']
admin = "from django.contrib import admin\nfrom . import models\n{% for model in fields_dict %}\n\n@admin.register(models.{{model.name}})\nclass {{ model.name }}Admin(admin.ModelAdmin):\n list_display = [{% for field in model.fields %}{% if field == 'id' %}'pk'{% else %}'{{field}}'{% endif %}, {%... |
SELECT_NOTICES_FOR_RE_PACKAGE_AND_RESET_STATUS_TASK_ID = "select_notices_for_re_package_and_reset_status"
TRIGGER_WORKER_FOR_PACKAGE_BRANCH_TASK_ID = "trigger_worker_for_package_branch"
def test_selector_repackage_process_orchestrator(dag_bag):
assert dag_bag.import_errors == {}
dag = dag_bag.get_dag(dag_id="... | select_notices_for_re_package_and_reset_status_task_id = 'select_notices_for_re_package_and_reset_status'
trigger_worker_for_package_branch_task_id = 'trigger_worker_for_package_branch'
def test_selector_repackage_process_orchestrator(dag_bag):
assert dag_bag.import_errors == {}
dag = dag_bag.get_dag(dag_id='s... |
def taylor(val,precision):
next = 1
total = 0
for i in range(0,precision):
posorneg = (-1) ** i
top = val ** (2 * i + 1 ) * posorneg
final = 1
for i in range(next):
final = final * (next -i)
next +=2
total += top/final
print(top,final)
... | def taylor(val, precision):
next = 1
total = 0
for i in range(0, precision):
posorneg = (-1) ** i
top = val ** (2 * i + 1) * posorneg
final = 1
for i in range(next):
final = final * (next - i)
next += 2
total += top / final
print(top, final... |
# -*- coding: utf-8 -*-
"""Project metadata
Information to describe this project.
NOTE:
Be sure to "not" include any dependency here, otherwise they will need to be added to
`setup.py` as well.
To import it to `setup.py`, use `imp.load_source()` method to directly load it as a module.
"""
# The package... | """Project metadata
Information to describe this project.
NOTE:
Be sure to "not" include any dependency here, otherwise they will need to be added to
`setup.py` as well.
To import it to `setup.py`, use `imp.load_source()` method to directly load it as a module.
"""
package = 'neoRNA'
project = 'neoRNA'
... |
class MathUtils:
@staticmethod
def average(a, b):
return (a + b)/2
if __name__ == '__main__':
print(MathUtils.average(1, 2))
| class Mathutils:
@staticmethod
def average(a, b):
return (a + b) / 2
if __name__ == '__main__':
print(MathUtils.average(1, 2)) |
# Copyright (c) 2018, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | __author__ = 'Peter Ogden'
__copyright__ = 'Copyright 2018, Xilinx'
__email__ = 'pynq_support@xilinx.com'
_dac_adp = [('BlockAvailable', 'C_DAC_Slice{}{}_Enable', 'int'), ('InvSyncEnable', 'C_DAC_Invsinc_Ctrl{}{}', 'int'), ('MixMode', 'C_DAC_Mixer_Mode{}{}', 'int'), ('DecoderMode', 'C_DAC_Decoder_Mode{}{}', 'int')]
_da... |
# SD-WAN vManager username and password
vManager_USERNAME = "devnetuser"
vManager_PASSWORD = "Cisco123!"
# DNA Center username and password
DNAC_USER = "devnetuser"
DNAC_PASSWORD = "Cisco123!"
# Meraki API key
MERAKI_API_KEY = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0"
# E-mail username and password
EMAIL_USERNAME =... | v_manager_username = 'devnetuser'
v_manager_password = 'Cisco123!'
dnac_user = 'devnetuser'
dnac_password = 'Cisco123!'
meraki_api_key = '6bec40cf957de430a6f1f2baa056b99a4fac9ea0'
email_username = 'email_username'
email_password = 'email_password'
webex_teams_space = 'webex_team_space_more_than_70_characters'
webex_tea... |
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums: return []
window,res=[],[]
#window stores indices,and res stores result
for i,x in enumerate(nums):... | class Solution(object):
def max_sliding_window(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return []
(window, res) = ([], [])
for (i, x) in enumerate(nums):
if i >= k and window[0] ... |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
def divide_conquer(low, high, nums, target):
mid = int(low+high)/2
if nums[mid] == target:
return mid
elif nums[mid] < target:
divide_conquer(mid+1, high, nums, ta... | class Solution:
def search_insert(self, nums: List[int], target: int) -> int:
def divide_conquer(low, high, nums, target):
mid = int(low + high) / 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
divide_conquer(mid + 1, high,... |
class TestLogicReset:
def __init__(self,ctx):
self.ctx_=ctx
def advance(self, tms, tdi):
if ( tms ):
return self
else:
return self.ctx_.RunTestIdle
class RunTestIdle:
def __init__(self,ctx):
self.ctx_=ctx
def advance(self, tms, tdi):
if ( tms ):
return self.ctx_.SelectDR... | class Testlogicreset:
def __init__(self, ctx):
self.ctx_ = ctx
def advance(self, tms, tdi):
if tms:
return self
else:
return self.ctx_.RunTestIdle
class Runtestidle:
def __init__(self, ctx):
self.ctx_ = ctx
def advance(self, tms, tdi):
... |
class Node:
def __init__(self, doc):
self.doc = doc
| class Node:
def __init__(self, doc):
self.doc = doc |
class Images:
@staticmethod
def save(data,filename):
result=""
for i in data:
result+=chr(i);
saveBytes(filename,result)
@staticmethod
def visualize(data,height,width,offsetH=0,offsetW=0,scale=1):
x=0
y=0
for elem in data:
pixel=ord... | class Images:
@staticmethod
def save(data, filename):
result = ''
for i in data:
result += chr(i)
save_bytes(filename, result)
@staticmethod
def visualize(data, height, width, offsetH=0, offsetW=0, scale=1):
x = 0
y = 0
for elem in data:
... |
class printerClass():
def print_table(self, data, header):
data = list(data)
MaxLength = 0
data.insert(0, header)
for i in range(0, len(data)):
for x in data[i]:
MaxLength = len(str(x)) if MaxLength < len(str(x)) else MaxLength
print("-" * MaxL... | class Printerclass:
def print_table(self, data, header):
data = list(data)
max_length = 0
data.insert(0, header)
for i in range(0, len(data)):
for x in data[i]:
max_length = len(str(x)) if MaxLength < len(str(x)) else MaxLength
print('-' * MaxLeng... |
class SVG_map:
"""
This class generates the svg for the API response
This class initializes itself with title, total range and progress.
It calculates the necessary measurements from these info to generate
the SVG.
Attributes
----------
__title__ : str
title of the progress-bar... | class Svg_Map:
"""
This class generates the svg for the API response
This class initializes itself with title, total range and progress.
It calculates the necessary measurements from these info to generate
the SVG.
Attributes
----------
__title__ : str
title of the progress-bar... |
class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longestIncreasingPath(self, matrix):
# write your code here
m = len(matrix)
if m == 0:
return 0
cache = {}
n = len(matrix[0])
ma... | class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longest_increasing_path(self, matrix):
m = len(matrix)
if m == 0:
return 0
cache = {}
n = len(matrix[0])
max_len = 0
def dfs(r... |
class Solution:
def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]:
lo, hi = 0, 1
n = len(A)
while True:
mid = (lo + hi) / 2
idxes = [bisect.bisect(A, num / mid) for num in A]
cnt = sum(n - idx for idx in idxes)
if cnt < K:
... | class Solution:
def kth_smallest_prime_fraction(self, A: List[int], K: int) -> List[int]:
(lo, hi) = (0, 1)
n = len(A)
while True:
mid = (lo + hi) / 2
idxes = [bisect.bisect(A, num / mid) for num in A]
cnt = sum((n - idx for idx in idxes))
if ... |
# Search directories (list is searched downward until file is found)
# cwd is searched first by default
# Set to get resolver messages through stderr
# (helpful for observing and debugging path resolution)
# setting _more lists every path resolution attempt
resolver_debug = False
resolver_debug_more = False
fhs_dirs ... | resolver_debug = False
resolver_debug_more = False
fhs_dirs = {'dld': ['./dld/', '~/dml/dld/', '/usr/local/share/dml/dld/', '/usr/share/dml/dld/', '/etc/dml/dld/'], 'dss': ['./dss/', '~/dml/dss/', '/usr/local/share/dml/dss/', '/usr/share/dml/dss/', '/etc/dml/dss/']}
windows_dirs = {'dld': [], 'dss': []} |
class Graph:
def __init__(self, vertexes: int) -> None:
self.vertexes = vertexes
self.graph = [[float("inf") for _ in range(self.vertexes)] for _ in range(self.vertexes)]
def connect(self, u: int, v: int, w: int) -> None:
self.graph[u][v] = w
def show(self, matrix: list) -> None:
... | class Graph:
def __init__(self, vertexes: int) -> None:
self.vertexes = vertexes
self.graph = [[float('inf') for _ in range(self.vertexes)] for _ in range(self.vertexes)]
def connect(self, u: int, v: int, w: int) -> None:
self.graph[u][v] = w
def show(self, matrix: list) -> None:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 15:40:19 2018
@author: User
"""
class Airlines(object):
''' Fields: code(Str), dates(Int), price(Nat)'''
allAirlines = []
allCodes = []
allDates = []
allPrices = []
registry = []
def addAir(self, name, code, dates, price):... | """
Created on Tue Jan 9 15:40:19 2018
@author: User
"""
class Airlines(object):
""" Fields: code(Str), dates(Int), price(Nat)"""
all_airlines = []
all_codes = []
all_dates = []
all_prices = []
registry = []
def add_air(self, name, code, dates, price):
self.registry.append(self)
... |
# Runtime: 40 ms, faster than 91.18% of Python3 online submissions for Find Peak Element.
# Memory Usage: 13.9 MB, less than 5.88% of Python3 online submissions for Find Peak Element.
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < righ... | class Solution:
def find_peak_element(self, nums: List[int]) -> int:
(left, right) = (0, len(nums) - 1)
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]:
return mid
if nums[mid] < nums[mid + ... |
__author__ = "Lukhnos Liu and The McBopomofo Authors"
__copyright__ = "Copyright 2022 and onwards The McBopomofo Authors"
__license__ = "MIT"
HEADER = '# format org.openvanilla.mcbopomofo.sorted\n'
def convert_vks_rows_to_sorted_kvs_rows(vks_rows):
"""Converts value-key-score rows to key-value-score rows, sorte... | __author__ = 'Lukhnos Liu and The McBopomofo Authors'
__copyright__ = 'Copyright 2022 and onwards The McBopomofo Authors'
__license__ = 'MIT'
header = '# format org.openvanilla.mcbopomofo.sorted\n'
def convert_vks_rows_to_sorted_kvs_rows(vks_rows):
"""Converts value-key-score rows to key-value-score rows, sorted b... |
# _SequenceManipulation.py
__module_name__ = "_SequenceManipulation.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
class _SequenceManipulation:
"""
Get the complement or reverse compliment of a DNA sequence.
Parameters:
-----------
sequence... | __module_name__ = '_SequenceManipulation.py'
__author__ = ', '.join(['Michael E. Vinyard'])
__email__ = ', '.join(['vinyard@g.harvard.edu'])
class _Sequencemanipulation:
"""
Get the complement or reverse compliment of a DNA sequence.
Parameters:
-----------
sequence
Returns:
--------
... |
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
new = sorted(nums1 + nums2)
if len(new)%2 == 0:
return (new[len(new)/2-1]+new[len(new)/2])/2.0
else:... | class Solution(object):
def find_median_sorted_arrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
new = sorted(nums1 + nums2)
if len(new) % 2 == 0:
return (new[len(new) / 2 - 1] + new[len(new) / 2]) / 2... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 14 00:56:21 2021
@author: Alexis
"""
perm_dict = {
"newbie":[
"/bq_user help",
"/bq_user refresh",
"/help",
"/tell",
"/chant (witchery)",
"/afk",
"/back",
"/bal (see your money)",
"/balancetop (sh... | """
Created on Sun Nov 14 00:56:21 2021
@author: Alexis
"""
perm_dict = {'newbie': ['/bq_user help', '/bq_user refresh', '/help', '/tell', '/chant (witchery)', '/afk', '/back', '/bal (see your money)', '/balancetop (shows the richest people on the server, takes time to process)', '/compass', '/plugins', '/depth', '/ec... |
rows, cols = [int(x) for x in input().split()]
matrix = [[x for x in input().split()] for _ in range(rows)]
squares_found = 0
for row in range(rows - 1):
for col in range(cols - 1):
if matrix[row][col] == \
matrix[row][col + 1] == \
matrix[row + 1][col] == \
... | (rows, cols) = [int(x) for x in input().split()]
matrix = [[x for x in input().split()] for _ in range(rows)]
squares_found = 0
for row in range(rows - 1):
for col in range(cols - 1):
if matrix[row][col] == matrix[row][col + 1] == matrix[row + 1][col] == matrix[row + 1][col + 1]:
squares_found +... |
str_year = input("what is your birth year:")
year = int(str_year)
age = 2020-year-1
print(f"hello, your age is {age}")
| str_year = input('what is your birth year:')
year = int(str_year)
age = 2020 - year - 1
print(f'hello, your age is {age}') |
"""
Demonstrates a try...except statement with else and finally clauses
"""
#Prompts the user to enter a number.
line = input("Enter a number: ")
try:
#Converts the input to an int.
number = int(line)
except ValueError:
#This statement will execute if the input could not be
#converted to an int (raised a Va... | """
Demonstrates a try...except statement with else and finally clauses
"""
line = input('Enter a number: ')
try:
number = int(line)
except ValueError:
print('Invalid value')
else:
print(number)
finally:
print('Goodbye!') |
# -*- coding: utf-8 -*-
description = 'Detector data acquisition setup'
group = 'lowlevel'
display_order = 25
includes = ['counter']
excludes = ['virtual_daq']
sysconfig = dict(
datasinks = ['kwsformat', 'yamlformat', 'binaryformat', 'livesink'],
)
tango_base = 'tango://phys.kws2.frm2:10000/kws2/'
devices = di... | description = 'Detector data acquisition setup'
group = 'lowlevel'
display_order = 25
includes = ['counter']
excludes = ['virtual_daq']
sysconfig = dict(datasinks=['kwsformat', 'yamlformat', 'binaryformat', 'livesink'])
tango_base = 'tango://phys.kws2.frm2:10000/kws2/'
devices = dict(kwsformat=device('nicos_mlz.kws2.de... |
#!/usr/bin/env python3
with open('27985_B.txt') as f:
nums = list([int(x) for x in f.readlines()][1:])
r2, r7, r14 = 0, 0, 0
for num in nums:
if num % 14 == 0:
r14 = max(r14, num)
if num % 2 == 0:
r2 = max(r2, num)
if num % 7 == 0:
r7 = max(r7, num)
print(max(r2 * r7, r14 * max(nums)))
| with open('27985_B.txt') as f:
nums = list([int(x) for x in f.readlines()][1:])
(r2, r7, r14) = (0, 0, 0)
for num in nums:
if num % 14 == 0:
r14 = max(r14, num)
if num % 2 == 0:
r2 = max(r2, num)
if num % 7 == 0:
r7 = max(r7, num)
print(max(r2 * r7, r14 * max(nums))) |
# -*- coding: utf-8 -*-
"""Registry keeping track of all registered pluggable components"""
# Dictionary storying all cache policy implementations keyed by ID
CACHE_POLICY = {}
# Dictionary storying all repo storage policy implementations keyed by ID
REPO_POLICY = {}
# Dictionary storying all strategy implementation... | """Registry keeping track of all registered pluggable components"""
cache_policy = {}
repo_policy = {}
strategy = {}
topology_factory = {}
cache_placement = {}
computation_placement = {}
content_placement = {}
workload = {}
data_collector = {}
results_reader = {}
results_writer = {}
logging_parameters = {}
def registe... |
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
def create_files_start_length_list(
files, func_get_nevents_in_file=None,
max_events=-1, max_events_per_run=-1,
max_files=-1, max_files_per_run=1):
files = _apply_max_files(files, max... | def create_files_start_length_list(files, func_get_nevents_in_file=None, max_events=-1, max_events_per_run=-1, max_files=-1, max_files_per_run=1):
files = _apply_max_files(files, max_files)
if max_events == 0 or max_events_per_run == 0:
return []
if max_events < 0 and max_events_per_run < 0:
... |
# time complexity O(n^2)
def find3Numbers(A, arr_size, sum):
A.sort()
# Now fix the first element
# one by one and find the
# other two elements
for i in range(0, arr_size-2):
# To find the other two elements,
# start two index variables from
# two corners of the a... | def find3_numbers(A, arr_size, sum):
A.sort()
for i in range(0, arr_size - 2):
l = i + 1
r = arr_size - 1
while l < r:
if A[i] + A[l] + A[r] == sum:
print('Triplet is', A[i], ', ', A[l], ', ', A[r])
return True
elif A[i] + A[l] + A[... |
r = input()
s = input()
a = r.split(",")
b = s.split(",")
count = 0
k = 0
for i in range(len(b)):
count = count + int(b[k])
k += 1
for j in a:
n = j.split(":")
if count == int(n[0]):
count = int(n[1])
if count>= 100:
print("Yes"... | r = input()
s = input()
a = r.split(',')
b = s.split(',')
count = 0
k = 0
for i in range(len(b)):
count = count + int(b[k])
k += 1
for j in a:
n = j.split(':')
if count == int(n[0]):
count = int(n[1])
if count >= 100:
print('Yes', end='')
else:
print('No', end='') |
# Get a list of space-separated input ints. Multiply a new input
nums = input().split()
multiplier = int(input())
result = [int(item) * multiplier for item in nums]
for item in result:
print(item, end = ' ')
print()
| nums = input().split()
multiplier = int(input())
result = [int(item) * multiplier for item in nums]
for item in result:
print(item, end=' ')
print() |
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
def win( c ):
col = [0]*3
row = [0]*3
right = 0
left = 0
total = 0
for i in range(3):
for j in range(3):
... | class Solution:
def valid_tic_tac_toe(self, board: List[str]) -> bool:
def win(c):
col = [0] * 3
row = [0] * 3
right = 0
left = 0
total = 0
for i in range(3):
for j in range(3):
if board[i][j] == c:... |
def square(number):
answer = number * number
return answer # note: this is not an eror, return an answer
# main code starts here :
useNumber = input("Enter a number: ")
useNumber = float(useNumber) # convert to float
numberSquarred = square(useNumber) # call the function and save the result
print("The sequ... | def square(number):
answer = number * number
return answer
use_number = input('Enter a number: ')
use_number = float(useNumber)
number_squarred = square(useNumber)
print('The sequare of your number is', numberSquarred) |
class Constants:
def __init__(self):
self.D20 = 20
self.D4 = 4
self.D6 = 6
self.D8 = 8
self.D10 = 10
self.D12 = 12
self.D100 = 100
self.CRITICALROLL = 20
self.CRITICAL = 100
self.FAILROLL = 1
self.FAIL = -100
self.ITEMAT... | class Constants:
def __init__(self):
self.D20 = 20
self.D4 = 4
self.D6 = 6
self.D8 = 8
self.D10 = 10
self.D12 = 12
self.D100 = 100
self.CRITICALROLL = 20
self.CRITICAL = 100
self.FAILROLL = 1
self.FAIL = -100
self.ITEMA... |
'''This is a custom layout for the WordClock widget.
Custom layouts can be created for the widget by creating a new file in the
"qtile_extras.resources.wordclock" folder.
Each layout must have the following variables:
LAYOUT: The grid layout. Must be a single string.
MAP: The mappin... | """This is a custom layout for the WordClock widget.
Custom layouts can be created for the widget by creating a new file in the
"qtile_extras.resources.wordclock" folder.
Each layout must have the following variables:
LAYOUT: The grid layout. Must be a single string.
MAP: The mappin... |
dummy_dict = {"Yes": 1, "No": 0}
internet_dict = {"No": 0, "No internet service": 1, "Yes": 2}
train_yesno_cols = [
"Partner",
"Dependents",
"PhoneService",
"PaperlessBilling",
"Churn",
]
inference_yesno_cols = ["Partner", "Dependents", "PhoneService", "PaperlessBilling"]
internet_cols = [
"Onli... | dummy_dict = {'Yes': 1, 'No': 0}
internet_dict = {'No': 0, 'No internet service': 1, 'Yes': 2}
train_yesno_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn']
inference_yesno_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling']
internet_cols = ['OnlineSecurity', 'OnlineBackup',... |
expected_output = {
"instance": {
"65109": {
"areas": {
"0.0.0.8": {
"interfaces": {
"Loopback0": {
"ip_address": "10.169.197.254/32",
"cost": 1,
"state... | expected_output = {'instance': {'65109': {'areas': {'0.0.0.8': {'interfaces': {'Loopback0': {'ip_address': '10.169.197.254/32', 'cost': 1, 'state': 'LOOP', 'nbrs_full': 0, 'nbrs_count': 0}, 'GigabitEthernet4': {'ip_address': '10.169.197.98/30', 'cost': 1000, 'state': 'P2P', 'nbrs_full': 1, 'nbrs_count': 1}, 'GigabitEth... |
datasetFile = open("datasets/rosalind_ba1d.txt", "r")
pattern = datasetFile.readline().strip()
genome = datasetFile.readline().strip()
def findInText(pattern, genome):
indices = []
for i in range(len(genome) - len(pattern) + 1):
if genome[i:i+len(pattern)] == pattern:
indices.append(i)
... | dataset_file = open('datasets/rosalind_ba1d.txt', 'r')
pattern = datasetFile.readline().strip()
genome = datasetFile.readline().strip()
def find_in_text(pattern, genome):
indices = []
for i in range(len(genome) - len(pattern) + 1):
if genome[i:i + len(pattern)] == pattern:
indices.append(i)... |
#f
row=0
while row<9:
col =0
while col<10:
if (col==4 and row!=0)or (row==0 and col==5)or (row==0 and col==6)or (row==0 and col==7)or (row==4):
print("*",end=" ")
else:
print(" ",end=" ")
col +=1
row +=1
print()
| row = 0
while row < 9:
col = 0
while col < 10:
if col == 4 and row != 0 or (row == 0 and col == 5) or (row == 0 and col == 6) or (row == 0 and col == 7) or (row == 4):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
row += 1
print() |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
default_sim_settings = {
# settings shared by example.py and benchmark.py
"max_frames": 1000,
"width": 640,
"height": 480,
... | default_sim_settings = {'max_frames': 1000, 'width': 640, 'height': 480, 'scene': 'test.glb', 'default_agent': 0, 'sensor_height': 1.5, 'color_sensor': True, 'semantic_sensor': False, 'depth_sensor': False, 'seed': 1, 'silent': False, 'save_png': False, 'print_semantic_scene': False, 'print_semantic_mask_stats': False,... |
"""
# SINGLE NUMBER II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Exa... | """
# SINGLE NUMBER II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Exa... |
class AssertRaises(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeErro... | class Assertraises(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeErro... |
# Demo Python Dictionaries - Dictionary
'''
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a ... | """
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the key... |
#!/usr/bin/env python3.10
#FILE = 'test_0.txt' # sol: 1384
#FILE = 'test.txt' # sol: 4140
FILE='input.txt' # sol: 3647
def parse_input(file):
lines = []
with open(file, 'r') as f:
for line in f:
lines.append(line.rstrip())
#print(f'lines: {lines}')
return lines
def to_string(n)... | file = 'input.txt'
def parse_input(file):
lines = []
with open(file, 'r') as f:
for line in f:
lines.append(line.rstrip())
return lines
def to_string(n):
if isinstance(n, int):
return str(n)
string = '['
for i in range(len(n)):
string += to_string(n[i])
... |
__author__ = 'rolandh'
INFORMATION = 0
OK = 1
WARNING = 2
ERROR = 3
CRITICAL = 4
INTERACTION = 5
STATUSCODE = ["INFORMATION", "OK", "WARNING", "ERROR", "CRITICAL",
"INTERACTION"]
| __author__ = 'rolandh'
information = 0
ok = 1
warning = 2
error = 3
critical = 4
interaction = 5
statuscode = ['INFORMATION', 'OK', 'WARNING', 'ERROR', 'CRITICAL', 'INTERACTION'] |
INF = 10**9
class Edge:
def __init__(self, _source, _target, _weight):
self.source = _source
self.target = _target
self.weight = _weight
def BellmanFord(s):
dist = [INF] * n
dist[s] = 0
for i in range(n - 1):
for edge in graph:
u, v, w = edge.source, edge.target, edge.weight
if dist[u] != INF and d... | inf = 10 ** 9
class Edge:
def __init__(self, _source, _target, _weight):
self.source = _source
self.target = _target
self.weight = _weight
def bellman_ford(s):
dist = [INF] * n
dist[s] = 0
for i in range(n - 1):
for edge in graph:
(u, v, w) = (edge.source, ... |
"""
@author: acfromspace
"""
def better_fibonacci(n):
n1, n2 = 0, 1
for index in range(n):
n1, n2 = n2, n1 + n2
return n1
n = int(input("Input an integer: "))
print("better_fibonacci():", better_fibonacci(n))
| """
@author: acfromspace
"""
def better_fibonacci(n):
(n1, n2) = (0, 1)
for index in range(n):
(n1, n2) = (n2, n1 + n2)
return n1
n = int(input('Input an integer: '))
print('better_fibonacci():', better_fibonacci(n)) |
def generate_rule_nums():
base1 = 3
base2 = 5
my_sum = 0
my_max = 10000
for i in range(1, 10000):
if i%base1 == 0 or i%base2 == 0:
my_sum += i
print(my_sum)
generate_rule_nums()
| def generate_rule_nums():
base1 = 3
base2 = 5
my_sum = 0
my_max = 10000
for i in range(1, 10000):
if i % base1 == 0 or i % base2 == 0:
my_sum += i
print(my_sum)
generate_rule_nums() |
"""
[REF] https://docs.python.org/3/tutorial/modules.html#packages
Este arquivo nao deve ser apagado
Ele serve para que o python interprete a pasta atual como
um modulo, isto eh, uma biblioteca python. Entao podemos
importar os arquivos que estao aqui dentro como pacotes da biblioteca
usando o comando 'import'.
""" | """
[REF] https://docs.python.org/3/tutorial/modules.html#packages
Este arquivo nao deve ser apagado
Ele serve para que o python interprete a pasta atual como
um modulo, isto eh, uma biblioteca python. Entao podemos
importar os arquivos que estao aqui dentro como pacotes da biblioteca
usando o comando 'import'.
""" |
class Solution:
def isAlienSorted(self, words, order):
for i in range(20):
tmp = [-1 if len(word) <= i else order.index(word[i]) for word in words]
if tmp != sorted(tmp): return False
if tmp == sorted(tmp) and len(tmp) == len(set(tmp)): return True
return True
| class Solution:
def is_alien_sorted(self, words, order):
for i in range(20):
tmp = [-1 if len(word) <= i else order.index(word[i]) for word in words]
if tmp != sorted(tmp):
return False
if tmp == sorted(tmp) and len(tmp) == len(set(tmp)):
... |
#!/usr/bin/python
#coding:utf8
def GC_content(s):
'''
Calculate GC content of DNA.
'''
s = s.upper()
G_content = s.count('G')
C_content = s.count('C')
ratio = (G_content + C_content) / float(len(s))
return format(ratio, '.2%')
def r_complement(s):
s = s.upper()
d... | def gc_content(s):
"""
Calculate GC content of DNA.
"""
s = s.upper()
g_content = s.count('G')
c_content = s.count('C')
ratio = (G_content + C_content) / float(len(s))
return format(ratio, '.2%')
def r_complement(s):
s = s.upper()
dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
... |
# Insertion sorting Algorithm
# @python
def insertion_sort(list_):
for x in range(1, len(list_)):
cursor = list_[x]
pos = x
while pos > 0 and list_[pos - 1] > cursor:
list_[pos] = list_[pos - 1]
pos = pos - 1
list_[pos] = cursor
return list_
array = [1... | def insertion_sort(list_):
for x in range(1, len(list_)):
cursor = list_[x]
pos = x
while pos > 0 and list_[pos - 1] > cursor:
list_[pos] = list_[pos - 1]
pos = pos - 1
list_[pos] = cursor
return list_
array = [15, 2, 4, 50, 30, 2, 0, 1, 4]
sorted = insert... |
s={'A',"A",99,96.5}
print(s)
#{96.5, 99, 'A'}
print(type(s))
#<class 'set'>
#print(s[2])
#'set' object does not support indexing
#s[0]="ASIT"
#'set' object does not support item assignment
print(id(s))
s.add("ASIT")
print(s)
print(id(s))
| s = {'A', 'A', 99, 96.5}
print(s)
print(type(s))
print(id(s))
s.add('ASIT')
print(s)
print(id(s)) |
"""
Custom errors used by PrivacyPanda
"""
class PrivacyError(RuntimeError):
def __init__(self, message):
super().__init__(message)
| """
Custom errors used by PrivacyPanda
"""
class Privacyerror(RuntimeError):
def __init__(self, message):
super().__init__(message) |
class Solution:
def rotate(self, nums, k):
k %= len(nums)
self.reverseArray(nums, 0, len(nums)-1)
self.reverseArray(nums, 0, k-1)
self.reverseArray(nums, k, len(nums)-1)
def reverseArray(self, nums, start, end):
while start < end:
nums[start], nums[end] = num... | class Solution:
def rotate(self, nums, k):
k %= len(nums)
self.reverseArray(nums, 0, len(nums) - 1)
self.reverseArray(nums, 0, k - 1)
self.reverseArray(nums, k, len(nums) - 1)
def reverse_array(self, nums, start, end):
while start < end:
(nums[start], nums[e... |
def add_native_methods(clazz):
def nOpen__int__(a0, a1):
raise NotImplementedError()
def nClose__long__(a0, a1):
raise NotImplementedError()
def nGetPortCount__long__(a0, a1):
raise NotImplementedError()
def nGetPortType__long__int__(a0, a1, a2):
raise NotImplementedEr... | def add_native_methods(clazz):
def n_open__int__(a0, a1):
raise not_implemented_error()
def n_close__long__(a0, a1):
raise not_implemented_error()
def n_get_port_count__long__(a0, a1):
raise not_implemented_error()
def n_get_port_type__long__int__(a0, a1, a2):
raise n... |
# -*- coding: utf-8 -*-
"""
Implementation of simple database containing some values (coordinates and intensity - like 2D image)
@author: ssklykov
"""
class ImageDict():
"""Base class - containing a list with points (dictionary): coordinates of a point and its intensity"""
point = {} # initializer for single... | """
Implementation of simple database containing some values (coordinates and intensity - like 2D image)
@author: ssklykov
"""
class Imagedict:
"""Base class - containing a list with points (dictionary): coordinates of a point and its intensity"""
point = {}
array_of_points = []
keys = ['x', 'y', 'inte... |
class NetworkSegmentInterface:
def build_network_segment(self, input_nodes):
raise Exception("Not implemented error")
| class Networksegmentinterface:
def build_network_segment(self, input_nodes):
raise exception('Not implemented error') |
# https://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-application
# https://dzone.com/articles/design-patterns-singleton
# https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htm
# https://code.google.com/archive/p/google-singleton-detector/... | class Singleton:
__instance = None
def __init__(self):
if Singleton.__instance != None:
raise exception('This class is a singleton!')
else:
Singleton.__instance = self
def get_instance(self):
if Singleton.__instance == None:
Singleton.__instance ... |
def rek(n):
if n == 1: return 1
if n == 0: return 1
return 4*rek(n-1)+5
print(rek(2))
print(rek(23)) | def rek(n):
if n == 1:
return 1
if n == 0:
return 1
return 4 * rek(n - 1) + 5
print(rek(2))
print(rek(23)) |
# -*- coding: utf-8 -*-
"""
@author: JulienWuthrich
"""
width = 28
height = 28
show_n_images = 5 # number of images to show during the training
batch_size = 32
z_dim = 100 # the dimension of z
learning_rate = .005
beta1 = .4 # the exponential decay rate for the 1st moment in the optimizer
epochs = 100
alpha = .01
... | """
@author: JulienWuthrich
"""
width = 28
height = 28
show_n_images = 5
batch_size = 32
z_dim = 100
learning_rate = 0.005
beta1 = 0.4
epochs = 100
alpha = 0.01
use_gpu = True |
dnas = [
['pX3Eo\\]', 38, 146, 1069.71, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 253, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema_slow': 40}],
['k[3Eo\\]', 38, 146, 1030.13, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 267, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'em... | dnas = [['pX3Eo\\]', 38, 146, 1069.71, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 253, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema_slow': 40}], ['k[3Eo\\]', 38, 146, 1030.13, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 267, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Yeolar
#
class DAGNode(object):
def __init__(self, name):
self.name = name
self.nexts = set()
self.prevs = set()
self.self_dep = False
self.done = False
class DAG(object):
def __init__(self):
sel... | class Dagnode(object):
def __init__(self, name):
self.name = name
self.nexts = set()
self.prevs = set()
self.self_dep = False
self.done = False
class Dag(object):
def __init__(self):
self.nodes = []
self.index = {}
self.cycle_dep = False
de... |
# -*- coding: utf-8 -*-
description = 'TOFTOF radial collimator'
group = 'optional'
tango_base = 'tango://tofhw.toftof.frm2:10000/toftof/'
devices = dict(
rc_onoff = device('nicos.devices.tango.NamedDigitalOutput',
description = 'Activates radial collimator',
tangodevice = tango_base + 'rc/_rc_o... | description = 'TOFTOF radial collimator'
group = 'optional'
tango_base = 'tango://tofhw.toftof.frm2:10000/toftof/'
devices = dict(rc_onoff=device('nicos.devices.tango.NamedDigitalOutput', description='Activates radial collimator', tangodevice=tango_base + 'rc/_rc_onoff', mapping={'on': 1, 'off': 0}), rc_motor=device('n... |
def series_ele(n):
pattern = []
for i in range(1,n):
next_element = (i**3) + i*2
pattern.append(next_element)
return pattern
if __name__ == "__main__":
input_number = int(input("Enter a number upto which you want to print the patter: "))
print(series_ele(input_number))
| def series_ele(n):
pattern = []
for i in range(1, n):
next_element = i ** 3 + i * 2
pattern.append(next_element)
return pattern
if __name__ == '__main__':
input_number = int(input('Enter a number upto which you want to print the patter: '))
print(series_ele(input_number)) |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Dependencies and Setup\n",
"from bs4 import BeautifulSoup\n",
"from splinter import Browser\n",
"import pandas as pd\n",
"import datetime as dt\n",
"\n",
"\n",
"# ... | {'cells': [{'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['# Dependencies and Setup\n', 'from bs4 import BeautifulSoup\n', 'from splinter import Browser\n', 'import pandas as pd\n', 'import datetime as dt\n', '\n', '\n', '# Set Executable Path & Initialize Chrome Browser\n', 'e... |
#! python3
# __author__ = "YangJiaHao"
# date: 2018/2/24
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cu... | class Solution:
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(cur_sum, max_su... |
CORS_ALLOW_ORIGINS = '*' # fixme!
CORS_ALLOW_METHODS = ['GET', 'POST', 'PATH', 'DELETE']
CORS_ALLOW_HEADERS = ['*'] # fixme!
DATABASE = {
'uri': 'mongodb://localhost:27017',
'max_pool_size': 10,
'db_name': 'uaberdb',
}
| cors_allow_origins = '*'
cors_allow_methods = ['GET', 'POST', 'PATH', 'DELETE']
cors_allow_headers = ['*']
database = {'uri': 'mongodb://localhost:27017', 'max_pool_size': 10, 'db_name': 'uaberdb'} |
lar = 0
sm = 0.0
while True :
st = input ('Enter a number: ')
if st == 'done':
break
try:
ft = int(st)
except:
print("Invalid input")
continue
print(ft)
num = num + 1
tot = tot + ft
print('All Done')
print(tot,num,tot/num)
| lar = 0
sm = 0.0
while True:
st = input('Enter a number: ')
if st == 'done':
break
try:
ft = int(st)
except:
print('Invalid input')
continue
print(ft)
num = num + 1
tot = tot + ft
print('All Done')
print(tot, num, tot / num) |
class StateChange:
VFX = 'vfx_state'
VFX_STATE = 'vfx_state_state'
AUDIO_STATE = 'audio_state'
AUDIO_EFFECT_STATE = 'audio_effect_state'
AUTONOMY_MODIFIERS = 'autonomy_modifiers'
AWARENESS = 'awareness'
BROADCASTER = 'broadcaster'
ENVIRONMENT_SCORE = 'environment_score'
PAINTING_REV... | class Statechange:
vfx = 'vfx_state'
vfx_state = 'vfx_state_state'
audio_state = 'audio_state'
audio_effect_state = 'audio_effect_state'
autonomy_modifiers = 'autonomy_modifiers'
awareness = 'awareness'
broadcaster = 'broadcaster'
environment_score = 'environment_score'
painting_reve... |
"""
Author: Nathan Do
Email: nathan.dole@gmail.com
Description: Hooks for Opencart API app
"""
app_name = "opencart_api"
app_title = "Opencart API"
app_publisher = "Nathan (Hoovix Consulting Pte. Ltd.)"
app_description = "App for connecting Opencart through APIs. Updating Products, recording transactions"
app_icon = "... | """
Author: Nathan Do
Email: nathan.dole@gmail.com
Description: Hooks for Opencart API app
"""
app_name = 'opencart_api'
app_title = 'Opencart API'
app_publisher = 'Nathan (Hoovix Consulting Pte. Ltd.)'
app_description = 'App for connecting Opencart through APIs. Updating Products, recording transactions'
app_icon = 'i... |
# -*- coding: utf-8 -*-
__author__ = """Chancy Kennedy"""
__email__ = 'kennedychancy+fuzzyjoin@gmail.com'
__version__ = '0.5.2'
| __author__ = 'Chancy Kennedy'
__email__ = 'kennedychancy+fuzzyjoin@gmail.com'
__version__ = '0.5.2' |
class User:
"""
a class for new users and login data
"""
user_list=[]
# created instance variables to take up email,name,username and password of user
def __init__(self,email,name,username,password):
self.email=email
self.name=name
self.username=username
self.pas... | class User:
"""
a class for new users and login data
"""
user_list = []
def __init__(self, email, name, username, password):
self.email = email
self.name = name
self.username = username
self.password = password
def save_login(self):
"""
a method ... |
n = int(input())
a = list(map(int, input().split()))
histogram = {}
res = 0
for i in range(n-1):
for j in range(i+1, n):
s = a[i] + a[j]
if s not in histogram:
histogram[s] = 0
histogram[s] += 1
res = max(res, histogram[s])
print(res)
| n = int(input())
a = list(map(int, input().split()))
histogram = {}
res = 0
for i in range(n - 1):
for j in range(i + 1, n):
s = a[i] + a[j]
if s not in histogram:
histogram[s] = 0
histogram[s] += 1
res = max(res, histogram[s])
print(res) |
"""
Minimum Add to Make Parentheses Valid
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a... | """
Minimum Add to Make Parentheses Valid
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a... |
# definition of U and V
class Direction(object):
def __init__(self, direction):
self.direction = direction
U = Direction('u')
V = Direction('v')
# definition of U0, U1, V0, V1 as the edges of surfaces
class Edge(object):
def __init__(self, direction, value):
self.direction = direction
... | class Direction(object):
def __init__(self, direction):
self.direction = direction
u = direction('u')
v = direction('v')
class Edge(object):
def __init__(self, direction, value):
self.direction = direction
self.value = value
u0 = edge(U, 0)
u1 = edge(U, 1)
v0 = edge(V, 0)
v1 = edge(V,... |
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
result = [None] * len(s)
for i, j in enumerate(indices):
result[j] = s[i]
return "".join(result) | class Solution:
def restore_string(self, s: str, indices: List[int]) -> str:
result = [None] * len(s)
for (i, j) in enumerate(indices):
result[j] = s[i]
return ''.join(result) |
"""
*Hue*
The hue ring.
"""
| """
*Hue*
The hue ring.
""" |
class Nothing:
"""A basic Callable NoneType
Use this object to write generic code pipelines
Makes your life easier when using the railway paradigm
Using Nothing lets you avoid errors like:
AttributeError: "NoneType" object has no attribute ...
TypeError: "NoneType" object is not callable... | class Nothing:
"""A basic Callable NoneType
Use this object to write generic code pipelines
Makes your life easier when using the railway paradigm
Using Nothing lets you avoid errors like:
AttributeError: "NoneType" object has no attribute ...
TypeError: "NoneType" object is not callable... |
class Dog:
name=None
legs=None
age=None
gender=None
isCute=None | class Dog:
name = None
legs = None
age = None
gender = None
is_cute = None |
'''
Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false.
The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a)
and for the string to be true each let... | """
Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false.
The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a)
and for the string to be true each letter... |
# from linked_list import LinkedList
def ll_merge(arg2, arg1):
if arg2._len <= 0 and arg1._len <= 0:
return False
if arg2.head is None:
return arg1
if arg1.head is None:
return arg2
if True:
ptr_left, ptr_right = arg1.head, arg2.head
while ptr_right is not Non... | def ll_merge(arg2, arg1):
if arg2._len <= 0 and arg1._len <= 0:
return False
if arg2.head is None:
return arg1
if arg1.head is None:
return arg2
if True:
(ptr_left, ptr_right) = (arg1.head, arg2.head)
while ptr_right is not None:
arg1.insert_before(ptr... |
upload_folder = './static/images/'
static_folder = '/static/'
testing_folder = './unit_tests/'
test_data_folder = '/tests/test_data'
class Config(object):
DEBUG = False
TESTING = False
class ProductionConfig(Config):
SECRET_KEY = 'Y\xbf\xb9\xb6\x9e\xca\xf0\tM\x08\x96\x17\xa1t\x90h\xaf\x92\xca1\xde\xcff... | upload_folder = './static/images/'
static_folder = '/static/'
testing_folder = './unit_tests/'
test_data_folder = '/tests/test_data'
class Config(object):
debug = False
testing = False
class Productionconfig(Config):
secret_key = 'Y¿¹¶\x9eÊð\tM\x08\x96\x17¡t\x90h¯\x92Ê1ÞÏfð'
encryption_rounds = 12
... |
__author__ = 'Christie'
# Write a function in any language that takes as input a list of lists of integers.
# The function should return void, and print to standard output the number of times each integer appeared at each index
# in an inner list. So for instance:
# countem ([ [ 1,2,3], [1,3,4], [1,3] ]) would outpu... | __author__ = 'Christie'
def countem(listOfListOfIntegers):
listof_lists = [[] for x in range(listOfListOfIntegers.__len__())]
for l in listOfListOfIntegers:
for (i, v) in enumerate(l):
listofLists[i].append(v)
for (i, v) in enumerate(listofLists):
a = set(v)
[print(j, '@... |
while True:
username = input("Type your username: ")
if (username != "Diego"):
continue
password = input("Type your password: ")
if (password == "pass21"):
break
print("Welcome! Access Allowed!")
| while True:
username = input('Type your username: ')
if username != 'Diego':
continue
password = input('Type your password: ')
if password == 'pass21':
break
print('Welcome! Access Allowed!') |
def square(number: int) -> int:
if 1 < number > 64:
raise ValueError(f"number should be between 1 and 64, was {number}")
return 1 << (number - 1) # 1 * 2^(number-1)
def total() -> int:
return (1 << 64) - 1 # 2^64 -1 = 1.844674407371e+19
| def square(number: int) -> int:
if 1 < number > 64:
raise value_error(f'number should be between 1 and 64, was {number}')
return 1 << number - 1
def total() -> int:
return (1 << 64) - 1 |
##############################################
# This for AVX2
REGISTER_TYPE="__m256d"
DATA_TYPE="double"
REGISTER_WIDTH = 4
NUMBER_OF_REGISTERS = 16
MASK_IN_REGISTER = 0 # should be 1 ??
#TARGET_ITILE = 4
#TARGET_JTILE = 12
TARGET_ITILE = 3
TARGET_JTILE = 16
TARGET_KTILE = 48
CACHE_SIZE = 8192
MAX_JTILE = 20
MAX_I... | register_type = '__m256d'
data_type = 'double'
register_width = 4
number_of_registers = 16
mask_in_register = 0
target_itile = 3
target_jtile = 16
target_ktile = 48
cache_size = 8192
max_jtile = 20
max_itile = 14 + 2
def zero(register):
print('%s=_mm256_setzero_pd(); ' % register, end='')
def load(register, ptr, ... |
# @author Huaze Shen
# @date 2020-01-29
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def flatten(root):
if root is None:
return
flatten(root.left)
flatten(root.right)
temp = root.right
root.right = root.left
root.l... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def flatten(root):
if root is None:
return
flatten(root.left)
flatten(root.right)
temp = root.right
root.right = root.left
root.left = None
while root.right is not Non... |
# Author - @Nathaniel Walker
# Date - 9/23/20
# Description - This method will get the area of a square given one side length.
# define method
def area_of_square(side):
return side * side
| def area_of_square(side):
return side * side |
class ArtistMethods(object):
"""Artist methods of the public API."""
def artist(self, artist_id, text_format=None):
"""Gets data for a specific artist.
Args:
artist_id (:obj:`int`): Genius artist ID
text_format (:obj:`str`, optional): Text format of the results
... | class Artistmethods(object):
"""Artist methods of the public API."""
def artist(self, artist_id, text_format=None):
"""Gets data for a specific artist.
Args:
artist_id (:obj:`int`): Genius artist ID
text_format (:obj:`str`, optional): Text format of the results
... |
# There are few cases when recursion is useful
# 1.When we need quick solution over efficient one
# 2.While traversing trees
# In this program we'll find factorial of a number
# O(n!)
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print(factorial(5))
| def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
print(factorial(5)) |
'''
Purpose :
In a trading system a product is bought in the morning and sold out on the same day.
If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get.
Input formate :
Line1 : Number of test cases
Line... | """
Purpose :
In a trading system a product is bought in the morning and sold out on the same day.
If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get.
Input formate :
Line1 : Number of test cases
Line... |
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# ('apple', 'banana', 'cherry')
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
# ('apple', 'banana', 'cherry', 'apple', 'cherry')
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
# 3
thistuple = ("apple",)
print(... | thistuple = ('apple', 'banana', 'cherry')
print(thistuple)
thistuple = ('apple', 'banana', 'cherry', 'apple', 'cherry')
print(thistuple)
thistuple = ('apple', 'banana', 'cherry')
print(len(thistuple))
thistuple = ('apple',)
print(type(thistuple))
thistuple = 'apple'
print(type(thistuple))
thistuple = tuple(('apple', 'b... |
class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for start, end in edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
print("Graph Dict:", s... | class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for (start, end) in edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
print('Graph Dict:'... |
# the operator looks the same but behaves differently depending on the input.
# Example: Addition (+ operator)
# number + number = sum
# string + string = concatenation
# Overriding
class Employee:
def setNumberOfWorkingHours(self):
self.numberOfWorkingHours = 40
def displayNumberOfWorkingHours(self)... | class Employee:
def set_number_of_working_hours(self):
self.numberOfWorkingHours = 40
def display_number_of_working_hours(self):
print(self.numberOfWorkingHours)
class Trainee(Employee):
def set_number_of_working_hours(self):
self.numberOfWorkingHours = 45
def reset_number_o... |
def get_nested(o, default, *args):
if o is None:
return default
current = o
for arg in args:
if current is None or arg is None or current.get(arg, None) is None:
return default
current = current.get(arg, default)
return current
| def get_nested(o, default, *args):
if o is None:
return default
current = o
for arg in args:
if current is None or arg is None or current.get(arg, None) is None:
return default
current = current.get(arg, default)
return current |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.