content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
# OpenWeatherMap API Key
weather_api_key = "Insert your own key"
# Google API Key
g_key = "Insert your own key"
|
weather_api_key = 'Insert your own key'
g_key = 'Insert your own key'
|
"Tests for pug bzl definitions"
load("@bazel_tools//tools/build_rules:test_rules.bzl", "file_test", "rule_test")
def _pug_binary_test(package):
rule_test(
name = "hello_world_rule_test",
generates = ["main.html"],
rule = package + "/hello_world:hello_world"
)
file_test(
name = "hello_world_file_test",
file = package + "/hello_world:main.html",
content = "<div>Hello World !</div>"
)
rule_test(
name = "mixin_rule_test",
generates = ["main.html"],
rule = package + "/mixin:mixin"
)
file_test(
name = "mixin_file_test",
file = package + "/mixin:main.html",
content = "<div>Hello World !</div><div>Mixin file</div><div>Mixin resource</div>"
)
def pug_rule_test(package):
"""Issue simple tests on pug rules."""
_pug_binary_test(package)
|
"""Tests for pug bzl definitions"""
load('@bazel_tools//tools/build_rules:test_rules.bzl', 'file_test', 'rule_test')
def _pug_binary_test(package):
rule_test(name='hello_world_rule_test', generates=['main.html'], rule=package + '/hello_world:hello_world')
file_test(name='hello_world_file_test', file=package + '/hello_world:main.html', content='<div>Hello World !</div>')
rule_test(name='mixin_rule_test', generates=['main.html'], rule=package + '/mixin:mixin')
file_test(name='mixin_file_test', file=package + '/mixin:main.html', content='<div>Hello World !</div><div>Mixin file</div><div>Mixin resource</div>')
def pug_rule_test(package):
"""Issue simple tests on pug rules."""
_pug_binary_test(package)
|
class Solution:
def countGoodSubstrings(self, s: str) -> int:
count, i, end = 0, 2, len(s)
while i < end:
a, b, c = s[i-2], s[i-1], s[i]
if a == b == c:
i += 2
continue
count += a != b and b != c and a != c
i += 1
return count
|
class Solution:
def count_good_substrings(self, s: str) -> int:
(count, i, end) = (0, 2, len(s))
while i < end:
(a, b, c) = (s[i - 2], s[i - 1], s[i])
if a == b == c:
i += 2
continue
count += a != b and b != c and (a != c)
i += 1
return count
|
(
XL_CELL_EMPTY, #0
XL_CELL_TEXT, #1
XL_CELL_NUMBER, #2
XL_CELl_DATE, #3
XL_CELL_BOOLEAN,#4
XL_CELL_ERROR, #5
XL_CELL_BLANK, #6
) = range(7)
ctype_text = {
XL_CELL_EMPTY: 'empty',
XL_CELL_TEXT:'text',
XL_CELL_NUMBER:'number',
XL_CELl_DATE:'date',
XL_CELL_BOOLEAN:'boolean',
XL_CELL_ERROR:'error',
XL_CELL_BLANK:'blank',
}
|
(xl_cell_empty, xl_cell_text, xl_cell_number, xl_ce_ll_date, xl_cell_boolean, xl_cell_error, xl_cell_blank) = range(7)
ctype_text = {XL_CELL_EMPTY: 'empty', XL_CELL_TEXT: 'text', XL_CELL_NUMBER: 'number', XL_CELl_DATE: 'date', XL_CELL_BOOLEAN: 'boolean', XL_CELL_ERROR: 'error', XL_CELL_BLANK: 'blank'}
|
"""
Dictionary key must be immutable
"""
string_dict = dict({"1": "1st", "2": "2nd", "3": "3rd"})
def add_element_to_string_dict(key: str, value: str):
string_dict[key] = value
def delete_element_to_string_dict(key: str):
del string_dict[key]
def get_element_from_string_dict(key: str):
if key in string_dict:
print("key: {} \t value: {}".format(key, string_dict[key]))
else:
print("key {} not found".format(key))
def are_equal(dict_one, dict_two):
return dict_one == dict_two
def is_key_in_dict(key, my_dict):
return key in my_dict
def list_keys(my_dict):
return list(my_dict.keys())
def list_values(my_dict):
return list(my_dict.values())
def list_items(my_dict):
return list(my_dict.items())
def print_info(my_dict):
for k in my_dict.keys():
print('\t', k)
print('')
for v in my_dict.values():
print('\t', v)
print('')
for k, v in my_dict.items():
print('\t', k, v)
def set_default(my_dict, key, value):
my_dict.setdefault(key, value)
return my_dict
if __name__ == '__main__':
print('base dict\n', string_dict)
add_element_to_string_dict("4", "4rd")
print('add an element\n', string_dict)
delete_element_to_string_dict("2")
print('delete an element\n', string_dict)
get_element_from_string_dict("8")
print('getting an element\n', string_dict)
get_element_from_string_dict("4")
a = {'name': 'Pit', 'age': 423}
b = {'age': 423, 'name': 'Pit'}
print('compare two dicts\n', are_equal(a, b))
print('look for a key in a dict\n', is_key_in_dict('hello', a))
print('list all the keys of a dict\n', list_keys(string_dict))
print('list all the values of a dict\n', list_values(string_dict))
print('list all the items of a dict\n', list_items(string_dict))
print('\nInfo: \n')
print_info(string_dict)
print('Set a new key whit its value\n', set_default(string_dict, '5', '5th'))
|
"""
Dictionary key must be immutable
"""
string_dict = dict({'1': '1st', '2': '2nd', '3': '3rd'})
def add_element_to_string_dict(key: str, value: str):
string_dict[key] = value
def delete_element_to_string_dict(key: str):
del string_dict[key]
def get_element_from_string_dict(key: str):
if key in string_dict:
print('key: {} \t value: {}'.format(key, string_dict[key]))
else:
print('key {} not found'.format(key))
def are_equal(dict_one, dict_two):
return dict_one == dict_two
def is_key_in_dict(key, my_dict):
return key in my_dict
def list_keys(my_dict):
return list(my_dict.keys())
def list_values(my_dict):
return list(my_dict.values())
def list_items(my_dict):
return list(my_dict.items())
def print_info(my_dict):
for k in my_dict.keys():
print('\t', k)
print('')
for v in my_dict.values():
print('\t', v)
print('')
for (k, v) in my_dict.items():
print('\t', k, v)
def set_default(my_dict, key, value):
my_dict.setdefault(key, value)
return my_dict
if __name__ == '__main__':
print('base dict\n', string_dict)
add_element_to_string_dict('4', '4rd')
print('add an element\n', string_dict)
delete_element_to_string_dict('2')
print('delete an element\n', string_dict)
get_element_from_string_dict('8')
print('getting an element\n', string_dict)
get_element_from_string_dict('4')
a = {'name': 'Pit', 'age': 423}
b = {'age': 423, 'name': 'Pit'}
print('compare two dicts\n', are_equal(a, b))
print('look for a key in a dict\n', is_key_in_dict('hello', a))
print('list all the keys of a dict\n', list_keys(string_dict))
print('list all the values of a dict\n', list_values(string_dict))
print('list all the items of a dict\n', list_items(string_dict))
print('\nInfo: \n')
print_info(string_dict)
print('Set a new key whit its value\n', set_default(string_dict, '5', '5th'))
|
def sum6(n):
nums = [i for i in range(1, n + 1)]
return sum(nums)
N = 10
S = sum6(N)
print(S)
|
def sum6(n):
nums = [i for i in range(1, n + 1)]
return sum(nums)
n = 10
s = sum6(N)
print(S)
|
class ValveStatus(object):
"""
An enumeration of possible valve states. OPEN_AND_DISABLED should never happen.
"""
OPEN_AND_ENABLED, CLOSED_AND_ENABLED, OPEN_AND_DISABLED, CLOSED_AND_DISABLED = (i for i in range(4))
|
class Valvestatus(object):
"""
An enumeration of possible valve states. OPEN_AND_DISABLED should never happen.
"""
(open_and_enabled, closed_and_enabled, open_and_disabled, closed_and_disabled) = (i for i in range(4))
|
def solve():
s = sum((x ** x for x in range(1, 1001)))
print(str(s)[-10:])
if __name__ == '__main__':
solve()
|
def solve():
s = sum((x ** x for x in range(1, 1001)))
print(str(s)[-10:])
if __name__ == '__main__':
solve()
|
#!/usr/bin/env python
"""Contains extractor configuration information
"""
# Setup the name of our extractor.
EXTRACTOR_NAME = ""
# Name of scientific method for this extractor. Leave commented out if it's unknown
#METHOD_NAME = ""
# The version number of the extractor
VERSION = "1.0"
# The extractor description
DESCRIPTION = ""
# The name of the author of the extractor
AUTHOR_NAME = ""
# The email of the author of the extractor
AUTHOR_EMAIL = ""
# Reposity URI
REPOSITORY = ""
# Output variable identifiers. Use a comma separated list if more than one value is returned.
# For example, "variable 1,variable 2" identifies the two variables returned by the extractor.
# If only one name is specified, no comma's are used.
# Note that variable names cannot have comma's in them: use a different separator instead. Also,
# all white space is kept intact; don't add any extra whitespace since it may cause name comparisons
# to fail
VARIABLE_NAMES = ""
|
"""Contains extractor configuration information
"""
extractor_name = ''
version = '1.0'
description = ''
author_name = ''
author_email = ''
repository = ''
variable_names = ''
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = head
while tmp and tmp.next:
head = head.next
tmp = tmp.next.next
return head
def test_middle_node_1():
s = Solution()
a = ListNode(2)
b = ListNode(1)
c = ListNode(3)
d = ListNode(5)
e = ListNode(6)
a.next = b
b.next = c
c.next = d
d.next = e
assert c == s.middleNode(a)
def test_middle_node_2():
s = Solution()
a = ListNode(2)
b = ListNode(1)
c = ListNode(3)
d = ListNode(5)
e = ListNode(6)
f = ListNode(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
assert d == s.middleNode(a)
|
class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def middle_node(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = head
while tmp and tmp.next:
head = head.next
tmp = tmp.next.next
return head
def test_middle_node_1():
s = solution()
a = list_node(2)
b = list_node(1)
c = list_node(3)
d = list_node(5)
e = list_node(6)
a.next = b
b.next = c
c.next = d
d.next = e
assert c == s.middleNode(a)
def test_middle_node_2():
s = solution()
a = list_node(2)
b = list_node(1)
c = list_node(3)
d = list_node(5)
e = list_node(6)
f = list_node(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
assert d == s.middleNode(a)
|
listaDePalavras = ('Aprender','Programar','Linguagem','Python','Curso','Gratis',
'Estudar','Praticar','Trabalhar','Mercado','Programador',
'Futuro')
for palavras in listaDePalavras:
print(f'\n A palavra {palavras} temos', end=' ')
for letras in palavras:
if letras.lower() in 'aeiou':
print(letras.lower(),end=' ')
|
lista_de_palavras = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar', 'Praticar', 'Trabalhar', 'Mercado', 'Programador', 'Futuro')
for palavras in listaDePalavras:
print(f'\n A palavra {palavras} temos', end=' ')
for letras in palavras:
if letras.lower() in 'aeiou':
print(letras.lower(), end=' ')
|
x = 1
y = 'Hello'
z = 10.123
d = x + z
print(d)
print(type(x))
print(type(y))
print(y.upper())
print(y.lower())
print(type(z))
a = [1,2,3,4,5,6,6,7,8]
print(len(a))
print(a.count(6))
b = list(range(10,100,10))
print(b)
stud_marks = {"Madhan":90, "Raj":25,"Mani":80}
print(stud_marks.keys())
print(stud_marks.values())
ab = list(range(10,100,10))
ab.append(100)
ab.append(110)
ab.remove(110)
print(ab[0:2])
|
x = 1
y = 'Hello'
z = 10.123
d = x + z
print(d)
print(type(x))
print(type(y))
print(y.upper())
print(y.lower())
print(type(z))
a = [1, 2, 3, 4, 5, 6, 6, 7, 8]
print(len(a))
print(a.count(6))
b = list(range(10, 100, 10))
print(b)
stud_marks = {'Madhan': 90, 'Raj': 25, 'Mani': 80}
print(stud_marks.keys())
print(stud_marks.values())
ab = list(range(10, 100, 10))
ab.append(100)
ab.append(110)
ab.remove(110)
print(ab[0:2])
|
# Generate .travis.yml automatically
# Configuration for Linux
configs = [
# OS, OS version, compiler, build type, task
("ubuntu", "18.04", "gcc", "DefaultDebug", "Test"),
("ubuntu", "18.04", "gcc", "DefaultRelease", "Test"),
("debian", "9", "gcc", "DefaultDebug", "Test"),
("debian", "9", "gcc", "DefaultRelease", "Test"),
("debian", "10", "gcc", "DefaultDebug", "Test"),
("debian", "10", "gcc", "DefaultRelease", "Test"),
("ubuntu", "20.04", "gcc", "DefaultDebugTravis", "TestDocker"),
("ubuntu", "20.04", "gcc", "DefaultReleaseTravis", "TestDockerDoxygen"),
# ("osx", "xcode9.3", "clang", "DefaultDebug", "Test"),
# ("osx", "xcode9.3", "clang", "DefaultRelease", "Test"),
]
# Stages in travis
build_stages = [
("Build (1st run)", "Build1"),
("Build (2nd run)", "Build2"),
("Build (3rd run)", "BuildLast"),
("Tasks", "Tasks"),
]
def get_env_string(os, os_version, compiler, build_type, task):
if os == "osx":
return "CONFIG={} TASK={} COMPILER={} STL=libc++\n".format(build_type, task, compiler)
else:
return "CONFIG={} TASK={} LINUX={} COMPILER={}\n".format(build_type, task, "{}-{}".format(os, os_version), compiler)
if __name__ == "__main__":
s = ""
# Initial config
s += "#\n"
s += "# General config\n"
s += "#\n"
s += "branches:\n"
s += " only:\n"
s += " - master\n"
s += " - stable\n"
s += "sudo: required\n"
s += "language: cpp\n"
s += "\n"
s += "git:\n"
s += " depth: false\n"
s += "\n"
s += "# Enable caching\n"
s += "cache:\n"
s += " timeout: 1000\n"
s += " directories:\n"
s += " - build\n"
s += " - travis/mtime_cache\n"
s += "\n"
s += "# Enable docker support\n"
s += "services:\n"
s += "- docker\n"
s += "\n"
s += "notifications:\n"
s += " email:\n"
s += " on_failure: always\n"
s += " on_success: change\n"
s += " recipients:\n"
s += ' - secure: "VWnsiQkt1xjgRo1hfNiNQqvLSr0fshFmLV7jJlUixhCr094mgD0U2bNKdUfebm28Byg9UyDYPbOFDC0sx7KydKiL1q7FKKXkyZH0k04wUu8XiNw+fYkDpmPnQs7G2n8oJ/GFJnr1Wp/1KI3qX5LX3xot4cJfx1I5iFC2O+p+ng6v/oSX+pewlMv4i7KL16ftHHHMo80N694v3g4B2NByn4GU2/bjVQcqlBp/TiVaUa5Nqu9DxZi/n9CJqGEaRHOblWyMO3EyTZsn45BNSWeQ3DtnMwZ73rlIr9CaEgCeuArc6RGghUAVqRI5ao+N5apekIaILwTgL6AJn+Lw/+NRPa8xclgd0rKqUQJMJCDZKjKz2lmIs3bxfELOizxJ3FJQ5R95FAxeAZ6rb/j40YqVVTw2IMBDnEE0J5ZmpUYNUtPti/Adf6GD9Fb2y8sLo0XDJzkI8OxYhfgjSy5KYmRj8O5MXcP2MAE8LQauNO3MaFnL9VMVOTZePJrPozQUgM021uyahf960+QNI06Uqlmg+PwWkSdllQlxHHplOgW7zClFhtSUpnJxcsUBzgg4kVg80gXUwAQkaDi7A9Wh2bs+TvMlmHzBwg+2SaAfWDgjeJIeOaipDkF1uSGzC+EHAiiKYMLd4Aahoi8SuelJUucoyJyLAq00WdUFQIh/izVhM4Y="\n'
s += "\n"
s += "#\n"
s += "# Configurations\n"
s += "#\n"
s += "jobs:\n"
s += " include:\n"
# Start with prebuilding carl for docker
s += "\n"
s += " ###\n"
s += " # Stage: Build Carl\n"
s += " ###\n"
for config in configs:
os, os_version, compiler, build_type, task = config
os_type = "osx" if os == "osx" else "linux"
if "Travis" in build_type:
s += " # {}-{} - {}\n".format(os, os_version, build_type)
buildConfig = ""
buildConfig += " - stage: Build Carl\n"
buildConfig += " os: {}\n".format(os_type)
buildConfig += " compiler: {}\n".format(compiler)
buildConfig += " env: {}".format(get_env_string(os, os_version, compiler, build_type, task))
buildConfig += " before_script:\n"
buildConfig += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n'
buildConfig += " script:\n"
buildConfig += " - travis/build_carl.sh\n"
buildConfig += " before_cache:\n"
buildConfig += " - docker cp carl:/opt/carl/. .\n"
# Upload to DockerHub
buildConfig += " deploy:\n"
buildConfig += " - provider: script\n"
buildConfig += " skip_cleanup: true\n"
buildConfig += " script: bash travis/deploy_docker.sh carl\n"
s += buildConfig
# Generate all build configurations
for stage in build_stages:
s += "\n"
s += " ###\n"
s += " # Stage: {}\n".format(stage[0])
s += " ###\n"
for config in configs:
os, os_version, compiler, build_type, task = config
os_type = "osx" if os == "osx" else "linux"
s += " # {}-{} - {}\n".format(os, os_version, build_type)
buildConfig = ""
buildConfig += " - stage: {}\n".format(stage[0])
buildConfig += " os: {}\n".format(os_type)
if os_type == "osx":
buildConfig += " osx_image: {}\n".format(os_version)
buildConfig += " compiler: {}\n".format(compiler)
buildConfig += " env: {}".format(get_env_string(os, os_version, compiler, build_type, task))
buildConfig += " install:\n"
if stage[1] == "Build1":
buildConfig += " - rm -rf build\n"
buildConfig += " - travis/skip_test.sh\n"
if os_type == "osx":
buildConfig += " - travis/install_osx.sh\n"
buildConfig += " before_script:\n"
buildConfig += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n'
buildConfig += " script:\n"
buildConfig += " - travis/build.sh {}\n".format(stage[1])
if os_type == "linux":
buildConfig += " before_cache:\n"
buildConfig += " - docker cp storm:/opt/storm/. .\n"
buildConfig += " after_failure:\n"
buildConfig += " - find build -iname '*err*.log' -type f -print -exec cat {} \;\n"
# Deployment
if stage[1] == "Tasks":
if "Docker" in task or "Doxygen" in task:
buildConfig += " deploy:\n"
if "Docker" in task:
buildConfig += " - provider: script\n"
buildConfig += " skip_cleanup: true\n"
buildConfig += " script: bash travis/deploy_docker.sh storm\n"
if "Doxygen" in task:
buildConfig += " - provider: pages\n"
buildConfig += " skip_cleanup: true\n"
buildConfig += " github_token: $GITHUB_TOKEN\n"
buildConfig += " local_dir: build/doc/html/\n"
buildConfig += " repo: moves-rwth/storm-doc\n"
buildConfig += " target_branch: master\n"
buildConfig += " on:\n"
buildConfig += " branch: master\n"
s += buildConfig
print(s)
|
configs = [('ubuntu', '18.04', 'gcc', 'DefaultDebug', 'Test'), ('ubuntu', '18.04', 'gcc', 'DefaultRelease', 'Test'), ('debian', '9', 'gcc', 'DefaultDebug', 'Test'), ('debian', '9', 'gcc', 'DefaultRelease', 'Test'), ('debian', '10', 'gcc', 'DefaultDebug', 'Test'), ('debian', '10', 'gcc', 'DefaultRelease', 'Test'), ('ubuntu', '20.04', 'gcc', 'DefaultDebugTravis', 'TestDocker'), ('ubuntu', '20.04', 'gcc', 'DefaultReleaseTravis', 'TestDockerDoxygen')]
build_stages = [('Build (1st run)', 'Build1'), ('Build (2nd run)', 'Build2'), ('Build (3rd run)', 'BuildLast'), ('Tasks', 'Tasks')]
def get_env_string(os, os_version, compiler, build_type, task):
if os == 'osx':
return 'CONFIG={} TASK={} COMPILER={} STL=libc++\n'.format(build_type, task, compiler)
else:
return 'CONFIG={} TASK={} LINUX={} COMPILER={}\n'.format(build_type, task, '{}-{}'.format(os, os_version), compiler)
if __name__ == '__main__':
s = ''
s += '#\n'
s += '# General config\n'
s += '#\n'
s += 'branches:\n'
s += ' only:\n'
s += ' - master\n'
s += ' - stable\n'
s += 'sudo: required\n'
s += 'language: cpp\n'
s += '\n'
s += 'git:\n'
s += ' depth: false\n'
s += '\n'
s += '# Enable caching\n'
s += 'cache:\n'
s += ' timeout: 1000\n'
s += ' directories:\n'
s += ' - build\n'
s += ' - travis/mtime_cache\n'
s += '\n'
s += '# Enable docker support\n'
s += 'services:\n'
s += '- docker\n'
s += '\n'
s += 'notifications:\n'
s += ' email:\n'
s += ' on_failure: always\n'
s += ' on_success: change\n'
s += ' recipients:\n'
s += ' - secure: "VWnsiQkt1xjgRo1hfNiNQqvLSr0fshFmLV7jJlUixhCr094mgD0U2bNKdUfebm28Byg9UyDYPbOFDC0sx7KydKiL1q7FKKXkyZH0k04wUu8XiNw+fYkDpmPnQs7G2n8oJ/GFJnr1Wp/1KI3qX5LX3xot4cJfx1I5iFC2O+p+ng6v/oSX+pewlMv4i7KL16ftHHHMo80N694v3g4B2NByn4GU2/bjVQcqlBp/TiVaUa5Nqu9DxZi/n9CJqGEaRHOblWyMO3EyTZsn45BNSWeQ3DtnMwZ73rlIr9CaEgCeuArc6RGghUAVqRI5ao+N5apekIaILwTgL6AJn+Lw/+NRPa8xclgd0rKqUQJMJCDZKjKz2lmIs3bxfELOizxJ3FJQ5R95FAxeAZ6rb/j40YqVVTw2IMBDnEE0J5ZmpUYNUtPti/Adf6GD9Fb2y8sLo0XDJzkI8OxYhfgjSy5KYmRj8O5MXcP2MAE8LQauNO3MaFnL9VMVOTZePJrPozQUgM021uyahf960+QNI06Uqlmg+PwWkSdllQlxHHplOgW7zClFhtSUpnJxcsUBzgg4kVg80gXUwAQkaDi7A9Wh2bs+TvMlmHzBwg+2SaAfWDgjeJIeOaipDkF1uSGzC+EHAiiKYMLd4Aahoi8SuelJUucoyJyLAq00WdUFQIh/izVhM4Y="\n'
s += '\n'
s += '#\n'
s += '# Configurations\n'
s += '#\n'
s += 'jobs:\n'
s += ' include:\n'
s += '\n'
s += ' ###\n'
s += ' # Stage: Build Carl\n'
s += ' ###\n'
for config in configs:
(os, os_version, compiler, build_type, task) = config
os_type = 'osx' if os == 'osx' else 'linux'
if 'Travis' in build_type:
s += ' # {}-{} - {}\n'.format(os, os_version, build_type)
build_config = ''
build_config += ' - stage: Build Carl\n'
build_config += ' os: {}\n'.format(os_type)
build_config += ' compiler: {}\n'.format(compiler)
build_config += ' env: {}'.format(get_env_string(os, os_version, compiler, build_type, task))
build_config += ' before_script:\n'
build_config += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n'
build_config += ' script:\n'
build_config += ' - travis/build_carl.sh\n'
build_config += ' before_cache:\n'
build_config += ' - docker cp carl:/opt/carl/. .\n'
build_config += ' deploy:\n'
build_config += ' - provider: script\n'
build_config += ' skip_cleanup: true\n'
build_config += ' script: bash travis/deploy_docker.sh carl\n'
s += buildConfig
for stage in build_stages:
s += '\n'
s += ' ###\n'
s += ' # Stage: {}\n'.format(stage[0])
s += ' ###\n'
for config in configs:
(os, os_version, compiler, build_type, task) = config
os_type = 'osx' if os == 'osx' else 'linux'
s += ' # {}-{} - {}\n'.format(os, os_version, build_type)
build_config = ''
build_config += ' - stage: {}\n'.format(stage[0])
build_config += ' os: {}\n'.format(os_type)
if os_type == 'osx':
build_config += ' osx_image: {}\n'.format(os_version)
build_config += ' compiler: {}\n'.format(compiler)
build_config += ' env: {}'.format(get_env_string(os, os_version, compiler, build_type, task))
build_config += ' install:\n'
if stage[1] == 'Build1':
build_config += ' - rm -rf build\n'
build_config += ' - travis/skip_test.sh\n'
if os_type == 'osx':
build_config += ' - travis/install_osx.sh\n'
build_config += ' before_script:\n'
build_config += ' - python -c "import fcntl; fcntl.fcntl(1, fcntl.F_SETFL, 0)" # Workaround for nonblocking mode\n'
build_config += ' script:\n'
build_config += ' - travis/build.sh {}\n'.format(stage[1])
if os_type == 'linux':
build_config += ' before_cache:\n'
build_config += ' - docker cp storm:/opt/storm/. .\n'
build_config += ' after_failure:\n'
build_config += " - find build -iname '*err*.log' -type f -print -exec cat {} \\;\n"
if stage[1] == 'Tasks':
if 'Docker' in task or 'Doxygen' in task:
build_config += ' deploy:\n'
if 'Docker' in task:
build_config += ' - provider: script\n'
build_config += ' skip_cleanup: true\n'
build_config += ' script: bash travis/deploy_docker.sh storm\n'
if 'Doxygen' in task:
build_config += ' - provider: pages\n'
build_config += ' skip_cleanup: true\n'
build_config += ' github_token: $GITHUB_TOKEN\n'
build_config += ' local_dir: build/doc/html/\n'
build_config += ' repo: moves-rwth/storm-doc\n'
build_config += ' target_branch: master\n'
build_config += ' on:\n'
build_config += ' branch: master\n'
s += buildConfig
print(s)
|
#########################
# #
# Developer: Luis Regus #
# Date: 11/24/15 #
# #
#########################
NORTH = "north"
EAST = "east"
SOUTH = "south"
WEST = "west"
class Robot:
'''
Custom object used to represent a robot
'''
def __init__(self, direction=NORTH, x_coord=0, y_coord=0):
self.coordinates = (x_coord, y_coord)
self.bearing = direction
def turn_right(self):
directions = {
NORTH: EAST,
EAST: SOUTH,
SOUTH: WEST,
WEST: NORTH}
self.bearing = directions.get(self.bearing, NORTH)
def turn_left(self):
directions = {
NORTH: WEST,
EAST: NORTH,
SOUTH: EAST,
WEST: SOUTH}
self.bearing = directions.get(self.bearing, NORTH)
def advance(self):
coords = {
NORTH: (self.coordinates[0], self.coordinates[1] + 1),
EAST: (self.coordinates[0] + 1, self.coordinates[1]),
SOUTH: (self.coordinates[0], self.coordinates[1] - 1),
WEST: (self.coordinates[0] - 1, self.coordinates[1])}
self.coordinates = coords.get(self.bearing, self.coordinates)
def simulate(self, movement):
for m in movement:
if m == 'R':
self.turn_right()
elif m == 'L':
self.turn_left()
elif m == 'A':
self.advance()
|
north = 'north'
east = 'east'
south = 'south'
west = 'west'
class Robot:
"""
Custom object used to represent a robot
"""
def __init__(self, direction=NORTH, x_coord=0, y_coord=0):
self.coordinates = (x_coord, y_coord)
self.bearing = direction
def turn_right(self):
directions = {NORTH: EAST, EAST: SOUTH, SOUTH: WEST, WEST: NORTH}
self.bearing = directions.get(self.bearing, NORTH)
def turn_left(self):
directions = {NORTH: WEST, EAST: NORTH, SOUTH: EAST, WEST: SOUTH}
self.bearing = directions.get(self.bearing, NORTH)
def advance(self):
coords = {NORTH: (self.coordinates[0], self.coordinates[1] + 1), EAST: (self.coordinates[0] + 1, self.coordinates[1]), SOUTH: (self.coordinates[0], self.coordinates[1] - 1), WEST: (self.coordinates[0] - 1, self.coordinates[1])}
self.coordinates = coords.get(self.bearing, self.coordinates)
def simulate(self, movement):
for m in movement:
if m == 'R':
self.turn_right()
elif m == 'L':
self.turn_left()
elif m == 'A':
self.advance()
|
class ToolBoxBaseException(Exception):
status_code = 500
error_name = 'base_exception'
def __init__(self, message):
self.message = message
def to_dict(self):
return dict(error_name=self.error_name, message=self.message)
class UnknownError(ToolBoxBaseException):
status_code = 500
error_name = 'unknown_error'
def __init__(self, e):
self.message = '{}'.format(e)
class BadRequest(ToolBoxBaseException):
status_code = 400
error_name = 'bad_request'
def __init__(self, message=None):
self.message = message
|
class Toolboxbaseexception(Exception):
status_code = 500
error_name = 'base_exception'
def __init__(self, message):
self.message = message
def to_dict(self):
return dict(error_name=self.error_name, message=self.message)
class Unknownerror(ToolBoxBaseException):
status_code = 500
error_name = 'unknown_error'
def __init__(self, e):
self.message = '{}'.format(e)
class Badrequest(ToolBoxBaseException):
status_code = 400
error_name = 'bad_request'
def __init__(self, message=None):
self.message = message
|
'''
lab 8 functions
'''
#3.1
def count_words(input_str):
return len(input_str.split())
#print(count_words('This is a string'))
#3.2
demo_str = 'Hello World!'
print(count_words(demo_str))
#3.3
def find_min(num_list):
min_item = num_list[0]
for num in num_list:
if type(num) is not str:
if min_item >= num:
min_item = num
return(min_item)
#print(find_min([1, 2, 3, 4]))
#3.4
demo_list = [1, 2, 3, 4, 5, 6]
print(find_min(demo_list))
#3.5
mix_list = [1, 2, 3, 4, 'a', 5, 6]
print(find_min(mix_list))
|
"""
lab 8 functions
"""
def count_words(input_str):
return len(input_str.split())
demo_str = 'Hello World!'
print(count_words(demo_str))
def find_min(num_list):
min_item = num_list[0]
for num in num_list:
if type(num) is not str:
if min_item >= num:
min_item = num
return min_item
demo_list = [1, 2, 3, 4, 5, 6]
print(find_min(demo_list))
mix_list = [1, 2, 3, 4, 'a', 5, 6]
print(find_min(mix_list))
|
users = {
'name': 'Elena',
'age': 100,
'town': 'Varna'
}
for key, value in users.items():
print(key, value)
for key in users.keys():
print(key)
for value in users.values():
print(value)
|
users = {'name': 'Elena', 'age': 100, 'town': 'Varna'}
for (key, value) in users.items():
print(key, value)
for key in users.keys():
print(key)
for value in users.values():
print(value)
|
class Solution:
def getSum(self, a: int, b: int) -> int:
# 32 bits integer max and min
MAX = 0x7FFFFFFF
MIN = 0x80000000
mask = 0xFFFFFFFF
while b != 0:
carry = a & b
a, b = (a ^ b) & mask, (carry << 1) & mask
return a if a <= MAX else ~(a ^ mask)
|
class Solution:
def get_sum(self, a: int, b: int) -> int:
max = 2147483647
min = 2147483648
mask = 4294967295
while b != 0:
carry = a & b
(a, b) = ((a ^ b) & mask, carry << 1 & mask)
return a if a <= MAX else ~(a ^ mask)
|
""" Compatibility related items. """
__author__ = "Brian Allen Vanderburg II"
__copyright__ = "Copyright (C) 2019 Brian Allen Vanderburg II"
__license__ = "Apache License 2.0"
|
""" Compatibility related items. """
__author__ = 'Brian Allen Vanderburg II'
__copyright__ = 'Copyright (C) 2019 Brian Allen Vanderburg II'
__license__ = 'Apache License 2.0'
|
CONFIG = {
"main_dir": "./tests/",
"results_dir": "results/",
"manips_dir": "manips/",
"parameters_dir": "parameters/",
"tikz_dir": "tikz/"
}
|
config = {'main_dir': './tests/', 'results_dir': 'results/', 'manips_dir': 'manips/', 'parameters_dir': 'parameters/', 'tikz_dir': 'tikz/'}
|
stack = []
while True:
print("1. Insert Element in the stack")
print("2. Remove element from stack")
print("3. Display elements in stack")
print("4. Exit")
choice = int(input("Enter your Choice: "))
if choice == 1:
if len(stack) == 5:
print("Sorry, stack is already full")
else:
element = int(input("Please enter element: "))
stack.append(element)
print(element, " inserted successfully")
elif choice == 2:
if len(stack) == 0:
print("Sorry, stack is already empty")
else:
element = stack.pop()
print(element, " was removed successfully")
elif choice == 3:
for i in range(len(stack)- 1, -1, -1):
print(stack[i])
elif choice == 4:
print("Thank You. See you later")
break
else:
print("Invalid option")
more = input("Do you want to continue?(y/n): ")
if more == 'Y' or more == 'y':
continue
else:
print("Thank You. See you later")
break
|
stack = []
while True:
print('1. Insert Element in the stack')
print('2. Remove element from stack')
print('3. Display elements in stack')
print('4. Exit')
choice = int(input('Enter your Choice: '))
if choice == 1:
if len(stack) == 5:
print('Sorry, stack is already full')
else:
element = int(input('Please enter element: '))
stack.append(element)
print(element, ' inserted successfully')
elif choice == 2:
if len(stack) == 0:
print('Sorry, stack is already empty')
else:
element = stack.pop()
print(element, ' was removed successfully')
elif choice == 3:
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
elif choice == 4:
print('Thank You. See you later')
break
else:
print('Invalid option')
more = input('Do you want to continue?(y/n): ')
if more == 'Y' or more == 'y':
continue
else:
print('Thank You. See you later')
break
|
# Operations on Sets ?
# Consider the following set:
S = {1,8,2,3}
# Len(s) : Returns 4, the length of the set
S = {1,8,2,3}
print(len(S)) #Length of the Set
# remove(8) : Updates the set S and removes 8 from S
S = {1,8,2,3}
S.remove(8) #Remove of the Set
print(S)
# pop() : Removes an arbitrary element from the set and returns the element removed.
S = {1,8,2,3}
print(S.pop()) # Returs the Removed Elements of the set
# clear() : Empties the set S
S = {1,8,2,3}
print(S.clear()) #the return is clear or None
# union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
S = {1,8,2,3}
print(S.union())
# intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}
S = {1,8,2,3}
print(S.intersection())
|
s = {1, 8, 2, 3}
s = {1, 8, 2, 3}
print(len(S))
s = {1, 8, 2, 3}
S.remove(8)
print(S)
s = {1, 8, 2, 3}
print(S.pop())
s = {1, 8, 2, 3}
print(S.clear())
s = {1, 8, 2, 3}
print(S.union())
s = {1, 8, 2, 3}
print(S.intersection())
|
idade = str(input("idade :"))
if not idade.isnumeric():
print("oi")
else:
print("passou")
|
idade = str(input('idade :'))
if not idade.isnumeric():
print('oi')
else:
print('passou')
|
CHUNK_SIZE = 16
CHUNK_SIZE_PIXELS = 256
RATTLE_DELAY = 10
RATTLE_RANGE = 3
|
chunk_size = 16
chunk_size_pixels = 256
rattle_delay = 10
rattle_range = 3
|
def is_std_ref(string):
"""
It finds whether the string has reference in itself.
"""
return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or 'Def.' in string
def std_ref_form(ref_string):
"""
Deletes unnecessary chars from the string.
Seperates combined references.
returns the refernces in a list.
"""
if ' corr.' in ref_string:
ref_string = ref_string.replace(' corr.','')
while ',' in ref_string:
ref_string = ref_string.replace(', ',']#[')
refs_list = ref_string.split('#')
return refs_list
def proposition_cleaner(lines):
"""
Lines is a list of strings dedicated to each propositon proof.
This function should return its referenced notions in a single list of name strings.
"""
ref_names = []
for line in lines:
for i in range(len(line)):
if line[i] == '[':
end_ref = line[i:].find(']') + i
if is_std_ref(line[i:end_ref + 1]): #check if it has info.
ref_names.extend(std_ref_form(line[i: end_ref + 1])) #put the standard refs. in the list.
while '[]' in ref_names:
ref_names.remove('[]')
return ref_names
|
def is_std_ref(string):
"""
It finds whether the string has reference in itself.
"""
return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or ('Def.' in string)
def std_ref_form(ref_string):
"""
Deletes unnecessary chars from the string.
Seperates combined references.
returns the refernces in a list.
"""
if ' corr.' in ref_string:
ref_string = ref_string.replace(' corr.', '')
while ',' in ref_string:
ref_string = ref_string.replace(', ', ']#[')
refs_list = ref_string.split('#')
return refs_list
def proposition_cleaner(lines):
"""
Lines is a list of strings dedicated to each propositon proof.
This function should return its referenced notions in a single list of name strings.
"""
ref_names = []
for line in lines:
for i in range(len(line)):
if line[i] == '[':
end_ref = line[i:].find(']') + i
if is_std_ref(line[i:end_ref + 1]):
ref_names.extend(std_ref_form(line[i:end_ref + 1]))
while '[]' in ref_names:
ref_names.remove('[]')
return ref_names
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast , slow = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
s1 = head
while s1 and slow:
if s1 == slow:
return slow
s1, slow = s1.next, slow.next
return True
return None
def run():
pass
|
class Solution(object):
def detect_cycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
(fast, slow) = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
s1 = head
while s1 and slow:
if s1 == slow:
return slow
(s1, slow) = (s1.next, slow.next)
return True
return None
def run():
pass
|
def solution(string, markers):
string = string.split('\n')
result = ''
for line in string:
for character in line:
if character not in markers:
result += character
else:
result = result[:-1]
break
result += '\n'
return result[:-1]
#Alternative solution
def solution(string, markers):
lines = string.split('\n')
for index, line in enumerate(lines):
for marker in markers:
if line.find(marker) != -1:
line = line[:line.find(marker)]
lines[index] = line.rstrip(' ')
return '\n'.join(lines)
|
def solution(string, markers):
string = string.split('\n')
result = ''
for line in string:
for character in line:
if character not in markers:
result += character
else:
result = result[:-1]
break
result += '\n'
return result[:-1]
def solution(string, markers):
lines = string.split('\n')
for (index, line) in enumerate(lines):
for marker in markers:
if line.find(marker) != -1:
line = line[:line.find(marker)]
lines[index] = line.rstrip(' ')
return '\n'.join(lines)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
errno.py
Error Code Define
Copyright: All Rights Reserved 2019-2019
History:
1 2019-07-14 Liu Yu ([email protected]) Initial Version
'''
SUCCESS = 'SUCC'
ERROR_SUCCESS = SUCCESS
FAIL = 'FAIL'
ERROR = FAIL
ERROR_INVALID = 'INVALID'
ERROR_UNSUPPORT = 'UNSUPPORT'
|
"""
errno.py
Error Code Define
Copyright: All Rights Reserved 2019-2019
History:
1 2019-07-14 Liu Yu ([email protected]) Initial Version
"""
success = 'SUCC'
error_success = SUCCESS
fail = 'FAIL'
error = FAIL
error_invalid = 'INVALID'
error_unsupport = 'UNSUPPORT'
|
# Write a Python program to add leading zeroes to a string
String = 'hello'
print(String.rjust(9, '0'))
|
string = 'hello'
print(String.rjust(9, '0'))
|
RETENTION_SQL = """
SELECT
datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval,
datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base,
COUNT(DISTINCT event.target) count
FROM (
{returning_event_query}
) event
JOIN (
{target_event_query}
) reference_event
ON (event.target = reference_event.target)
WHERE {trunc_func}(event.event_date) > {trunc_func}(reference_event.event_date)
GROUP BY base_interval, intervals_from_base
ORDER BY base_interval, intervals_from_base
"""
RETENTION_BREAKDOWN_SQL = """
SELECT
target_event.breakdown_values AS breakdown_values,
datediff(
%(period)s,
target_event.event_date,
dateTrunc(%(period)s, toDateTime(returning_event.event_date))
) AS intervals_from_base,
COUNT(DISTINCT returning_event.target) AS count
FROM
({returning_event_query}) AS returning_event
JOIN ({target_event_query}) target_event
ON returning_event.target = target_event.target
WHERE
dateTrunc(%(period)s, returning_event.event_date) >
dateTrunc(%(period)s, target_event.event_date)
GROUP BY
breakdown_values,
intervals_from_base
ORDER BY
breakdown_values,
intervals_from_base
"""
REFERENCE_EVENT_SQL = """
SELECT DISTINCT
{trunc_func}(e.timestamp) as event_date,
pdi.person_id as person_id,
e.uuid as uuid,
e.event as event
from events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id
where toDateTime(e.timestamp) >= toDateTime(%(reference_start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(reference_end_date)s)
AND e.team_id = %(team_id)s {target_query} {filters}
"""
REFERENCE_EVENT_UNIQUE_SQL = """
SELECT DISTINCT
min({trunc_func}(e.timestamp)) as event_date,
pdi.person_id as person_id,
argMin(e.uuid, {trunc_func}(e.timestamp)) as min_uuid,
argMin(e.event, {trunc_func}(e.timestamp)) as min_event
from events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id
WHERE e.team_id = %(team_id)s {target_query} {filters}
GROUP BY person_id HAVING
event_date >= toDateTime(%(reference_start_date)s) AND event_date <= toDateTime(%(reference_end_date)s)
"""
RETENTION_PEOPLE_SQL = """
SELECT DISTINCT person_id
FROM events e join ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id
where toDateTime(e.timestamp) >= toDateTime(%(start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(end_date)s)
AND e.team_id = %(team_id)s AND person_id IN (
SELECT person_id FROM ({reference_event_query}) as persons
) {target_query} {filters}
LIMIT 100 OFFSET %(offset)s
"""
INITIAL_INTERVAL_SQL = """
SELECT datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), event_date) event_date,
count(DISTINCT target) FROM (
{reference_event_sql}
) GROUP BY event_date ORDER BY event_date
"""
INITIAL_BREAKDOWN_INTERVAL_SQL = """
SELECT
target_event.breakdown_values AS breakdown_values,
count(DISTINCT target_event.target)
FROM ({reference_event_sql}) AS target_event
GROUP BY breakdown_values ORDER BY breakdown_values
"""
|
retention_sql = '\nSELECT\n datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval,\n datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base,\n COUNT(DISTINCT event.target) count\nFROM (\n {returning_event_query}\n) event\nJOIN (\n {target_event_query}\n) reference_event\n ON (event.target = reference_event.target)\nWHERE {trunc_func}(event.event_date) > {trunc_func}(reference_event.event_date)\nGROUP BY base_interval, intervals_from_base\nORDER BY base_interval, intervals_from_base\n'
retention_breakdown_sql = '\n SELECT\n target_event.breakdown_values AS breakdown_values,\n datediff(\n %(period)s, \n target_event.event_date, \n dateTrunc(%(period)s, toDateTime(returning_event.event_date))\n ) AS intervals_from_base,\n COUNT(DISTINCT returning_event.target) AS count\n\n FROM\n ({returning_event_query}) AS returning_event\n JOIN ({target_event_query}) target_event\n ON returning_event.target = target_event.target\n\n WHERE \n dateTrunc(%(period)s, returning_event.event_date) >\n dateTrunc(%(period)s, target_event.event_date)\n\n GROUP BY \n breakdown_values, \n intervals_from_base\n\n ORDER BY \n breakdown_values, \n intervals_from_base\n'
reference_event_sql = '\nSELECT DISTINCT\n{trunc_func}(e.timestamp) as event_date,\npdi.person_id as person_id,\ne.uuid as uuid,\ne.event as event\nfrom events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id\nwhere toDateTime(e.timestamp) >= toDateTime(%(reference_start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(reference_end_date)s)\nAND e.team_id = %(team_id)s {target_query} {filters}\n'
reference_event_unique_sql = '\nSELECT DISTINCT\nmin({trunc_func}(e.timestamp)) as event_date,\npdi.person_id as person_id,\nargMin(e.uuid, {trunc_func}(e.timestamp)) as min_uuid,\nargMin(e.event, {trunc_func}(e.timestamp)) as min_event\nfrom events e JOIN ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id\nWHERE e.team_id = %(team_id)s {target_query} {filters}\nGROUP BY person_id HAVING\nevent_date >= toDateTime(%(reference_start_date)s) AND event_date <= toDateTime(%(reference_end_date)s)\n'
retention_people_sql = '\nSELECT DISTINCT person_id\nFROM events e join ({GET_TEAM_PERSON_DISTINCT_IDS}) pdi on e.distinct_id = pdi.distinct_id\nwhere toDateTime(e.timestamp) >= toDateTime(%(start_date)s) AND toDateTime(e.timestamp) <= toDateTime(%(end_date)s)\nAND e.team_id = %(team_id)s AND person_id IN (\n SELECT person_id FROM ({reference_event_query}) as persons\n) {target_query} {filters}\nLIMIT 100 OFFSET %(offset)s\n'
initial_interval_sql = '\nSELECT datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), event_date) event_date,\n count(DISTINCT target) FROM (\n {reference_event_sql}\n) GROUP BY event_date ORDER BY event_date\n'
initial_breakdown_interval_sql = '\n SELECT \n target_event.breakdown_values AS breakdown_values,\n count(DISTINCT target_event.target)\n FROM ({reference_event_sql}) AS target_event\n GROUP BY breakdown_values ORDER BY breakdown_values\n'
|
def dos2unix(file_path):
"""This is copied from Stack Overflow pretty much as is
Opens a file, converts the line endings to unix, and
then overwrites the file.
"""
# replacement strings
WINDOWS_LINE_ENDING = b'\r\n'
UNIX_LINE_ENDING = b'\n'
with open(file_path, 'rb') as open_file:
content = open_file.read()
content = content.replace(WINDOWS_LINE_ENDING, UNIX_LINE_ENDING)
with open(file_path, 'wb') as open_file:
open_file.write(content)
|
def dos2unix(file_path):
"""This is copied from Stack Overflow pretty much as is
Opens a file, converts the line endings to unix, and
then overwrites the file.
"""
windows_line_ending = b'\r\n'
unix_line_ending = b'\n'
with open(file_path, 'rb') as open_file:
content = open_file.read()
content = content.replace(WINDOWS_LINE_ENDING, UNIX_LINE_ENDING)
with open(file_path, 'wb') as open_file:
open_file.write(content)
|
class InputMode:
def __init__(self):
pass
def GetTitle(self):
return ""
def TitleHighlighted(self):
return True
def GetHelpText(self):
return None
def OnMouse(self, event):
pass
def OnKeyDown(self, event):
pass
def OnKeyUp(self, event):
pass
def OnModeChange(self):
return True
def GetTools(self, t_list, p):
pass
def OnRender(self):
pass
def GetProperties(self, p_list):
pass
|
class Inputmode:
def __init__(self):
pass
def get_title(self):
return ''
def title_highlighted(self):
return True
def get_help_text(self):
return None
def on_mouse(self, event):
pass
def on_key_down(self, event):
pass
def on_key_up(self, event):
pass
def on_mode_change(self):
return True
def get_tools(self, t_list, p):
pass
def on_render(self):
pass
def get_properties(self, p_list):
pass
|
# -*- coding: utf-8 -*-
"""Generic errors for immutable data validation."""
class ImmutableDataValidationError(Exception):
def __init__(self, msg: str = None, append_text: str = None):
if append_text is not None:
msg = "%s %s" % (msg, append_text)
super().__init__(msg)
class ImmutableDataValidationValueError(ImmutableDataValidationError, ValueError):
pass
class ImmutableDataValidationTypeError(ImmutableDataValidationError, TypeError):
pass
class WrappedValidationCollectionError(ImmutableDataValidationError):
pass
class MissingTimezoneError(ImmutableDataValidationValueError):
pass
class TimezoneNotUtcError(ImmutableDataValidationValueError):
pass
class MicrosecondsInSqlTimeError(ImmutableDataValidationValueError):
pass
# wrapped errors for validation_collection
class WrapperValidationCollectionError(ImmutableDataValidationError):
pass
class ValidationCollectionEmptyValueError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
class ValidationCollectionMinimumLengthError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
class ValidationCollectionMaximumLengthError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
class ValidationCollectionCannotCoerceError(
ImmutableDataValidationTypeError, WrapperValidationCollectionError
):
pass
class ValidationCollectionNotAnIntegerError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
class ValidationCollectionMinimumValueError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
class ValidationCollectionMaximumValueError(
ImmutableDataValidationValueError, WrapperValidationCollectionError
):
pass
|
"""Generic errors for immutable data validation."""
class Immutabledatavalidationerror(Exception):
def __init__(self, msg: str=None, append_text: str=None):
if append_text is not None:
msg = '%s %s' % (msg, append_text)
super().__init__(msg)
class Immutabledatavalidationvalueerror(ImmutableDataValidationError, ValueError):
pass
class Immutabledatavalidationtypeerror(ImmutableDataValidationError, TypeError):
pass
class Wrappedvalidationcollectionerror(ImmutableDataValidationError):
pass
class Missingtimezoneerror(ImmutableDataValidationValueError):
pass
class Timezonenotutcerror(ImmutableDataValidationValueError):
pass
class Microsecondsinsqltimeerror(ImmutableDataValidationValueError):
pass
class Wrappervalidationcollectionerror(ImmutableDataValidationError):
pass
class Validationcollectionemptyvalueerror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
class Validationcollectionminimumlengtherror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
class Validationcollectionmaximumlengtherror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
class Validationcollectioncannotcoerceerror(ImmutableDataValidationTypeError, WrapperValidationCollectionError):
pass
class Validationcollectionnotanintegererror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
class Validationcollectionminimumvalueerror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
class Validationcollectionmaximumvalueerror(ImmutableDataValidationValueError, WrapperValidationCollectionError):
pass
|
#!/usr/bin/env python3
""" String Objects
"""
def get_str():
"""
Prompt user for a string
"""
valid_input = False
while not valid_input:
try:
sample_str = input('>>> ')
valid_input = True
return sample_str
except Exception as err:
return 'Expected String : {0}'.format(err)
if __name__ == '__main__':
name = {} # Init name
print('Enter Name :', end='')
name['Name'] = list(get_str().strip().upper().split(' '))
print(name)
|
""" String Objects
"""
def get_str():
"""
Prompt user for a string
"""
valid_input = False
while not valid_input:
try:
sample_str = input('>>> ')
valid_input = True
return sample_str
except Exception as err:
return 'Expected String : {0}'.format(err)
if __name__ == '__main__':
name = {}
print('Enter Name :', end='')
name['Name'] = list(get_str().strip().upper().split(' '))
print(name)
|
src = Split('''
hal_test.c
''')
component = aos_component('hal_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
|
src = split('\n hal_test.c\n')
component = aos_component('hal_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
|
class resizable_array:
def __init__(self,arraysize):
self.arraysize = arraysize
self.array = [None for i in range(self.arraysize)]
self.temp =1
def __insert(self,value):
for i in range(len(self.array)):
if self.array[i] == None:
self.array[i] = value
break
#print(self.array)
#return self.array
def insert_at_end(self, value):
if None not in self.array :
self.newsize= self.temp+len(self.array)
self.newarray = [None for i in range(self.newsize)]
for i in range(len(self.array)):
self.newarray[i]=self.array[i]
# temp contains value of i
i_temp=i
self.newarray[i_temp+1]=value
self.array = self.newarray
self.newarray = None
#print(self.array)
#return self.array
else:
self.__insert(value)
def printarray(self):
return self.array
def insert_at_first(self, value):
self.create_new_size = len(self.array)+1
self.create_new_size = ['insert' for i in range(self.create_new_size)]
self.create_new_size[0] = value
n = len(self.array)
for i in range(1,n+1):
self.create_new_size[i] = self.array[i-1]
self.array = self.create_new_size
self.create_new_size = None
#print(self.array)
#return self.array
def delete_at_end(self):
if len(self.array) == 0:
print("Array is empty")
else:
self.newsize = len(self.array)-1
self.newarray = [None for i in range(self.newsize)]
for i in range(len(self.array)-1):
self.newarray[i] = self.array[i]
self.array=self.newarray
#print(self.array)
#return(self.array)
def delete_at_first(self):
if len(self.array) == 0:
print('Array is empty!')
else:
if len(self.array)==1:
self.array =[]
else:
self.create_new_size = len(self.array) - 1
self.newarray = ['insert' for i in range(self.create_new_size)]
n = len(self.newarray)
for i in range(0,n):
self.newarray[i] = self.array[i+1]
self.array = self.newarray
self.newarray = None
#print(self.array)
#return self.array
def insert_at_middle(self, insertafter, insertedvalue):
self.create_new_size = len(self.array) + 1
self.newarray = [None for i in range(self.create_new_size)] #3
n = len(self.array)-1 #2
if self.array[n] == insertafter:
self.insert_at_end(insertedvalue)
elif insertafter in self.array:
for i in range(0, n):
if self.array[i] == insertafter:
self.newarray[i] = self.array[i]
self.newarray[i + 1] = insertedvalue
i = i + 2
break
else:
self.newarray[i] = self.array[i]
for j in range(i , len(self.newarray)):
self.newarray[j] = self.array[j - 1]
self.array = self.newarray
self.newarray = None
#print(self.array)
#return self.array
else:
print("value does not exists in Array after which you want to insert new value!")
def shrink(self,value):
self.create_new_size = len(self.array)-1
self.newarray = [None for i in range(self.create_new_size)]
flag=False
if len(self.array)==0:
print("Array is empty!")
else:
for i in range(len(self.array)):
try:
if self.array[i]!=value and flag == False:
self.newarray[i]=self.array[i]
elif flag == True or self.array[i]==value:
self.newarray[i]=self.array[i+1]
flag = True
else:
flag=True
except:
pass
self.array=self.newarray
self.newarray=None
#print(self.array)
#return self.array
def maximum_value(self):
max=self.array[0]
for i in range(len(self.array)):
for j in range(len(self.array)):
if max<self.array[j]:
max = self.array[j]
print("maximum value in array is: {}".format( max))
return max
def minimum_value(self):
min=self.array[0]
for i in range(len(self.array)):
for j in range(len(self.array)):
if min>self.array[j]:
min = self.array[j]
print("minimum value in array is: {}".format(min))
return min
ob1= resizable_array(1)
print("\n---------Initial Array---------")
print(ob1.printarray())
print("\n---------Insert at End---------")
ob1.insert_at_end(5)
ob1.insert_at_end(6)
ob1.insert_at_end(7)
ob1.insert_at_end(7.5)
print(ob1.printarray())
print('\n---------Insert at First---------')
ob1.insert_at_first(4)
ob1.insert_at_first(3)
ob1.insert_at_first(2)
ob1.insert_at_first(1)
ob1.insert_at_first(0.5)
print(ob1.printarray())
print('\n---------Delete at First---------')
ob1.delete_at_first()
print(ob1.printarray())
print("\n---------Delete at End---------")
ob1.delete_at_end()
print(ob1.printarray())
print("\n---------Insert at Middle--------- ")
ob1.insert_at_middle(5, 5.5)
ob1.insert_at_middle(6, 6.5)
ob1.insert_at_middle(7, 7.5)
print(ob1.printarray())
ob1.insert_at_middle(8, 88)
print("\n---------Shrink--------- ")
ob1.shrink(5.5)
ob1.shrink(6.5)
ob1.shrink(7.5)
print(ob1.printarray())
print("\n---------Maximum Value--------- ")
ob1.maximum_value()
print("\n---------Minimum Value--------- ")
ob1.minimum_value()
|
class Resizable_Array:
def __init__(self, arraysize):
self.arraysize = arraysize
self.array = [None for i in range(self.arraysize)]
self.temp = 1
def __insert(self, value):
for i in range(len(self.array)):
if self.array[i] == None:
self.array[i] = value
break
def insert_at_end(self, value):
if None not in self.array:
self.newsize = self.temp + len(self.array)
self.newarray = [None for i in range(self.newsize)]
for i in range(len(self.array)):
self.newarray[i] = self.array[i]
i_temp = i
self.newarray[i_temp + 1] = value
self.array = self.newarray
self.newarray = None
else:
self.__insert(value)
def printarray(self):
return self.array
def insert_at_first(self, value):
self.create_new_size = len(self.array) + 1
self.create_new_size = ['insert' for i in range(self.create_new_size)]
self.create_new_size[0] = value
n = len(self.array)
for i in range(1, n + 1):
self.create_new_size[i] = self.array[i - 1]
self.array = self.create_new_size
self.create_new_size = None
def delete_at_end(self):
if len(self.array) == 0:
print('Array is empty')
else:
self.newsize = len(self.array) - 1
self.newarray = [None for i in range(self.newsize)]
for i in range(len(self.array) - 1):
self.newarray[i] = self.array[i]
self.array = self.newarray
def delete_at_first(self):
if len(self.array) == 0:
print('Array is empty!')
elif len(self.array) == 1:
self.array = []
else:
self.create_new_size = len(self.array) - 1
self.newarray = ['insert' for i in range(self.create_new_size)]
n = len(self.newarray)
for i in range(0, n):
self.newarray[i] = self.array[i + 1]
self.array = self.newarray
self.newarray = None
def insert_at_middle(self, insertafter, insertedvalue):
self.create_new_size = len(self.array) + 1
self.newarray = [None for i in range(self.create_new_size)]
n = len(self.array) - 1
if self.array[n] == insertafter:
self.insert_at_end(insertedvalue)
elif insertafter in self.array:
for i in range(0, n):
if self.array[i] == insertafter:
self.newarray[i] = self.array[i]
self.newarray[i + 1] = insertedvalue
i = i + 2
break
else:
self.newarray[i] = self.array[i]
for j in range(i, len(self.newarray)):
self.newarray[j] = self.array[j - 1]
self.array = self.newarray
self.newarray = None
else:
print('value does not exists in Array after which you want to insert new value!')
def shrink(self, value):
self.create_new_size = len(self.array) - 1
self.newarray = [None for i in range(self.create_new_size)]
flag = False
if len(self.array) == 0:
print('Array is empty!')
else:
for i in range(len(self.array)):
try:
if self.array[i] != value and flag == False:
self.newarray[i] = self.array[i]
elif flag == True or self.array[i] == value:
self.newarray[i] = self.array[i + 1]
flag = True
else:
flag = True
except:
pass
self.array = self.newarray
self.newarray = None
def maximum_value(self):
max = self.array[0]
for i in range(len(self.array)):
for j in range(len(self.array)):
if max < self.array[j]:
max = self.array[j]
print('maximum value in array is: {}'.format(max))
return max
def minimum_value(self):
min = self.array[0]
for i in range(len(self.array)):
for j in range(len(self.array)):
if min > self.array[j]:
min = self.array[j]
print('minimum value in array is: {}'.format(min))
return min
ob1 = resizable_array(1)
print('\n---------Initial Array---------')
print(ob1.printarray())
print('\n---------Insert at End---------')
ob1.insert_at_end(5)
ob1.insert_at_end(6)
ob1.insert_at_end(7)
ob1.insert_at_end(7.5)
print(ob1.printarray())
print('\n---------Insert at First---------')
ob1.insert_at_first(4)
ob1.insert_at_first(3)
ob1.insert_at_first(2)
ob1.insert_at_first(1)
ob1.insert_at_first(0.5)
print(ob1.printarray())
print('\n---------Delete at First---------')
ob1.delete_at_first()
print(ob1.printarray())
print('\n---------Delete at End---------')
ob1.delete_at_end()
print(ob1.printarray())
print('\n---------Insert at Middle--------- ')
ob1.insert_at_middle(5, 5.5)
ob1.insert_at_middle(6, 6.5)
ob1.insert_at_middle(7, 7.5)
print(ob1.printarray())
ob1.insert_at_middle(8, 88)
print('\n---------Shrink--------- ')
ob1.shrink(5.5)
ob1.shrink(6.5)
ob1.shrink(7.5)
print(ob1.printarray())
print('\n---------Maximum Value--------- ')
ob1.maximum_value()
print('\n---------Minimum Value--------- ')
ob1.minimum_value()
|
qt=int(input())
for i in range(qt):
jogadores=input().split()
nome1=str(jogadores[0])
escolha1=str(jogadores[1])
nome2 = str(jogadores[2])
escolha2 = str(jogadores[3])
numeros=input().split()
numerosJ1=int(numeros[0])
numerosJ2=int(numeros[1])
if escolha1=="PAR" and escolha2=="IMPAR":
if (numerosJ1+numerosJ2)%2==0:
print(nome1)
else:
print(nome2)
if escolha1 == "IMPAR" and escolha2 == "PAR":
if (numerosJ1 + numerosJ2) % 2 == 0:
print(nome2)
else:
print(nome1)
|
qt = int(input())
for i in range(qt):
jogadores = input().split()
nome1 = str(jogadores[0])
escolha1 = str(jogadores[1])
nome2 = str(jogadores[2])
escolha2 = str(jogadores[3])
numeros = input().split()
numeros_j1 = int(numeros[0])
numeros_j2 = int(numeros[1])
if escolha1 == 'PAR' and escolha2 == 'IMPAR':
if (numerosJ1 + numerosJ2) % 2 == 0:
print(nome1)
else:
print(nome2)
if escolha1 == 'IMPAR' and escolha2 == 'PAR':
if (numerosJ1 + numerosJ2) % 2 == 0:
print(nome2)
else:
print(nome1)
|
"""
Aliyun API
==========
The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_.
Each service's API is very similar: There are regions, actions, and each action has many parameters.
It is an OAuth2 API, so you need to have an ID and a secret. You can get these from the Aliyun management console.
Authentication
==============
You will need security credentials for your Aliyun account. You can view and
create them in the `Aliyun management console <http://console.aliyun.com>`_. This
library will look for credentials in the following places:
1. Environment variables `ALI_ACCESS_KEY_ID` and `ALI_SECRET_ACCESS_KEY`
2. An ini-style configuration file at `~/.aliyun.cfg` with contents like:
::
[default]
access_key_id=xxxxxxxxxxxxx
secret_access_key=xxxxxxxxxxxxxxxxxxxxxxx
..
3. A system-wide version of that file at /etc/aliyun.cfg with similar contents.
We recommend using environment variables whenever possible.
Main Interfaces
===============
The main components of python-aliyun are ECS and SLB. Other Aliyun products will
be added as API support develops. Within each Aliyun product, we tried to
implement every API Action variation available. We used a boto-style design
where most API interaction is done with a connection object which marshalls
Python objects and API representations.
*ECS*:
You can create a new ECS connection and interact with ECS like this::
import aliyun.ecs.connection
conn = aliyun.ecs.connection.EcsConnection('cn-hangzhou')
print conn.get_all_instance_ids()
See more at :mod:`aliyun.ecs`
*SLB*:
Similarly for SLB, get the connection object like this::
import aliyun.slb.connection
conn = aliyun.slb.connection.SlbConnection('cn-hangzhou')
print conn.get_all_load_balancer_ids()
See more at :mod:`aliyun.slb`
*DNS*:
Similarly for ECS, get the connection object like this::
import aliyun.dns.connection
conn = aliyun.dns.connection.DnsConnection('cn-hangzhou')
print conn.get_all_records(domainname='quixey.be')
ali command
===========
The ali commandline tool is mostly used for debugging the Aliyun API interactions.
It accepts arbitrary Key=Value pairs and passes them on to the API after wrapping them.
::
ali --region cn-hangzhou ecs Action=DescribeRegions
ali --region cn-hangzhou slb Action=DescribeLoadBalancers
"""
__version__ = "1.1.0"
|
"""
Aliyun API
==========
The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_.
Each service's API is very similar: There are regions, actions, and each action has many parameters.
It is an OAuth2 API, so you need to have an ID and a secret. You can get these from the Aliyun management console.
Authentication
==============
You will need security credentials for your Aliyun account. You can view and
create them in the `Aliyun management console <http://console.aliyun.com>`_. This
library will look for credentials in the following places:
1. Environment variables `ALI_ACCESS_KEY_ID` and `ALI_SECRET_ACCESS_KEY`
2. An ini-style configuration file at `~/.aliyun.cfg` with contents like:
::
[default]
access_key_id=xxxxxxxxxxxxx
secret_access_key=xxxxxxxxxxxxxxxxxxxxxxx
..
3. A system-wide version of that file at /etc/aliyun.cfg with similar contents.
We recommend using environment variables whenever possible.
Main Interfaces
===============
The main components of python-aliyun are ECS and SLB. Other Aliyun products will
be added as API support develops. Within each Aliyun product, we tried to
implement every API Action variation available. We used a boto-style design
where most API interaction is done with a connection object which marshalls
Python objects and API representations.
*ECS*:
You can create a new ECS connection and interact with ECS like this::
import aliyun.ecs.connection
conn = aliyun.ecs.connection.EcsConnection('cn-hangzhou')
print conn.get_all_instance_ids()
See more at :mod:`aliyun.ecs`
*SLB*:
Similarly for SLB, get the connection object like this::
import aliyun.slb.connection
conn = aliyun.slb.connection.SlbConnection('cn-hangzhou')
print conn.get_all_load_balancer_ids()
See more at :mod:`aliyun.slb`
*DNS*:
Similarly for ECS, get the connection object like this::
import aliyun.dns.connection
conn = aliyun.dns.connection.DnsConnection('cn-hangzhou')
print conn.get_all_records(domainname='quixey.be')
ali command
===========
The ali commandline tool is mostly used for debugging the Aliyun API interactions.
It accepts arbitrary Key=Value pairs and passes them on to the API after wrapping them.
::
ali --region cn-hangzhou ecs Action=DescribeRegions
ali --region cn-hangzhou slb Action=DescribeLoadBalancers
"""
__version__ = '1.1.0'
|
class VertexPaint:
use_group_restrict = None
use_normal = None
use_spray = None
|
class Vertexpaint:
use_group_restrict = None
use_normal = None
use_spray = None
|
@app.post('/login')
def login(response: Response):
...
token = manager.create_access_token(
data=dict(sub=user.email)
)
manager.set_cookie(response, token)
return response
|
@app.post('/login')
def login(response: Response):
...
token = manager.create_access_token(data=dict(sub=user.email))
manager.set_cookie(response, token)
return response
|
print("Pass statement in Python");
for i in range (1,11,1):
if(i==3):
i = i + 1;
pass;
else:
print(i);
i = i + 1;
|
print('Pass statement in Python')
for i in range(1, 11, 1):
if i == 3:
i = i + 1
pass
else:
print(i)
i = i + 1
|
# Runtime error
N = int(input())
X = list(map(int, input().split())) # Memory problem
tot = sum(X)
visited = [False for k in range(N)]
currentStar = 0
while True:
if currentStar < 0 or currentStar > N-1:
break
else:
visited[currentStar] = True
if X[currentStar] >= 1:
if X[currentStar] % 2 == 0:
X[currentStar] -= 1
currentStar -= 1
else:
X[currentStar] -= 1
currentStar += 1
tot -= 1
else:
if X[currentStar] % 2 == 0:
currentStar -= 1
else:
currentStar += 1
print("{0} {1}".format(sum(visited), tot))
|
n = int(input())
x = list(map(int, input().split()))
tot = sum(X)
visited = [False for k in range(N)]
current_star = 0
while True:
if currentStar < 0 or currentStar > N - 1:
break
else:
visited[currentStar] = True
if X[currentStar] >= 1:
if X[currentStar] % 2 == 0:
X[currentStar] -= 1
current_star -= 1
else:
X[currentStar] -= 1
current_star += 1
tot -= 1
elif X[currentStar] % 2 == 0:
current_star -= 1
else:
current_star += 1
print('{0} {1}'.format(sum(visited), tot))
|
n = int(input())
for i in range(n):
dieta = list(input())
cafe = list(input())
almoco = list(input())
todos = cafe + almoco
cheat = False
for comido in todos:
if comido in dieta:
dieta.remove(comido)
else:
cheat = True
if not cheat:
print("".join(sorted(dieta)))
else:
print("CHEATER")
|
n = int(input())
for i in range(n):
dieta = list(input())
cafe = list(input())
almoco = list(input())
todos = cafe + almoco
cheat = False
for comido in todos:
if comido in dieta:
dieta.remove(comido)
else:
cheat = True
if not cheat:
print(''.join(sorted(dieta)))
else:
print('CHEATER')
|
first_name = input("Enter you name")
last_name = input("Enter you surname")
past_year = input("MS program start year?")
a = 2 + int(past_year)
print(f"{first_name} {last_name} {past_year} you are graduate in {a}")
|
first_name = input('Enter you name')
last_name = input('Enter you surname')
past_year = input('MS program start year?')
a = 2 + int(past_year)
print(f'{first_name} {last_name} {past_year} you are graduate in {a}')
|
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
#print(class_1)
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
#print(class_2)
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {
"Math":65,
"English":70,
"History":80,
"French":70,
"Science":60
}
print(courses['Math'])
print(courses['English'])
print(courses['History'])
print(courses['French'])
print(courses['Science'])
total = courses['Math'] + courses['English'] + courses['History'] + courses['French'] + courses['Science']
print(total)
percentage = (total / 500) * 100
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = {
"Geoffrey Hinton":78,
"Andrew Ng":95,
"Sebastian Raschka":65,
"Yoshua Benjio":50,
"Hilary Mason":70,
"Corinna Cortes":66,
"Peter Warden":75
}
topper = max(mathematics,key = mathematics.get)
print(topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
topper = "andrew ng"
topper = topper.split()
first_name = topper[0]
last_name = topper[1]
full_name = last_name + " " + first_name
certificate_name = full_name.upper()
print(certificate_name)
# Code ends here
|
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60}
print(courses['Math'])
print(courses['English'])
print(courses['History'])
print(courses['French'])
print(courses['Science'])
total = courses['Math'] + courses['English'] + courses['History'] + courses['French'] + courses['Science']
print(total)
percentage = total / 500 * 100
print(percentage)
mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 66, 'Peter Warden': 75}
topper = max(mathematics, key=mathematics.get)
print(topper)
topper = 'andrew ng'
topper = 'andrew ng'
topper = topper.split()
first_name = topper[0]
last_name = topper[1]
full_name = last_name + ' ' + first_name
certificate_name = full_name.upper()
print(certificate_name)
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and not popped:
return True
aux = []
idx = 0
for _ in pushed:
aux.append(_)
while aux and aux[-1] == popped[idx]:
aux.pop()
idx += 1
return not aux
|
class Solution:
def validate_stack_sequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and (not popped):
return True
aux = []
idx = 0
for _ in pushed:
aux.append(_)
while aux and aux[-1] == popped[idx]:
aux.pop()
idx += 1
return not aux
|
widget = WidgetDefault()
widget.border = "None"
commonDefaults["GroupBoxWidget"] = widget
def generateGroupBoxWidget(file, screen, box, parentName):
name = box.getName()
file.write(" %s = leGroupBoxWidget_New();" % (name))
generateBaseWidget(file, screen, box)
writeSetStringAssetName(file, name, "String", box.getStringName())
file.write(" %s->fn->addChild(%s, (leWidget*)%s);" % (parentName, parentName, name))
file.writeNewLine()
def generateGroupBoxAction(text, variables, owner, event, action):
name = action.targetName
if action.actionID == "SetString":
val = getActionArgumentValue(action, "String")
writeActionFunc(text, action, "setString", [val])
else:
generateWidgetAction(text, variables, owner, event, action)
|
widget = widget_default()
widget.border = 'None'
commonDefaults['GroupBoxWidget'] = widget
def generate_group_box_widget(file, screen, box, parentName):
name = box.getName()
file.write(' %s = leGroupBoxWidget_New();' % name)
generate_base_widget(file, screen, box)
write_set_string_asset_name(file, name, 'String', box.getStringName())
file.write(' %s->fn->addChild(%s, (leWidget*)%s);' % (parentName, parentName, name))
file.writeNewLine()
def generate_group_box_action(text, variables, owner, event, action):
name = action.targetName
if action.actionID == 'SetString':
val = get_action_argument_value(action, 'String')
write_action_func(text, action, 'setString', [val])
else:
generate_widget_action(text, variables, owner, event, action)
|
# Problem Statement Link: https://www.hackerrank.com/challenges/the-minion-game/problem
def minion_game(w):
s = k = 0
v = ['A', 'E', 'I', 'O', 'U']
for x in range( len(w) ):
if w[x] in v:
k += (len(w)-x)
else:
s += (len(w)-x)
if s == k: print("Draw")
else:
if s > k: print("Stuart", s)
else: print("Kevin", k)
if __name__ == '__main__':
s = input()
minion_game(s)
|
def minion_game(w):
s = k = 0
v = ['A', 'E', 'I', 'O', 'U']
for x in range(len(w)):
if w[x] in v:
k += len(w) - x
else:
s += len(w) - x
if s == k:
print('Draw')
elif s > k:
print('Stuart', s)
else:
print('Kevin', k)
if __name__ == '__main__':
s = input()
minion_game(s)
|
a = 10
print(a)
|
a = 10
print(a)
|
def stations_level_over_threshold(stations, tol): #2B part 2
stationList = []
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
if station.relative_water_level() > tol:
stationList.append((station, station.relative_water_level()))
sortedList = sorted(stationList, key=lambda x: x[1], reverse=True)
return sortedList
def stations_highest_rel_level(stations, N):
stationList = list()
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
stationList.append((station, station.relative_water_level()))
sortedList = sorted(stationList, key=lambda x: x[1], reverse=True)
Nslice = sortedList[0:N]
return Nslice
|
def stations_level_over_threshold(stations, tol):
station_list = []
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
if station.relative_water_level() > tol:
stationList.append((station, station.relative_water_level()))
sorted_list = sorted(stationList, key=lambda x: x[1], reverse=True)
return sortedList
def stations_highest_rel_level(stations, N):
station_list = list()
for station in stations:
if station.typical_range_consistent() and station.latest_level != None:
stationList.append((station, station.relative_water_level()))
sorted_list = sorted(stationList, key=lambda x: x[1], reverse=True)
nslice = sortedList[0:N]
return Nslice
|
lanches = ['X-Bacon','X-Tudo','X-Calabresa', 'CalaFrango','X-Salada','CalaFrango','X-Bacon','CalaFrango']
lanches_finais = []
print('Estamos sem CalaFrango')
while 'CalaFrango' in lanches:
lanches.remove('CalaFrango')
while lanches:
preparo = lanches.pop()
print('Preparei seu lanche de {}'.format(preparo))
lanches_finais.append(preparo)
print('\nOs lanches finais hoje foram:')
for lanche in lanches_finais:
print('\t{}'.format(lanche))
|
lanches = ['X-Bacon', 'X-Tudo', 'X-Calabresa', 'CalaFrango', 'X-Salada', 'CalaFrango', 'X-Bacon', 'CalaFrango']
lanches_finais = []
print('Estamos sem CalaFrango')
while 'CalaFrango' in lanches:
lanches.remove('CalaFrango')
while lanches:
preparo = lanches.pop()
print('Preparei seu lanche de {}'.format(preparo))
lanches_finais.append(preparo)
print('\nOs lanches finais hoje foram:')
for lanche in lanches_finais:
print('\t{}'.format(lanche))
|
# -*- coding: utf-8 -*-
# list of system groups ordered descending by rights in application
groups = ['wheel', 'sudo', 'users']
|
groups = ['wheel', 'sudo', 'users']
|
def escreva(frase):
a = len(frase)+2
print('~'*(a+2))
print(f' {frase}')
print('~' * (a + 2))
escreva('Gustavo Guanabara')
escreva('Curso de Python no YouTube')
escreva('CeV')
|
def escreva(frase):
a = len(frase) + 2
print('~' * (a + 2))
print(f' {frase}')
print('~' * (a + 2))
escreva('Gustavo Guanabara')
escreva('Curso de Python no YouTube')
escreva('CeV')
|
# Find the set of maximums and minimums in a series,
# with some tolerance for multiple max or minimums
# if some highest or lowest values in a series are
# tolerance_threshold away
def find_maxs_or_mins_in_series(series, kind, tolerance_threshold):
isolated_globals = []
if kind == "max":
global_max_or_min = series.max()
else:
global_max_or_min = series.min()
for idx, val in series.items():
if val == global_max_or_min or abs(global_max_or_min - val ) < tolerance_threshold:
isolated_globals.append(idx)
return isolated_globals
# Find the average distance between High and Low price in a set of candles
def avg_candle_range(candles):
return max((candles.df.High - candles.df.Low).mean(), 0.01)
# Find mean in a list of int or floats
def mean(ls):
total = 0
for n in ls: total+=n
return total/len(ls)
|
def find_maxs_or_mins_in_series(series, kind, tolerance_threshold):
isolated_globals = []
if kind == 'max':
global_max_or_min = series.max()
else:
global_max_or_min = series.min()
for (idx, val) in series.items():
if val == global_max_or_min or abs(global_max_or_min - val) < tolerance_threshold:
isolated_globals.append(idx)
return isolated_globals
def avg_candle_range(candles):
return max((candles.df.High - candles.df.Low).mean(), 0.01)
def mean(ls):
total = 0
for n in ls:
total += n
return total / len(ls)
|
load("//cipd/internal:cipd_client.bzl", "cipd_client_deps")
def cipd_deps():
cipd_client_deps()
|
load('//cipd/internal:cipd_client.bzl', 'cipd_client_deps')
def cipd_deps():
cipd_client_deps()
|
class Holding:
"""A single holding in a fund. Subclasses of Holding include Equity, Bond, and Cash."""
def __init__(self, name):
self.name = name
"""The name of the security."""
self.identifier_cusip = None
"""The CUSIP identifier for the security, if available and applicable."""
self.identifier_isin = None
"""The ISIN identifier for the security, if available and applicable."""
self.identifier_figi = None
"""The FIGI identifier for the security, if available and applicable."""
self.identifier_sedol = None
"""The SEDOL identifier for the security, if available and applicable."""
self.percent_weighting = None
"""The percentage of the fund's resources that are contributed to this holding."""
self.market_value = None
"""The total market value of this holding. In almost all cases this will be in US Dollars unless
otherwise indicated by the Cash object's currency field."""
|
class Holding:
"""A single holding in a fund. Subclasses of Holding include Equity, Bond, and Cash."""
def __init__(self, name):
self.name = name
'The name of the security.'
self.identifier_cusip = None
'The CUSIP identifier for the security, if available and applicable.'
self.identifier_isin = None
'The ISIN identifier for the security, if available and applicable.'
self.identifier_figi = None
'The FIGI identifier for the security, if available and applicable.'
self.identifier_sedol = None
'The SEDOL identifier for the security, if available and applicable.'
self.percent_weighting = None
"The percentage of the fund's resources that are contributed to this holding."
self.market_value = None
"The total market value of this holding. In almost all cases this will be in US Dollars unless \n otherwise indicated by the Cash object's currency field."
|
'''
Detect Cantor set membership
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
while True:
value = input()
if value == 'END':
break
value = float(value)
lhs, rhs, ternary = 0.0, 1.0, ''
for _ in range(12):
third = (rhs - lhs) / 3
if value <= lhs + third:
ternary += '0'
rhs = lhs + third
elif value >= rhs - third:
ternary += '2'
lhs = rhs - third
else:
ternary += '1'
break
if ternary[-1] == '1':
print('NON-MEMBER')
else:
print('MEMBER')
###############################################################################
if __name__ == '__main__':
main()
|
"""
Detect Cantor set membership
Status: Accepted
"""
def main():
"""Read input and print output"""
while True:
value = input()
if value == 'END':
break
value = float(value)
(lhs, rhs, ternary) = (0.0, 1.0, '')
for _ in range(12):
third = (rhs - lhs) / 3
if value <= lhs + third:
ternary += '0'
rhs = lhs + third
elif value >= rhs - third:
ternary += '2'
lhs = rhs - third
else:
ternary += '1'
break
if ternary[-1] == '1':
print('NON-MEMBER')
else:
print('MEMBER')
if __name__ == '__main__':
main()
|
class State:
def __init__(self):
self.pixel = None
self.keyboard = None
self.keyboard_layout = None
pass
def start(self):
pass
def end(self):
pass
def onTick(self):
pass
def onButtonPress(self):
pass
def onButtonRelease(self):
pass
|
class State:
def __init__(self):
self.pixel = None
self.keyboard = None
self.keyboard_layout = None
pass
def start(self):
pass
def end(self):
pass
def on_tick(self):
pass
def on_button_press(self):
pass
def on_button_release(self):
pass
|
def convert( s: str, numRows: int) -> str:
print('hi')
# Algorithm:
# Output: Linearize the zig zagged string matrix
# input: string and number of rows in which to make the string zag zag
# Algorithm steps:
# d and nd list /diagonal and nondiagonal lists
#remove all prints if pasting in leetcode
if numRows == 1:
return s
step = 1
pos = 1
lines = {}
for c in s:
if pos not in lines:
print(pos, 'im pos', 'and im step',step)
lines[pos] = c
print(lines, 'when pos not in lines')
else:
print(pos, 'im pos', 'and im step',step)
lines[pos] += c
print(lines, 'when pos in lines'),
pos += step
if pos == 1 or pos == numRows:
step *= -1
sol = ""
for i in range(1, numRows + 1):
try:
sol += lines[i]
print('im sol', sol)
except:
return sol
return sol
s1 = "PAYPALISHIRING" #14
numRows1 = 3
# Output: "PAHNAPLSIIGYIR" #7 columns
s2 = "PAYPALISHIRING" #14
numRows2 = 4
print(convert(s2,numRows2))
# Output: "PINALSIGYAHRPI" #7 columns
|
def convert(s: str, numRows: int) -> str:
print('hi')
if numRows == 1:
return s
step = 1
pos = 1
lines = {}
for c in s:
if pos not in lines:
print(pos, 'im pos', 'and im step', step)
lines[pos] = c
print(lines, 'when pos not in lines')
else:
print(pos, 'im pos', 'and im step', step)
lines[pos] += c
(print(lines, 'when pos in lines'),)
pos += step
if pos == 1 or pos == numRows:
step *= -1
sol = ''
for i in range(1, numRows + 1):
try:
sol += lines[i]
print('im sol', sol)
except:
return sol
return sol
s1 = 'PAYPALISHIRING'
num_rows1 = 3
s2 = 'PAYPALISHIRING'
num_rows2 = 4
print(convert(s2, numRows2))
|
class Node:
"""create a Node"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
return 'Node Val: {}'.format(self.val)
def __str__(self):
return str(self.val)
|
class Node:
"""create a Node"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
return 'Node Val: {}'.format(self.val)
def __str__(self):
return str(self.val)
|
class Solution:
def reconstructQueue(self, people: list) -> list:
if not people:
return []
def func(x):
return -x[0], x[1]
people.sort(key=func)
new_people = [people[0]]
for i in people[1:]:
new_people.insert(i[1], i)
return new_people
|
class Solution:
def reconstruct_queue(self, people: list) -> list:
if not people:
return []
def func(x):
return (-x[0], x[1])
people.sort(key=func)
new_people = [people[0]]
for i in people[1:]:
new_people.insert(i[1], i)
return new_people
|
# -*- coding: utf-8 -*-
"""
equip.visitors.classes
~~~~~~~~~~~~~~~~~~~~~~
Callback the visit method for each encountered class in the program.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
class ClassVisitor(object):
"""
A class visitor that is triggered for all encountered ``TypeDeclaration``.
Example, listing all types declared in the bytecode::
class TypeDeclVisitor(ClassVisitor):
def __init__(self):
ClassVisitor.__init__(self)
def visit(self, typeDecl):
print "New type: %s (parentDecl=%s)" \\
% (typeDecl.type_name, typeDecl.parent)
"""
def __init__(self):
pass
def visit(self, typeDecl):
pass
|
"""
equip.visitors.classes
~~~~~~~~~~~~~~~~~~~~~~
Callback the visit method for each encountered class in the program.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
class Classvisitor(object):
"""
A class visitor that is triggered for all encountered ``TypeDeclaration``.
Example, listing all types declared in the bytecode::
class TypeDeclVisitor(ClassVisitor):
def __init__(self):
ClassVisitor.__init__(self)
def visit(self, typeDecl):
print "New type: %s (parentDecl=%s)" \\
% (typeDecl.type_name, typeDecl.parent)
"""
def __init__(self):
pass
def visit(self, typeDecl):
pass
|
class Post():
def __init__(self, userIden, content, timestamp, image=None, score='0', replies=None):
self.userIden = userIden
self.content = content
self.timestamp = timestamp
self.image = image
self.score = score
self.replies = [] if not replies else replies
|
class Post:
def __init__(self, userIden, content, timestamp, image=None, score='0', replies=None):
self.userIden = userIden
self.content = content
self.timestamp = timestamp
self.image = image
self.score = score
self.replies = [] if not replies else replies
|
def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return ((alist[index]//(base**digit)) % base)
return key
largest = max(alist)
exp = 0
while base**exp <= largest:
alist = counting_sort(alist, base - 1, key_factory(exp, base))
exp = exp + 1
return alist
def counting_sort(arr, exp1):
n = len(arr)
# The output array elements that will have sorted arr
output = [0] * (n)
# initialize count array as 0
count = [0] * (10)
# Store count of occurrences in count[]
for i in range(0, n):
index = (arr[i]/exp1)
count[ (index)%10 ] += 1
# Change count[i] so that count[i] now contains actual
# position of this digit in output array
for i in range(1,10):
count[i] += count[i-1]
# Build the output array
i = n-1
while i>=0:
index = (arr[i]/exp1)
output[ count[ (index)%10 ] - 1] = arr[i]
count[ (index)%10 ] -= 1
i -= 1
# Copying the output array to arr[],
# so that arr now contains sorted numbers
i = 0
for i in range(0,len(arr)):
arr[i] = output[i]
# def counting_sort(alist, largest, key):
# c = [0]*(largest + 1)
# for i in range(len(alist)):
# c[key(alist, i)] = c[key(alist, i)] + 1
# # Find the last index for each element
# c[0] = c[0] - 1 # to decrement each element for zero-based indexing
# for i in range(1, largest + 1):
# c[i] = c[i] + c[i - 1]
# result = [None]*len(alist)
# for i in range(len(alist) - 1, -1, -1):
# result[c[key(alist, i)]] = alist[i]
# c[key(alist, i)] = c[key(alist, i)] - 1
# return result
|
def radix_sort(alist, base=10):
if alist == []:
return
def key_factory(digit, base):
def key(alist, index):
return alist[index] // base ** digit % base
return key
largest = max(alist)
exp = 0
while base ** exp <= largest:
alist = counting_sort(alist, base - 1, key_factory(exp, base))
exp = exp + 1
return alist
def counting_sort(arr, exp1):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(0, n):
index = arr[i] / exp1
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] / exp1
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
|
N, *A = map(int, open(0).read().split())
result = 0
for i in range(2, 1000):
t = 0
for a in A:
if a % i == 0:
t += 1
result = max(result, t)
print(result)
|
(n, *a) = map(int, open(0).read().split())
result = 0
for i in range(2, 1000):
t = 0
for a in A:
if a % i == 0:
t += 1
result = max(result, t)
print(result)
|
#{
#Driver Code Starts
#Initial Template for Python 3
# } Driver Code Ends
#User function Template for python3
# Function to calculate average
def calc_average(nums):
# Your code here
mini = min(nums)
maxi = max(nums)
n = len(nums)
s = sum(nums)-mini-maxi
s = s//(n-2)
return s
#{
#Driver Code Starts.
# Driver Code
def main():
# Testcase input
testcases = int(input())
# Looping through testcases
while(testcases > 0):
size_arr = int(input())
a = input().split()
arr = list()
for i in range(0, size_arr, 1):
arr.append(int(a[i]))
print (calc_average(arr))
testcases -= 1
if __name__ == '__main__':
main()
#} Driver Code Ends
|
def calc_average(nums):
mini = min(nums)
maxi = max(nums)
n = len(nums)
s = sum(nums) - mini - maxi
s = s // (n - 2)
return s
def main():
testcases = int(input())
while testcases > 0:
size_arr = int(input())
a = input().split()
arr = list()
for i in range(0, size_arr, 1):
arr.append(int(a[i]))
print(calc_average(arr))
testcases -= 1
if __name__ == '__main__':
main()
|
# in file: models/db_custom.py
db.define_table('company', Field('name', notnull = True, unique = True), format = '%(name)s')
db.define_table(
'contact',
Field('name', notnull = True),
Field('company', 'reference company'),
Field('picture', 'upload'),
Field('email', requires = IS_EMAIL()),
Field('phone_number', requires = IS_MATCH('[\d\-\(\) ]+')),
Field('address'),
format = '%(name)s'
)
db.define_table(
'logs',
Field('body', 'text', notnull = True),
Field('posted_on', 'datetime'),
Field('contact', 'reference contact')
)
|
db.define_table('company', field('name', notnull=True, unique=True), format='%(name)s')
db.define_table('contact', field('name', notnull=True), field('company', 'reference company'), field('picture', 'upload'), field('email', requires=is_email()), field('phone_number', requires=is_match('[\\d\\-\\(\\) ]+')), field('address'), format='%(name)s')
db.define_table('logs', field('body', 'text', notnull=True), field('posted_on', 'datetime'), field('contact', 'reference contact'))
|
def main():
i = 0
while True:
print(i)
i += 1
if i > 5:
break
j = 10
while j < 100:
print(j)
j += 10
while 1:
print(j + i)
break
while 0.1:
print(j + i)
break
while 0:
print("This never executes")
while 0.0:
print("This never executes")
while None:
print("This never executes")
while False:
print("This never executes")
while "":
print("This never executes")
while "hi":
print("This executes")
break
if __name__ == '__main__':
main()
|
def main():
i = 0
while True:
print(i)
i += 1
if i > 5:
break
j = 10
while j < 100:
print(j)
j += 10
while 1:
print(j + i)
break
while 0.1:
print(j + i)
break
while 0:
print('This never executes')
while 0.0:
print('This never executes')
while None:
print('This never executes')
while False:
print('This never executes')
while '':
print('This never executes')
while 'hi':
print('This executes')
break
if __name__ == '__main__':
main()
|
example = """
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#"""
example_list = [list(x) for x in example.split()]
with open('test.in', mode='r') as f:
puzzle_input = [list(x.strip()) for x in f.readlines()]
def tree_hitting_function(right, down, tree_input):
# Get the height and width based on the list lengths
height = len(tree_input)
width = len(tree_input[0])
# Set initial values
trees = 0
step = 0
# Walk down the "hill" using range.
for y in range(down, height, down):
# We need to track steps down so we know how far to the right.
step += 1
# Modulo trick to cycle through the width values and loop back around to the front
x_axis = (step * right) % width
# Check if a tree and increment
if tree_input[y][x_axis] == "#":
trees += 1
return trees
def slope_multiplier(slopes, tree_input):
total = 1
# Loop through the slopes and calc the trees hit. Multiply them together.
for slope in slopes:
right = slope[0]
down = slope[1]
total *= tree_hitting_function(right, down, tree_input)
return total
if __name__ == '__main__':
print(tree_hitting_function(3, 1, puzzle_input))
slope_list = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2)
]
print(slope_multiplier(slope_list, puzzle_input))
|
example = '\n..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#'
example_list = [list(x) for x in example.split()]
with open('test.in', mode='r') as f:
puzzle_input = [list(x.strip()) for x in f.readlines()]
def tree_hitting_function(right, down, tree_input):
height = len(tree_input)
width = len(tree_input[0])
trees = 0
step = 0
for y in range(down, height, down):
step += 1
x_axis = step * right % width
if tree_input[y][x_axis] == '#':
trees += 1
return trees
def slope_multiplier(slopes, tree_input):
total = 1
for slope in slopes:
right = slope[0]
down = slope[1]
total *= tree_hitting_function(right, down, tree_input)
return total
if __name__ == '__main__':
print(tree_hitting_function(3, 1, puzzle_input))
slope_list = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
print(slope_multiplier(slope_list, puzzle_input))
|
'''
Synchronization phenomena in networked dynamics
'''
def kuramoto(G, k: float, w: Callable):
'''
Kuramoto lattice
k: coupling gain
w: intrinsic frequency
'''
phase = gds.node_gds(G)
w_vec = np.array([w(x) for x in phase.X])
phase.set_evolution(dydt=lambda t, y: w_vec + k * phase.div(np.sin(phase.grad())))
amplitude = phase.project(GraphDomain.nodes, lambda t, y: np.sin(y))
return phase, amplitude
|
"""
Synchronization phenomena in networked dynamics
"""
def kuramoto(G, k: float, w: Callable):
"""
Kuramoto lattice
k: coupling gain
w: intrinsic frequency
"""
phase = gds.node_gds(G)
w_vec = np.array([w(x) for x in phase.X])
phase.set_evolution(dydt=lambda t, y: w_vec + k * phase.div(np.sin(phase.grad())))
amplitude = phase.project(GraphDomain.nodes, lambda t, y: np.sin(y))
return (phase, amplitude)
|
'''
Determine sum of integer digits between two inclusive limits
Status: Accepted
'''
###############################################################################
def digit_sum(value):
"""Return the sum of all digits between 0 and input value"""
result = 0
if value > 0:
magnitude = value // 10
magnitude_sum = sum([int(i) for i in list(str(magnitude))])
result = digit_sum(magnitude - 1) * 10
result += 45 * magnitude
for last_digit in range(1 + value % 10):
result += magnitude_sum + last_digit
return result
###############################################################################
def main():
"""Read input and print output for sum of digits between 2 numbers"""
for _ in range(int(input().strip())):
lo_value, hi_value = [int(i) for i in input().split()]
if hi_value:
if lo_value:
print(str(digit_sum(hi_value) - digit_sum(lo_value - 1)))
else:
print(str(digit_sum(hi_value)))
else:
print('0')
###############################################################################
if __name__ == '__main__':
main()
|
"""
Determine sum of integer digits between two inclusive limits
Status: Accepted
"""
def digit_sum(value):
"""Return the sum of all digits between 0 and input value"""
result = 0
if value > 0:
magnitude = value // 10
magnitude_sum = sum([int(i) for i in list(str(magnitude))])
result = digit_sum(magnitude - 1) * 10
result += 45 * magnitude
for last_digit in range(1 + value % 10):
result += magnitude_sum + last_digit
return result
def main():
"""Read input and print output for sum of digits between 2 numbers"""
for _ in range(int(input().strip())):
(lo_value, hi_value) = [int(i) for i in input().split()]
if hi_value:
if lo_value:
print(str(digit_sum(hi_value) - digit_sum(lo_value - 1)))
else:
print(str(digit_sum(hi_value)))
else:
print('0')
if __name__ == '__main__':
main()
|
def Markov1_3D_BC_taper_init(particle, fieldset, time):
# Initialize random velocity magnitudes in the isopycnal plane
u_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
v_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
# (double) derivatives in density field are assumed available
# Computation of taper function
Sx = - drhodx / drhodz
Sy = - drhody / drhodz
Sabs = math.sqrt(Sx**2 + Sy**2)
# Tapering based on Danabasoglu and McWilliams, J. Clim. 1995
# Tapering is discrete outside of a given range, to prevent
# it from having its own decay timescale
if Sabs < fieldset.Sc - 3. * fieldset.Sd:
taper1 = 1.
elif Sabs > fieldset.Sc + 3. * fieldset.Sd:
taper1 = 0.
else:
taper1 = 0.5 * (1 + math.tanh((fieldset.Sc - Sabs)/fieldset.Sd))
# Near boundaries, drop to 0
if fieldset.boundaryMask[particle] < 0.95:
taper2 = 0.
else:
taper2 = 1.
# Compute the gradient vector, which is perpendicular to the local isoneutral
grad = [drhodx, drhody, drhodz]
# Compute u in the isopycnal plane (arbitrary direction)
# by ensuring dot(u_iso, grad) = 0
u_iso = [-(drhody+drhodz)/drhodx, 1, 1]
u_iso_norm = math.sqrt(u_iso[0]**2 + u_iso[1]**2 + u_iso[2]**2)
u_iso_normed = [u_iso[0]/u_iso_norm, u_iso[1]/u_iso_norm, u_iso[2]/u_iso_norm]
# Fix v_iso by computing cross(u_iso, grad)
v_iso = [grad[1]*u_iso[2] - grad[2]*u_iso[1],
grad[2]*u_iso[0] - grad[0]*u_iso[2],
grad[0]*u_iso[1] - grad[1]*u_iso[0]]
v_iso_norm = math.sqrt(v_iso[0]**2 + v_iso[1]**2 + v_iso[2]**2)
v_iso_normed = [v_iso[0]/v_iso_norm, v_iso[1]/v_iso_norm, v_iso[2]/v_iso_norm]
# Compute the initial isopycnal velocity vector, which is a linear combination
# of u_iso and v_iso
vel_init = [u_iso_prime_abs * u_iso_normed[0] + v_iso_prime_abs * v_iso_normed[0],
u_iso_prime_abs * u_iso_normed[1] + v_iso_prime_abs * v_iso_normed[1],
u_iso_prime_abs * u_iso_normed[2] + v_iso_prime_abs * v_iso_normed[2]]
particle.u_prime = taper1 * taper2 * vel_init[0]
particle.v_prime = taper1 * taper2 * vel_init[1]
particle.w_prime = taper1 * taper2 * vel_init[2]
|
def markov1_3_d_bc_taper_init(particle, fieldset, time):
u_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
v_iso_prime_abs = ParcelsRandom.normalvariate(0, math.sqrt(fieldset.nusquared))
sx = -drhodx / drhodz
sy = -drhody / drhodz
sabs = math.sqrt(Sx ** 2 + Sy ** 2)
if Sabs < fieldset.Sc - 3.0 * fieldset.Sd:
taper1 = 1.0
elif Sabs > fieldset.Sc + 3.0 * fieldset.Sd:
taper1 = 0.0
else:
taper1 = 0.5 * (1 + math.tanh((fieldset.Sc - Sabs) / fieldset.Sd))
if fieldset.boundaryMask[particle] < 0.95:
taper2 = 0.0
else:
taper2 = 1.0
grad = [drhodx, drhody, drhodz]
u_iso = [-(drhody + drhodz) / drhodx, 1, 1]
u_iso_norm = math.sqrt(u_iso[0] ** 2 + u_iso[1] ** 2 + u_iso[2] ** 2)
u_iso_normed = [u_iso[0] / u_iso_norm, u_iso[1] / u_iso_norm, u_iso[2] / u_iso_norm]
v_iso = [grad[1] * u_iso[2] - grad[2] * u_iso[1], grad[2] * u_iso[0] - grad[0] * u_iso[2], grad[0] * u_iso[1] - grad[1] * u_iso[0]]
v_iso_norm = math.sqrt(v_iso[0] ** 2 + v_iso[1] ** 2 + v_iso[2] ** 2)
v_iso_normed = [v_iso[0] / v_iso_norm, v_iso[1] / v_iso_norm, v_iso[2] / v_iso_norm]
vel_init = [u_iso_prime_abs * u_iso_normed[0] + v_iso_prime_abs * v_iso_normed[0], u_iso_prime_abs * u_iso_normed[1] + v_iso_prime_abs * v_iso_normed[1], u_iso_prime_abs * u_iso_normed[2] + v_iso_prime_abs * v_iso_normed[2]]
particle.u_prime = taper1 * taper2 * vel_init[0]
particle.v_prime = taper1 * taper2 * vel_init[1]
particle.w_prime = taper1 * taper2 * vel_init[2]
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversalRec(self, root, row, col, columns):
if not root:
return
columns[col].append((row, root.val))
self.verticalTraversalRec(root.left, row+1, col-1, columns)
self.verticalTraversalRec(root.right, row+1, col+1, columns)
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
columns = collections.defaultdict(list)
if not root:
return []
self.verticalTraversalRec(root, 0, 0, columns)
# sort by column first, and then sort each column
verticalOrder = []
for col in sorted(columns):
nodes = sorted(columns[col])
verticalOrder.append([node[1] for node in nodes])
return verticalOrder
# O(nlgn) solution
# def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
# # list of nodes - (col, row, value)
# nodes = []
# if not root:
# return []
# def BFS(root):
# queue = collections.deque([(root, 0, 0)])
# while queue:
# node, row, col = queue.popleft()
# if node:
# nodes.append((col, row, node.val))
# queue.append((node.left, row+1, col-1))
# queue.append((node.right, row+1, col+1))
# BFS(root)
# nodes.sort()
# columns = collections.OrderedDict()
# for col, row, val in nodes:
# if col in columns:
# columns[col].append(val)
# else:
# columns[col] = [val]
# return list(columns.values())
|
class Solution:
def vertical_traversal_rec(self, root, row, col, columns):
if not root:
return
columns[col].append((row, root.val))
self.verticalTraversalRec(root.left, row + 1, col - 1, columns)
self.verticalTraversalRec(root.right, row + 1, col + 1, columns)
def vertical_traversal(self, root: TreeNode) -> List[List[int]]:
columns = collections.defaultdict(list)
if not root:
return []
self.verticalTraversalRec(root, 0, 0, columns)
vertical_order = []
for col in sorted(columns):
nodes = sorted(columns[col])
verticalOrder.append([node[1] for node in nodes])
return verticalOrder
|
'''
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-09-25
content:
'''
_base_ = [
'../_base_/models/deeplabv3_r50a-d8.py',
'../_base_/datasets/sn6_sar_pro.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_20k.py'
]
model = dict(
decode_head=dict(num_classes=2), auxiliary_head=dict(num_classes=2))
|
"""
Author: Shuailin Chen
Created Date: 2021-09-14
Last Modified: 2021-09-25
content:
"""
_base_ = ['../_base_/models/deeplabv3_r50a-d8.py', '../_base_/datasets/sn6_sar_pro.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_20k.py']
model = dict(decode_head=dict(num_classes=2), auxiliary_head=dict(num_classes=2))
|
"""
Module provides state and state history for agent.
"""
class AgentState(object):
"""
AgentState class.
Agent state is a class that specifies current agent behaviour. It
provides methods that describe the way agent cooperate with
percepted stimulus coming from environment.
@attention: You can redefine or change this class to provide new
functionality to an agent. It is recommended to change AgentState or build
inherited class instead of changing Agent class.
@sort: __init__, clone, clone_state, get_state
"""
def __init__(self):
"""
Initialize an AgentState.
@attention: You should specify type of AgentState. You can add
new type of agent state by implementing new class and redefining
this function.
"""
self.state = None
def clone(self):
"""
Return a copy of whole current AgentState.
@rtype: AgentState
@return: Return new instance of AgentState.
"""
#return self.deepcopy()
pass
def clone_state(self):
"""
Return a copy of current agent low-level state.
@attention: This function does not clone whole instance of AgentState.
@rtype: state
@return: Return new instance (copy) of low-level state.
"""
return self.state.clone()
def get_state(self):
"""
Retrun object that represent concrete state.
@rtype: state
@return: Return object that keeps current information about agent state
e.g. high-level classifier.
"""
return self.state
def clean(self, environment, sensor):
"""
Alows agent state to clean up before dumping into file
"""
pass
class StateHistory(object):
"""
StateHistory class.
StateHistory class provides a set of states from agent history.
@attention: This class does not keep whole AgentState objects, but
low-level states.
@sort: __init__, __len__, add_state, get_state
"""
def __init__(self, freq = None):
"""
Initialize a StateHistory for an agent.
@type freq: number
@param freq: Frequency of saving changed states to the history.
@attention: You should specify frequency of saving states to history.
In other case all states will be saved.
"""
if (freq is None):
self.freq = 1
else:
self.freq = freq
self.counter = self.freq #counter used to skip states
self.states = [] #list of states
def __len__(self):
"""
Return the number of states in the history when requested by len().
@rtype: number
@return: Size of the hypergraph.
"""
return len(self.states)
def add_state(self, state):
"""
Add state to state history.
@type state: state
@param state: Current low-level state of agent.
"""
if (self.counter == self.freq):
self.states.append(state.clone_state())
self.counter = 1
else: #skips state and increases counter
self.counter += 1
def get_state(self, number):
"""
Return chosen state from history.
@type number: number
@param number: Chronological position of state in history.
@rtype: state
@return: Chosen state from agent history.
"""
return self.states[number]
|
"""
Module provides state and state history for agent.
"""
class Agentstate(object):
"""
AgentState class.
Agent state is a class that specifies current agent behaviour. It
provides methods that describe the way agent cooperate with
percepted stimulus coming from environment.
@attention: You can redefine or change this class to provide new
functionality to an agent. It is recommended to change AgentState or build
inherited class instead of changing Agent class.
@sort: __init__, clone, clone_state, get_state
"""
def __init__(self):
"""
Initialize an AgentState.
@attention: You should specify type of AgentState. You can add
new type of agent state by implementing new class and redefining
this function.
"""
self.state = None
def clone(self):
"""
Return a copy of whole current AgentState.
@rtype: AgentState
@return: Return new instance of AgentState.
"""
pass
def clone_state(self):
"""
Return a copy of current agent low-level state.
@attention: This function does not clone whole instance of AgentState.
@rtype: state
@return: Return new instance (copy) of low-level state.
"""
return self.state.clone()
def get_state(self):
"""
Retrun object that represent concrete state.
@rtype: state
@return: Return object that keeps current information about agent state
e.g. high-level classifier.
"""
return self.state
def clean(self, environment, sensor):
"""
Alows agent state to clean up before dumping into file
"""
pass
class Statehistory(object):
"""
StateHistory class.
StateHistory class provides a set of states from agent history.
@attention: This class does not keep whole AgentState objects, but
low-level states.
@sort: __init__, __len__, add_state, get_state
"""
def __init__(self, freq=None):
"""
Initialize a StateHistory for an agent.
@type freq: number
@param freq: Frequency of saving changed states to the history.
@attention: You should specify frequency of saving states to history.
In other case all states will be saved.
"""
if freq is None:
self.freq = 1
else:
self.freq = freq
self.counter = self.freq
self.states = []
def __len__(self):
"""
Return the number of states in the history when requested by len().
@rtype: number
@return: Size of the hypergraph.
"""
return len(self.states)
def add_state(self, state):
"""
Add state to state history.
@type state: state
@param state: Current low-level state of agent.
"""
if self.counter == self.freq:
self.states.append(state.clone_state())
self.counter = 1
else:
self.counter += 1
def get_state(self, number):
"""
Return chosen state from history.
@type number: number
@param number: Chronological position of state in history.
@rtype: state
@return: Chosen state from agent history.
"""
return self.states[number]
|
# encoding=utf-8
d = dict(one=1, two=2)
d1 = {'one': 1, "two": 2}
d2 = dict()
d2['one'] = 1
d2['two'] = 2
# [(key,value), (key, value)]
my_dict = {}.setdefault().append(1)
print(my_dict[1])
|
d = dict(one=1, two=2)
d1 = {'one': 1, 'two': 2}
d2 = dict()
d2['one'] = 1
d2['two'] = 2
my_dict = {}.setdefault().append(1)
print(my_dict[1])
|
# Matrix Ops some helper functions for matrix operations
#
# Legal:
# ==============
# Copyright 2021 lukasjoc<[email protected]>
# 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.
#
def get_rows(arr):
""" return the rows for a given matrix """
return [arr[row] for row in range(len(arr))]
def get_cols(arr):
""" returns the cols for a given matrix """
cols = []
for row in range(len(arr)):
for col in range(len(arr[0])):
cols.append(arr[col][row])
return cols
def get_diagonals(arr):
"""returns the diagonals for a given matrix """
d1, d2 = [], []
for row in range(len(arr)):
forwardDiag = arr[row][row]
d1.append(forwardDiag)
backwardDiag = arr[row][len(arr[row]) - 1 - row]
d2.append(backwardDiag)
return d1, d2
|
def get_rows(arr):
""" return the rows for a given matrix """
return [arr[row] for row in range(len(arr))]
def get_cols(arr):
""" returns the cols for a given matrix """
cols = []
for row in range(len(arr)):
for col in range(len(arr[0])):
cols.append(arr[col][row])
return cols
def get_diagonals(arr):
"""returns the diagonals for a given matrix """
(d1, d2) = ([], [])
for row in range(len(arr)):
forward_diag = arr[row][row]
d1.append(forwardDiag)
backward_diag = arr[row][len(arr[row]) - 1 - row]
d2.append(backwardDiag)
return (d1, d2)
|
"""Problem 001
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
ans = sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
print(ans)
|
"""Problem 001
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
ans = sum((n for n in range(1000) if n % 3 == 0 or n % 5 == 0))
print(ans)
|
@app.route('/home')
def home():
return redirect(url_for('about', name='World'))
@app.route('/about/<name>')
def about(name):
return f'Hello {name}'
|
@app.route('/home')
def home():
return redirect(url_for('about', name='World'))
@app.route('/about/<name>')
def about(name):
return f'Hello {name}'
|
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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.
#
# Const Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.rendering
class PanoseStrokeVariation(object):
"""
Const Class
See Also:
`API PanoseStrokeVariation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1rendering_1_1PanoseStrokeVariation.html>`_
"""
__ooo_ns__: str = 'com.sun.star.rendering'
__ooo_full_ns__: str = 'com.sun.star.rendering.PanoseStrokeVariation'
__ooo_type_name__: str = 'const'
ANYTHING = 0
NO_FIT = 1
GRADUAL_DIAGONAL = 2
GRADUAL_TRANSITIONAL = 3
GRADUAL_VERTICAL = 4
GRADUAL_HORIZONTAL = 5
RAPID_VERTICAL = 6
RAPID_HORIZONTAL = 7
INSTANT_VERTICAL = 8
__all__ = ['PanoseStrokeVariation']
|
class Panosestrokevariation(object):
"""
Const Class
See Also:
`API PanoseStrokeVariation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1rendering_1_1PanoseStrokeVariation.html>`_
"""
__ooo_ns__: str = 'com.sun.star.rendering'
__ooo_full_ns__: str = 'com.sun.star.rendering.PanoseStrokeVariation'
__ooo_type_name__: str = 'const'
anything = 0
no_fit = 1
gradual_diagonal = 2
gradual_transitional = 3
gradual_vertical = 4
gradual_horizontal = 5
rapid_vertical = 6
rapid_horizontal = 7
instant_vertical = 8
__all__ = ['PanoseStrokeVariation']
|
def Naturals(n):
yield n
yield from Naturals(n+1)
s = Naturals(1)
print("Natural #s", next(s), next(s), next(s), next(s))
def sieve(s):
n = next(s)
yield n
yield from sieve(i for i in s if i%n != 0)
p = sieve(Naturals(2))
print("Prime #s", next(p), next(p), next(p), \
next(p), next(p), next(p), next(p), next(p))
def gensend():
item = yield
yield item
g = gensend()
next(g)
print ( g.send("hello"))
|
def naturals(n):
yield n
yield from naturals(n + 1)
s = naturals(1)
print('Natural #s', next(s), next(s), next(s), next(s))
def sieve(s):
n = next(s)
yield n
yield from sieve((i for i in s if i % n != 0))
p = sieve(naturals(2))
print('Prime #s', next(p), next(p), next(p), next(p), next(p), next(p), next(p), next(p))
def gensend():
item = (yield)
yield item
g = gensend()
next(g)
print(g.send('hello'))
|
"""
Storage for script settings and parameter grids
Authors: Vincent Yu
Date: 12/03/2020
"""
# GENERAL SETTINGS
# Set to true to re-read the latest version of the dataset csv files
update_dset = False
# Set the rescale factor to inflate the dataset
rescale = 1000
# FINE TUNING RELATED
# Set the random grid search status
random = True
random_size_LSTM = 50
random_size_ARIMAX = 1
# MODEL RELATED
# Set ARIMAX fine tuning parameters
params_ARIMAX = {
'num_extra_states': [i for i in range(6)],
'p': [i for i in range(5, 10)],
'd': [i for i in range(2)],
'q': [i for i in range(2)]
}
# Set LSTM fine tuning parameters
params_LSTM = {
'order': [i for i in range(15)],
'num_extra_states': [i for i in range(2, 7)],
'cases_lag': [i for i in range(11)],
'deaths_lag': [i for i in range(10)],
'aug_lag': [i for i in range(10)]
}
# Some LSTM related hyper-parameters
batch_size = 10
epochs = 25
# PREDICTION RELATED
# Testing or Predicted
pred_mode = True
# Rolling prediction iterations
rolling_iters = 10
|
"""
Storage for script settings and parameter grids
Authors: Vincent Yu
Date: 12/03/2020
"""
update_dset = False
rescale = 1000
random = True
random_size_lstm = 50
random_size_arimax = 1
params_arimax = {'num_extra_states': [i for i in range(6)], 'p': [i for i in range(5, 10)], 'd': [i for i in range(2)], 'q': [i for i in range(2)]}
params_lstm = {'order': [i for i in range(15)], 'num_extra_states': [i for i in range(2, 7)], 'cases_lag': [i for i in range(11)], 'deaths_lag': [i for i in range(10)], 'aug_lag': [i for i in range(10)]}
batch_size = 10
epochs = 25
pred_mode = True
rolling_iters = 10
|
##
## parse argument
##
## written by @ciku370
##
def toxic(wibu_bau,bawang):
shit = bawang.split(',')
dan_buriq = 0
result = {}
for i in wibu_bau:
if i in shit:
try:
result.update({wibu_bau[dan_buriq]:wibu_bau[dan_buriq+1]})
except IndexError:
continue
dan_buriq += 1
return result
|
def toxic(wibu_bau, bawang):
shit = bawang.split(',')
dan_buriq = 0
result = {}
for i in wibu_bau:
if i in shit:
try:
result.update({wibu_bau[dan_buriq]: wibu_bau[dan_buriq + 1]})
except IndexError:
continue
dan_buriq += 1
return result
|
raise NotImplementedError("'str' object has no attribute named '__getitem__' looks like I can't index a string?")
def countGroups(related):
groups = 0
def follow_subusers(matrix_lookup, user_id, users_in_group):
"""
Recursive helper to follow users across matrix that have associations possibly separated from the original
user. Examples didn't show what happened when associations don't pass from the originating user, and we
assume we continue to chase them around the matrix until all degrees of users are represented from the
originator.
"""
if user_id not in users_in_group:
users_in_group.append(user_id)
while len(matrix_lookup[user_id]) > 0:
follow_subusers(matrix_lookup, matrix_lookup[user_id].pop(), users_in_group)
# Let's make a scratch lookup table and remove connections as we create groups
lookup = {}
for row_i in range(len(related)):
for col_i in range(len(related)): # It's square so it doesn't matter what we use to reference
if related[row_i][col_i] == '1':
if col_i not in lookup:
lookup[col_i] = [row_i]
else:
lookup[col_i].append(row_i)
for from_user_id in lookup.keys():
current_group = []
if len(lookup[from_user_id]) > 0:
follow_subusers(lookup, from_user_id, current_group)
if len(current_group) > 0:
#print(f"Found group: {current_group}")
groups += 1
return groups
print(countGroups(["1100", "1110", "0110", "0001"]))
|
raise not_implemented_error("'str' object has no attribute named '__getitem__' looks like I can't index a string?")
def count_groups(related):
groups = 0
def follow_subusers(matrix_lookup, user_id, users_in_group):
"""
Recursive helper to follow users across matrix that have associations possibly separated from the original
user. Examples didn't show what happened when associations don't pass from the originating user, and we
assume we continue to chase them around the matrix until all degrees of users are represented from the
originator.
"""
if user_id not in users_in_group:
users_in_group.append(user_id)
while len(matrix_lookup[user_id]) > 0:
follow_subusers(matrix_lookup, matrix_lookup[user_id].pop(), users_in_group)
lookup = {}
for row_i in range(len(related)):
for col_i in range(len(related)):
if related[row_i][col_i] == '1':
if col_i not in lookup:
lookup[col_i] = [row_i]
else:
lookup[col_i].append(row_i)
for from_user_id in lookup.keys():
current_group = []
if len(lookup[from_user_id]) > 0:
follow_subusers(lookup, from_user_id, current_group)
if len(current_group) > 0:
groups += 1
return groups
print(count_groups(['1100', '1110', '0110', '0001']))
|
for linha in range(5):
for coluna in range(3):
if (linha == 0 and coluna == 0) or (linha == 4 and coluna == 0):
print(' ', end='')
elif linha == 0 or linha == 4 or coluna == 0:
print('*', end='')
else:
print(' ', end='')
print()
|
for linha in range(5):
for coluna in range(3):
if linha == 0 and coluna == 0 or (linha == 4 and coluna == 0):
print(' ', end='')
elif linha == 0 or linha == 4 or coluna == 0:
print('*', end='')
else:
print(' ', end='')
print()
|
IV = bytearray.fromhex("391e95a15847cfd95ecee8f7fe7efd66")
CT = bytearray.fromhex("8473dcb86bc12c6b6087619c00b6657e")
# Hashes from the description of challenge
ORIGINAL_MESSAGE = bytearray.fromhex(
"464952455f4e554b45535f4d454c4121") # FIRE_NUKES_MELA!
ALTERED_MESSAGE = bytearray.fromhex(
"53454e445f4e554445535f4d454c4121") # SEND_NUDES_MELA!
ALTERED_IV = bytearray()
# XOR
for i in range(16):
ALTERED_IV.append(ALTERED_MESSAGE[i] ^ ORIGINAL_MESSAGE[i] ^ IV[i])
print(f'Flag: flag{{{ALTERED_IV.hex()},{CT.hex()}}}')
|
iv = bytearray.fromhex('391e95a15847cfd95ecee8f7fe7efd66')
ct = bytearray.fromhex('8473dcb86bc12c6b6087619c00b6657e')
original_message = bytearray.fromhex('464952455f4e554b45535f4d454c4121')
altered_message = bytearray.fromhex('53454e445f4e554445535f4d454c4121')
altered_iv = bytearray()
for i in range(16):
ALTERED_IV.append(ALTERED_MESSAGE[i] ^ ORIGINAL_MESSAGE[i] ^ IV[i])
print(f'Flag: flag{{{ALTERED_IV.hex()},{CT.hex()}}}')
|
def draw(stick: int, cx: str):
"""Function to draw of the board.
Args:
stick: nb of sticks left
cx: past
"""
if stick == 11:
print(
"#######################\n | | | | | | | | | | | \n#######################"
)
if stick == 10:
print(
"#######################\n | | | | | | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 9:
print(
"#######################\n | | | | | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 8:
print(
"#######################\n | | | | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 7:
print(
"######################\n | | | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 6:
print(
"#######################\n | | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 5:
print(
"########################\n | | | | |",
"# ",
cx,
" \n#######################",
)
if stick == 4:
print(
"#######################\n | | | |", "# ", cx, " \n#######################"
)
if stick == 3:
print("#######################\n | | |", "# ", cx, " \n#######################")
if stick == 2:
print("#######################\n | |", "# ", cx, " \n#######################")
if stick == 1:
print("#######################\n |", "# ", cx, " \n#######################")
|
def draw(stick: int, cx: str):
"""Function to draw of the board.
Args:
stick: nb of sticks left
cx: past
"""
if stick == 11:
print('#######################\n | | | | | | | | | | | \n#######################')
if stick == 10:
print('#######################\n | | | | | | | | | |', '# ', cx, ' \n#######################')
if stick == 9:
print('#######################\n | | | | | | | | |', '# ', cx, ' \n#######################')
if stick == 8:
print('#######################\n | | | | | | | |', '# ', cx, ' \n#######################')
if stick == 7:
print('######################\n | | | | | | |', '# ', cx, ' \n#######################')
if stick == 6:
print('#######################\n | | | | | |', '# ', cx, ' \n#######################')
if stick == 5:
print('########################\n | | | | |', '# ', cx, ' \n#######################')
if stick == 4:
print('#######################\n | | | |', '# ', cx, ' \n#######################')
if stick == 3:
print('#######################\n | | |', '# ', cx, ' \n#######################')
if stick == 2:
print('#######################\n | |', '# ', cx, ' \n#######################')
if stick == 1:
print('#######################\n |', '# ', cx, ' \n#######################')
|
#Check String
'''To check if a certain phrase or character is present in a string, we can use the keyword in.'''
#Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
txt = "Hello buddie owo!"
if "owo" in txt:
print("Yes, 'owo' is present.")
'''
Terminal:
True
Yes, 'owo' is present.
'''
#Learn more about If statements in our Python If...Else chapter: https://www.w3schools.com/python/python_conditions.asp
#https://www.w3schools.com/python/python_strings.asp
|
"""To check if a certain phrase or character is present in a string, we can use the keyword in."""
txt = 'The best things in life are free!'
print('free' in txt)
txt = 'Hello buddie owo!'
if 'owo' in txt:
print("Yes, 'owo' is present.")
"\nTerminal:\nTrue\nYes, 'owo' is present.\n"
|
testes = int(input())
casos = []
for x in range(testes):
casos_ = input().split()
casos.append(casos_)
for x in range(testes):
a = int(casos[x][0])
b = int(casos[x][1])
print(a+b)
|
testes = int(input())
casos = []
for x in range(testes):
casos_ = input().split()
casos.append(casos_)
for x in range(testes):
a = int(casos[x][0])
b = int(casos[x][1])
print(a + b)
|
# led-control WS2812B LED Controller Server
# Copyright 2021 jackw01. Released under the MIT License (see LICENSE for details).
default = {
0: {
'name': 'Sunset Light',
'mode': 0,
'colors': [
[
0.11311430089613972,
1,
1
],
[
0.9936081381405101,
0.6497928024431981,
1
],
[
0.9222222222222223,
0.9460097254004577,
1
],
[
0.7439005234662223,
0.7002515180395283,
1
],
[
0.6175635842715993,
0.6474992244615467,
1
]
]
},
10: {
'name': 'Sunset Dark',
'mode': 0,
'colors': [
[
0.11311430089613972,
1,
1
],
[
0.0083333333333333,
0.8332790409753081,
1
],
[
0.9222222222222223,
0.8539212428101706,
0.7776361353257123
],
[
0.8833333333333333,
0.8974992244615467,
0.2942011216107537
]
]
},
20: {
'name': 'Miami',
'mode': 0,
'colors': [
[
0.973575367647059,
0.792691647597254,
1
],
[
0.935202205882353,
0.8132866132723112,
1
],
[
0.8012408088235294,
0.6622568649885584,
0.992876838235294
],
[
0.59375,
0.6027602974828375,
1
],
[
0.5480238970588235,
0.9482980549199085,
1
],
[
0.5022977941176471,
0.9460097254004577,
1
]
]
},
90: {
'name': 'Spectrum',
'mode': 0,
'colors': [
[
0,
1,
1
],
[
1,
1,
1
]
]
},
30: {
'name': 'Lemonbars',
'mode': 0,
'colors': [
[
1,
0.9989988558352403,
1
],
[
0.7807904411764706,
0.9989988558352403,
1
],
[
0.5985753676470589,
0.9979987139601192,
1
]
],
},
40: {
'name': 'Viridis',
'mode': 0,
'colors': [
[
0.7663143382352942,
0.9989988558352403,
0.6528033088235294
],
[
0.6029411764705882,
0.9989988558352403,
1
],
[
0.4028033088235295,
0.5249570938215103,
1
],
[
0.12339154411764706,
0.9989988558352403,
1
]
],
},
150: {
'name': 'Fire',
'mode': 0,
'colors': [
[
0,
0.9989988558352403,
1
],
[
0.04549632352941176,
0.9989988558352403,
1
],
[
0.11,
0.9989988558352403,
1
],
[
0.08639705882352941,
0.667,
1
],
[
0,
0,
1
]
]
},
160: {
'name': 'Golden Hour',
'mode': 0,
'colors': [
[
0.09122242647058823,
0.9960014330660517,
1
],
[
0.1484375,
0.9960014330660517,
1
],
[
0.13947610294117646,
0.4311355835240275,
0.6178768382352942
]
],
},
170: {
'name': 'Ocean',
'mode': 0,
'colors': [
[
0.6190257352941176,
0.9969995733712004,
1
],
[
0.5659466911764706,
0.9989988558352403,
1
],
[
0.4834558823529411,
0.746925057208238,
1
]
],
},
190: {
'name': 'Sky Blue',
'mode': 0,
'colors': [
[
0.5824908088235294,
0.8762614416475973,
1
],
[
0.5808823529411765,
0.8132866132723112,
1
],
[
0.5659466911764706,
0.5821653318077803,
1
]
],
},
200: {
'name': 'Purple',
'mode': 0,
'colors': [
[
0.7456341911764706,
0.9969995733712004,
1
],
[
0.6541819852941176,
0.9979987139601192,
1
],
[
0.68359375,
0.5913186498855835,
1
]
],
},
210: {
'name': 'Hot Pink',
'mode': 0,
'colors': [
[
0.979549632352941,
0.9989988558352403,
1
],
[
0.9338235294117647,
0.8727831807780321,
1
],
[
0.9542738970588235,
0.7240417620137299,
1
]
],
},
}
|
default = {0: {'name': 'Sunset Light', 'mode': 0, 'colors': [[0.11311430089613972, 1, 1], [0.9936081381405101, 0.6497928024431981, 1], [0.9222222222222223, 0.9460097254004577, 1], [0.7439005234662223, 0.7002515180395283, 1], [0.6175635842715993, 0.6474992244615467, 1]]}, 10: {'name': 'Sunset Dark', 'mode': 0, 'colors': [[0.11311430089613972, 1, 1], [0.0083333333333333, 0.8332790409753081, 1], [0.9222222222222223, 0.8539212428101706, 0.7776361353257123], [0.8833333333333333, 0.8974992244615467, 0.2942011216107537]]}, 20: {'name': 'Miami', 'mode': 0, 'colors': [[0.973575367647059, 0.792691647597254, 1], [0.935202205882353, 0.8132866132723112, 1], [0.8012408088235294, 0.6622568649885584, 0.992876838235294], [0.59375, 0.6027602974828375, 1], [0.5480238970588235, 0.9482980549199085, 1], [0.5022977941176471, 0.9460097254004577, 1]]}, 90: {'name': 'Spectrum', 'mode': 0, 'colors': [[0, 1, 1], [1, 1, 1]]}, 30: {'name': 'Lemonbars', 'mode': 0, 'colors': [[1, 0.9989988558352403, 1], [0.7807904411764706, 0.9989988558352403, 1], [0.5985753676470589, 0.9979987139601192, 1]]}, 40: {'name': 'Viridis', 'mode': 0, 'colors': [[0.7663143382352942, 0.9989988558352403, 0.6528033088235294], [0.6029411764705882, 0.9989988558352403, 1], [0.4028033088235295, 0.5249570938215103, 1], [0.12339154411764706, 0.9989988558352403, 1]]}, 150: {'name': 'Fire', 'mode': 0, 'colors': [[0, 0.9989988558352403, 1], [0.04549632352941176, 0.9989988558352403, 1], [0.11, 0.9989988558352403, 1], [0.08639705882352941, 0.667, 1], [0, 0, 1]]}, 160: {'name': 'Golden Hour', 'mode': 0, 'colors': [[0.09122242647058823, 0.9960014330660517, 1], [0.1484375, 0.9960014330660517, 1], [0.13947610294117646, 0.4311355835240275, 0.6178768382352942]]}, 170: {'name': 'Ocean', 'mode': 0, 'colors': [[0.6190257352941176, 0.9969995733712004, 1], [0.5659466911764706, 0.9989988558352403, 1], [0.4834558823529411, 0.746925057208238, 1]]}, 190: {'name': 'Sky Blue', 'mode': 0, 'colors': [[0.5824908088235294, 0.8762614416475973, 1], [0.5808823529411765, 0.8132866132723112, 1], [0.5659466911764706, 0.5821653318077803, 1]]}, 200: {'name': 'Purple', 'mode': 0, 'colors': [[0.7456341911764706, 0.9969995733712004, 1], [0.6541819852941176, 0.9979987139601192, 1], [0.68359375, 0.5913186498855835, 1]]}, 210: {'name': 'Hot Pink', 'mode': 0, 'colors': [[0.979549632352941, 0.9989988558352403, 1], [0.9338235294117647, 0.8727831807780321, 1], [0.9542738970588235, 0.7240417620137299, 1]]}}
|
class Solution:
def myAtoi(self, s: str) -> int:
s = s.strip(' ')
s = s.rstrip('.')
lens = len(s)
if (not s) or s[0].isalpha() or (lens == 1 and not s[0].isdecimal()):
return 0
string, i = '', 0
if s[0] in {'-', '+'}:
i = 1
string += s[0]
while i < lens:
char = s[i]
if char.isdecimal():
string += char
else:
break
i += 1
if (not string) or (len(string) == 1 and not string[0].isdecimal()):
return 0
sol, mini, maxi = int(string), -2147483648, 2147483647
if sol < mini:
return mini
elif sol > maxi:
return maxi
else:
return sol
|
class Solution:
def my_atoi(self, s: str) -> int:
s = s.strip(' ')
s = s.rstrip('.')
lens = len(s)
if not s or s[0].isalpha() or (lens == 1 and (not s[0].isdecimal())):
return 0
(string, i) = ('', 0)
if s[0] in {'-', '+'}:
i = 1
string += s[0]
while i < lens:
char = s[i]
if char.isdecimal():
string += char
else:
break
i += 1
if not string or (len(string) == 1 and (not string[0].isdecimal())):
return 0
(sol, mini, maxi) = (int(string), -2147483648, 2147483647)
if sol < mini:
return mini
elif sol > maxi:
return maxi
else:
return sol
|
while(True):
try:
n,k=map(int,input().split())
text=input()
except EOFError:
break
p=0
for i in range(1,n):
if text[0:i]==text[n-i:n]:
p=i
#print(p)
s=text+text[p:]*(k-1)
print(s)
|
while True:
try:
(n, k) = map(int, input().split())
text = input()
except EOFError:
break
p = 0
for i in range(1, n):
if text[0:i] == text[n - i:n]:
p = i
s = text + text[p:] * (k - 1)
print(s)
|
class ExileError(Exception):
pass
class SCardError(ExileError):
pass
class YKOATHError(ExileError):
pass
|
class Exileerror(Exception):
pass
class Scarderror(ExileError):
pass
class Ykoatherror(ExileError):
pass
|
class Team:
def __init__(self, client):
self.client = client
async def info(self):
result = await self.client.api_call('GET', 'team.info')
return result['team']
|
class Team:
def __init__(self, client):
self.client = client
async def info(self):
result = await self.client.api_call('GET', 'team.info')
return result['team']
|
def chunk_string(string, chunk_size=450):
# Limit = 462, cutting off at 450 to be safe.
string_chunks = []
while len(string) != 0:
current_chunk = string[0:chunk_size]
string_chunks.append(current_chunk)
string = string[len(current_chunk):]
return string_chunks
|
def chunk_string(string, chunk_size=450):
string_chunks = []
while len(string) != 0:
current_chunk = string[0:chunk_size]
string_chunks.append(current_chunk)
string = string[len(current_chunk):]
return string_chunks
|
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
l, r = 0, len(numbers) - 1
while numbers[l] + numbers[r] != target:
if numbers[l] + numbers[r] < target:
l += 1
else:
r -= 1
return [l + 1, r + 1]
def twoSum2(self, nums, target):
i, j = 0, len(numbers) - 1
while i < j:
if numbers[i] + numbers[j] == target:
return [i + 1, j + 1]
elif numbers[i] + numbers[j] < target:
i += 1
while i < j and numbers[i] == numbers[i - 1]:
i += 1
else:
j -= 1
while i < j and numbers[j] == numbers[j + 1]:
j -= 1
"""
@param nums: an array of integer
@param target: An integer
@return: An integer
"""
# two sum unique pair
def twoSum6(self, nums, target):
if not nums or len(nums) < 2:
return 0
nums.sort()
count = 0
left, right = 0, len(nums) - 1
while left < right:
if nums[left] + nums[right] == target:
count, left, right = count + 1, left + 1, right - 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
else:
left += 1
return count
solver = Solution()
print(solver.twoSum([2,7,11,15], 9))
|
class Solution:
def two_sum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
(l, r) = (0, len(numbers) - 1)
while numbers[l] + numbers[r] != target:
if numbers[l] + numbers[r] < target:
l += 1
else:
r -= 1
return [l + 1, r + 1]
def two_sum2(self, nums, target):
(i, j) = (0, len(numbers) - 1)
while i < j:
if numbers[i] + numbers[j] == target:
return [i + 1, j + 1]
elif numbers[i] + numbers[j] < target:
i += 1
while i < j and numbers[i] == numbers[i - 1]:
i += 1
else:
j -= 1
while i < j and numbers[j] == numbers[j + 1]:
j -= 1
'\n @param nums: an array of integer\n @param target: An integer\n @return: An integer\n '
def two_sum6(self, nums, target):
if not nums or len(nums) < 2:
return 0
nums.sort()
count = 0
(left, right) = (0, len(nums) - 1)
while left < right:
if nums[left] + nums[right] == target:
(count, left, right) = (count + 1, left + 1, right - 1)
while left < right and nums[right] == nums[right + 1]:
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
else:
left += 1
return count
solver = solution()
print(solver.twoSum([2, 7, 11, 15], 9))
|
def maiusculas(frase):
palavra = ''
for letra in frase:
if ord(letra) >= 65 and ord(letra) <= 90:
palavra += letra
return palavra
def maiusculas2(frase):
palavra = ''
for letra in frase:
if letra.isupper():
palavra += letra
return palavra
|
def maiusculas(frase):
palavra = ''
for letra in frase:
if ord(letra) >= 65 and ord(letra) <= 90:
palavra += letra
return palavra
def maiusculas2(frase):
palavra = ''
for letra in frase:
if letra.isupper():
palavra += letra
return palavra
|
# SQRT(X) LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def mySqrt(self, x):
# declaring a variable to track the output.
i = 0
# creating a while-loop to run while the output variable squared is less than or equal to the desired value.
while i * i <= x:
# incrementing the output variable's value.
i += 1
# returning the value of the output variable with modifications.
return i - 1
|
class Solution(object):
def my_sqrt(self, x):
i = 0
while i * i <= x:
i += 1
return i - 1
|
with open("input_blocks.txt") as file:
content = file.read()
for idx, block in enumerate(content.strip().split("---\n")):
with open(f"blocks/{idx+1}.txt", "w") as file:
print(block.rstrip(), file=file)
|
with open('input_blocks.txt') as file:
content = file.read()
for (idx, block) in enumerate(content.strip().split('---\n')):
with open(f'blocks/{idx + 1}.txt', 'w') as file:
print(block.rstrip(), file=file)
|
# Defining a Function
def iterPower(base, exp):
# Making an Iterative Call
result = 1
while exp > 0:
result *= base
exp -= 1
return result
|
def iter_power(base, exp):
result = 1
while exp > 0:
result *= base
exp -= 1
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.