content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
content = '''
<script>
function createimagemodal(path,cap) {
var html = '<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static">\
<span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span>\
<img class="modal-content" id="img01" style="max-height: -webkit-fill-available; width: auto;"></img>\
<div id="caption"></div>\
</div>';
$("#imagemodal").html(html);
$("#modalWindow1").modal();
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
modalImg.src = path;
captionText.innerHTML = cap;
}
</script>
'''
|
content = '\n <script>\n function createimagemodal(path,cap) {\n var html = \'<div id="modalWindow1" class="modal" data-keyboard="false" data-backdrop="static"> <span class="close1" onclick=deletemodal("modalWindow1") data-dismiss="modal">×</span> <img class="modal-content" id="img01" style="max-height: -webkit-fill-available; width: auto;"></img> <div id="caption"></div> </div>\';\n $("#imagemodal").html(html);\n $("#modalWindow1").modal();\n var modalImg = document.getElementById("img01");\n var captionText = document.getElementById("caption");\n modalImg.src = path;\n captionText.innerHTML = cap;\n }\n </script>\n '
|
a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if (b - c) < a < (b + c) and (a - c) < b < (a + c) and (a - b) < c < (a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo')
|
a = int(input('Digite o primeiro segmento '))
b = int(input('Digite o segundo segmento: '))
c = int(input('Digite o terceiro segmento '))
if b - c < a < b + c and a - c < b < a + c and (a - b < c < a + b):
print('Formam um triangulo')
else:
print('Nao formam um triangulo')
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RunNowPhysicalParameters(object):
"""Implementation of the 'RunNowPhysicalParameters' model.
Attributes:
metadata_file_path (string): Specifies metadata file path during
run-now requests for physical file based backups for some specific
host entity. If specified, it will override any default
metadata/directive file path set at the job level for the host.
Also note that if the job default does not specify a
metadata/directive file path for the host, then specifying this
field for that host during run-now request will be rejected.
"""
# Create a mapping from Model property names to API property names
_names = {
"metadata_file_path":'metadataFilePath'
}
def __init__(self,
metadata_file_path=None):
"""Constructor for the RunNowPhysicalParameters class"""
# Initialize members of the class
self.metadata_file_path = metadata_file_path
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
metadata_file_path = dictionary.get('metadataFilePath')
# Return an object of this model
return cls(metadata_file_path)
|
class Runnowphysicalparameters(object):
"""Implementation of the 'RunNowPhysicalParameters' model.
Attributes:
metadata_file_path (string): Specifies metadata file path during
run-now requests for physical file based backups for some specific
host entity. If specified, it will override any default
metadata/directive file path set at the job level for the host.
Also note that if the job default does not specify a
metadata/directive file path for the host, then specifying this
field for that host during run-now request will be rejected.
"""
_names = {'metadata_file_path': 'metadataFilePath'}
def __init__(self, metadata_file_path=None):
"""Constructor for the RunNowPhysicalParameters class"""
self.metadata_file_path = metadata_file_path
@classmethod
def from_dictionary(cls, dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
metadata_file_path = dictionary.get('metadataFilePath')
return cls(metadata_file_path)
|
SECTION_OFFSET_START = 0x0
SECTION_ADDRESS_START = 0x48
SECTION_SIZE_START = 0x90
BSS_START = 0xD8
BSS_SIZE = 0xDC
TEXT_SECTION_COUNT = 7
DATA_SECTION_COUNT = 11
SECTION_COUNT = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
PATCH_SECTION = 3
ORIGINAL_DOL_END = 0x804DEC00
def word(data, offset):
return sum(data[offset + i] << (24 - i * 8) for i in range(4))
def word_to_bytes(word):
return bytes((word >> (24 - i * 8)) & 0xFF for i in range(4))
def get_dol_end(data):
def get_section_end(index):
address = word(data, SECTION_ADDRESS_START + index * 4)
size = word(data, SECTION_SIZE_START + index * 4)
return address + size
bss_end = word(data, BSS_START) + word(data, BSS_SIZE)
return max(bss_end, *(get_section_end(i) for i in range(SECTION_COUNT)))
def address_to_offset(data, value):
for i in range(0, SECTION_COUNT):
address = word(data, SECTION_ADDRESS_START + i * 4)
size = word(data, SECTION_SIZE_START + i * 4)
if address <= value < address + size:
offset = word(data, SECTION_OFFSET_START + i * 4)
return value - address + offset
def patch_load_imm32(data, address, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(lis)
data[offset+4:offset+8] = word_to_bytes(ori)
def patch_load_imm32_split(data, lis_addr, ori_addr, reg, imm):
lis = 0x3C000000 | (reg << 21) | (imm >> 16)
ori = 0x60000000 | (reg << 21) | (reg << 16) | (imm & 0xFFFF)
lis_offset = address_to_offset(data, lis_addr)
ori_offset = address_to_offset(data, ori_addr)
data[lis_offset:lis_offset+4] = word_to_bytes(lis)
data[ori_offset:ori_offset+4] = word_to_bytes(ori)
def patch_branch(data, address, target):
delta = target - address
if delta < 0:
# Two's complement
delta = ~(-delta) + 1
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(0x48000000 | (delta & 0x3FFFFFC))
def patch_stack_and_heap(data):
delta = get_dol_end(data) - ORIGINAL_DOL_END
print(f"DOL virtual size delta: 0x{delta:X} bytes")
patch_load_imm32(data, 0x80343094, 3, 0x804F0C00 + delta)
patch_load_imm32(data, 0x803430CC, 3, 0x804EEC00 + delta)
patch_load_imm32(data, 0x8034AC78, 0, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x8034AC80, 0x8034AC88, 0, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x802256D0, 0x802256D8, 3, 0x804DEC00 + delta)
patch_load_imm32_split(data, 0x8022570C, 0x80225714, 4, 0x804EEC00 + delta)
patch_load_imm32_split(data, 0x80225718, 0x80225720, 5, 0x804DEC00 + delta)
# Stack
patch_load_imm32(data, 0x80005340, 1, 0x804EEC00 + delta)
def apply_hooks(data):
hooks_offset = word(data, SECTION_OFFSET_START + PATCH_SECTION * 4)
hooks_address = word(data, SECTION_ADDRESS_START + PATCH_SECTION * 4)
hooks_size = word(data, SECTION_SIZE_START + PATCH_SECTION * 4)
for i in range(hooks_size // 8):
offset = hooks_offset + i * 8
original = word(data, offset)
hook = word(data, offset + 4)
# Replace the patch data with the overwritten instruction + branch back
# to the original
original_offset = address_to_offset(data, original)
data[offset:offset+4] = data[original_offset:original_offset+4]
patch_branch(data, hooks_address + i * 8 + 4, original + 4)
patch_branch(data, original, hook)
print(f"Hook {original:08X} -> {hook:08X}")
def apply_extra_patches(data):
with open("patches") as f:
while True:
line = f.readline()
if not line:
return
if line.find("#") != -1:
line = line[:line.find("#")]
if len(line.split()) == 0:
continue
address, word = [int(x, 16) for x in line.split()]
offset = address_to_offset(data, address)
data[offset:offset+4] = word_to_bytes(word)
print(f"Patch {address:08X} -> {word:08X}")
def main():
with open("bin/sys/main.dol", "rb") as f:
data = bytearray(f.read())
patch_stack_and_heap(data)
apply_hooks(data)
apply_extra_patches(data)
with open("bin/sys/main.dol", "wb") as f:
f.write(data)
if __name__ == "__main__":
main()
|
section_offset_start = 0
section_address_start = 72
section_size_start = 144
bss_start = 216
bss_size = 220
text_section_count = 7
data_section_count = 11
section_count = TEXT_SECTION_COUNT + DATA_SECTION_COUNT
patch_section = 3
original_dol_end = 2152590336
def word(data, offset):
return sum((data[offset + i] << 24 - i * 8 for i in range(4)))
def word_to_bytes(word):
return bytes((word >> 24 - i * 8 & 255 for i in range(4)))
def get_dol_end(data):
def get_section_end(index):
address = word(data, SECTION_ADDRESS_START + index * 4)
size = word(data, SECTION_SIZE_START + index * 4)
return address + size
bss_end = word(data, BSS_START) + word(data, BSS_SIZE)
return max(bss_end, *(get_section_end(i) for i in range(SECTION_COUNT)))
def address_to_offset(data, value):
for i in range(0, SECTION_COUNT):
address = word(data, SECTION_ADDRESS_START + i * 4)
size = word(data, SECTION_SIZE_START + i * 4)
if address <= value < address + size:
offset = word(data, SECTION_OFFSET_START + i * 4)
return value - address + offset
def patch_load_imm32(data, address, reg, imm):
lis = 1006632960 | reg << 21 | imm >> 16
ori = 1610612736 | reg << 21 | reg << 16 | imm & 65535
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(lis)
data[offset + 4:offset + 8] = word_to_bytes(ori)
def patch_load_imm32_split(data, lis_addr, ori_addr, reg, imm):
lis = 1006632960 | reg << 21 | imm >> 16
ori = 1610612736 | reg << 21 | reg << 16 | imm & 65535
lis_offset = address_to_offset(data, lis_addr)
ori_offset = address_to_offset(data, ori_addr)
data[lis_offset:lis_offset + 4] = word_to_bytes(lis)
data[ori_offset:ori_offset + 4] = word_to_bytes(ori)
def patch_branch(data, address, target):
delta = target - address
if delta < 0:
delta = ~-delta + 1
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(1207959552 | delta & 67108860)
def patch_stack_and_heap(data):
delta = get_dol_end(data) - ORIGINAL_DOL_END
print(f'DOL virtual size delta: 0x{delta:X} bytes')
patch_load_imm32(data, 2150903956, 3, 2152664064 + delta)
patch_load_imm32(data, 2150904012, 3, 2152655872 + delta)
patch_load_imm32(data, 2150935672, 0, 2152655872 + delta)
patch_load_imm32_split(data, 2150935680, 2150935688, 0, 2152590336 + delta)
patch_load_imm32_split(data, 2149734096, 2149734104, 3, 2152590336 + delta)
patch_load_imm32_split(data, 2149734156, 2149734164, 4, 2152655872 + delta)
patch_load_imm32_split(data, 2149734168, 2149734176, 5, 2152590336 + delta)
patch_load_imm32(data, 2147504960, 1, 2152655872 + delta)
def apply_hooks(data):
hooks_offset = word(data, SECTION_OFFSET_START + PATCH_SECTION * 4)
hooks_address = word(data, SECTION_ADDRESS_START + PATCH_SECTION * 4)
hooks_size = word(data, SECTION_SIZE_START + PATCH_SECTION * 4)
for i in range(hooks_size // 8):
offset = hooks_offset + i * 8
original = word(data, offset)
hook = word(data, offset + 4)
original_offset = address_to_offset(data, original)
data[offset:offset + 4] = data[original_offset:original_offset + 4]
patch_branch(data, hooks_address + i * 8 + 4, original + 4)
patch_branch(data, original, hook)
print(f'Hook {original:08X} -> {hook:08X}')
def apply_extra_patches(data):
with open('patches') as f:
while True:
line = f.readline()
if not line:
return
if line.find('#') != -1:
line = line[:line.find('#')]
if len(line.split()) == 0:
continue
(address, word) = [int(x, 16) for x in line.split()]
offset = address_to_offset(data, address)
data[offset:offset + 4] = word_to_bytes(word)
print(f'Patch {address:08X} -> {word:08X}')
def main():
with open('bin/sys/main.dol', 'rb') as f:
data = bytearray(f.read())
patch_stack_and_heap(data)
apply_hooks(data)
apply_extra_patches(data)
with open('bin/sys/main.dol', 'wb') as f:
f.write(data)
if __name__ == '__main__':
main()
|
class MetaSingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance = super().__call__(*args, **kwargs)
cls.instance[key] = instance
else:
instance = cls.instance[key]
instance.__init__(*args, **kwargs)
return instance
class Singleton(metaclass=MetaSingleton):
def __init__(self, *args, **kwargs):
pass
def singleton(name):
cls = type(name, (Singleton,), {})
return cls()
|
class Metasingleton(type):
instance = {}
def __init__(cls, name, bases, attrs, **kwargs):
cls.__copy__ = lambda self: self
cls.__deepcopy__ = lambda self, memo: self
def __call__(cls, *args, **kwargs):
key = cls.__qualname__
if key not in cls.instance:
instance = super().__call__(*args, **kwargs)
cls.instance[key] = instance
else:
instance = cls.instance[key]
instance.__init__(*args, **kwargs)
return instance
class Singleton(metaclass=MetaSingleton):
def __init__(self, *args, **kwargs):
pass
def singleton(name):
cls = type(name, (Singleton,), {})
return cls()
|
"""Top-level package for baseline."""
__author__ = """Leon Kozlowski"""
__email__ = "leonkozlowski@gmail.com"
|
"""Top-level package for baseline."""
__author__ = 'Leon Kozlowski'
__email__ = 'leonkozlowski@gmail.com'
|
#
# This file contains the Python code from Program 15.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_10.txt
#
class HeapSorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolateDown(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] \
> self._array[j]:
j = j + 1
if self._array[i] \
>= self._array[j]:
break
self.swap(i, j)
i = j
# ...
|
class Heapsorter(Sorter):
def __init__(self):
super(HeapSorter, self).__init__()
def percolate_down(self, i, length):
while 2 * i <= length:
j = 2 * i
if j < length and self._array[j + 1] > self._array[j]:
j = j + 1
if self._array[i] >= self._array[j]:
break
self.swap(i, j)
i = j
|
#!/usr/bin/python3
# coding=utf-8
# Copyright 2019 getcarrier.io
#
# 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Constants
"""
# Legacy
JIRA_FIELD_DO_NOT_USE_VALUE = '!remove'
JIRA_FIELD_USE_DEFAULT_VALUE = '!default'
JIRA_SEVERITIES = {
'Trivial': 4,
'Minor': 3,
'Medium': 2,
'Major': 1,
'Critical': 0,
'Blocker': 0
}
JIRA_ALTERNATIVES = {
'Trivial': ['Low', 'Minor'],
'Minor': ['Low', 'Medium'],
'Medium': ['Major'],
'Major': ['High', 'Critical'],
'Critical': ['Very High', 'Blocker'],
'Blocker': ['Very High', 'Critical']
}
JIRA_OPENED_STATUSES = ['Open', 'In Progress']
JIRA_DESCRIPTION_MAX_SIZE = 61908
# This is jira.text.field.character.limit default value
JIRA_COMMENT_MAX_SIZE = 32767
# Priority/Severity mapping
JIRA_SEVERITY_MAPPING = {
"Critical": "Critical",
"High": "Major",
"Medium": "Medium",
"Low": "Minor",
"Info": "Trivial"
}
|
"""
Constants
"""
jira_field_do_not_use_value = '!remove'
jira_field_use_default_value = '!default'
jira_severities = {'Trivial': 4, 'Minor': 3, 'Medium': 2, 'Major': 1, 'Critical': 0, 'Blocker': 0}
jira_alternatives = {'Trivial': ['Low', 'Minor'], 'Minor': ['Low', 'Medium'], 'Medium': ['Major'], 'Major': ['High', 'Critical'], 'Critical': ['Very High', 'Blocker'], 'Blocker': ['Very High', 'Critical']}
jira_opened_statuses = ['Open', 'In Progress']
jira_description_max_size = 61908
jira_comment_max_size = 32767
jira_severity_mapping = {'Critical': 'Critical', 'High': 'Major', 'Medium': 'Medium', 'Low': 'Minor', 'Info': 'Trivial'}
|
"""
Draw discontinu form
"""
|
"""
Draw discontinu form
"""
|
'''
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
'''
def insertTopStreams(dbConnection, cursor, time, topStreams):
# multidimensional list
# list order: [channel_id, display_name, language, game, created_at, followers, views, viewers, preview_template]
items = []
for stream in topStreams:
item = []
item.append(str(stream['channel']['_id']))
item.append(str(stream['channel']['display_name']))
item.append(str(stream['channel']['language']))
item.append(str(stream['game']))
item.append(str(stream['created_at']))
item.append(str(stream['channel']['followers']))
item.append(str(stream['channel']['views']))
item.append(str(stream['viewers']))
item.append(str(stream['preview']['template']))
items.append(item)
query = 'INSERT INTO top_streams (custom_timestamp, stream_01, stream_02, stream_03, stream_04, stream_05, stream_06, stream_07, stream_08, stream_09, stream_10, stream_11, stream_12, stream_13, stream_14, stream_15, stream_16, stream_17, stream_18, stream_19, stream_20) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(
query,
[
time,
items[0], items[1], items[2], items[3], items[4],
items[5], items[6], items[7], items[8], items[9],
items[10], items[11], items[12], items[13], items[14],
items[15], items[16], items[17], items[18], items[19]
]
)
dbConnection.commit()
|
"""
@name -> insertTopStreams
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@param (time) -> a list of 5 integers that means [year, month, day, hour, minute]
@param (topStreams) -> list of 20 dictionary objects
"""
def insert_top_streams(dbConnection, cursor, time, topStreams):
items = []
for stream in topStreams:
item = []
item.append(str(stream['channel']['_id']))
item.append(str(stream['channel']['display_name']))
item.append(str(stream['channel']['language']))
item.append(str(stream['game']))
item.append(str(stream['created_at']))
item.append(str(stream['channel']['followers']))
item.append(str(stream['channel']['views']))
item.append(str(stream['viewers']))
item.append(str(stream['preview']['template']))
items.append(item)
query = 'INSERT INTO top_streams (custom_timestamp, stream_01, stream_02, stream_03, stream_04, stream_05, stream_06, stream_07, stream_08, stream_09, stream_10, stream_11, stream_12, stream_13, stream_14, stream_15, stream_16, stream_17, stream_18, stream_19, stream_20) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(query, [time, items[0], items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9], items[10], items[11], items[12], items[13], items[14], items[15], items[16], items[17], items[18], items[19]])
dbConnection.commit()
|
class BinaryIndexedTree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
# add low bit
i += (i & -i)
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i -= (i & -i)
return ret
|
class Binaryindexedtree:
def __init__(self, n):
self.sums = [0] * (n + 1)
def update(self, i, delta):
while i < len(self.sums):
self.sums[i] += delta
i += i & -i
def prefix_sum(self, i):
ret = 0
while i:
ret += self.sums[i]
i -= i & -i
return ret
|
#stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner.
#In stack, a new element is added at one end and an element is removed from that end only.
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
# pop() function to pop element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
|
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack')
print(stack)
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
|
# ------------------------------
# 223. Rectangle Area
#
# Description:
# Find the total area covered by two rectilinear rectangles in a 2D plane.
# Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
#
# Example:
# Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
# Output: 45
# Note:
# Assume that the total area is never beyond the maximum possible value of int.
#
# Version: 1.0
# 09/19/18 by Jianfa
# ------------------------------
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
left = max(A, E) # left coordinate of overlap area (if exists)
right = max(min(C, G), left) # right coordinate. If no overlap, then right == left (because left >= min(C, G))
top = min(D, H)
bottom = min(max(B, F), top)
return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bottom)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Follow idea from https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way
|
class Solution(object):
def compute_area(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
left = max(A, E)
right = max(min(C, G), left)
top = min(D, H)
bottom = min(max(B, F), top)
return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bottom)
if __name__ == '__main__':
test = solution()
|
"""
Goal:
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment
required by the credit card company each month.
For each month, calculate statements on the monthly payment and remaining balance.
At the end of 12 months, print out the remaining balance.
Be sure to print out no more than two decimal digits of accuracy
Variables
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
The code you paste into the following box should not specify the values for the variables
balance, annualInterestRate, or monthlyPaymentRate
A summary of the required math is found below:
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
# Test case 1
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# Test case 2
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
Result Your Code Should Generate Below:
Remaining balance: 361.61
"""
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
i = 1
while i < 13:
min_payment = monthlyPaymentRate * balance
outstanding = balance - min_payment
balance = outstanding * (1. + annualInterestRate / 12.) # outstanding balance + interest due
i += 1
# print(f"Remaining balance: {balance: .2f}")
print("Remaining balance:", round(balance, 2))
|
"""
Goal:
Write a program to calculate the credit card balance after one year
if a person only pays the minimum monthly payment
required by the credit card company each month.
For each month, calculate statements on the monthly payment and remaining balance.
At the end of 12 months, print out the remaining balance.
Be sure to print out no more than two decimal digits of accuracy
Variables
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
The code you paste into the following box should not specify the values for the variables
balance, annualInterestRate, or monthlyPaymentRate
A summary of the required math is found below:
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
# Test case 1
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# Test case 2
balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
Result Your Code Should Generate Below:
Remaining balance: 361.61
"""
balance = 484
annual_interest_rate = 0.2
monthly_payment_rate = 0.04
i = 1
while i < 13:
min_payment = monthlyPaymentRate * balance
outstanding = balance - min_payment
balance = outstanding * (1.0 + annualInterestRate / 12.0)
i += 1
print('Remaining balance:', round(balance, 2))
|
student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not in b or student[i] in b and student[i] not in a:
t2.append(student[i])
if student[i] not in a and student[i] not in b:
t3.append(student[i])
if student[i] in a and student[i] in c and student[i] not in b:
t4.append(student[i])
print("List of student who play both cricket and badminton :", t1)
print("List of student who play either cricket or badminton but not both:", t2)
print("No. of students who play neither cricket nor badminton :", len(t3))
print("No. of students who play cricket and football but not badminton :", len(t4))
|
student = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
a = [1, 2, 6, 7, 13, 15, 11]
b = [3, 4, 6, 8, 12, 13]
c = [6, 7, 8, 9, 14, 15]
t1 = []
t2 = []
t3 = []
t4 = []
for i in range(len(student)):
if student[i] in a and student[i] in b:
t1.append(student[i])
if student[i] in a and student[i] not in b or (student[i] in b and student[i] not in a):
t2.append(student[i])
if student[i] not in a and student[i] not in b:
t3.append(student[i])
if student[i] in a and student[i] in c and (student[i] not in b):
t4.append(student[i])
print('List of student who play both cricket and badminton :', t1)
print('List of student who play either cricket or badminton but not both:', t2)
print('No. of students who play neither cricket nor badminton :', len(t3))
print('No. of students who play cricket and football but not badminton :', len(t4))
|
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, "already_selfrole", _emote="WARN"))
if role.position >= ctx.guild.me.top_role.position:
return await ctx.send(plugin.t(ctx.guild, "role_too_high", _emote="WARN"))
if role == ctx.guild.default_role:
return await ctx.send(plugin.t(ctx.guild, "default_role_forbidden", _emote="WARN"))
roles[name] = str(role_id)
plugin.db.configs.update(ctx.guild.id, "selfroles", roles)
await ctx.send(plugin.t(ctx.guild, "selfrole_added", _emote="YES", role=role.name, name=name, prefix=plugin.bot.get_guild_prefix(ctx.guild)))
|
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
name = name.lower()
if role_id in [roles[x] for x in roles] or name in roles:
return await ctx.send(plugin.t(ctx.guild, 'already_selfrole', _emote='WARN'))
if role.position >= ctx.guild.me.top_role.position:
return await ctx.send(plugin.t(ctx.guild, 'role_too_high', _emote='WARN'))
if role == ctx.guild.default_role:
return await ctx.send(plugin.t(ctx.guild, 'default_role_forbidden', _emote='WARN'))
roles[name] = str(role_id)
plugin.db.configs.update(ctx.guild.id, 'selfroles', roles)
await ctx.send(plugin.t(ctx.guild, 'selfrole_added', _emote='YES', role=role.name, name=name, prefix=plugin.bot.get_guild_prefix(ctx.guild)))
|
code = """/* Disabled External File Drag */
window.addEventListener("dragover",function(e){
if (e.target.type != "file") {
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
window.addEventListener("dragenter",function(e){
if (e.target.type != "file") {
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
window.addEventListener("drop",function(e){
if (e.target.type != "file") { // e.target.tagName == "INPUT"
e.preventDefault();
e.dataTransfer.effectAllowed = "none";
e.dataTransfer.dropEffect = "none";
}
},false);
"""
|
code = '/* Disabled External File Drag */\nwindow.addEventListener("dragover",function(e){\n if (e.target.type != "file") {\n e.preventDefault();\n e.dataTransfer.effectAllowed = "none";\n e.dataTransfer.dropEffect = "none";\n }\n},false);\nwindow.addEventListener("dragenter",function(e){\n if (e.target.type != "file") {\n e.preventDefault();\n e.dataTransfer.effectAllowed = "none";\n e.dataTransfer.dropEffect = "none";\n }\n},false);\nwindow.addEventListener("drop",function(e){\n if (e.target.type != "file") { // e.target.tagName == "INPUT" \n e.preventDefault();\n e.dataTransfer.effectAllowed = "none";\n e.dataTransfer.dropEffect = "none";\n }\n},false);\n'
|
'''
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
'''
print("Hello World!")
|
"""
LANGUAGE: Python
AUTHOR: Weiyi
GITHUB: https://github.com/weiyi-m
"""
print('Hello World!')
|
"""implements required text elements for the app"""
APP_NAME = "OSCAR"
WELCOME = "Welcome to " + APP_NAME
CREATE_PROJECT = {
'main': "Create ...",
'sub': "New " + APP_NAME + " project"
}
OPEN_PROJECT = {
'main': "Open ...",
'sub': "Existing " + APP_NAME + " project"
}
SECTIONS = {
'over': "Overview",
'energy': "Energy",
'water': "Water",
'food': "Food",
'busi': "Business"
}
|
"""implements required text elements for the app"""
app_name = 'OSCAR'
welcome = 'Welcome to ' + APP_NAME
create_project = {'main': 'Create ...', 'sub': 'New ' + APP_NAME + ' project'}
open_project = {'main': 'Open ...', 'sub': 'Existing ' + APP_NAME + ' project'}
sections = {'over': 'Overview', 'energy': 'Energy', 'water': 'Water', 'food': 'Food', 'busi': 'Business'}
|
"""
Useful functions
"""
def singleton(cls):
"""turn a class into a singleton class"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
|
"""
Useful functions
"""
def singleton(cls):
"""turn a class into a singleton class"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
|
hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate *no_weeks
print(monthly_pay)
|
hours = 40
pay_rate = 400
no_weeks = 4
monthly_pay = hours * pay_rate * no_weeks
print(monthly_pay)
|
def is_leap(year):
leap = False
# Write your logic here
# thought process
#if year%4==0:
# return True
#elif year%100==0:
# return False
#elif year%400==0:
# return True
# Optimized, Python 3
return ((year%4==0)and(year%100!=0)or(year%400==0))
|
def is_leap(year):
leap = False
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
|
"""Constants for the Ziggo Mediabox Next integration."""
ZIGGO_API = "ziggo_api"
CONF_COUNTRY_CODE = "country_code"
RECORD = "record"
REWIND = "rewind"
FAST_FORWARD = "fast_forward"
|
"""Constants for the Ziggo Mediabox Next integration."""
ziggo_api = 'ziggo_api'
conf_country_code = 'country_code'
record = 'record'
rewind = 'rewind'
fast_forward = 'fast_forward'
|
'''
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer'
3. Write a Python program to find the single number in a list that doesn't occur twice
Input : [5, 3, 4, 3, 4]
Output : 5
'''
|
"""
1. Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number
Input : [1, 0, -1, 0, -2, 2], 0)
Output : [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
2. Write a Python program to compute and return the square root of a given 'integer'.
Input : 16
Output : 4
Note : The returned value will be an 'integer'
3. Write a Python program to find the single number in a list that doesn't occur twice
Input : [5, 3, 4, 3, 4]
Output : 5
"""
|
def main():
for i in range(10):
print(f"The square of {i} is {square(i)}")
return
def square(n):
return n**2
if __name__ == '__main__':
main()
|
def main():
for i in range(10):
print(f'The square of {i} is {square(i)}')
return
def square(n):
return n ** 2
if __name__ == '__main__':
main()
|
'''
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case description should be on a single line.
2. Reform and clean your model ( In the Vensim menu: Model, Reform and
Clean). Choose
* Equation Order: Alphabetical by group (not really necessary)
* Equation Format: Terse
3. Save your model as text (File, Save as..., Save as Type: Text Format
Models
4. Run this script
5. If the print in the end is not set([]), but set([array]), the array
gives the values that where not found and changed
5. Run your new model (for example 'new text.mdl')
6. Vensim tells you about your critical mistake
'''
fileSpecifyingError = ""
pathToExistingModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen incorrect.mdl"
pathToNewModel = r"C:\workspace\EMA-workbench\models\salinization\Verzilting_aanpassingen correct.mdl"
newModel = open(pathToNewModel, 'w')
# line = open(fileSpecifyingError).read()
line = 'rainfall : 0.154705633188; adaptation time from non irrigated agriculture : 0.915157119079; salt effect multiplier : 1.11965969891; adaptation time to non irrigated agriculture : 0.48434342934; adaptation time to irrigated agriculture : 0.330990830832; water shortage multiplier : 0.984356102036; delay time salt seepage : 6.0; adaptation time : 6.90258192256; births multiplier : 1.14344734715; diffusion lookup : [(0, 8.0), (10, 8.0), (20, 8.0), (30, 8.0), (40, 7.9999999999999005), (50, 4.0), (60, 9.982194802803703e-14), (70, 1.2455526635140464e-27), (80, 1.5541686655435471e-41), (90, 1.9392517969836692e-55)]; salinity effect multiplier : 1.10500381093; technological developments in irrigation : 0.0117979353255; adaptation time from irrigated agriculture : 1.58060947607; food shortage multiplier : 0.955325345996; deaths multiplier : 0.875605669911; '
# we assume the case specification was copied from the logger
splitOne = line.split(';')
variable = {}
for n in range(len(splitOne) - 1):
splitTwo = splitOne[n].split(':')
variableElement = splitTwo[0]
# Delete the spaces and other rubish on the sides of the variable name
variableElement = variableElement.lstrip()
variableElement = variableElement.lstrip("'")
variableElement = variableElement.rstrip()
variableElement = variableElement.rstrip("'")
print(variableElement)
valueElement = splitTwo[1]
valueElement = valueElement.lstrip()
valueElement = valueElement.rstrip()
variable[variableElement] = valueElement
print(variable)
# This generates a new (text-formatted) model
changeNextLine = False
settedValues = []
for line in open(pathToExistingModel):
if line.find("=") != -1:
elements = line.split("=")
value = elements[0]
value = value.strip()
if value in variable:
elements[1] = variable.get(value)
line = elements[0] + " = " + elements[1]
settedValues.append(value)
newModel.write(line)
notSet = set(variable.keys()) - set(settedValues)
print(notSet)
|
"""
Created on 11 aug. 2011
.. codeauthor:: wauping <w.auping (at) student (dot) tudelft (dot) nl>
jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
To be able to debug the Vensim model, a few steps are needed:
1. The case that gave a bug, needs to be saved in a text file. The entire
case description should be on a single line.
2. Reform and clean your model ( In the Vensim menu: Model, Reform and
Clean). Choose
* Equation Order: Alphabetical by group (not really necessary)
* Equation Format: Terse
3. Save your model as text (File, Save as..., Save as Type: Text Format
Models
4. Run this script
5. If the print in the end is not set([]), but set([array]), the array
gives the values that where not found and changed
5. Run your new model (for example 'new text.mdl')
6. Vensim tells you about your critical mistake
"""
file_specifying_error = ''
path_to_existing_model = 'C:\\workspace\\EMA-workbench\\models\\salinization\\Verzilting_aanpassingen incorrect.mdl'
path_to_new_model = 'C:\\workspace\\EMA-workbench\\models\\salinization\\Verzilting_aanpassingen correct.mdl'
new_model = open(pathToNewModel, 'w')
line = 'rainfall : 0.154705633188; adaptation time from non irrigated agriculture : 0.915157119079; salt effect multiplier : 1.11965969891; adaptation time to non irrigated agriculture : 0.48434342934; adaptation time to irrigated agriculture : 0.330990830832; water shortage multiplier : 0.984356102036; delay time salt seepage : 6.0; adaptation time : 6.90258192256; births multiplier : 1.14344734715; diffusion lookup : [(0, 8.0), (10, 8.0), (20, 8.0), (30, 8.0), (40, 7.9999999999999005), (50, 4.0), (60, 9.982194802803703e-14), (70, 1.2455526635140464e-27), (80, 1.5541686655435471e-41), (90, 1.9392517969836692e-55)]; salinity effect multiplier : 1.10500381093; technological developments in irrigation : 0.0117979353255; adaptation time from irrigated agriculture : 1.58060947607; food shortage multiplier : 0.955325345996; deaths multiplier : 0.875605669911; '
split_one = line.split(';')
variable = {}
for n in range(len(splitOne) - 1):
split_two = splitOne[n].split(':')
variable_element = splitTwo[0]
variable_element = variableElement.lstrip()
variable_element = variableElement.lstrip("'")
variable_element = variableElement.rstrip()
variable_element = variableElement.rstrip("'")
print(variableElement)
value_element = splitTwo[1]
value_element = valueElement.lstrip()
value_element = valueElement.rstrip()
variable[variableElement] = valueElement
print(variable)
change_next_line = False
setted_values = []
for line in open(pathToExistingModel):
if line.find('=') != -1:
elements = line.split('=')
value = elements[0]
value = value.strip()
if value in variable:
elements[1] = variable.get(value)
line = elements[0] + ' = ' + elements[1]
settedValues.append(value)
newModel.write(line)
not_set = set(variable.keys()) - set(settedValues)
print(notSet)
|
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
sort_nums = nums.copy()
sort_nums.sort()
nums_order = [nums[i]==sort_nums[i] for i in range(n)]
if all(nums_order):
return 0
else:
invaild_pos = [idx for idx, flag in enumerate(nums_order) if not flag]
return invaild_pos[-1]-invaild_pos[0]+1
|
class Solution:
def find_unsorted_subarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
sort_nums = nums.copy()
sort_nums.sort()
nums_order = [nums[i] == sort_nums[i] for i in range(n)]
if all(nums_order):
return 0
else:
invaild_pos = [idx for (idx, flag) in enumerate(nums_order) if not flag]
return invaild_pos[-1] - invaild_pos[0] + 1
|
game = {
'leds': (
# GPIO05 - Pin 29
5,
# GPIO12 - Pin 32
12,
# GPIO17 - Pin 11
17,
# GPIO22 - Pin 15
22,
# GPIO25 - Pin 22
25
),
'switches': (
# GPIO06 - Pin 31
6,
# GPIO13 - Pin 33
13,
# GPIO19 - Pin 35
19,
# GPIO23 - Pin 16
23,
# GPIO24 - Pin 18
24
),
'countdown': 5,
'game_time': 60,
'score_increment': 1
}
|
game = {'leds': (5, 12, 17, 22, 25), 'switches': (6, 13, 19, 23, 24), 'countdown': 5, 'game_time': 60, 'score_increment': 1}
|
"""See navigate.__doc__."""
room = [
"Crypt Entrance", "Math Room", "English Room", "NCEA Headquaters",
"Fancy Wall"
]
N = [2, 4, 4, 4]
S = [4, 4, 0, 4]
E = [3, 0, 4, 4]
W = [1, 4, 4, 0]
desc = [
"A dull enclosed space with three doors",
"A dull enclosed space with one door",
"A dull enclosed space with one door",
"A dull enclosed space with one door"
]
def navigate(location=0): # noqa: D205
"""Show the user the options for navigation and give them a prompt.
Check that the user has selected a valid target and move their
location to that target.
Show the user the options for navigation by getting their location and
finding possible exits through the NSEW lists. Find the names of the rooms
on the other side of the exits by consulting the room list and the
description list. Give the user a prompt where they answer the room they
want to go to as a number 1-4 corresponding to the number beside the room
shown in the prompt. Make sure the room is not 4 and return the users
updated location.
Args:
location:
Optional; The room the user is currently in, defaults to 0.
Returns:
The location of the user as an int.
"""
user_input = input(f"""
Navigation:
1) North: {room[N[location]]};
2) South: {room[S[location]]};
3) East: {room[E[location]]};
4) West: {room[W[location]]};
[1-4]: """)
if user_input == '1':
if N[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return N[location]
elif user_input == '2':
if S[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return S[location]
elif user_input == '3':
if E[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return E[location]
elif user_input == '4':
if W[location] == 4:
input("""
That wall sure looks like a hidden entrance. You try and activate it,
it doesn't react.""")
return navigate(location)
return W[location]
else:
input("""
When prompted, enter one of the numbers 1, 2, 3, 4.
Each number corresponds to an action printed on screen""")
return navigate(location)
if __name__ == "__main__":
print(navigate(int(input())))
|
"""See navigate.__doc__."""
room = ['Crypt Entrance', 'Math Room', 'English Room', 'NCEA Headquaters', 'Fancy Wall']
n = [2, 4, 4, 4]
s = [4, 4, 0, 4]
e = [3, 0, 4, 4]
w = [1, 4, 4, 0]
desc = ['A dull enclosed space with three doors', 'A dull enclosed space with one door', 'A dull enclosed space with one door', 'A dull enclosed space with one door']
def navigate(location=0):
"""Show the user the options for navigation and give them a prompt.
Check that the user has selected a valid target and move their
location to that target.
Show the user the options for navigation by getting their location and
finding possible exits through the NSEW lists. Find the names of the rooms
on the other side of the exits by consulting the room list and the
description list. Give the user a prompt where they answer the room they
want to go to as a number 1-4 corresponding to the number beside the room
shown in the prompt. Make sure the room is not 4 and return the users
updated location.
Args:
location:
Optional; The room the user is currently in, defaults to 0.
Returns:
The location of the user as an int.
"""
user_input = input(f'\n Navigation:\n 1) North: {room[N[location]]};\n 2) South: {room[S[location]]};\n 3) East: {room[E[location]]};\n 4) West: {room[W[location]]};\n [1-4]: ')
if user_input == '1':
if N[location] == 4:
input("\n That wall sure looks like a hidden entrance. You try and activate it,\n it doesn't react.")
return navigate(location)
return N[location]
elif user_input == '2':
if S[location] == 4:
input("\n That wall sure looks like a hidden entrance. You try and activate it,\n it doesn't react.")
return navigate(location)
return S[location]
elif user_input == '3':
if E[location] == 4:
input("\n That wall sure looks like a hidden entrance. You try and activate it,\n it doesn't react.")
return navigate(location)
return E[location]
elif user_input == '4':
if W[location] == 4:
input("\n That wall sure looks like a hidden entrance. You try and activate it,\n it doesn't react.")
return navigate(location)
return W[location]
else:
input('\n When prompted, enter one of the numbers 1, 2, 3, 4.\n Each number corresponds to an action printed on screen')
return navigate(location)
if __name__ == '__main__':
print(navigate(int(input())))
|
# Databricks notebook source
# MAGIC %run ./_utility-methods $lesson="3.1"
# COMMAND ----------
DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f"{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv", f"{DA.paths.working_dir}/flights/departuredelays.csv", "csv", "flights")
DA.conclude_setup()
|
DA.cleanup()
DA.init(create_db=False)
install_dtavod_datasets(reinstall=False)
print()
copy_source_dataset(f'{DA.working_dir_prefix}/source/dtavod/flights/departuredelays.csv', f'{DA.paths.working_dir}/flights/departuredelays.csv', 'csv', 'flights')
DA.conclude_setup()
|
class CNConfig:
interp_factor = 0.075
sigma = 0.2
lambda_= 0.01
output_sigma_factor=1./16
padding=1
cn_type = 'pyECO'
|
class Cnconfig:
interp_factor = 0.075
sigma = 0.2
lambda_ = 0.01
output_sigma_factor = 1.0 / 16
padding = 1
cn_type = 'pyECO'
|
def sumLoad(mirror):
"""Returns system sums of active PSLF load as [Pload, Qload]"""
sysPload = 0.0
sysQload = 0.0
# for each area
for area in mirror.Area:
# reset current sums
area.cv['P'] = 0.0
area.cv['Q'] = 0.0
# sum each active load P and Q to area agent
for load in area.Load:
if load.cv['St'] == 1:
area.cv['P'] += load.cv['P']
area.cv['Q'] += load.cv['Q']
# sum area agent totals to system
sysPload += area.cv['P']
sysQload += area.cv['Q']
return [sysPload,sysQload]
|
def sum_load(mirror):
"""Returns system sums of active PSLF load as [Pload, Qload]"""
sys_pload = 0.0
sys_qload = 0.0
for area in mirror.Area:
area.cv['P'] = 0.0
area.cv['Q'] = 0.0
for load in area.Load:
if load.cv['St'] == 1:
area.cv['P'] += load.cv['P']
area.cv['Q'] += load.cv['Q']
sys_pload += area.cv['P']
sys_qload += area.cv['Q']
return [sysPload, sysQload]
|
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
sum_subarr = 0
l = len(arr)
odd_arr_len = 1 # to be increased by 2 after every iteration until equal to or less than l
while(odd_arr_len <= l):
i = 0
while(i + odd_arr_len < l + 1):
sum_subarr += sum(arr[i: i + odd_arr_len])
i += 1
odd_arr_len += 2
return sum_subarr
def main():
arr = [1,4,2,5,3]
# arr = [10,11,12]
# arr = [1,2]
obj = Solution()
return obj.sumOddLengthSubarrays(arr)
if __name__ == '__main__':
print(main())
|
class Solution(object):
def sum_odd_length_subarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
sum_subarr = 0
l = len(arr)
odd_arr_len = 1
while odd_arr_len <= l:
i = 0
while i + odd_arr_len < l + 1:
sum_subarr += sum(arr[i:i + odd_arr_len])
i += 1
odd_arr_len += 2
return sum_subarr
def main():
arr = [1, 4, 2, 5, 3]
obj = solution()
return obj.sumOddLengthSubarrays(arr)
if __name__ == '__main__':
print(main())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jared
"""
#DB Config File
host='localhost'
port=27017
dummy=True
saveFeatures = True
featureDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/featureDB2/'
crystalDBFolder = '/Users/Jared/Dropbox/Master Thesis/Data/crystalDB2/'
saveFeaturesFile='junk.csv'
saveFeaturesPath='./data/features/'
|
"""
@author: Jared
"""
host = 'localhost'
port = 27017
dummy = True
save_features = True
feature_db_folder = '/Users/Jared/Dropbox/Master Thesis/Data/featureDB2/'
crystal_db_folder = '/Users/Jared/Dropbox/Master Thesis/Data/crystalDB2/'
save_features_file = 'junk.csv'
save_features_path = './data/features/'
|
sortname = {
'bubblesort': f'Bubble Sort O(n\N{SUPERSCRIPT TWO})', 'insertionsort': f'Insertion Sort O(n\N{SUPERSCRIPT TWO})',
'selectionsort': f'Selection Sort O(n\N{SUPERSCRIPT TWO})', 'mergesort': 'Merge Sort O(n log n)',
'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'
}
|
sortname = {'bubblesort': f'Bubble Sort O(n²)', 'insertionsort': f'Insertion Sort O(n²)', 'selectionsort': f'Selection Sort O(n²)', 'mergesort': 'Merge Sort O(n log n)', 'quicksort': 'Quick Sort O(n log n)', 'heapsort': 'Heap Sort O(n log n)'}
|
class Cons():
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
Nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return Cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt
|
class Cons:
def __init__(self, data, nxt):
self.data = data
self.nxt = nxt
nil = None
def new(*elems):
if len(elems) == 0:
return Nil
else:
return cons(elems[0], new(*elems[1:]))
def printls(xs):
i = xs
while i != Nil:
print(i.data)
i = i.nxt
|
"""Default inputs used in the absence of user making a choice. \n
For information on the physical meaning of each of the constants see scientific background.
Variables:
number_of_models: number of models to compare (int) \n
model_1_inputs: input information for model 1 (dict) \n
model_2_inputs: input information for model 2 (dict)
model_dictionaries:
mX_time: time the model runs for (h) \n
mX_timestep: time step for model calculations (h) \n
mX_continous_dose_amount: |Dose| [ng] \n
mX_instantaneous_dose_amount: |Dose| [ng] \n
mX_dose_times: (t) in Dose(t) [hours] \n
mX_dose_entry: subcutaneous or intravenous bolus \n
mX_number_of_compartments: number of peripheral compartments \n
mX_volume_c: V_c [mL] \n
mX_q_c_initial: q_c(t=0) [ng] \n
mX_CL: CL [mL/hour] \n
mX_volume_1: V_{p1} [mL] \n
mX_q_1_initial: q_{p1}(t=0) [ng] \n
mX_flux_1: Q_{p1} [mL/hour] \n
mX_volume_2: V_{p2} [mL] \n
mX_q_2_initial: q_{p2}(t=0) [ng] \n
mX_flux_2": Q_{p2} [mL/hour] \n
mX_k_a": k_a [/hour] \n
mX_q_0_initial: q_0(t=0) [ng] \n
"""
#Models
number_of_models = 2 # number of models to compare
model_1_inputs = {"m1_time": 1, #time the first model runs for
"m1_timestep": 0.001, #time step for model calculations
"m1_continous_dose_amount": 1, # |Dose| [ng]
"m1_instantaneous_dose_amount": 1, # |Dose| [ng]
"m1_dose_times": [0, 1 / 2, 1], # (t) in Dose(t) [hours]
"m1_dose_entry": 'intravenous', # subcutaneous or intravenous bolus
"m1_number_of_compartments": 2, # number of peripheral compartments
"m1_volume_c": 1, # V_c [mL]
"m1_q_c_initial": 1, # q_c(t=0) [ng]
"m1_CL": 1, # CL [mL/hour]
"m1_volume_1": 1, # V_{p1} [mL]
"m1_q_1_initial": 1, # q_{p1}(t=0) [ng]
"m1_flux_1": 1, # Q_{p1} [mL/hour]
"m1_volume_2": 2, # V_{p2} [mL]
"m1_q_2_initial": 1, # q_{p2}(t=0) [ng]
"m1_flux_2": 2, # Q_{p2} [mL/hour]
"m1_k_a": 1, # k_a [/hour]
"m1_q_0_initial": 1} # q_0(t=0) [ng]
model_2_inputs = {"m2_time": 1, #time the first model runs for
"m2_timestep": 0.001, #time step for model calculations
"m2_continous_dose_amount": 1, # |Dose| [ng]
"m2_instantaneous_dose_amount": 1, # |Dose| [ng]
"m2_dose_times": [0, 1 / 2, 1], #(t) in Dose(t) [hours]
"m2_dose_entry": 'subcutaneous', # subcutaneous or intravenous bolus
"m2_number_of_compartments": 2, # number of peripheral compartments
"m2_volume_c": 1, # V_c [mL]
"m2_q_c_initial": 1, # q_c(t=0) [ng]
"m2_CL": 1, # CL [mL/hour]
"m2_volume_1": 1, # V_{p1} [mL]
"m2_q_1_initial": 1, # q_{p2}(t=0) [ng]
"m2_flux_1": 1, # Q_{p1} [mL/hour]
"m2_volume_2": 2, # V_{p2} [mL]
"m2_q_2_initial": 1, # q_{p2}(t=0) [ng]
"m2_flux_2": 2, # Q_{p2} [mL/hour]
"m2_k_a": 1, # k_a [/hour]
"m2_q_0_initial": 1} # q_0(t=0) [ng]
|
"""Default inputs used in the absence of user making a choice.
For information on the physical meaning of each of the constants see scientific background.
Variables:
number_of_models: number of models to compare (int)
model_1_inputs: input information for model 1 (dict)
model_2_inputs: input information for model 2 (dict)
model_dictionaries:
mX_time: time the model runs for (h)
mX_timestep: time step for model calculations (h)
mX_continous_dose_amount: |Dose| [ng]
mX_instantaneous_dose_amount: |Dose| [ng]
mX_dose_times: (t) in Dose(t) [hours]
mX_dose_entry: subcutaneous or intravenous bolus
mX_number_of_compartments: number of peripheral compartments
mX_volume_c: V_c [mL]
mX_q_c_initial: q_c(t=0) [ng]
mX_CL: CL [mL/hour]
mX_volume_1: V_{p1} [mL]
mX_q_1_initial: q_{p1}(t=0) [ng]
mX_flux_1: Q_{p1} [mL/hour]
mX_volume_2: V_{p2} [mL]
mX_q_2_initial: q_{p2}(t=0) [ng]
mX_flux_2": Q_{p2} [mL/hour]
mX_k_a": k_a [/hour]
mX_q_0_initial: q_0(t=0) [ng]
"""
number_of_models = 2
model_1_inputs = {'m1_time': 1, 'm1_timestep': 0.001, 'm1_continous_dose_amount': 1, 'm1_instantaneous_dose_amount': 1, 'm1_dose_times': [0, 1 / 2, 1], 'm1_dose_entry': 'intravenous', 'm1_number_of_compartments': 2, 'm1_volume_c': 1, 'm1_q_c_initial': 1, 'm1_CL': 1, 'm1_volume_1': 1, 'm1_q_1_initial': 1, 'm1_flux_1': 1, 'm1_volume_2': 2, 'm1_q_2_initial': 1, 'm1_flux_2': 2, 'm1_k_a': 1, 'm1_q_0_initial': 1}
model_2_inputs = {'m2_time': 1, 'm2_timestep': 0.001, 'm2_continous_dose_amount': 1, 'm2_instantaneous_dose_amount': 1, 'm2_dose_times': [0, 1 / 2, 1], 'm2_dose_entry': 'subcutaneous', 'm2_number_of_compartments': 2, 'm2_volume_c': 1, 'm2_q_c_initial': 1, 'm2_CL': 1, 'm2_volume_1': 1, 'm2_q_1_initial': 1, 'm2_flux_1': 1, 'm2_volume_2': 2, 'm2_q_2_initial': 1, 'm2_flux_2': 2, 'm2_k_a': 1, 'm2_q_0_initial': 1}
|
"""
Entradas
lote de naranjas compradas-->int-->X
Precio de naranjas por docena-->float-->Y
Dinero obtenido por la venta de las naranjas-->float-->K
Salidas
Porcentaje de ganancias-->float-->porcentaje
"""
#Entradas
X=int(input("Digite el lote de naranjas compradas: "))
Y=float(input("Digite el precio por docena de las naranjas: "))
K=float(input("Digite el dinero obtenido por la venta de las naranjas: "))
#Caja negra
docenas=X/12
gasto=docenas*Y
ganancias=K-gasto
porcentaje=(ganancias/gasto)*100
#Salidas
print("El porcentaje de ganancias obtenidas es de:",porcentaje,"%")
|
"""
Entradas
lote de naranjas compradas-->int-->X
Precio de naranjas por docena-->float-->Y
Dinero obtenido por la venta de las naranjas-->float-->K
Salidas
Porcentaje de ganancias-->float-->porcentaje
"""
x = int(input('Digite el lote de naranjas compradas: '))
y = float(input('Digite el precio por docena de las naranjas: '))
k = float(input('Digite el dinero obtenido por la venta de las naranjas: '))
docenas = X / 12
gasto = docenas * Y
ganancias = K - gasto
porcentaje = ganancias / gasto * 100
print('El porcentaje de ganancias obtenidas es de:', porcentaje, '%')
|
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
# prints from third to end
print(names[2:4])
# prints third to fourth, does not include last one
names[0] = 'Jon'
# Find largest number in list
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f"The largest number is {max_number}.")
# 2D Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# matrix[0][1] = 20
# print(matrix[0][1])
# for row in matrix:
# for item in row:
# print(item)
# List Methods
numbers = [5, 2, 1, 7, 4, 5, 5, 5]
numbers.append(20)
numbers.insert(0, 10)
# removes first mention of 5
numbers.remove(5)
# clears entire list
# numbers.clear()
# removes last item
numbers.pop()
print(numbers)
# finds index of first occurence of item
print(numbers.index(5))
# safer version, if not found returns false
print(50 in numbers)
print(numbers.count(5))
numbers.sort()
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers2.append(10)
print(numbers2)
# Write a program to remove the duplicates in a list
list1 = [1, 3, 5, 5, 7, 9, 9, 9, 1]
checked_number = 0
check_count = 0
for item in list1:
checked_number = item
check_count = 0
for number in list1:
if checked_number == number:
check_count += 1
if check_count > 1:
list1.remove(checked_number)
print(list1)
#Solution
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
|
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(names[2])
print(names[-1])
print(names[2:])
print(names[2:4])
names[0] = 'Jon'
numbers = [1, 34, 34, 12312, 123, 23, 903, 341093, 34]
max_number = numbers[0]
for item in numbers:
if item > max_number:
max_number = item
print(f'The largest number is {max_number}.')
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
numbers = [5, 2, 1, 7, 4, 5, 5, 5]
numbers.append(20)
numbers.insert(0, 10)
numbers.remove(5)
numbers.pop()
print(numbers)
print(numbers.index(5))
print(50 in numbers)
print(numbers.count(5))
numbers.sort()
numbers.reverse()
print(numbers)
numbers2 = numbers.copy()
numbers2.append(10)
print(numbers2)
list1 = [1, 3, 5, 5, 7, 9, 9, 9, 1]
checked_number = 0
check_count = 0
for item in list1:
checked_number = item
check_count = 0
for number in list1:
if checked_number == number:
check_count += 1
if check_count > 1:
list1.remove(checked_number)
print(list1)
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
|
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print("All numbers should be positive between 0 and 100 000!")
n = int(input("n: "))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
n+=1
line = [None] * n # None-> empty; 1-> first person dot; 2-> second person dot
#populate the line with dots
i = 0
while i <= (n-1)/a:
line[i*a] = 1
i+=1
i = 0
line[n - 1] = 2
while i <= (n-1)/b:
line[(n - 1) - (i * b)] = 2
i+=1
painted_red_segment_length = 0
i = 0
#calcualte the length of the painted segment
while i < n:
if i == 0:
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
elif i == n-1:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
else:
if (line[i] != line[i - 1]) and (line[i] != None) and (line[i - 1] != None):
painted_red_segment_length += 1
if (line[i] != line[i + 1]) and (line[i] != None) and (line[i + 1] != None):
painted_red_segment_length += 1
i+=1
i+=1
#calculate the length of the segment that is not painted
result = (n-1) - painted_red_segment_length
print("result: " + str(result))
|
n = int(input('n: '))
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
while (n <= 0 or n >= 100000) or (a <= 0 or a >= 100000) or (b <= 0 or b >= 100000) or (c <= 0 or c >= 100000):
print('All numbers should be positive between 0 and 100 000!')
n = int(input('n: '))
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
n += 1
line = [None] * n
i = 0
while i <= (n - 1) / a:
line[i * a] = 1
i += 1
i = 0
line[n - 1] = 2
while i <= (n - 1) / b:
line[n - 1 - i * b] = 2
i += 1
painted_red_segment_length = 0
i = 0
while i < n:
if i == 0:
if line[i] != line[i + 1] and line[i] != None and (line[i + 1] != None):
painted_red_segment_length += 1
i += 1
elif i == n - 1:
if line[i] != line[i - 1] and line[i] != None and (line[i - 1] != None):
painted_red_segment_length += 1
else:
if line[i] != line[i - 1] and line[i] != None and (line[i - 1] != None):
painted_red_segment_length += 1
if line[i] != line[i + 1] and line[i] != None and (line[i + 1] != None):
painted_red_segment_length += 1
i += 1
i += 1
result = n - 1 - painted_red_segment_length
print('result: ' + str(result))
|
def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker = ''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result = False
for note in task['notes']:
if note.strip() != '':
result = True
break
return result
if is_task_with_notes(task):
notes = '\n'.join(task['notes'])
handle.write(notes)
write_empty_line(handle)
|
def write_empty_line(handle):
handle.write('\n')
def write_title(handle, title, marker=''):
if marker == '':
line = '{0}\n'.format(title)
else:
line = '{0} {1}\n'.format(marker, title)
handle.write(line)
def write_notes(handle, task):
def is_task_with_notes(task):
result = False
for note in task['notes']:
if note.strip() != '':
result = True
break
return result
if is_task_with_notes(task):
notes = '\n'.join(task['notes'])
handle.write(notes)
write_empty_line(handle)
|
def goodSegement1(badList,l,r):
sortedBadList = sorted(badList)
current =sortedBadList[0]
maxVal = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
maxIndex = i+1
# first value
if i == 0 and l<=current<=r:
val = current - l
prev = l
print("first index value")
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("1. (s,e)",l,current)
# other middle values
elif l<=current<=r:
prev = sortedBadList[i-1]
val = current - prev
print("prev, current : ",prev,current)
if(val>maxVal):
maxVal = val
print("2. (s,e)",prev,current)
# last value
if maxIndex == len(sortedBadList) and l<=current<=r:
print("last index value")
next = r
val = next - current
if(val>maxVal):
maxVal = val
print("3. (s,e)",current,next)
print("maxVal:",maxVal-1)
pass
goodSegement1([2,5,8,10,3],1,12)
goodSegement1([37,7,22,15,49,60],3,48)
|
def good_segement1(badList, l, r):
sorted_bad_list = sorted(badList)
current = sortedBadList[0]
max_val = 0
for i in range(len(sortedBadList)):
current = sortedBadList[i]
max_index = i + 1
if i == 0 and l <= current <= r:
val = current - l
prev = l
print('first index value')
print('prev, current : ', prev, current)
if val > maxVal:
max_val = val
print('1. (s,e)', l, current)
elif l <= current <= r:
prev = sortedBadList[i - 1]
val = current - prev
print('prev, current : ', prev, current)
if val > maxVal:
max_val = val
print('2. (s,e)', prev, current)
if maxIndex == len(sortedBadList) and l <= current <= r:
print('last index value')
next = r
val = next - current
if val > maxVal:
max_val = val
print('3. (s,e)', current, next)
print('maxVal:', maxVal - 1)
pass
good_segement1([2, 5, 8, 10, 3], 1, 12)
good_segement1([37, 7, 22, 15, 49, 60], 3, 48)
|
l, r = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * cnt)
else:
res += cnt * (b_f + e_f) // 2
b_f = e_f + 2
e_f = e_f + 2 * (4 * cnt)
x -= cnt
if x < 0:
if f:
b_s -= 2
res -= abs(x) * (b_s + b_s - abs(x + 1) * 2) // 2
else:
b_f -= 2
res -= abs(x) * (b_f + b_f - abs(x + 1) * 2) // 2
cnt *= 2
f = 1 - f
return res
print((f(r) - f(l - 1)) % mod)
|
(l, r) = map(int, input().split())
mod = 10 ** 9 + 7
def f(x):
if x == 0:
return 0
res = 1
cnt = 2
f = 1
b_s = 2
e_s = 4
b_f = 3
e_f = 9
x -= 1
while x > 0:
if f:
res += cnt * (b_s + e_s) // 2
b_s = e_s + 2
e_s = e_s + 2 * (4 * cnt)
else:
res += cnt * (b_f + e_f) // 2
b_f = e_f + 2
e_f = e_f + 2 * (4 * cnt)
x -= cnt
if x < 0:
if f:
b_s -= 2
res -= abs(x) * (b_s + b_s - abs(x + 1) * 2) // 2
else:
b_f -= 2
res -= abs(x) * (b_f + b_f - abs(x + 1) * 2) // 2
cnt *= 2
f = 1 - f
return res
print((f(r) - f(l - 1)) % mod)
|
def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i+1])
if a == b:
total += a
return total
# print(sum_doubles()) # 1341
def sum_halfway(numbers):
total = 0
delta = int(len(numbers) / 2)
for i in range(len(numbers) - 1):
bi = (i + delta) % len(numbers)
a = int(numbers[i])
b = int(numbers[bi])
if a == b:
total += a
return total
print(sum_halfway(open('1.txt').readline())) # 1348
# print(sum_halfway("12131415"))
|
def sum_doubles():
numbers = open('1.txt').readline()
numbers = numbers + numbers[0]
total = 0
for i in range(len(numbers) - 1):
a = int(numbers[i])
b = int(numbers[i + 1])
if a == b:
total += a
return total
def sum_halfway(numbers):
total = 0
delta = int(len(numbers) / 2)
for i in range(len(numbers) - 1):
bi = (i + delta) % len(numbers)
a = int(numbers[i])
b = int(numbers[bi])
if a == b:
total += a
return total
print(sum_halfway(open('1.txt').readline()))
|
def reader():
...
|
def reader():
...
|
"""
Entradas
a-->int-->Cantidad de billetes de 50000
b-->int-->Cantidad de billetes de 20000
c-->int-->Cantidad de billetes de 10000
d-->int-->Cantidad de billetes de 5000
e-->int-->Cantidad de billetes de 2000
f-->int-->Cantidad de billetes de 1000
g-->int-->Cantidad de billetes de 500
h-->int-->Cantidad de billetes de 100
Salidas
i-->int-->Cantidad total de dinero
"""
inp=input().split()
q,w,e,r,t,j,u,p=inp
q=int(q)
w=int(w)
e=int(e)
r=int(r)
t=int(t)
j=int(j)
u=int(u)
p=int(p)
#caja negra
i=(q*50000)+(w*20000)+(e*10000)+(r*5000)+(t*2000)+(j*1000)+(u*500)+(p*100)
print("La cantidad total de dinero es "+str(i))
|
"""
Entradas
a-->int-->Cantidad de billetes de 50000
b-->int-->Cantidad de billetes de 20000
c-->int-->Cantidad de billetes de 10000
d-->int-->Cantidad de billetes de 5000
e-->int-->Cantidad de billetes de 2000
f-->int-->Cantidad de billetes de 1000
g-->int-->Cantidad de billetes de 500
h-->int-->Cantidad de billetes de 100
Salidas
i-->int-->Cantidad total de dinero
"""
inp = input().split()
(q, w, e, r, t, j, u, p) = inp
q = int(q)
w = int(w)
e = int(e)
r = int(r)
t = int(t)
j = int(j)
u = int(u)
p = int(p)
i = q * 50000 + w * 20000 + e * 10000 + r * 5000 + t * 2000 + j * 1000 + u * 500 + p * 100
print('La cantidad total de dinero es ' + str(i))
|
def C(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = "ATATATTAG" if not x else x
x += "$"
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def BWT(x, suffix):
x = "ATATATTAG" if not x else x
x += "$"
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x="ATATATTAG"):
x = x + '$' if '$' not in x else x
shifts = [x]
for i in range(1, len(x)):
shifts.append(x[i:] + x[:i])
shifts.sort()
suffix_arr = [len(shift) - shift.index('$') for shift in shifts]
return shifts, suffix_arr
def main():
x = 'ATATATTAG'
S = [10, 8, 1, 3, 5, 9, 7, 2, 4, 6]
print(C())
print(BWT(x, S))
if __name__ == '__main__':
main()
|
def c(x=None, ls=('$', 'A', 'C', 'G', 'T')):
x = 'ATATATTAG' if not x else x
x += '$'
dictir = {i: sum([x.count(j) for j in ls[:ls.index(i)]]) for i in ls}
return dictir
def bwt(x, suffix):
x = 'ATATATTAG' if not x else x
x += '$'
return ''.join([x[i - 2] for i in suffix])
def suffix_arr(x='ATATATTAG'):
x = x + '$' if '$' not in x else x
shifts = [x]
for i in range(1, len(x)):
shifts.append(x[i:] + x[:i])
shifts.sort()
suffix_arr = [len(shift) - shift.index('$') for shift in shifts]
return (shifts, suffix_arr)
def main():
x = 'ATATATTAG'
s = [10, 8, 1, 3, 5, 9, 7, 2, 4, 6]
print(c())
print(bwt(x, S))
if __name__ == '__main__':
main()
|
CONTEXT = {'cell_line': 'Cell Line',
'cellline': 'Cell Line',
'cell_type': 'Cell Type',
'celltype': 'Cell Type',
'tissue': 'Tissue',
'interactome': 'Interactome'
}
HIDDEN_FOLDER = '.contnext'
ZENODO_URL = 'https://zenodo.org/record/5831786/files/data.zip?download=1'
|
context = {'cell_line': 'Cell Line', 'cellline': 'Cell Line', 'cell_type': 'Cell Type', 'celltype': 'Cell Type', 'tissue': 'Tissue', 'interactome': 'Interactome'}
hidden_folder = '.contnext'
zenodo_url = 'https://zenodo.org/record/5831786/files/data.zip?download=1'
|
def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag
|
def diag_diff(matriza):
first_diag = second_diag = 0
razmer = len(matriza)
for i in range(razmer):
first_diag += matriza[i][i]
second_diag += matriza[i][razmer - i - 1]
return first_diag - second_diag
|
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = [
'standard', 'sampletable',
]
sysconfig = dict(
datasinks = ['caresssink'],
)
devices = dict(
chis = device('nicos.devices.generic.Axis',
description = 'Simulated CHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-180, 180),
visibility = (),
speed = 2,
),
precision = 0.001,
),
phis = device('nicos.devices.generic.Axis',
description = 'Simulated PHIS axis',
motor = device('nicos.devices.generic.VirtualMotor',
fmtstr = '%.2f',
unit = 'deg',
abslimits = (-720, 720),
visibility = (),
speed = 2,
),
precision = 0.001,
),
)
startupcode = '''
SetDetectors(adet)
'''
|
description = 'STRESS-SPEC setup with Eulerian cradle'
group = 'basic'
includes = ['standard', 'sampletable']
sysconfig = dict(datasinks=['caresssink'])
devices = dict(chis=device('nicos.devices.generic.Axis', description='Simulated CHIS axis', motor=device('nicos.devices.generic.VirtualMotor', fmtstr='%.2f', unit='deg', abslimits=(-180, 180), visibility=(), speed=2), precision=0.001), phis=device('nicos.devices.generic.Axis', description='Simulated PHIS axis', motor=device('nicos.devices.generic.VirtualMotor', fmtstr='%.2f', unit='deg', abslimits=(-720, 720), visibility=(), speed=2), precision=0.001))
startupcode = '\nSetDetectors(adet)\n'
|
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s=0
for i in range(0,len(nums),2):
s+=nums[i]
return s
|
class Solution:
def array_pair_sum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s = 0
for i in range(0, len(nums), 2):
s += nums[i]
return s
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AclModeEnum(object):
"""Implementation of the 'AclMode' enum.
ACL mode for this SMB share.
'kNative' specifies native ACL mode supports UNIX-like ACLs and Windows
ACLs. In native mode, because SMB natively supports both ACLs while NFS
only supports UNIX ACLs, ACLs will not be shared between SMB and NFS.
'kShared' shares UNIX-like ACL permissions with the NFS protocol.
In shared mode both protocol ACL permissions are required to match.
When one protocol creates files or modifies permissions, they must comply
with the permission settings of the other protocol.
Attributes:
KSHARED: TODO: type description here.
KNATIVE: TODO: type description here.
"""
KSHARED = 'kShared'
KNATIVE = 'kNative'
|
class Aclmodeenum(object):
"""Implementation of the 'AclMode' enum.
ACL mode for this SMB share.
'kNative' specifies native ACL mode supports UNIX-like ACLs and Windows
ACLs. In native mode, because SMB natively supports both ACLs while NFS
only supports UNIX ACLs, ACLs will not be shared between SMB and NFS.
'kShared' shares UNIX-like ACL permissions with the NFS protocol.
In shared mode both protocol ACL permissions are required to match.
When one protocol creates files or modifies permissions, they must comply
with the permission settings of the other protocol.
Attributes:
KSHARED: TODO: type description here.
KNATIVE: TODO: type description here.
"""
kshared = 'kShared'
knative = 'kNative'
|
def Text(Text="", classname="", Type="h1", TextStyle="", Id="0"):
if TextStyle != "":
if classname != "":
return f"""<{Type} id={Id} class='{classname}' style='{TextStyle}'>{Text}</{Type}>"""
else:
return f"""<{Type} id={Id} style='{TextStyle}'>{Text}</{Type}>"""
else:
if classname != "":
return f"""<{Type} id={Id} class='{classname}'>{Text}</{Type}>"""
else:
return f"""<{Type} id={Id} >{Text}</{Type}>"""
|
def text(Text='', classname='', Type='h1', TextStyle='', Id='0'):
if TextStyle != '':
if classname != '':
return f"<{Type} id={Id} class='{classname}' style='{TextStyle}'>{Text}</{Type}>"
else:
return f"<{Type} id={Id} style='{TextStyle}'>{Text}</{Type}>"
elif classname != '':
return f"<{Type} id={Id} class='{classname}'>{Text}</{Type}>"
else:
return f'<{Type} id={Id} >{Text}</{Type}>'
|
# Copyright (C) 2017 Ming-Shing Chen
def gf2_mul( a , b ):
return a&b
# gf4 := gf2[x]/x^2+x+1
# 4 and , 3 xor
def gf4_mul( a , b ):
a0 = a&1
a1 = (a>>1)&1
b0 = b&1
b1 = (b>>1)&1
ab0 = a0&b0
ab1 = (a1&b0)^(a0&b1)
ab2 = a1&b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= (ab1<<1)
return ab0
# gf16 := gf4[y]/y^2+y+x
# gf16 mul: xor: 18 ,and: 12
def gf16_mul( a , b ):
a0 = a&3
a1 = (a>>2)&3
b0 = b&3
b1 = (b>>2)&3
a0b0 = gf4_mul( a0 , b0 )
a1b1 = gf4_mul( a1 , b1 )
a0a1xb0b1_a0b0 = gf4_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf4_mul( 2 , a1b1 )
a0b0 ^= rd0
return a0b0|(a0a1xb0b1_a0b0<<2)
# gf256 := gf16[x]/x^2 + x + 0x8
def gf256_mul( a , b ):
a0 = a&15
a1 = (a>>4)&15
b0 = b&15
b1 = (b>>4)&15
ab0 = gf16_mul( a0 , b0 )
ab1 = gf16_mul( a1 , b0 ) ^ gf16_mul( a0 , b1 )
ab2 = gf16_mul( a1 , b1 )
ab0 ^= gf16_mul( ab2 , 8 )
ab1 ^= ab2
ab0 ^= (ab1<<4)
return ab0
#382 bit operations
def gf216_mul( a , b ):
a0 = a&0xff
a1 = (a>>8)&0xff
b0 = b&0xff
b1 = (b>>8)&0xff
a0b0 = gf256_mul( a0 , b0 )
a1b1 = gf256_mul( a1 , b1 )
#a0b1_a1b0 = gf16_mul( a0^a1 , b0^b1 ) ^ a0b0 ^ a1b1 ^a1b1
a0b1_a1b0 = gf256_mul( a0^a1 , b0^b1 ) ^ a0b0
rd0 = gf256_mul( a1b1 , 0x80 )
return (a0b1_a1b0<<8)|(rd0^a0b0)
#gf65536 := gf256[x]/x^2 + x + 0x80
def gf65536_mul( a , b ):
a0 = a&0xff;
a1 = (a>>8)&0xff;
b0 = b&0xff;
b1 = (b>>8)&0xff;
ab0 = gf256_mul( a0 , b0 );
ab2 = gf256_mul( a1 , b1 );
ab1 = gf256_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<8)^(ab0^gf256_mul(ab2,0x80));
#gf832 := gf65536[x]/x^2 + x + 0x8000
def gf832_mul( a , b ):
a0 = a&0xffff;
a1 = (a>>16)&0xffff;
b0 = b&0xffff;
b1 = (b>>16)&0xffff;
ab0 = gf65536_mul( a0 , b0 );
ab2 = gf65536_mul( a1 , b1 );
ab1 = gf65536_mul( a0^a1 , b0^b1 )^ab0;
return (ab1<<16)^(ab0^gf65536_mul(ab2,0x8000));
def gf832_inv(a) :
r = a
for i in range(2,32):
r = gf832_mul(r,r)
r = gf832_mul(r,a)
return gf832_mul(r,r)
|
def gf2_mul(a, b):
return a & b
def gf4_mul(a, b):
a0 = a & 1
a1 = a >> 1 & 1
b0 = b & 1
b1 = b >> 1 & 1
ab0 = a0 & b0
ab1 = a1 & b0 ^ a0 & b1
ab2 = a1 & b1
ab0 ^= ab2
ab1 ^= ab2
ab0 ^= ab1 << 1
return ab0
def gf16_mul(a, b):
a0 = a & 3
a1 = a >> 2 & 3
b0 = b & 3
b1 = b >> 2 & 3
a0b0 = gf4_mul(a0, b0)
a1b1 = gf4_mul(a1, b1)
a0a1xb0b1_a0b0 = gf4_mul(a0 ^ a1, b0 ^ b1) ^ a0b0
rd0 = gf4_mul(2, a1b1)
a0b0 ^= rd0
return a0b0 | a0a1xb0b1_a0b0 << 2
def gf256_mul(a, b):
a0 = a & 15
a1 = a >> 4 & 15
b0 = b & 15
b1 = b >> 4 & 15
ab0 = gf16_mul(a0, b0)
ab1 = gf16_mul(a1, b0) ^ gf16_mul(a0, b1)
ab2 = gf16_mul(a1, b1)
ab0 ^= gf16_mul(ab2, 8)
ab1 ^= ab2
ab0 ^= ab1 << 4
return ab0
def gf216_mul(a, b):
a0 = a & 255
a1 = a >> 8 & 255
b0 = b & 255
b1 = b >> 8 & 255
a0b0 = gf256_mul(a0, b0)
a1b1 = gf256_mul(a1, b1)
a0b1_a1b0 = gf256_mul(a0 ^ a1, b0 ^ b1) ^ a0b0
rd0 = gf256_mul(a1b1, 128)
return a0b1_a1b0 << 8 | rd0 ^ a0b0
def gf65536_mul(a, b):
a0 = a & 255
a1 = a >> 8 & 255
b0 = b & 255
b1 = b >> 8 & 255
ab0 = gf256_mul(a0, b0)
ab2 = gf256_mul(a1, b1)
ab1 = gf256_mul(a0 ^ a1, b0 ^ b1) ^ ab0
return ab1 << 8 ^ (ab0 ^ gf256_mul(ab2, 128))
def gf832_mul(a, b):
a0 = a & 65535
a1 = a >> 16 & 65535
b0 = b & 65535
b1 = b >> 16 & 65535
ab0 = gf65536_mul(a0, b0)
ab2 = gf65536_mul(a1, b1)
ab1 = gf65536_mul(a0 ^ a1, b0 ^ b1) ^ ab0
return ab1 << 16 ^ (ab0 ^ gf65536_mul(ab2, 32768))
def gf832_inv(a):
r = a
for i in range(2, 32):
r = gf832_mul(r, r)
r = gf832_mul(r, a)
return gf832_mul(r, r)
|
#Dictionary and Class usage and examples
#cleaning up the input values
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return(mins + '.' + secs)
#reading in the coaches data
def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File Error' + str(ioerr))
return(None)
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
'''
#function call to read in sarah's data
sarah = get_coach_data('sarah2.txt')
#(sarah_name, sarah_dob) = sarah.pop(0),sarah.pop(0)
print(sarah_name + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
'''
#shortcoming of this code is that it's only written for Sarah, you would still need to alter
#print statements for each runner, easy with 4 runners, difficult with 4000 runners.
#the three pieces of data about sarah are all disjointed or independent of each other
#Enter the Dictionary (Key/Value Pairs), aka mapping a hash or an associative array
#Keys: Name/DOB/Times Values: sarah's data
#can you have an unlimited number of keys?
#The order the data is added to the dict isn't maintained, but the key/value association is maintained
runnersDict={}
runnersDict['name'] = sarah.pop(0)
runnersDict['dob'] = sarah.pop(0)
runnersDict['times'] = sarah
print(runnersDict['name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
|
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + '.' + secs
def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
return data.strip().split(',')
except IOError as ioerr:
print('File Error' + str(ioerr))
return None
sarah = get_coach_data('sarah2.txt')
' \n#function call to read in sarah\'s data \nsarah = get_coach_data(\'sarah2.txt\')\n\n#(sarah_name, sarah_dob) = sarah.pop(0),sarah.pop(0)\n\nprint(sarah_name + "\'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))\n'
runners_dict = {}
runnersDict['name'] = sarah.pop(0)
runnersDict['dob'] = sarah.pop(0)
runnersDict['times'] = sarah
print(runnersDict['name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
|
a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=", ")
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=", ")
a1 = a2
a2 = an
print("Even term sum =", sum_)
|
a1 = 1
a2 = 2
an = a1 + a2
sum_ = a2
print(a1, ',', a2, end=', ')
for n in range(100):
an = a1 + a2
if an > 4000000:
print('\n=== DONE ===')
break
if an % 2 == 0:
sum_ += an
print(an, end=', ')
a1 = a2
a2 = an
print('Even term sum =', sum_)
|
# Difficulty Level: Easy
# Question: Filter the dictionary by removing all items with a value of greater
# than 1.
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# {'a': 1}
# Hint 1: Use dictionary comprehension.
# Hint 2: Inside the dictionary comprehension access dictionary items with
# d.items() if you are on Python 3, or dict.iteritems() if you are on Python 2
# Program
# Solution 1
d = {"a": 1, "b": 2, "c": 3}
print({ i:j for i,j in d.items() if j <= 1})
# Solution 2
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)
# Output
# shubhamvaishnav:python-bootcamp$ python3 21_dictionary_filtering.py
# {'a': 1}
|
d = {'a': 1, 'b': 2, 'c': 3}
print({i: j for (i, j) in d.items() if j <= 1})
d = {'a': 1, 'b': 2, 'c': 3}
d = dict(((key, value) for (key, value) in d.items() if value <= 1))
print(d)
|
"""
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
The search only considers the portion from low to high inclusive.
"""
if low > high:
return False # interval is empty - no match.
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid-1)
else:
return binary_search(data, target, mid+1, high)
def binary_search_iterative(data, target):
"""Return True if target is foudn in the given list."""
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]: # Found a match.
return True
elif target < data[mid]:
high = mid - 1 # consider values left of mid.
else:
low = mid + 1 # consider values right of mid.
return False
|
"""
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
The search only considers the portion from low to high inclusive.
"""
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid - 1)
else:
return binary_search(data, target, mid + 1, high)
def binary_search_iterative(data, target):
"""Return True if target is foudn in the given list."""
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
high = mid - 1
else:
low = mid + 1
return False
|
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n-1) * n
example = int(input())
print(factorial(example))
|
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return factorial(n - 1) * n
example = int(input())
print(factorial(example))
|
'''
Created on Mar 9, 2019
@author: hzhang0418
'''
|
"""
Created on Mar 9, 2019
@author: hzhang0418
"""
|
r=open('all.protein.faa','r')
w=open('context.processed.all.protein.faa','w')
start = True
mem = ""
for line in r:
if '>' in line and not start:
list_char = list(mem.replace('\n',''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp=""
for j in range(i-list_context_length_before,i+list_context_length_after+1):
if j < 0 or j>=len(list_char):
tmp=tmp+'-'
else:
tmp=tmp+list_char[j]
list_context.append(tmp)
w.write (" ".join(list_context)+"\n")
mem = ""
else:
if not start:
mem=mem+line
start = False
r.close()
w.close()
|
r = open('all.protein.faa', 'r')
w = open('context.processed.all.protein.faa', 'w')
start = True
mem = ''
for line in r:
if '>' in line and (not start):
list_char = list(mem.replace('\n', ''))
list_context = []
list_context_length_before = 1
list_context_length_after = 1
for i in range(len(list_char)):
tmp = ''
for j in range(i - list_context_length_before, i + list_context_length_after + 1):
if j < 0 or j >= len(list_char):
tmp = tmp + '-'
else:
tmp = tmp + list_char[j]
list_context.append(tmp)
w.write(' '.join(list_context) + '\n')
mem = ''
else:
if not start:
mem = mem + line
start = False
r.close()
w.close()
|
number = int(input())
dots = ((3 * number) - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
ex = number
dots = ((3 * number) - ((ex * 2) + 1)) // 2
for i in range(1, (number // 2) + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, (number // 2) + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = ((3 * number) - 1) // 2
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
print('.' * dots + 'x' + '.' * dots)
|
number = int(input())
dots = (3 * number - 1) // 2
print('.' * dots + 'x' + '.' * dots)
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
ex = number
dots = (3 * number - (ex * 2 + 1)) // 2
for i in range(1, number // 2 + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, number // 2 + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = (3 * number - 1) // 2
print('.' * (dots - 1) + '/' + 'x' + '\\' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
ex = number
dots = (3 * number - (ex * 2 + 1)) // 2
for i in range(1, number // 2 + 2):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots - 1
ex = ex + 1
ex = ex - 2
dots = dots + 2
for a in range(1, number // 2 + 1):
print('.' * dots + 'x' * ex + '|' + 'x' * ex + '.' * dots)
dots = dots + 1
ex = ex - 1
dots = (3 * number - 1) // 2
print('.' * (dots - 1) + 'x' + '|' + 'x' + '.' * (dots - 1))
print('.' * (dots - 1) + '\\' + 'x' + '/' + '.' * (dots - 1))
print('.' * dots + 'x' + '.' * dots)
|
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))
print(' '.join(map(str, pins[3:6])))
print(' '.join(map(str, pins[1:3])))
print(' '.join(map(str, pins[0])))
if __name__ == '__main__':
main()
|
def main():
(a, b) = map(int, input().split())
pins = ['x' for _ in range(10)]
p = list(map(int, input().split()))
for pi in p:
pins[pi - 1] = '.'
if b > 0:
q = list(map(int, input().split()))
for qi in q:
pins[qi - 1] = 'o'
print(' '.join(map(str, pins[6:])))
print(' '.join(map(str, pins[3:6])))
print(' '.join(map(str, pins[1:3])))
print(' '.join(map(str, pins[0])))
if __name__ == '__main__':
main()
|
'''
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. '''
## Variable
weight = float(input("Please enter your current weight: "))
## Create Protein Function
def protein(weight):
fitnessLvl0 = .5
fitnessLvl1 = .75
fitnessLvl2 = 1
fitnessLvl3 = 1.25
fitnessLvl = int(input("Please enter your fitness level (i.e. 1 = New to Training, 2 = In Shape, 3 = Competing, 4 = No Training): "))
if fitnessLvl == 4:
pro = fitnessLvl0 * weight
return pro
elif fitnessLvl == 1:
pro = fitnessLvl1 * weight
return pro
elif fitnessLvl == 2:
pro = fitnessLvl2 * weight
return pro
elif fitnessLvl == 3:
pro = fitnessLvl3 * weight
return pro
## Create Fat Function
def fat(weight):
fat1 = .3
fat2 = .35
fat3 = .4
fatLvl = int(input("Please enter your fat level (i.e. 1 = Love Carbs, 2 = Mix, 3 = Love Fat (nuts, peanut butter, etc): "))
if fatLvl == 1:
fats = fat1 * weight
return fats
elif fatLvl == 2:
fats = fat2 * weight
return fats
elif fatLvl == 3:
fats = fat3 * weight
return fats
## Create Calorie Function
def calories(weight):
cal1 = 14
cal2 = 15
cal3 = 16
calLvl = int(input("Please enter your activity level (i.e. 1 = Less Movement, 2 = Moderately Moving, 3 = Actively Moving): "))
if calLvl == 1:
cal = cal1 * weight
return cal
elif calLvl == 2:
cal = cal2 * weight
return cal
elif calLvl == 3:
cal = cal3 * weight
return cal
cals = calories(weight)
protein = round(protein(weight))
fat = round(fat(weight))
## Create New Physique
def physique(cals):
shred = 500
maintain = 0
gain = 500
phyLvl = input(str("Please enter your physique goal (i.e. shred, maintain, gain): "))
if phyLvl == "shred":
phy = cals - shred
return phy
elif phyLvl == "maintain":
phy = cals - maintain
return phy
elif phyLvl == "gain":
phy = cals + gain
return phy
phyCal= physique(cals)
## Create Caloric Intake Function
# 4 x 9 x 4 Rule Applies Here
def cal(phyCal):
calPro = protein * 4
calFat = fat * 9
sumProFat = calPro + calFat
carbCal = phyCal - sumProFat
return carbCal
carbCal = cal(phyCal)
## Create Carbs Function
def carbs(carbCal):
carb = carbCal / 4
return carb
carb = round(carbs(carbCal))
print("")
## Results
print("Macros")
print("Protein: " + str(protein) + "g")
print("Fat: " + str(fat) + "g")
print("Carbohydrate: " + str(carb) + "g")
print("Total Calories per day: " + str(round(phyCal)) + "cal")
|
"""
Macros Calculator
MIT License
Copyright (c) 2018 Casey Chad Salvador
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. """
weight = float(input('Please enter your current weight: '))
def protein(weight):
fitness_lvl0 = 0.5
fitness_lvl1 = 0.75
fitness_lvl2 = 1
fitness_lvl3 = 1.25
fitness_lvl = int(input('Please enter your fitness level (i.e. 1 = New to Training, 2 = In Shape, 3 = Competing, 4 = No Training): '))
if fitnessLvl == 4:
pro = fitnessLvl0 * weight
return pro
elif fitnessLvl == 1:
pro = fitnessLvl1 * weight
return pro
elif fitnessLvl == 2:
pro = fitnessLvl2 * weight
return pro
elif fitnessLvl == 3:
pro = fitnessLvl3 * weight
return pro
def fat(weight):
fat1 = 0.3
fat2 = 0.35
fat3 = 0.4
fat_lvl = int(input('Please enter your fat level (i.e. 1 = Love Carbs, 2 = Mix, 3 = Love Fat (nuts, peanut butter, etc): '))
if fatLvl == 1:
fats = fat1 * weight
return fats
elif fatLvl == 2:
fats = fat2 * weight
return fats
elif fatLvl == 3:
fats = fat3 * weight
return fats
def calories(weight):
cal1 = 14
cal2 = 15
cal3 = 16
cal_lvl = int(input('Please enter your activity level (i.e. 1 = Less Movement, 2 = Moderately Moving, 3 = Actively Moving): '))
if calLvl == 1:
cal = cal1 * weight
return cal
elif calLvl == 2:
cal = cal2 * weight
return cal
elif calLvl == 3:
cal = cal3 * weight
return cal
cals = calories(weight)
protein = round(protein(weight))
fat = round(fat(weight))
def physique(cals):
shred = 500
maintain = 0
gain = 500
phy_lvl = input(str('Please enter your physique goal (i.e. shred, maintain, gain): '))
if phyLvl == 'shred':
phy = cals - shred
return phy
elif phyLvl == 'maintain':
phy = cals - maintain
return phy
elif phyLvl == 'gain':
phy = cals + gain
return phy
phy_cal = physique(cals)
def cal(phyCal):
cal_pro = protein * 4
cal_fat = fat * 9
sum_pro_fat = calPro + calFat
carb_cal = phyCal - sumProFat
return carbCal
carb_cal = cal(phyCal)
def carbs(carbCal):
carb = carbCal / 4
return carb
carb = round(carbs(carbCal))
print('')
print('Macros')
print('Protein: ' + str(protein) + 'g')
print('Fat: ' + str(fat) + 'g')
print('Carbohydrate: ' + str(carb) + 'g')
print('Total Calories per day: ' + str(round(phyCal)) + 'cal')
|
"""
test
~~~~
Flask-Monitor is a simple extension to Flask allowing you to add
prometheus middleware to add basic but very useful metrics for
your Python Flask app.
:license: MIT, see LICENSE for more details.
"""
|
"""
test
~~~~
Flask-Monitor is a simple extension to Flask allowing you to add
prometheus middleware to add basic but very useful metrics for
your Python Flask app.
:license: MIT, see LICENSE for more details.
"""
|
"""
Implement an iterator over a binary search tree (BST). Your iterator will
be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
7
/ \
3 15
/ \
9 20
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note:
- next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
- You may assume that next() call will always be valid, that is, there
will be at least a next smallest number in the BST when next() is
called.
"""
#Difficulty: Medium
#62 / 62 test cases passed.
#Runtime: 92 ms
#Memory Usage: 20 MB
#Runtime: 92 ms, faster than 38.46% of Python3 online submissions for Binary Search Tree Iterator.
#Memory Usage: 20 MB, less than 97.86% of Python3 online submissions for Binary Search Tree Iterator.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.inorder(root, self.stack)
self.stack.reverse()
def next(self) -> int:
"""
@return the next smallest number
"""
if self.stack:
return self.stack.pop()
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return True if self.stack else False
def inorder(self, root, stack):
"""
prepare stack
"""
if not root:
return 0
self.inorder(root.left, stack)
stack.append(root.val)
self.inorder(root.right, stack)
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
"""
Implement an iterator over a binary search tree (BST). Your iterator will
be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
7
/ 3 15
/ 9 20
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note:
- next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
- You may assume that next() call will always be valid, that is, there
will be at least a next smallest number in the BST when next() is
called.
"""
class Bstiterator:
def __init__(self, root: TreeNode):
self.stack = []
self.inorder(root, self.stack)
self.stack.reverse()
def next(self) -> int:
"""
@return the next smallest number
"""
if self.stack:
return self.stack.pop()
def has_next(self) -> bool:
"""
@return whether we have a next smallest number
"""
return True if self.stack else False
def inorder(self, root, stack):
"""
prepare stack
"""
if not root:
return 0
self.inorder(root.left, stack)
stack.append(root.val)
self.inorder(root.right, stack)
|
JETBRAINS_IDES = {
'androidstudio': 'Android Studio',
'appcode': 'AppCode',
'datagrip': 'DataGrip',
'goland': 'GoLand',
'intellij': 'IntelliJ IDEA',
'pycharm': 'PyCharm',
'rubymine': 'RubyMine',
'webstorm': 'WebStorm'
}
JETBRAINS_IDE_NAMES = list(JETBRAINS_IDES.values())
|
jetbrains_ides = {'androidstudio': 'Android Studio', 'appcode': 'AppCode', 'datagrip': 'DataGrip', 'goland': 'GoLand', 'intellij': 'IntelliJ IDEA', 'pycharm': 'PyCharm', 'rubymine': 'RubyMine', 'webstorm': 'WebStorm'}
jetbrains_ide_names = list(JETBRAINS_IDES.values())
|
mystr="Python is a multipurpose and simply learning langauge"
for i in mystr:
print(i,end=" ")
print()
print(mystr.find("simply"))
print(mystr[0:11]+ " programming")
|
mystr = 'Python is a multipurpose and simply learning langauge'
for i in mystr:
print(i, end=' ')
print()
print(mystr.find('simply'))
print(mystr[0:11] + ' programming')
|
T1, T2 = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i)
|
(t1, t2) = map(int, input().split())
n = 1000001
sieve = [True] * n
m = int(n ** 0.5)
for i in range(2, m + 1):
if sieve[i] == True:
for j in range(i + i, n, i):
sieve[j] = False
for i in range(T1, T2 + 1):
if i == 1:
continue
if sieve[i]:
print(i)
|
#
# Copyright 2012 Sonya Huang
#
# 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# file that records common things relevant to bea data
use_table_margins = [
"margins", # negative
"rail_margin", "truck_margin", "water_margin", "air_margin",
"pipe_margin", "gaspipe_margin",
"wholesale_margin", "retail_margin"]
FINAL_DEMAND = "f"
VALUE_ADDED = "v"
INTERMEDIATE_OUTPUT = "i"
fd_sectors = {
1972: {"pce": "910000", "imports": "950000", "exports": "940000"},
1977: {"pce": "910000", "imports": "950000", "exports": "940000"},
1982: {"pce": "910000", "imports": "950000", "exports": "940000"},
1987: {"pce": "910000", "imports": "950000", "exports": "940000"},
1992: {"pce": "910000", "imports": "950000", "exports": "940000"},
1997: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
2002: {"pce": "F01000", "imports": "F05000", "exports": "F04000"},
}
fd_sector_names = {
"total": "All final demand",
"pce": "Personal Consumption Expenditures",
"imports": "Imports",
"exports": "Exports",
}
fd_sector_criteria = {
1972: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1977: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# based on similarity to 1987
1982: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p84)
1987: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN " + \
"('91', '92', '93', '94', '95', '96', '97', '98', '99')",
1997: "code LIKE 'F%'",
2002: "code LIKE 'F%'",
}
va_sector_criteria = {
1972: "code IN ('880000', '890000', '900000')",
1977: "code IN ('880000', '890000', '900000')",
1982: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/pdf/national/inputout/1994/0494ied.pdf (p115)
1987: "code IN ('880000', '890000', '900000')",
# http://www.bea.gov/scb/account_articles/national/1197io/appxB.htm
1992: "SUBSTRING(code FROM 1 FOR 2) IN ('88', '89', '90')",
1997: "code LIKE 'V%'",
2002: "code LIKE 'V%'",
}
scrap_used_codes = {
1972: ("810000",),
1977: ("810001", "810002"),
1982: ("810001", "810002"),
1987: ("810001", "810002"),
1992: ("810001", "810002"),
1997: ("S00401", "S00402"),
2002: ("S00401", "S00402"),
}
tourism_adjustment_codes = {
1972: '830000',
1977: '830000',
1982: '830000',
1987: '830001',
1992: '830001',
1997: 'S00600',
2002: 'S00900',
}
nipa_groups = [
"Clothing and footwear",
"Financial services and insurance",
"Food and beverages purchased for off-premises consumption",
"Food services and accommodations",
"Furnishings and durable household equipment",
"Gasoline and other energy goods",
"Gross output of nonprofit institutions",
"Health care",
"Housing and utilities",
#"Less: Receipts from sales of goods and services by nonprofit institutions",
"Motor vehicles and parts",
"Other durable goods",
"Other nondurable goods",
"Other services",
"Recreational goods and vehicles",
"Recreation services",
"Transportation services",
]
short_nipa = {
"Clothing and footwear": "Apparel",
"Financial services and insurance": "Financial services",
"Food and beverages purchased for off-premises consumption": "Food products",
"Food services and accommodations": "Food services",
"Gasoline and other energy goods": "Gasoline",
"Other durable goods": "Other durables",
"Other nondurable goods": "Other nondurables",
"Transportation services": "Transport",
"Housing and utilities": "Utilities",
}
standard_sectors = {
1972: ('540200'),
1977: ('540200'),
1982: ('540200'),
1987: ('540200'),
1992: ('540200'),
1997: ('335222'),
2002: ('335222'),
}
|
use_table_margins = ['margins', 'rail_margin', 'truck_margin', 'water_margin', 'air_margin', 'pipe_margin', 'gaspipe_margin', 'wholesale_margin', 'retail_margin']
final_demand = 'f'
value_added = 'v'
intermediate_output = 'i'
fd_sectors = {1972: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1977: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1982: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1987: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1992: {'pce': '910000', 'imports': '950000', 'exports': '940000'}, 1997: {'pce': 'F01000', 'imports': 'F05000', 'exports': 'F04000'}, 2002: {'pce': 'F01000', 'imports': 'F05000', 'exports': 'F04000'}}
fd_sector_names = {'total': 'All final demand', 'pce': 'Personal Consumption Expenditures', 'imports': 'Imports', 'exports': 'Exports'}
fd_sector_criteria = {1972: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1977: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1982: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1987: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1992: 'SUBSTRING(code FROM 1 FOR 2) IN ' + "('91', '92', '93', '94', '95', '96', '97', '98', '99')", 1997: "code LIKE 'F%'", 2002: "code LIKE 'F%'"}
va_sector_criteria = {1972: "code IN ('880000', '890000', '900000')", 1977: "code IN ('880000', '890000', '900000')", 1982: "code IN ('880000', '890000', '900000')", 1987: "code IN ('880000', '890000', '900000')", 1992: "SUBSTRING(code FROM 1 FOR 2) IN ('88', '89', '90')", 1997: "code LIKE 'V%'", 2002: "code LIKE 'V%'"}
scrap_used_codes = {1972: ('810000',), 1977: ('810001', '810002'), 1982: ('810001', '810002'), 1987: ('810001', '810002'), 1992: ('810001', '810002'), 1997: ('S00401', 'S00402'), 2002: ('S00401', 'S00402')}
tourism_adjustment_codes = {1972: '830000', 1977: '830000', 1982: '830000', 1987: '830001', 1992: '830001', 1997: 'S00600', 2002: 'S00900'}
nipa_groups = ['Clothing and footwear', 'Financial services and insurance', 'Food and beverages purchased for off-premises consumption', 'Food services and accommodations', 'Furnishings and durable household equipment', 'Gasoline and other energy goods', 'Gross output of nonprofit institutions', 'Health care', 'Housing and utilities', 'Motor vehicles and parts', 'Other durable goods', 'Other nondurable goods', 'Other services', 'Recreational goods and vehicles', 'Recreation services', 'Transportation services']
short_nipa = {'Clothing and footwear': 'Apparel', 'Financial services and insurance': 'Financial services', 'Food and beverages purchased for off-premises consumption': 'Food products', 'Food services and accommodations': 'Food services', 'Gasoline and other energy goods': 'Gasoline', 'Other durable goods': 'Other durables', 'Other nondurable goods': 'Other nondurables', 'Transportation services': 'Transport', 'Housing and utilities': 'Utilities'}
standard_sectors = {1972: '540200', 1977: '540200', 1982: '540200', 1987: '540200', 1992: '540200', 1997: '335222', 2002: '335222'}
|
class FieldOffsetAttribute(Attribute,_Attribute):
"""
Indicates the physical position of fields within the unmanaged representation of a class or structure.
FieldOffsetAttribute(offset: int)
"""
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,offset):
""" __new__(cls: type,offset: int) """
pass
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the offset from the beginning of the structure to the beginning of the field.
Get: Value(self: FieldOffsetAttribute) -> int
"""
|
class Fieldoffsetattribute(Attribute, _Attribute):
"""
Indicates the physical position of fields within the unmanaged representation of a class or structure.
FieldOffsetAttribute(offset: int)
"""
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, offset):
""" __new__(cls: type,offset: int) """
pass
value = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the offset from the beginning of the structure to the beginning of the field.\n\n\n\nGet: Value(self: FieldOffsetAttribute) -> int\n\n\n\n'
|
config_object = {
"org_id": "",
"client_id": "",
"tech_id": "",
"pathToKey": "",
"secret": "",
"date_limit": 0,
"token": "",
"tokenEndpoint": "https://ims-na1.adobelogin.com/ims/exchange/jwt"
}
header = {"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer ",
"x-api-key": ""
}
endpoints = {
"global": 'https://cja.adobe.io'
}
|
config_object = {'org_id': '', 'client_id': '', 'tech_id': '', 'pathToKey': '', 'secret': '', 'date_limit': 0, 'token': '', 'tokenEndpoint': 'https://ims-na1.adobelogin.com/ims/exchange/jwt'}
header = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ', 'x-api-key': ''}
endpoints = {'global': 'https://cja.adobe.io'}
|
INITIAL_HPS = {
'image_classifier': [{
'image_block_1/block_type': 'vanilla',
'image_block_1/normalize': True,
'image_block_1/augment': False,
'image_block_1_vanilla/kernel_size': 3,
'image_block_1_vanilla/num_blocks': 1,
'image_block_1_vanilla/separable': False,
'image_block_1_vanilla/dropout_rate': 0.25,
'image_block_1_vanilla/filters_0_1': 32,
'image_block_1_vanilla/filters_0_2': 64,
'spatial_reduction_1/reduction_type': 'flatten',
'dense_block_1/num_layers': 1,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 128,
'classification_head_1/dropout_rate': 0.5,
'optimizer': 'adam'
}, {
'image_block_1/block_type': 'resnet',
'image_block_1/normalize': True,
'image_block_1/augment': True,
'image_block_1_resnet/version': 'v2',
'image_block_1_resnet/pooling': 'avg',
'image_block_1_resnet/conv3_depth': 4,
'image_block_1_resnet/conv4_depth': 6,
'dense_block_1/num_layers': 2,
'dense_block_1/use_batchnorm': False,
'dense_block_1/dropout_rate': 0,
'dense_block_1/units_0': 32,
'dense_block_1/units_1': 32,
'classification_head_1/dropout_rate': 0,
'optimizer': 'adam'
}],
}
|
initial_hps = {'image_classifier': [{'image_block_1/block_type': 'vanilla', 'image_block_1/normalize': True, 'image_block_1/augment': False, 'image_block_1_vanilla/kernel_size': 3, 'image_block_1_vanilla/num_blocks': 1, 'image_block_1_vanilla/separable': False, 'image_block_1_vanilla/dropout_rate': 0.25, 'image_block_1_vanilla/filters_0_1': 32, 'image_block_1_vanilla/filters_0_2': 64, 'spatial_reduction_1/reduction_type': 'flatten', 'dense_block_1/num_layers': 1, 'dense_block_1/use_batchnorm': False, 'dense_block_1/dropout_rate': 0, 'dense_block_1/units_0': 128, 'classification_head_1/dropout_rate': 0.5, 'optimizer': 'adam'}, {'image_block_1/block_type': 'resnet', 'image_block_1/normalize': True, 'image_block_1/augment': True, 'image_block_1_resnet/version': 'v2', 'image_block_1_resnet/pooling': 'avg', 'image_block_1_resnet/conv3_depth': 4, 'image_block_1_resnet/conv4_depth': 6, 'dense_block_1/num_layers': 2, 'dense_block_1/use_batchnorm': False, 'dense_block_1/dropout_rate': 0, 'dense_block_1/units_0': 32, 'dense_block_1/units_1': 32, 'classification_head_1/dropout_rate': 0, 'optimizer': 'adam'}]}
|
file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close()
|
file = open('names.txt', 'w')
file.write('amirreza\n')
file.write('setayesh\n')
file.write('artin\n')
file.write('iliya\n')
file.write('mohammadjavad\n')
file.close()
|
CAPACITY = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0]*CAPACITY
def insert(self, item):
# when heap is full
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
# check heap properties
self.fix_heap(self.heap_size-1)
# starting with actual node inserted to root node, compare values for swap operations-> log(N) operations, O(log(N))
def fix_heap(self, index):
# for node with index i, left child has index = 2i+1, right child has index 2i+2
# hence, reverse the eqn-> l = 2i+1, r = 2i+2-> i=l-1/2
parent_index = (index - 1)//2
# now consider all items above til root node, if heap prop is violated then swap parent with child
if index > 0 and self.heap[index] > self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index]
self.fix_heap(parent_index)
def get_max_item(self):
return self.heap[0]
# return the max element and remove it from the heap
def poll_heap(self):
max_item = self.get_max_item()
# swap the root with the last item
self.heap[0], self.heap[self.heap_size-1] = self.heap[self.heap_size-1], self.heap[0]
self.heap_size -= 1
# now perform heapify operation
self.heapify(0)
return max_item
# start from root node and rearrange heap to make sure heap properties are not violated, O(log(N))
def heapify(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
largest_index = index
# look for the largest(parent or left node)
if index_left < self.heap_size and self.heap[index_left] > self.heap[index]:
largest_index = index_left
# if right child > left child, then largest_index = right child
if index_right < self.heap_size and self.heap[index_right] > self.heap[index]:
largest_index = index_right
# If parent larger than child: it is valid heap and we terminate all recursive calls further
if index != largest_index:
self.heap[index], self.heap[largest_index] = self.heap[largest_index], self.heap[index]
self.heapify(largest_index)
# O(Nlog(N)) -> N items and O(logN) for poll_heap operation
def heap_sort(self):
for _ in range(self.heap_size):
max_item = self.poll_heap()
print(max_item)
if __name__ == "__main__":
heap = Heap()
heap.insert(13)
heap.insert(-2)
heap.insert(0)
heap.insert(8)
heap.insert(1)
heap.insert(-5)
heap.insert(99)
heap.insert(100)
print(heap.heap)
print("----------------------------")
heap.heap_sort()
|
capacity = 10
class Heap:
def __init__(self):
self.heap_size = 0
self.heap = [0] * CAPACITY
def insert(self, item):
if self.heap_size == CAPACITY:
return
self.heap[self.heap_size] = item
self.heap_size += 1
self.fix_heap(self.heap_size - 1)
def fix_heap(self, index):
parent_index = (index - 1) // 2
if index > 0 and self.heap[index] > self.heap[parent_index]:
(self.heap[index], self.heap[parent_index]) = (self.heap[parent_index], self.heap[index])
self.fix_heap(parent_index)
def get_max_item(self):
return self.heap[0]
def poll_heap(self):
max_item = self.get_max_item()
(self.heap[0], self.heap[self.heap_size - 1]) = (self.heap[self.heap_size - 1], self.heap[0])
self.heap_size -= 1
self.heapify(0)
return max_item
def heapify(self, index):
index_left = 2 * index + 1
index_right = 2 * index + 2
largest_index = index
if index_left < self.heap_size and self.heap[index_left] > self.heap[index]:
largest_index = index_left
if index_right < self.heap_size and self.heap[index_right] > self.heap[index]:
largest_index = index_right
if index != largest_index:
(self.heap[index], self.heap[largest_index]) = (self.heap[largest_index], self.heap[index])
self.heapify(largest_index)
def heap_sort(self):
for _ in range(self.heap_size):
max_item = self.poll_heap()
print(max_item)
if __name__ == '__main__':
heap = heap()
heap.insert(13)
heap.insert(-2)
heap.insert(0)
heap.insert(8)
heap.insert(1)
heap.insert(-5)
heap.insert(99)
heap.insert(100)
print(heap.heap)
print('----------------------------')
heap.heap_sort()
|
src = Split('''
ota_service.c
ota_util.c
ota_update_manifest.c
ota_version.c
''')
component = aos_component('fota', src)
dependencis = Split('''
framework/fota/platform
framework/fota/download
utility/digest_algorithm
utility/cjson
''')
for i in dependencis:
component.add_comp_deps(i)
component.add_global_includes('.')
component.add_global_macros('AOS_FOTA')
|
src = split('\n ota_service.c\n ota_util.c\n ota_update_manifest.c\n ota_version.c\n')
component = aos_component('fota', src)
dependencis = split('\n framework/fota/platform\n framework/fota/download \n utility/digest_algorithm \n utility/cjson \n')
for i in dependencis:
component.add_comp_deps(i)
component.add_global_includes('.')
component.add_global_macros('AOS_FOTA')
|
# Works only with a good seed
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("chain-lightning", hero.findNearestEnemy())
|
hero.cast('chain-lightning', hero.findNearestEnemy())
|
def main():
rst = bf_cal()
print(f"{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5")
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f"processing {x0} in (0..250)")
for x1 in range(x0, max_n):
for x2 in range(x1, max_n):
for x3 in range(x2, max_n):
y_pwr5 = sum(pwr_pool[i] for i in (x0, x1, x2, x3))
if y_pwr5 in y_pwr_pool:
y = y_pwr_pool[y_pwr5]
if y not in (x0, x1, x2, x3):
return x0, x1, x2, x3, y
if __name__ == "__main__":
main()
# 27^5 + 84^5 + 110^5 + 133^5 = 144^5
|
def main():
rst = bf_cal()
print(f'{rst[0]}^5 + {rst[1]}^5 + {rst[2]}^5 + {rst[3]}^5 = {rst[4]}^5')
def bf_cal():
max_n = 250
pwr_pool = [n ** 5 for n in range(max_n)]
y_pwr_pool = {n ** 5: n for n in range(max_n)}
for x0 in range(1, max_n):
print(f'processing {x0} in (0..250)')
for x1 in range(x0, max_n):
for x2 in range(x1, max_n):
for x3 in range(x2, max_n):
y_pwr5 = sum((pwr_pool[i] for i in (x0, x1, x2, x3)))
if y_pwr5 in y_pwr_pool:
y = y_pwr_pool[y_pwr5]
if y not in (x0, x1, x2, x3):
return (x0, x1, x2, x3, y)
if __name__ == '__main__':
main()
|
sq_sum, sum = 0, 0
for i in range(1, 101):
sq_sum = sq_sum + (i * i)
sum = sum + i
print((sum * sum) - sq_sum)
|
(sq_sum, sum) = (0, 0)
for i in range(1, 101):
sq_sum = sq_sum + i * i
sum = sum + i
print(sum * sum - sq_sum)
|
class NotFoundException(Exception):
pass
class BadRequestException(Exception):
pass
class JobExistsException(Exception):
pass
class NoSuchImportableDataset(Exception):
pass
|
class Notfoundexception(Exception):
pass
class Badrequestexception(Exception):
pass
class Jobexistsexception(Exception):
pass
class Nosuchimportabledataset(Exception):
pass
|
#!/usr/bin/python3
"""
This module provides feedback control for motors
So far a PID controller......
"""
class PIDfeedback():
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_controller)
It handles only the error value, the calling software works out what the error is to allow it to be calculated in
or measured in different ways.
This is a pretty trivial class so far
"""
def __init__(self, timenow, Pfact, Ifact, Dfact):
"""
timenow : timestamp of initial reading / setup
Pfact : Proportion factor
Ifact : Integral factor
Dfact : Derivative (slope) factor
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal= 0
self.Pfact = Pfact
self.Ifact = Ifact
self.Dfact = Dfact
def reset(self, timenow, errornow):
"""
simple reset function to save having to discard and recreate an instance
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal= 0
def factors(self, Pfact=None, Ifact=None, Dfact=None):
"""
set and return any combination of the factors
Any parameter not None will update that factor to the supplied Value.
return a 3-tuple of the values
"""
if not Pfact is None:
self.Pfact=Pfact
if not Ifact is None:
self.Ifact=Pfact
if not Dfact is None:
self.Dfact=Pfact
return self.Pfact, self.Ifact, self.Dfact
def onefact(self, factor, newvalue):
"""
set and return a single factor
factor : 'P', 'I', or 'D'
value : None to just return the current value, or an integer or float to set and return the new value
"""
assert newvalue is None or isinstance(newvalue,(int, float, str)), 'Value is not a number'
value = float(newvalue) if isinstance(newvalue, str) else newvalue
if factor=='P':
if not value is None:
self.Pfact=value
return self.Pfact
elif factor=='I':
if not value is None:
self.Ifact=value
return self.Ifact
elif factor=='D':
if not value is None:
self.Dfact=='D'
return self.Dfact
else:
raise ValueError('factor should be "P", "I" or "D"; not %S' % str(factor))
def ticker(self, timenow, errornow):
"""
called on a regular basis, this calculates the correction factor to be applied.
as long as ticks are regular we don't need to use the time as part of the slope calculation,
timenow : time at which the position was measured
errornow : the absolute error at that time - note this is the error in position, not the error in velocity
"""
lastinterval = timenow-self.timeprev
slope = errornow-self.errorprev
self.errortotal += errornow
self.errorprev = errornow
self.timeprev = timenow
return self.Pfact*errornow + self.Ifact*self.errortotal + self.Dfact*slope
def odef(self):
return {'className': type(self).__name__, 'Pfact': self.Pfact, 'Ifact': self.Ifact, 'Dfact': self.Dfact}
|
"""
This module provides feedback control for motors
So far a PID controller......
"""
class Pidfeedback:
"""
This class can be used as part of a dc motor controller. It provides feedback control using a PID controller
(https://en.wikipedia.org/wiki/PID_controller)
It handles only the error value, the calling software works out what the error is to allow it to be calculated in
or measured in different ways.
This is a pretty trivial class so far
"""
def __init__(self, timenow, Pfact, Ifact, Dfact):
"""
timenow : timestamp of initial reading / setup
Pfact : Proportion factor
Ifact : Integral factor
Dfact : Derivative (slope) factor
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal = 0
self.Pfact = Pfact
self.Ifact = Ifact
self.Dfact = Dfact
def reset(self, timenow, errornow):
"""
simple reset function to save having to discard and recreate an instance
"""
self.timeprev = timenow
self.timestart = timenow
self.errorprev = 0
self.errortotal = 0
def factors(self, Pfact=None, Ifact=None, Dfact=None):
"""
set and return any combination of the factors
Any parameter not None will update that factor to the supplied Value.
return a 3-tuple of the values
"""
if not Pfact is None:
self.Pfact = Pfact
if not Ifact is None:
self.Ifact = Pfact
if not Dfact is None:
self.Dfact = Pfact
return (self.Pfact, self.Ifact, self.Dfact)
def onefact(self, factor, newvalue):
"""
set and return a single factor
factor : 'P', 'I', or 'D'
value : None to just return the current value, or an integer or float to set and return the new value
"""
assert newvalue is None or isinstance(newvalue, (int, float, str)), 'Value is not a number'
value = float(newvalue) if isinstance(newvalue, str) else newvalue
if factor == 'P':
if not value is None:
self.Pfact = value
return self.Pfact
elif factor == 'I':
if not value is None:
self.Ifact = value
return self.Ifact
elif factor == 'D':
if not value is None:
self.Dfact == 'D'
return self.Dfact
else:
raise value_error('factor should be "P", "I" or "D"; not %S' % str(factor))
def ticker(self, timenow, errornow):
"""
called on a regular basis, this calculates the correction factor to be applied.
as long as ticks are regular we don't need to use the time as part of the slope calculation,
timenow : time at which the position was measured
errornow : the absolute error at that time - note this is the error in position, not the error in velocity
"""
lastinterval = timenow - self.timeprev
slope = errornow - self.errorprev
self.errortotal += errornow
self.errorprev = errornow
self.timeprev = timenow
return self.Pfact * errornow + self.Ifact * self.errortotal + self.Dfact * slope
def odef(self):
return {'className': type(self).__name__, 'Pfact': self.Pfact, 'Ifact': self.Ifact, 'Dfact': self.Dfact}
|
n = int(input('Enter A Number: '))
def findFactors(num):
arr = []
for x in range(1, n + 1 ,1):
if num % x == 0:
arr.append(x)
return arr
if len(findFactors(n)) == 2: # Array will have 1 and the number itself
print(f"{n} Is Prime.")
else :
print(f"{n} Is Composite")
|
n = int(input('Enter A Number: '))
def find_factors(num):
arr = []
for x in range(1, n + 1, 1):
if num % x == 0:
arr.append(x)
return arr
if len(find_factors(n)) == 2:
print(f'{n} Is Prime.')
else:
print(f'{n} Is Composite')
|
'''
Created on 1.12.2016
@author: Darren
'''
'''
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
'''
|
"""
Created on 1.12.2016
@author: Darren
"""
'\nGiven a binary search tree and a node in it, find the in-order successor of that node in the BST.\n\nNote: If the given node has no in-order successor in the tree, return null.\n'
|
def printCommands():
print("Congratulations! You're running Ryan's Task list program.")
print("What would you like to do next?")
print("1. List all tasks.")
print("2. Add a task to the list.")
print("3. Delete a task.")
print("q. To quit the program")
printCommands()
aTaskListArray = ["bob", "dave"]
userSelection = input('Enter a command: ')
if userSelection == "1":
for itemList in aTaskListArray:
print(itemList)
userSelection = input('Enter a command: ')
if userSelection == "2":
newTask = input("What would you like to add? ")
aTaskListArray.append(newTask)
userSelection = input("Enter a command: ")
if userSelection == "3":
newTask = input("What would you like to remove? ")
aTaskListArray.remove(newTask)
userSelection = input("Enter a command: ")
if userSelection == "q":
quit()
else:
print("Not a command")
print(aTaskListArray)
|
def print_commands():
print("Congratulations! You're running Ryan's Task list program.")
print('What would you like to do next?')
print('1. List all tasks.')
print('2. Add a task to the list.')
print('3. Delete a task.')
print('q. To quit the program')
print_commands()
a_task_list_array = ['bob', 'dave']
user_selection = input('Enter a command: ')
if userSelection == '1':
for item_list in aTaskListArray:
print(itemList)
user_selection = input('Enter a command: ')
if userSelection == '2':
new_task = input('What would you like to add? ')
aTaskListArray.append(newTask)
user_selection = input('Enter a command: ')
if userSelection == '3':
new_task = input('What would you like to remove? ')
aTaskListArray.remove(newTask)
user_selection = input('Enter a command: ')
if userSelection == 'q':
quit()
else:
print('Not a command')
print(aTaskListArray)
|
data = open("input.txt", "r")
data = data.read().split(",")
check = True
index = 0
while check is True:
section = data[index]
firstNum = int(data[int(data[index + 1])])
secondNum = int(data[int(data[index + 2])])
if section == "1":
total = firstNum + secondNum
if section == "2":
total = firstNum * secondNum
data[int(data[index + 3])] = str(total)
if data[index + 4] == "99":
check = False
index = index + 4
print("Your answer is... " + data[0])
|
data = open('input.txt', 'r')
data = data.read().split(',')
check = True
index = 0
while check is True:
section = data[index]
first_num = int(data[int(data[index + 1])])
second_num = int(data[int(data[index + 2])])
if section == '1':
total = firstNum + secondNum
if section == '2':
total = firstNum * secondNum
data[int(data[index + 3])] = str(total)
if data[index + 4] == '99':
check = False
index = index + 4
print('Your answer is... ' + data[0])
|
mod = 10**9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n-1):
sumation -= a[i]
answer += a[i]*sumation
answer %= mod
print(answer)
|
mod = 10 ** 9 + 7
n = int(input())
a = list(map(int, input().split()))
answer = 0
sumation = sum(a)
for i in range(n - 1):
sumation -= a[i]
answer += a[i] * sumation
answer %= mod
print(answer)
|
{
"targets": [
{
"target_name": "sharedMemory",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/sharedMemory.cpp" ],
"libraries": [],
},
{
"target_name": "messaging",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")"
],
"sources": [ "./src/messaging.cpp" ],
"libraries": [],
}
]
}
|
{'targets': [{'target_name': 'sharedMemory', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/sharedMemory.cpp'], 'libraries': []}, {'target_name': 'messaging', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")'], 'sources': ['./src/messaging.cpp'], 'libraries': []}]}
|
def protected(func):
def wrapper(password):
if password=='platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == "__main__":
password=str(raw_input('Ingresa tu contrasena: '))
# wrapper=protected(protected_func)
# wrapper(password)
protected_func(password)
|
def protected(func):
def wrapper(password):
if password == 'platzi':
return func()
else:
print('Contrasena invalida')
return wrapper
@protected
def protected_func():
print('To contrasena es correcta')
if __name__ == '__main__':
password = str(raw_input('Ingresa tu contrasena: '))
protected_func(password)
|
s=input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon')
|
s = input()
if s[-1] in '24579':
print('hon')
elif s[-1] in '0168':
print('pon')
else:
print('bon')
|
# Text Type: str
# Numeric Types: int, float, complex
# Sequence Types: list, tuple, range
# Mapping Type: dict
# Set Types: set, frozenset
# Boolean Type: bool
# Binary Types: bytes, bytearray, memoryview
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
print("--------------------------------------------------------")
num =6
print(num)
print(str(num)+ " is my num")
# print(num + "my num")
# print(num + "my num") - will not work
print("--------------------------------------------------------")
|
x = float(1)
y = float(2.8)
z = float('3')
w = float('4.2')
print('--------------------------------------------------------')
num = 6
print(num)
print(str(num) + ' is my num')
print('--------------------------------------------------------')
|
"""Extended Euclidean Algorithm
==============================
GCD of two numbers is the largest number that divides both of them.
A simple way to find GCD is to factorize both numbers and multiply
common factors.
GCD(a,b) = ax + by
If we can find the value of x and y then we can easily find the
value of GCD(a,b) by replacing (x,y) with their respective values.
"""
def gcdFunction(a, b, x, y):
if a == 0:
x = 0
y = 1
return b
x1 = 0; y1 = 0
gcd = gcdFunction(b % a, a, x1, y1)
x = y1 - int(b / a) * x1
y = x1
return gcd
a = 98; b = 21
x = 0; y = 0
print("GCD of numbers " + str(a) + " and " + str(b) + " is " + str(gcdFunction(a, b, x, y)))
''' Output
GCD of numbers 98 and 21 is 7
'''
|
"""Extended Euclidean Algorithm
==============================
GCD of two numbers is the largest number that divides both of them.
A simple way to find GCD is to factorize both numbers and multiply
common factors.
GCD(a,b) = ax + by
If we can find the value of x and y then we can easily find the
value of GCD(a,b) by replacing (x,y) with their respective values.
"""
def gcd_function(a, b, x, y):
if a == 0:
x = 0
y = 1
return b
x1 = 0
y1 = 0
gcd = gcd_function(b % a, a, x1, y1)
x = y1 - int(b / a) * x1
y = x1
return gcd
a = 98
b = 21
x = 0
y = 0
print('GCD of numbers ' + str(a) + ' and ' + str(b) + ' is ' + str(gcd_function(a, b, x, y)))
' Output\n\nGCD of numbers 98 and 21 is 7\n\n'
|
TRAIN_DATA_PATH = "data/processed/train_folds.csv"
TEST_DATA_PATH = "data/processed/test.csv"
MODEL_PATH = "models/"
NUM_FOLDS = 5
SEED = 23
VERBOSE = 0
FEATURE_COLS = [
"Pclass",
"Sex",
"Age",
"SibSp",
"Parch",
"Ticket",
"Fare",
"Cabin",
"Embarked",
"Title",
"Surname",
"Family_Size",
]
TARGET_COL = "Survived"
|
train_data_path = 'data/processed/train_folds.csv'
test_data_path = 'data/processed/test.csv'
model_path = 'models/'
num_folds = 5
seed = 23
verbose = 0
feature_cols = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'Title', 'Surname', 'Family_Size']
target_col = 'Survived'
|
"""
author: Alice Francener
problem: 1082 - Connected Components
description: https://www.urionlinejudge.com.br/judge/en/problems/view/1082
"""
'''Problema: quantos grafos conexos existem'''
class DisjointSets:
def __init__(self, n):
self.rank = [0] * n
self.parent = []
for i in range(0, n):
self.parent.append(i)
def find(self, u):
if u != self.parent[u]:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] > self.rank[y]:
self.parent[y] = x
else:
self.parent[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] = self.rank[y] + 1
'''input: 1. numero de casos, 2. numero de nos & numero de arestas, 3. arestas'''
n_casos = int(input())
for caso in range(n_casos):
entrada = input().split()
n_nodes = int(entrada[0])
n_edges = int(entrada[1])
alfabeto = DisjointSets(n_nodes)
for e in range(n_edges):
edge = input().split()
alfabeto.union(ord(edge[0])-97, ord(edge[1])-97)
for i in range(0, n_nodes):
alfabeto.find(i)
print("Case #{}:".format(caso+1))
connected = 0
for i in range(0, len(alfabeto.parent)):
graph = ''
if alfabeto.parent[i] != -1:
graph = graph + chr(i+97) + ','
for j in range(i+1, len(alfabeto.parent)):
if alfabeto.parent[i] == alfabeto.parent[j]:
graph = graph + chr(j+97) + ','
alfabeto.parent[j] = -1
if len(graph):
print(graph)
connected = connected + 1
print('{} connected components\n'.format(connected))
|
"""
author: Alice Francener
problem: 1082 - Connected Components
description: https://www.urionlinejudge.com.br/judge/en/problems/view/1082
"""
'Problema: quantos grafos conexos existem'
class Disjointsets:
def __init__(self, n):
self.rank = [0] * n
self.parent = []
for i in range(0, n):
self.parent.append(i)
def find(self, u):
if u != self.parent[u]:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] > self.rank[y]:
self.parent[y] = x
else:
self.parent[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] = self.rank[y] + 1
'input: 1. numero de casos, 2. numero de nos & numero de arestas, 3. arestas'
n_casos = int(input())
for caso in range(n_casos):
entrada = input().split()
n_nodes = int(entrada[0])
n_edges = int(entrada[1])
alfabeto = disjoint_sets(n_nodes)
for e in range(n_edges):
edge = input().split()
alfabeto.union(ord(edge[0]) - 97, ord(edge[1]) - 97)
for i in range(0, n_nodes):
alfabeto.find(i)
print('Case #{}:'.format(caso + 1))
connected = 0
for i in range(0, len(alfabeto.parent)):
graph = ''
if alfabeto.parent[i] != -1:
graph = graph + chr(i + 97) + ','
for j in range(i + 1, len(alfabeto.parent)):
if alfabeto.parent[i] == alfabeto.parent[j]:
graph = graph + chr(j + 97) + ','
alfabeto.parent[j] = -1
if len(graph):
print(graph)
connected = connected + 1
print('{} connected components\n'.format(connected))
|
def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(" ")
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.strip().split('/')
print('PUBLIC ' + segments[len(segments)-1].split('.')[0].upper())
f.close()
def main():
create_list_of_libs()
if __name__ == '__main__':
main()
|
def parse_ninja():
f = open('out/peerconnection_client.ninja', 'r')
for line in f.readlines():
lines = line.split(' ')
for l in lines:
print(l)
f.close()
def create_list_of_libs():
f = open('out/client_libs.txt', 'r')
for line in f.readlines():
segments = line.strip().split('/')
print('PUBLIC ' + segments[len(segments) - 1].split('.')[0].upper())
f.close()
def main():
create_list_of_libs()
if __name__ == '__main__':
main()
|
#(n-1)%M = x - 1
#(n-1)%N = y - 1
gcd = lambda a,b: gcd(b,a%b) if b else a
def finder(M,N,x,y):
for i in range(N//gcd(M,N)):
if (x-1+i*M)%N==y-1:
return x+i*M
return -1
for _ in range(int(input())):
M,N,x,y = map(int,input().split())
print(finder(M,N,x,y))
|
gcd = lambda a, b: gcd(b, a % b) if b else a
def finder(M, N, x, y):
for i in range(N // gcd(M, N)):
if (x - 1 + i * M) % N == y - 1:
return x + i * M
return -1
for _ in range(int(input())):
(m, n, x, y) = map(int, input().split())
print(finder(M, N, x, y))
|
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(
type='PoseDetDetector',
pretrained='pretrained/dla34-ba72cf86.pth',
# pretrained='open-mmlab://msra/hrnetv2_w32',
backbone=dict(
type='DLA',
return_levels=True,
levels=[1, 1, 1, 2, 2, 1],
channels=[16, 32, 64, 128, 256, 512],
ouput_indice=[3,4,5,6],
),
neck=dict(
type='FPN',
in_channels=[64, 128, 256, 512],
out_channels=128,
start_level=1,
add_extra_convs='on_input',
num_outs=4,
# num_outs=3,
norm_cfg=norm_cfg,),
bbox_head=dict(
# type='PoseDetHead',
type='PoseDetHeadHeatMapMl',
norm_cfg=norm_cfg,
num_classes=1,
in_channels=128,
feat_channels=128,
embedding_feat_channels=128,
init_convs=3,
refine_convs=2,
cls_convs=2,
gradient_mul=0.1,
dcn_kernel=(1,17),
refine_num=1,
point_strides=[8, 16, 32, 64],
point_base_scale=4,
num_keypoints=17,
loss_cls=dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_keypoints_init=dict(type='KeypointsLoss',
d_type='L2',
weight=.1,
stage='init',
normalize_factor=1,
),
loss_keypoints_refine=dict(type='KeypointsLoss',
d_type='L2',
weight=.2,
stage='refine',
normalize_factor=1,
),
loss_heatmap=dict(type='HeatmapLoss', weight=.1, with_sigmas=False),
)
)
# training and testing settings
train_cfg = dict(
init=dict(
assigner=dict(type='KeypointsAssigner',
scale=4,
pos_num=1,
number_keypoints_thr=3,
num_keypoints=17,
center_type='keypoints',
# center_type='box'
),
allowed_border=-1,
pos_weight=-1,
debug=False),
refine=dict(
assigner=dict(
type='OksAssigner',
pos_PD_thr=0.7,
neg_PD_thr=0.7,
min_pos_iou=0.52,
ignore_iof_thr=-1,
match_low_quality=True,
num_keypoints=17,
number_keypoints_thr=3, #
),
allowed_border=-1,
pos_weight=-1,
debug=False
),
cls=dict(
assigner=dict(
type='OksAssigner',
pos_PD_thr=0.6,
neg_PD_thr=0.5,
min_pos_iou=0.5,
ignore_iof_thr=-1,
match_low_quality=False,
num_keypoints=17,
number_keypoints_thr=3,
),
allowed_border=-1,
pos_weight=-1,
debug=False
),
)
test_cfg = dict(
nms_pre=500,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='keypoints_nms', iou_thr=0.2),
max_per_img=100)
|
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', backbone=dict(type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channels=[16, 32, 64, 128, 256, 512], ouput_indice=[3, 4, 5, 6]), neck=dict(type='FPN', in_channels=[64, 128, 256, 512], out_channels=128, start_level=1, add_extra_convs='on_input', num_outs=4, norm_cfg=norm_cfg), bbox_head=dict(type='PoseDetHeadHeatMapMl', norm_cfg=norm_cfg, num_classes=1, in_channels=128, feat_channels=128, embedding_feat_channels=128, init_convs=3, refine_convs=2, cls_convs=2, gradient_mul=0.1, dcn_kernel=(1, 17), refine_num=1, point_strides=[8, 16, 32, 64], point_base_scale=4, num_keypoints=17, loss_cls=dict(type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_keypoints_init=dict(type='KeypointsLoss', d_type='L2', weight=0.1, stage='init', normalize_factor=1), loss_keypoints_refine=dict(type='KeypointsLoss', d_type='L2', weight=0.2, stage='refine', normalize_factor=1), loss_heatmap=dict(type='HeatmapLoss', weight=0.1, with_sigmas=False)))
train_cfg = dict(init=dict(assigner=dict(type='KeypointsAssigner', scale=4, pos_num=1, number_keypoints_thr=3, num_keypoints=17, center_type='keypoints'), allowed_border=-1, pos_weight=-1, debug=False), refine=dict(assigner=dict(type='OksAssigner', pos_PD_thr=0.7, neg_PD_thr=0.7, min_pos_iou=0.52, ignore_iof_thr=-1, match_low_quality=True, num_keypoints=17, number_keypoints_thr=3), allowed_border=-1, pos_weight=-1, debug=False), cls=dict(assigner=dict(type='OksAssigner', pos_PD_thr=0.6, neg_PD_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1, match_low_quality=False, num_keypoints=17, number_keypoints_thr=3), allowed_border=-1, pos_weight=-1, debug=False))
test_cfg = dict(nms_pre=500, min_bbox_size=0, score_thr=0.05, nms=dict(type='keypoints_nms', iou_thr=0.2), max_per_img=100)
|
"""top-level pytest config
options can only be defined here,
not in binderhub/tests/conftest.py
"""
def pytest_addoption(parser):
parser.addoption(
"--helm",
action="store_true",
default=False,
help="Run tests marked with pytest.mark.helm",
)
|
"""top-level pytest config
options can only be defined here,
not in binderhub/tests/conftest.py
"""
def pytest_addoption(parser):
parser.addoption('--helm', action='store_true', default=False, help='Run tests marked with pytest.mark.helm')
|
# Exceptions
class SequenceFieldException(Exception):
pass
|
class Sequencefieldexception(Exception):
pass
|
try:
x = int(input("X: "))
except ValueError:
print("That is not an int!")
exit()
try:
y = int(input("Y: "))
except ValueError:
print("That is not an int!")
exit()
print (x + y)
|
try:
x = int(input('X: '))
except ValueError:
print('That is not an int!')
exit()
try:
y = int(input('Y: '))
except ValueError:
print('That is not an int!')
exit()
print(x + y)
|
# Design Linked List
class ListNode:
def __init__(self, x):
self.value = x
self.next = None
class LinkedList:
def __init__(self):
self.size = 0
self.head = ListNode(0) # Sentinel Node as psuedo-head
# add at head
def addAtHead(self, val):
self.addAtHead(0, val)
# add at tail
def addAtTail(self, val):
self.addAtTail(self.size, val)
# add at index
def addAtIndex(self, index, val):
if index > self.size:
return
if index < 0:
index = 0
self.size += 1
# predecessor of the node
prd = self.head
for _ in range(index):
prd = prd.next
# node to be added
to_add = ListNode(val)
# Insert
to_add.next = prd.next
prd.next = to_add
# delete at index
def delAtIndex(self,index):
if index < 0 or index >= index.size:
return
self.size -= 1
prd = self.head
for _ in range(index):
prd = prd.next
prd.next = prd.next.next
# get element
def getElement(self,index):
if index < 0 or index >= self.size:
return -1
curr = self.head
for _ in range(index + 1):
curr = curr.next
return curr.val
|
class Listnode:
def __init__(self, x):
self.value = x
self.next = None
class Linkedlist:
def __init__(self):
self.size = 0
self.head = list_node(0)
def add_at_head(self, val):
self.addAtHead(0, val)
def add_at_tail(self, val):
self.addAtTail(self.size, val)
def add_at_index(self, index, val):
if index > self.size:
return
if index < 0:
index = 0
self.size += 1
prd = self.head
for _ in range(index):
prd = prd.next
to_add = list_node(val)
to_add.next = prd.next
prd.next = to_add
def del_at_index(self, index):
if index < 0 or index >= index.size:
return
self.size -= 1
prd = self.head
for _ in range(index):
prd = prd.next
prd.next = prd.next.next
def get_element(self, index):
if index < 0 or index >= self.size:
return -1
curr = self.head
for _ in range(index + 1):
curr = curr.next
return curr.val
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.