content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# created by Bruce Yuan on 17-11-27
class ConstError(Exception):
def __init__(self, message):
self._message = str(message)
def __str__(self):
return self._message
__repr__ = __str__
| class Consterror(Exception):
def __init__(self, message):
self._message = str(message)
def __str__(self):
return self._message
__repr__ = __str__ |
banyakPerulangan = 10
i = 0
while (i < banyakPerulangan):
print('Hello World')
i += 1 | banyak_perulangan = 10
i = 0
while i < banyakPerulangan:
print('Hello World')
i += 1 |
class Solution:
def sortSentence(self, s: str) -> str:
s=s.split()
s.sort(key = lambda x: x[-1])
sent=""
for i in s:
sent += (i[:-1]+" ")
s=sent.strip()
return s | class Solution:
def sort_sentence(self, s: str) -> str:
s = s.split()
s.sort(key=lambda x: x[-1])
sent = ''
for i in s:
sent += i[:-1] + ' '
s = sent.strip()
return s |
a=10
b=20
print(b-a)
print("SUBTRACTED b-a")
| a = 10
b = 20
print(b - a)
print('SUBTRACTED b-a') |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'camera',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'change_picture',
'dependencies': [
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/compiled_resources2.gyp:iron-selector-extracted',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'../compiled_resources2.gyp:route',
'camera',
'change_picture_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'change_picture_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'easy_unlock_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'easy_unlock_turn_off_dialog',
'dependencies': [
'<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'easy_unlock_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'import_data_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'manage_profile',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'manage_profile_browser_proxy',
'sync_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'manage_profile_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'password_prompt_dialog',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):quick_unlock_private',
'lock_screen_constants',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'people_page',
'dependencies': [
'../compiled_resources2.gyp:route',
'../settings_page/compiled_resources2.gyp:settings_animated_pages',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:icon',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'easy_unlock_browser_proxy',
'easy_unlock_turn_off_dialog',
'lock_screen_constants',
'lock_state_behavior',
'profile_info_browser_proxy',
'sync_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'profile_info_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_state_behavior',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):quick_unlock_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_screen_constants',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_screen',
'dependencies': [
'../compiled_resources2.gyp:route',
'lock_screen_constants',
'lock_state_behavior',
'password_prompt_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'setup_pin_dialog',
'dependencies': [
'../compiled_resources2.gyp:route',
'lock_screen_constants',
'password_prompt_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'sync_page',
'dependencies': [
'../compiled_resources2.gyp:route',
'../settings_page/compiled_resources2.gyp:settings_animated_pages',
'sync_browser_proxy',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'sync_browser_proxy',
'dependencies': [
'<(DEPTH)/third_party/closure_compiler/externs/compiled_resources2.gyp:metrics_private',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'user_list',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):settings_private',
'<(EXTERNS_GYP):users_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'users_add_user_dialog',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(EXTERNS_GYP):users_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'users_page',
'dependencies': [
'user_list',
'users_add_user_dialog',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'import_data_dialog',
'dependencies': [
'../prefs/compiled_resources2.gyp:prefs_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'import_data_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
],
}
| {'targets': [{'target_name': 'camera', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'change_picture', 'dependencies': ['<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/compiled_resources2.gyp:iron-selector-extracted', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', '../compiled_resources2.gyp:route', 'camera', 'change_picture_browser_proxy'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'change_picture_browser_proxy', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'easy_unlock_browser_proxy', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'easy_unlock_turn_off_dialog', 'dependencies': ['<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', 'easy_unlock_browser_proxy'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'import_data_browser_proxy', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'manage_profile', 'dependencies': ['../compiled_resources2.gyp:route', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', 'manage_profile_browser_proxy', 'sync_browser_proxy'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'manage_profile_browser_proxy', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'password_prompt_dialog', 'dependencies': ['../compiled_resources2.gyp:route', '<(EXTERNS_GYP):quick_unlock_private', 'lock_screen_constants'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'people_page', 'dependencies': ['../compiled_resources2.gyp:route', '../settings_page/compiled_resources2.gyp:settings_animated_pages', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:icon', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', 'easy_unlock_browser_proxy', 'easy_unlock_turn_off_dialog', 'lock_screen_constants', 'lock_state_behavior', 'profile_info_browser_proxy', 'sync_browser_proxy'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'profile_info_browser_proxy', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'lock_state_behavior', 'dependencies': ['../compiled_resources2.gyp:route', '<(EXTERNS_GYP):quick_unlock_private'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'lock_screen_constants', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'lock_screen', 'dependencies': ['../compiled_resources2.gyp:route', 'lock_screen_constants', 'lock_state_behavior', 'password_prompt_dialog', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'setup_pin_dialog', 'dependencies': ['../compiled_resources2.gyp:route', 'lock_screen_constants', 'password_prompt_dialog', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'sync_page', 'dependencies': ['../compiled_resources2.gyp:route', '../settings_page/compiled_resources2.gyp:settings_animated_pages', 'sync_browser_proxy', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'sync_browser_proxy', 'dependencies': ['<(DEPTH)/third_party/closure_compiler/externs/compiled_resources2.gyp:metrics_private', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'user_list', 'dependencies': ['../compiled_resources2.gyp:route', '<(EXTERNS_GYP):settings_private', '<(EXTERNS_GYP):users_private'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'users_add_user_dialog', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(EXTERNS_GYP):users_private'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'users_page', 'dependencies': ['user_list', 'users_add_user_dialog'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'import_data_dialog', 'dependencies': ['../prefs/compiled_resources2.gyp:prefs_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', 'import_data_browser_proxy'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}]} |
print("Rock..Paper..Scissors..")
print("Type rock or paper or scissors")
player1 = input("player 1, Your move: ")
player2 = input("player 2, Your move: ")
if player1 == player2:
print("It's a draw!")
elif player1 == "rock":
if player2 == "scissors":
print("player1 wins!")
elif player2 == "paper":
print("player2 wins!")
elif player1 == "paper":
if player2 == "rock":
print("player1 wins!")
elif player2 == "scissors":
print("player2 wins!")
elif player1 == "scissors":
if player2 == "paper":
print("player1 wins!")
elif player2 == "rock":
print("player2 wins!")
else:
print("Check spelling") | print('Rock..Paper..Scissors..')
print('Type rock or paper or scissors')
player1 = input('player 1, Your move: ')
player2 = input('player 2, Your move: ')
if player1 == player2:
print("It's a draw!")
elif player1 == 'rock':
if player2 == 'scissors':
print('player1 wins!')
elif player2 == 'paper':
print('player2 wins!')
elif player1 == 'paper':
if player2 == 'rock':
print('player1 wins!')
elif player2 == 'scissors':
print('player2 wins!')
elif player1 == 'scissors':
if player2 == 'paper':
print('player1 wins!')
elif player2 == 'rock':
print('player2 wins!')
else:
print('Check spelling') |
ATTR_CODE = "auth_code"
CONF_MQTT_IN = "mqtt_in"
CONF_MQTT_OUT = "mqtt_out"
DATA_KEY = "media_player.hisense_tv"
DEFAULT_CLIENT_ID = "HomeAssistant"
DEFAULT_MQTT_PREFIX = "hisense"
DEFAULT_NAME = "Hisense TV"
DOMAIN = "hisense_tv"
| attr_code = 'auth_code'
conf_mqtt_in = 'mqtt_in'
conf_mqtt_out = 'mqtt_out'
data_key = 'media_player.hisense_tv'
default_client_id = 'HomeAssistant'
default_mqtt_prefix = 'hisense'
default_name = 'Hisense TV'
domain = 'hisense_tv' |
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
first, second = len(word1), len(word2)
result = ""
for one, two in zip(word1, word2):
result += one + two
diff = first - second
if not diff:
return result
elif diff > 0:
result += word1[-diff:]
else:
result += word2[diff:]
return result
| class Solution:
def merge_alternately(self, word1: str, word2: str) -> str:
(first, second) = (len(word1), len(word2))
result = ''
for (one, two) in zip(word1, word2):
result += one + two
diff = first - second
if not diff:
return result
elif diff > 0:
result += word1[-diff:]
else:
result += word2[diff:]
return result |
matches = 0
for line in open('2/input.txt'):
acceptable_range, letter, password = line.split(" ")
low, high = acceptable_range.split("-")
count = password.count(letter[0])
if count in range(int(low), int(high)+1):
matches += 1
print(matches) | matches = 0
for line in open('2/input.txt'):
(acceptable_range, letter, password) = line.split(' ')
(low, high) = acceptable_range.split('-')
count = password.count(letter[0])
if count in range(int(low), int(high) + 1):
matches += 1
print(matches) |
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
count = 0
for row in grid:
for c in row:
if c < 0: count += 1
return count | class Solution:
def count_negatives(self, grid: List[List[int]]) -> int:
count = 0
for row in grid:
for c in row:
if c < 0:
count += 1
return count |
class MyHashSet:
def __init__(self):
self.set = [False] * 1000001
def add(self, key: int) -> None:
self.set[key] = True
def remove(self, key: int) -> None:
self.set[key] = False
def contains(self, key: int) -> bool:
return self.set[key]
| class Myhashset:
def __init__(self):
self.set = [False] * 1000001
def add(self, key: int) -> None:
self.set[key] = True
def remove(self, key: int) -> None:
self.set[key] = False
def contains(self, key: int) -> bool:
return self.set[key] |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-many-statements
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=unused-argument
def create_healthcareapis(cmd, client,
resource_group,
name,
kind,
location,
access_policies_object_id,
tags=None,
etag=None,
cosmos_db_offer_throughput=None,
authentication_authority=None,
authentication_audience=None,
authentication_smart_proxy_enabled=None,
cors_origins=None,
cors_headers=None,
cors_methods=None,
cors_max_age=None,
cors_allow_credentials=None):
service_description = {}
service_description['location'] = location
service_description['kind'] = kind
service_description['properties'] = {}
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
service_description['properties']['cors_configuration'] = {}
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
service_description['properties']['cosmos_db_configuration'] = {}
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
service_description['authentication_configuration'] = {}
service_description['authentication_configuration']['authority'] = authentication_authority
service_description['authentication_configuration']['audience'] = authentication_audience
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def update_healthcareapis(cmd, client,
resource_group,
name,
kind=None,
location=None,
access_policies_object_id=None,
tags=None,
etag=None,
cosmos_db_offer_throughput=None,
authentication_authority=None,
authentication_audience=None,
authentication_smart_proxy_enabled=None,
cors_origins=None,
cors_headers=None,
cors_methods=None,
cors_max_age=None,
cors_allow_credentials=None):
service_description = client.get(resource_group_name=resource_group, resource_name=name).as_dict()
if location is not None:
service_description['location'] = location
if kind is not None:
service_description['kind'] = kind
if access_policies_object_id is not None:
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
if service_description['properties'].get('cors_configuration') is None:
service_description['properties']['cors_configuration'] = {}
if cors_origins is not None:
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
if cors_headers is not None:
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
if cors_methods is not None:
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
if cors_max_age is not None:
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
if cors_allow_credentials is not None:
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
if service_description['properties'].get('cosmos_db_configuration') is None:
service_description['properties']['cosmos_db_configuration'] = {}
if cosmos_db_offer_throughput is not None:
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
if service_description['properties'].get('authentication_configuration') is None:
service_description['authentication_configuration'] = {}
if authentication_authority is not None:
service_description['authentication_configuration']['authority'] = authentication_authority
if authentication_audience is not None:
service_description['authentication_configuration']['audience'] = authentication_audience
if authentication_smart_proxy_enabled is not None:
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def list_healthcareapis(cmd, client,
resource_group=None):
if resource_group is not None:
return client.list_by_resource_group(resource_group_name=resource_group)
return client.list()
def show_healthcareapis(cmd, client,
resource_group,
name):
return client.get(resource_group_name=resource_group, resource_name=name)
def delete_healthcareapis(cmd, client,
resource_group,
name):
return client.delete(resource_group_name=resource_group, resource_name=name)
| def create_healthcareapis(cmd, client, resource_group, name, kind, location, access_policies_object_id, tags=None, etag=None, cosmos_db_offer_throughput=None, authentication_authority=None, authentication_audience=None, authentication_smart_proxy_enabled=None, cors_origins=None, cors_headers=None, cors_methods=None, cors_max_age=None, cors_allow_credentials=None):
service_description = {}
service_description['location'] = location
service_description['kind'] = kind
service_description['properties'] = {}
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
service_description['properties']['cors_configuration'] = {}
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
service_description['properties']['cosmos_db_configuration'] = {}
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
service_description['authentication_configuration'] = {}
service_description['authentication_configuration']['authority'] = authentication_authority
service_description['authentication_configuration']['audience'] = authentication_audience
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def update_healthcareapis(cmd, client, resource_group, name, kind=None, location=None, access_policies_object_id=None, tags=None, etag=None, cosmos_db_offer_throughput=None, authentication_authority=None, authentication_audience=None, authentication_smart_proxy_enabled=None, cors_origins=None, cors_headers=None, cors_methods=None, cors_max_age=None, cors_allow_credentials=None):
service_description = client.get(resource_group_name=resource_group, resource_name=name).as_dict()
if location is not None:
service_description['location'] = location
if kind is not None:
service_description['kind'] = kind
if access_policies_object_id is not None:
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
if service_description['properties'].get('cors_configuration') is None:
service_description['properties']['cors_configuration'] = {}
if cors_origins is not None:
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
if cors_headers is not None:
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
if cors_methods is not None:
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
if cors_max_age is not None:
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
if cors_allow_credentials is not None:
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
if service_description['properties'].get('cosmos_db_configuration') is None:
service_description['properties']['cosmos_db_configuration'] = {}
if cosmos_db_offer_throughput is not None:
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
if service_description['properties'].get('authentication_configuration') is None:
service_description['authentication_configuration'] = {}
if authentication_authority is not None:
service_description['authentication_configuration']['authority'] = authentication_authority
if authentication_audience is not None:
service_description['authentication_configuration']['audience'] = authentication_audience
if authentication_smart_proxy_enabled is not None:
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def list_healthcareapis(cmd, client, resource_group=None):
if resource_group is not None:
return client.list_by_resource_group(resource_group_name=resource_group)
return client.list()
def show_healthcareapis(cmd, client, resource_group, name):
return client.get(resource_group_name=resource_group, resource_name=name)
def delete_healthcareapis(cmd, client, resource_group, name):
return client.delete(resource_group_name=resource_group, resource_name=name) |
'''
import cachetools
from . import lang
enabled = True
maxsize = 1000
scriptures = {}
for each in lang.available:
scriptures[each] = cachetools.LRUCache(maxsize=maxsize)
''' | """
import cachetools
from . import lang
enabled = True
maxsize = 1000
scriptures = {}
for each in lang.available:
scriptures[each] = cachetools.LRUCache(maxsize=maxsize)
""" |
class Solution:
def mySqrt(self, x: int) -> int:
low=0
high=x
middle= (low+high)//2
while(high>middle and middle>low):
square=middle*middle
if (square==x):
return int(middle)
if (square>x):
high=middle
else:
low=middle
middle=(low+high)//2
if x<high*high: #check this condition for x=8 or x=1
return int(low)
else:
return int(high)
| class Solution:
def my_sqrt(self, x: int) -> int:
low = 0
high = x
middle = (low + high) // 2
while high > middle and middle > low:
square = middle * middle
if square == x:
return int(middle)
if square > x:
high = middle
else:
low = middle
middle = (low + high) // 2
if x < high * high:
return int(low)
else:
return int(high) |
print("Podaj a:")
a = int(input())
print("Podaj b:")
b = int(input())
print("A") if a > b else print("=") if a == b else print("B")
| print('Podaj a:')
a = int(input())
print('Podaj b:')
b = int(input())
print('A') if a > b else print('=') if a == b else print('B') |
class DB:
'''
Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly.
Usage:
dB = DB()
.
. (later)
.
gain = 15 * dB
'''
def __rmul__(self, val):
'''
Only allow multiplication from the right to avoid confusing situation
like: 15 * dB * 10
'''
return 10 ** (val / 10.)
def __test__():
dB = DB()
gain = 10 * dB
assert abs(gain - 10) < 1e-8
try:
gain2 = dB * 10
raise Exception('Should raise a type error!')
except TypeError:
pass
__test__()
| class Db:
"""
Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly.
Usage:
dB = DB()
.
. (later)
.
gain = 15 * dB
"""
def __rmul__(self, val):
"""
Only allow multiplication from the right to avoid confusing situation
like: 15 * dB * 10
"""
return 10 ** (val / 10.0)
def __test__():
d_b = db()
gain = 10 * dB
assert abs(gain - 10) < 1e-08
try:
gain2 = dB * 10
raise exception('Should raise a type error!')
except TypeError:
pass
__test__() |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
Dogfood_RMEndpoint = 'https://api-dogfood.resources.windows-int.net/'
Helm_Environment_File_Fault_Type = 'helm-environment-file-error'
Invalid_Location_Fault_Type = 'location-validation-error'
Load_Kubeconfig_Fault_Type = 'kubeconfig-load-error'
Read_ConfigMap_Fault_Type = 'configmap-read-error'
Get_ResourceProvider_Fault_Type = 'resource-provider-fetch-error'
Get_ConnectedCluster_Fault_Type = 'connected-cluster-fetch-error'
Create_ConnectedCluster_Fault_Type = 'connected-cluster-create-error'
Delete_ConnectedCluster_Fault_Type = 'connected-cluster-delete-error'
Bad_DeleteRequest_Fault_Type = 'bad-delete-request-error'
Cluster_Already_Onboarded_Fault_Type = 'cluster-already-onboarded-error'
Resource_Already_Exists_Fault_Type = 'resource-already-exists-error'
Resource_Does_Not_Exist_Fault_Type = 'resource-does-not-exist-error'
Create_ResourceGroup_Fault_Type = 'resource-group-creation-error'
Add_HelmRepo_Fault_Type = 'helm-repo-add-error'
List_HelmRelease_Fault_Type = 'helm-list-release-error'
KeyPair_Generate_Fault_Type = 'keypair-generation-error'
PublicKey_Export_Fault_Type = 'publickey-export-error'
PrivateKey_Export_Fault_Type = 'privatekey-export-error'
Install_HelmRelease_Fault_Type = 'helm-release-install-error'
Delete_HelmRelease_Fault_Type = 'helm-release-delete-error'
Check_PodStatus_Fault_Type = 'check-pod-status-error'
Kubernetes_Connectivity_FaultType = 'kubernetes-cluster-connection-error'
Helm_Version_Fault_Type = 'helm-not-updated-error'
Check_HelmVersion_Fault_Type = 'helm-version-check-error'
Helm_Installation_Fault_Type = 'helm-not-installed-error'
Check_HelmInstallation_Fault_Type = 'check-helm-installed-error'
Get_HelmRegistery_Path_Fault_Type = 'helm-registry-path-fetch-error'
Pull_HelmChart_Fault_Type = 'helm-chart-pull-error'
Export_HelmChart_Fault_Type = 'helm-chart-export-error'
Get_Kubernetes_Version_Fault_Type = 'kubernetes-get-version-error'
Get_Kubernetes_Distro_Fault_Type = 'kubernetes-get-distribution-error'
Get_Kubernetes_Namespace_Fault_Type = 'kubernetes-get-namespace-error'
Update_Agent_Success = 'Agents for Connected Cluster {} have been updated successfully'
Update_Agent_Failure = 'Error while updating agents. Please run \"kubectl get pods -n azure-arc\" to check the pods in case of timeout error. Error: {}'
Cluster_Info_Not_Found_Type = 'Error while finding current cluster server details'
Kubeconfig_Failed_To_Load_Fault_Type = "failed-to-load-kubeconfig-file"
Proxy_Cert_Path_Does_Not_Exist_Fault_Type = 'proxy-cert-path-does-not-exist-error'
Proxy_Cert_Path_Does_Not_Exist_Error = 'Proxy cert path {} does not exist. Please check the path provided'
| dogfood_rm_endpoint = 'https://api-dogfood.resources.windows-int.net/'
helm__environment__file__fault__type = 'helm-environment-file-error'
invalid__location__fault__type = 'location-validation-error'
load__kubeconfig__fault__type = 'kubeconfig-load-error'
read__config_map__fault__type = 'configmap-read-error'
get__resource_provider__fault__type = 'resource-provider-fetch-error'
get__connected_cluster__fault__type = 'connected-cluster-fetch-error'
create__connected_cluster__fault__type = 'connected-cluster-create-error'
delete__connected_cluster__fault__type = 'connected-cluster-delete-error'
bad__delete_request__fault__type = 'bad-delete-request-error'
cluster__already__onboarded__fault__type = 'cluster-already-onboarded-error'
resource__already__exists__fault__type = 'resource-already-exists-error'
resource__does__not__exist__fault__type = 'resource-does-not-exist-error'
create__resource_group__fault__type = 'resource-group-creation-error'
add__helm_repo__fault__type = 'helm-repo-add-error'
list__helm_release__fault__type = 'helm-list-release-error'
key_pair__generate__fault__type = 'keypair-generation-error'
public_key__export__fault__type = 'publickey-export-error'
private_key__export__fault__type = 'privatekey-export-error'
install__helm_release__fault__type = 'helm-release-install-error'
delete__helm_release__fault__type = 'helm-release-delete-error'
check__pod_status__fault__type = 'check-pod-status-error'
kubernetes__connectivity__fault_type = 'kubernetes-cluster-connection-error'
helm__version__fault__type = 'helm-not-updated-error'
check__helm_version__fault__type = 'helm-version-check-error'
helm__installation__fault__type = 'helm-not-installed-error'
check__helm_installation__fault__type = 'check-helm-installed-error'
get__helm_registery__path__fault__type = 'helm-registry-path-fetch-error'
pull__helm_chart__fault__type = 'helm-chart-pull-error'
export__helm_chart__fault__type = 'helm-chart-export-error'
get__kubernetes__version__fault__type = 'kubernetes-get-version-error'
get__kubernetes__distro__fault__type = 'kubernetes-get-distribution-error'
get__kubernetes__namespace__fault__type = 'kubernetes-get-namespace-error'
update__agent__success = 'Agents for Connected Cluster {} have been updated successfully'
update__agent__failure = 'Error while updating agents. Please run "kubectl get pods -n azure-arc" to check the pods in case of timeout error. Error: {}'
cluster__info__not__found__type = 'Error while finding current cluster server details'
kubeconfig__failed__to__load__fault__type = 'failed-to-load-kubeconfig-file'
proxy__cert__path__does__not__exist__fault__type = 'proxy-cert-path-does-not-exist-error'
proxy__cert__path__does__not__exist__error = 'Proxy cert path {} does not exist. Please check the path provided' |
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n, res = len(prices), 0
if n < 2:
return 0
if k > n // 2:
for i in range(1, n):
if prices[i] > prices[i - 1]:
res += prices[i] - prices[i - 1]
return res
hold, sold = [float('-inf')] * (k + 1), [0] * (k + 1)
for price in prices:
for j in range(1, k + 1):
hold[j] = max(hold[j], sold[j - 1] - price)
sold[j] = max(sold[j], hold[j] + price)
return sold[k]
| class Solution:
def max_profit(self, k: int, prices: List[int]) -> int:
(n, res) = (len(prices), 0)
if n < 2:
return 0
if k > n // 2:
for i in range(1, n):
if prices[i] > prices[i - 1]:
res += prices[i] - prices[i - 1]
return res
(hold, sold) = ([float('-inf')] * (k + 1), [0] * (k + 1))
for price in prices:
for j in range(1, k + 1):
hold[j] = max(hold[j], sold[j - 1] - price)
sold[j] = max(sold[j], hold[j] + price)
return sold[k] |
def proper_divisors_sum(n):
return sum(a for a in xrange(1, n) if not n % a)
def amicable_numbers(a, b):
return proper_divisors_sum(a) == b and proper_divisors_sum(b) == a
# def amicable_numbers(a, b):
# # this works after multiple submissions to get lucky on random inputs
# return sum(c for c in xrange(1, a) if not a % c) == b
| def proper_divisors_sum(n):
return sum((a for a in xrange(1, n) if not n % a))
def amicable_numbers(a, b):
return proper_divisors_sum(a) == b and proper_divisors_sum(b) == a |
MESSAGE_TIMESPAN = 2000
SIMULATED_DATA = False
I2C_ADDRESS = 0x77
GPIO_PIN_ADDRESS = 24
BLINK_TIMESPAN = 1000
| message_timespan = 2000
simulated_data = False
i2_c_address = 119
gpio_pin_address = 24
blink_timespan = 1000 |
pkgname = "evolution-data-server"
pkgver = "3.44.0"
pkgrel = 0
build_style = "cmake"
# TODO: libgdata
configure_args = [
"-DENABLE_GOOGLE=OFF", "-DWITH_LIBDB=OFF",
"-DSYSCONF_INSTALL_DIR=/etc", "-DENABLE_INTROSPECTION=ON",
"-DENABLE_VALA_BINDINGS=ON",
]
hostmakedepends = [
"cmake", "ninja", "pkgconf", "flex", "glib-devel", "gperf",
"gobject-introspection", "gettext-tiny", "vala", "perl",
]
makedepends = [
"libglib-devel", "libcanberra-devel", "libical-devel", "heimdal-devel",
"webkitgtk-devel", "libsecret-devel", "gnome-online-accounts-devel",
"gcr-devel", "sqlite-devel", "libgweather-devel", "libsoup-devel",
"json-glib-devel", "nss-devel", "nspr-devel", "vala-devel",
"openldap-devel",
]
checkdepends = ["dbus"]
pkgdesc = "Centralized access to appointments and contacts"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.0-or-later"
url = "https://gitlab.gnome.org/GNOME/evolution-data-server"
source = f"$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz"
sha256 = "0d8881b5c51e1b91761b1945db264a46aabf54a73eea1ca8f448b207815d582e"
# internally passes some stuff that only goes to linker
tool_flags = {"CFLAGS": ["-Wno-unused-command-line-argument"]}
options = ["!cross"]
def post_install(self):
self.rm(self.destdir / "usr/lib/systemd", recursive = True)
@subpackage("evolution-data-server-devel")
def _devel(self):
return self.default_devel()
| pkgname = 'evolution-data-server'
pkgver = '3.44.0'
pkgrel = 0
build_style = 'cmake'
configure_args = ['-DENABLE_GOOGLE=OFF', '-DWITH_LIBDB=OFF', '-DSYSCONF_INSTALL_DIR=/etc', '-DENABLE_INTROSPECTION=ON', '-DENABLE_VALA_BINDINGS=ON']
hostmakedepends = ['cmake', 'ninja', 'pkgconf', 'flex', 'glib-devel', 'gperf', 'gobject-introspection', 'gettext-tiny', 'vala', 'perl']
makedepends = ['libglib-devel', 'libcanberra-devel', 'libical-devel', 'heimdal-devel', 'webkitgtk-devel', 'libsecret-devel', 'gnome-online-accounts-devel', 'gcr-devel', 'sqlite-devel', 'libgweather-devel', 'libsoup-devel', 'json-glib-devel', 'nss-devel', 'nspr-devel', 'vala-devel', 'openldap-devel']
checkdepends = ['dbus']
pkgdesc = 'Centralized access to appointments and contacts'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'LGPL-2.0-or-later'
url = 'https://gitlab.gnome.org/GNOME/evolution-data-server'
source = f'$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz'
sha256 = '0d8881b5c51e1b91761b1945db264a46aabf54a73eea1ca8f448b207815d582e'
tool_flags = {'CFLAGS': ['-Wno-unused-command-line-argument']}
options = ['!cross']
def post_install(self):
self.rm(self.destdir / 'usr/lib/systemd', recursive=True)
@subpackage('evolution-data-server-devel')
def _devel(self):
return self.default_devel() |
budget = float(input())
name = "Hello, there!"
count = 0
diff_count = 0
fee = 0
while True:
name = input()
if name == "Stop":
print(f"You bought {count} products for {fee:.2f} leva.")
break
price = float(input())
diff_count += 1
if diff_count%3 == 0:
price = price / 2
if price > budget:
print(f"You don't have enough money!")
print (f"You need {price-budget:.2f} leva!")
break
budget -= price
fee += price
count += 1
| budget = float(input())
name = 'Hello, there!'
count = 0
diff_count = 0
fee = 0
while True:
name = input()
if name == 'Stop':
print(f'You bought {count} products for {fee:.2f} leva.')
break
price = float(input())
diff_count += 1
if diff_count % 3 == 0:
price = price / 2
if price > budget:
print(f"You don't have enough money!")
print(f'You need {price - budget:.2f} leva!')
break
budget -= price
fee += price
count += 1 |
'''Taking the input of CIPHERTEXT from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Input = input("Enter ciphertext:")
Input = Input.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Input:
if i in NotRecog:
Input = Input.replace(i,'')
'''Taking the input of KEY from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Key = input("Enter key:")
Key = Key.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Key:
if i in NotRecog:
Key = Key.replace(i,'')
'''Making the KEYWORD which will be used to decipher the ciphertext
Keyword is made on the basis of two things:
1) LENGTH of the Ciphertext = Keyword
2) The KEY is REPEATED again and again till the length is statisfied
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword:HippoHippo'''
Keyword = ''
for i in range(0,len(Input)):
if len(Keyword)<=len(Input):
if len(Input)==len(Key):
n = len(Input)
Keyword += Key[0:n]
elif len(Input)-len(Key)<=len(Input)-len(Keyword):
n = len(Input)-len(Key)
Keyword += Key[0:n]
else:
n = len(Input)-len(Keyword)
Keyword += Key[0:n]
if len(Keyword)==len(Input):
break
'''Deciphering the Ciphertext using the Keyword and TempLists
The AlphaList and TempLists are reversed,i.e.,A will be Z, B will be Y and so on, This is the main difference between
Vigenere and Beaufort Cipher'''
AlphaList = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
Result = ''
'''Creation of TempLists:
TempLists(Required row of letters from vigenere grid) is made on the basis of Caesar shift.
A Beaufort Square has 26 Rows & Columns each labeled as a LETTER of the ALPHABET in ORDER.
Each row is shifted(Caesar Shift) according to the formula: Index/Number of Label Letter-1
Ex: Let the row be Z
Number of Label Letter: 26
Shift: 26-1=25
After Shifting the List is reversed on the basis explained above.
Deciphering:
Deciphering is done in 3 steps:
1) A letter of the Keyword is taken
2) Corresponding(Same index/number) Letter of Ciphertext is searched in the row of TempLists
3) After finding the Ciphertext Letter the Column Letter/Index(Check the letter at same index in original AlphaList) is
the Deciphered Letter
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword: Hippohippo
Let letter be H
Corresponding Letter in Ciphertext: A
TempList: ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I']
Location of A in TempList: Index 7
In AlphaList at Index 7 is H
ColumnName/Index: H
Deciphered Letter: H'''
for i in range(0,len(Keyword)):
TempLi = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
if Keyword[i]=='A':
Result += Input[i]
else:
for j in range(0,AlphaList.index(Keyword[i])):
TempLi+=[TempLi.pop(0)]
L = Input[i]
n = TempLi.index(L)
Result += AlphaList[25-n]
print("Deciphered text:",Result) | """Taking the input of CIPHERTEXT from the user and removing UNWANTED CHARACTERS and/or WHITESPACES"""
input = input('Enter ciphertext:')
input = Input.upper()
not_recog = '`~1234567890!@#$%^&*()-_=+[{]}\\|\'";:.>/?,< '
for i in Input:
if i in NotRecog:
input = Input.replace(i, '')
'Taking the input of KEY from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'
key = input('Enter key:')
key = Key.upper()
not_recog = '`~1234567890!@#$%^&*()-_=+[{]}\\|\'";:.>/?,< '
for i in Key:
if i in NotRecog:
key = Key.replace(i, '')
'Making the KEYWORD which will be used to decipher the ciphertext\nKeyword is made on the basis of two things:\n1) LENGTH of the Ciphertext = Keyword\n2) The KEY is REPEATED again and again till the length is statisfied\nEx: Ciphertext: Aeeealuyel\n Key: Hippo\n Keyword:HippoHippo'
keyword = ''
for i in range(0, len(Input)):
if len(Keyword) <= len(Input):
if len(Input) == len(Key):
n = len(Input)
keyword += Key[0:n]
elif len(Input) - len(Key) <= len(Input) - len(Keyword):
n = len(Input) - len(Key)
keyword += Key[0:n]
else:
n = len(Input) - len(Keyword)
keyword += Key[0:n]
if len(Keyword) == len(Input):
break
'Deciphering the Ciphertext using the Keyword and TempLists\nThe AlphaList and TempLists are reversed,i.e.,A will be Z, B will be Y and so on, This is the main difference between \nVigenere and Beaufort Cipher'
alpha_list = ['Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
result = ''
"Creation of TempLists:\nTempLists(Required row of letters from vigenere grid) is made on the basis of Caesar shift.\nA Beaufort Square has 26 Rows & Columns each labeled as a LETTER of the ALPHABET in ORDER.\nEach row is shifted(Caesar Shift) according to the formula: Index/Number of Label Letter-1\nEx: Let the row be Z\n Number of Label Letter: 26\n Shift: 26-1=25\nAfter Shifting the List is reversed on the basis explained above.\n\nDeciphering:\nDeciphering is done in 3 steps:\n1) A letter of the Keyword is taken\n2) Corresponding(Same index/number) Letter of Ciphertext is searched in the row of TempLists\n3) After finding the Ciphertext Letter the Column Letter/Index(Check the letter at same index in original AlphaList) is\nthe Deciphered Letter\nEx: Ciphertext: Aeeealuyel\n Key: Hippo\n Keyword: Hippohippo\n Let letter be H\n Corresponding Letter in Ciphertext: A\n TempList: ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I']\n Location of A in TempList: Index 7\n In AlphaList at Index 7 is H\n ColumnName/Index: H\n Deciphered Letter: H"
for i in range(0, len(Keyword)):
temp_li = ['Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
if Keyword[i] == 'A':
result += Input[i]
else:
for j in range(0, AlphaList.index(Keyword[i])):
temp_li += [TempLi.pop(0)]
l = Input[i]
n = TempLi.index(L)
result += AlphaList[25 - n]
print('Deciphered text:', Result) |
class Geometric:
def Area(self, x, y):
return x * y
| class Geometric:
def area(self, x, y):
return x * y |
# Solution to day 10 of AOC 2015, Elves Look, Elves Say
# https://adventofcode.com/2015/day/10
new_sequence = '1113222113'
for i in range(50):
print('i, len(new_sequence)', i, len(new_sequence))
sequence = new_sequence
run_digit = None
run_length = 0
new_sequence = ''
for head in sequence:
if run_digit is not None and run_digit != head: # Time to add to new_sequence.
new_sequence = new_sequence + str(run_length) + run_digit
# Start new run.
run_length = 1
else:
run_length += 1
run_digit = head
new_sequence = new_sequence + str(run_length) + run_digit # Time to add to new_sequence.
# print('sequence, new_sequence:', new_sequence)
print('Solution:', len(new_sequence))
| new_sequence = '1113222113'
for i in range(50):
print('i, len(new_sequence)', i, len(new_sequence))
sequence = new_sequence
run_digit = None
run_length = 0
new_sequence = ''
for head in sequence:
if run_digit is not None and run_digit != head:
new_sequence = new_sequence + str(run_length) + run_digit
run_length = 1
else:
run_length += 1
run_digit = head
new_sequence = new_sequence + str(run_length) + run_digit
print('Solution:', len(new_sequence)) |
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
head = list1
for i in range(a - 1):
list1 = list1.next
a_1 = list1
for i in range(b - a + 1):
list1 = list1.next
b_1 = list1.next
list1.next = None
a_1.next = list2
while list2.next:
list2 = list2.next
list2.next = b_1
return head
| class Solution:
def merge_in_between(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
head = list1
for i in range(a - 1):
list1 = list1.next
a_1 = list1
for i in range(b - a + 1):
list1 = list1.next
b_1 = list1.next
list1.next = None
a_1.next = list2
while list2.next:
list2 = list2.next
list2.next = b_1
return head |
# problem3.py
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
number = 600851475143
divider = 2
while number != 1:
if number % divider == 0:
number = number / divider
print(divider)
else:
divider += 1
| number = 600851475143
divider = 2
while number != 1:
if number % divider == 0:
number = number / divider
print(divider)
else:
divider += 1 |
class Solution:
# Accumulator List (Accepted), O(n) time and space
def waysToMakeFair(self, nums: List[int]) -> int:
acc = []
is_even = True
n = len(nums)
for i in range(n):
even, odd = acc[i-1] if i > 0 else (0, 0)
if is_even:
even += nums[i]
else:
odd += nums[i]
is_even = not is_even
acc.append((even, odd))
res = 0
for i in range(n):
even = odd = 0
if i > 0:
even += acc[i-1][0]
odd += acc[i-1][1]
if i < n-1:
even += acc[n-1][1] - acc[i][1]
odd += acc[n-1][0] - acc[i][0]
if even == odd:
res += 1
return res
# Two Sum Pairs for even and odd (Top Voted), O(n) time, O(1) space
def waysToMakeFair(self, A: List[int]) -> int:
s1, s2 = [0, 0], [sum(A[0::2]), sum(A[1::2])]
res = 0
for i, a in enumerate(A):
s2[i % 2] -= a
res += s1[0] + s2[1] == s1[1] + s2[0]
s1[i % 2] += a
return res
| class Solution:
def ways_to_make_fair(self, nums: List[int]) -> int:
acc = []
is_even = True
n = len(nums)
for i in range(n):
(even, odd) = acc[i - 1] if i > 0 else (0, 0)
if is_even:
even += nums[i]
else:
odd += nums[i]
is_even = not is_even
acc.append((even, odd))
res = 0
for i in range(n):
even = odd = 0
if i > 0:
even += acc[i - 1][0]
odd += acc[i - 1][1]
if i < n - 1:
even += acc[n - 1][1] - acc[i][1]
odd += acc[n - 1][0] - acc[i][0]
if even == odd:
res += 1
return res
def ways_to_make_fair(self, A: List[int]) -> int:
(s1, s2) = ([0, 0], [sum(A[0::2]), sum(A[1::2])])
res = 0
for (i, a) in enumerate(A):
s2[i % 2] -= a
res += s1[0] + s2[1] == s1[1] + s2[0]
s1[i % 2] += a
return res |
#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
idx = 0
results = []
error = None
while list_division and idx < list_length:
try:
results.append(my_list_1[idx] / my_list_2[idx])
except ZeroDivisionError:
error = "division by 0"
results.append(0)
except(TypeError, ValueError):
error = "wrong type"
results.append(0)
except IndexError:
error = "out of range"
results.append(0)
finally:
if error is not None:
print(error)
error = None
idx += 1
return results
| def list_division(my_list_1, my_list_2, list_length):
idx = 0
results = []
error = None
while list_division and idx < list_length:
try:
results.append(my_list_1[idx] / my_list_2[idx])
except ZeroDivisionError:
error = 'division by 0'
results.append(0)
except (TypeError, ValueError):
error = 'wrong type'
results.append(0)
except IndexError:
error = 'out of range'
results.append(0)
finally:
if error is not None:
print(error)
error = None
idx += 1
return results |
# Section 6.2.5 snippets
country_capitals1 = {'Belgium': 'Brussels',
'Haiti': 'Port-au-Prince'}
country_capitals2 = {'Nepal': 'Kathmandu',
'Uruguay': 'Montevideo'}
country_capitals3 = {'Haiti': 'Port-au-Prince',
'Belgium': 'Brussels'}
country_capitals1 == country_capitals2
country_capitals1 == country_capitals3
country_capitals1 != country_capitals2
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
| country_capitals1 = {'Belgium': 'Brussels', 'Haiti': 'Port-au-Prince'}
country_capitals2 = {'Nepal': 'Kathmandu', 'Uruguay': 'Montevideo'}
country_capitals3 = {'Haiti': 'Port-au-Prince', 'Belgium': 'Brussels'}
country_capitals1 == country_capitals2
country_capitals1 == country_capitals3
country_capitals1 != country_capitals2 |
N = int(input())
Y = 0
for _ in range(N):
t = input().split()
x = float(t[0])
u = t[1]
if u == 'JPY':
Y += x
elif u == 'BTC':
Y += x * 380000.0
print(Y)
| n = int(input())
y = 0
for _ in range(N):
t = input().split()
x = float(t[0])
u = t[1]
if u == 'JPY':
y += x
elif u == 'BTC':
y += x * 380000.0
print(Y) |
def reverse(x: int) -> int:
neg = x < 0
if neg:
x *= -1
result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if not neg else -1 * result
assert reverse(123) == 321
assert reverse(-123) == -321
| def reverse(x: int) -> int:
neg = x < 0
if neg:
x *= -1
result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if not neg else -1 * result
assert reverse(123) == 321
assert reverse(-123) == -321 |
matriz = [[], [], []]
for i in range(0, 3):
matriz[0].append(int(input(f'Digite um valor para [{0}, {i}]: ')))
for i in range(0, 3):
matriz[1].append(int(input(f'Digite um valor para [{1}, {i}]: ')))
for i in range(0, 3):
matriz[2].append(int(input(f'Digite um valor para [{2}, {i}]: ')))
print(f'{matriz[0]}\n{matriz[1]}\n{matriz[2]}')
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matriz[[l][c]] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('-=' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l] [c]}]', end='')
print()
| matriz = [[], [], []]
for i in range(0, 3):
matriz[0].append(int(input(f'Digite um valor para [{0}, {i}]: ')))
for i in range(0, 3):
matriz[1].append(int(input(f'Digite um valor para [{1}, {i}]: ')))
for i in range(0, 3):
matriz[2].append(int(input(f'Digite um valor para [{2}, {i}]: ')))
print(f'{matriz[0]}\n{matriz[1]}\n{matriz[2]}')
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matriz[[l][c]] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('-=' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]}]', end='')
print() |
class Solution:
def __init__(self):
self.map = {}
def cloneGraph(self, node):
if node is None:
return None
next = UndirectedGraphNode(node.label)
self.map[str(node.label)] = next
for tmp in node.neighbors:
if str(tmp.label) in self.map:
next.neighbors.append(self.map.get(str(tmp.label)))
else:
next.neighbors.append(self.cloneGraph(tmp))
return self.map.get(str(node.label))
| class Solution:
def __init__(self):
self.map = {}
def clone_graph(self, node):
if node is None:
return None
next = undirected_graph_node(node.label)
self.map[str(node.label)] = next
for tmp in node.neighbors:
if str(tmp.label) in self.map:
next.neighbors.append(self.map.get(str(tmp.label)))
else:
next.neighbors.append(self.cloneGraph(tmp))
return self.map.get(str(node.label)) |
with open('input.txt') as f:
octopus = list(map(lambda line: list(map(int, line.strip())), f.readlines()))
def print_grid(grid):
for line in grid:
print(''.join(map(str, line)))
def update(grid):
flash_count = 0
# increase all
flashed = set()
to_updates = []
for row in range(len(grid)):
for col in range(len(grid[0])):
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(
list(filter(
lambda x: x[0] >= 0 and x[0] < len(grid) and x[1] >= 0 and x[1] < len(grid[0]),
[(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)]
))
)
# loop update
while len(to_updates) > 0:
row, col = to_updates.pop()
if (row, col) in flashed: continue
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(
list(filter(
lambda x: x[0] >= 0 and x[0] < len(grid) and x[1] >= 0 and x[1] < len(grid[0]),
[(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)]
))
)
# clear
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] >= 10:
grid[row][col] = 0
flash_count += 1
def check_all_flash(grid):
return all(map(lambda line: sum(line) == 0, grid))
res = 0
while True:
update(octopus)
res += 1
if check_all_flash(octopus):
break
print(res)
| with open('input.txt') as f:
octopus = list(map(lambda line: list(map(int, line.strip())), f.readlines()))
def print_grid(grid):
for line in grid:
print(''.join(map(str, line)))
def update(grid):
flash_count = 0
flashed = set()
to_updates = []
for row in range(len(grid)):
for col in range(len(grid[0])):
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(list(filter(lambda x: x[0] >= 0 and x[0] < len(grid) and (x[1] >= 0) and (x[1] < len(grid[0])), [(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)])))
while len(to_updates) > 0:
(row, col) = to_updates.pop()
if (row, col) in flashed:
continue
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(list(filter(lambda x: x[0] >= 0 and x[0] < len(grid) and (x[1] >= 0) and (x[1] < len(grid[0])), [(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)])))
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] >= 10:
grid[row][col] = 0
flash_count += 1
def check_all_flash(grid):
return all(map(lambda line: sum(line) == 0, grid))
res = 0
while True:
update(octopus)
res += 1
if check_all_flash(octopus):
break
print(res) |
#
# PySNMP MIB module CISCO-FIPS-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-FIPS-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:41:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
NotificationType, Bits, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32, IpAddress, iso, Gauge32, MibIdentifier, ModuleIdentity, Unsigned32, ObjectIdentity, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Integer32", "IpAddress", "iso", "Gauge32", "MibIdentifier", "ModuleIdentity", "Unsigned32", "ObjectIdentity", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoFipsStatsMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 999999))
ciscoFipsStatsMIB.setRevisions(('2003-03-10 00:00',))
if mibBuilder.loadTexts: ciscoFipsStatsMIB.setLastUpdated('200303100000Z')
if mibBuilder.loadTexts: ciscoFipsStatsMIB.setOrganization('Cisco Systems, Inc.')
ciscoFipsStatsMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 0))
ciscoFipsStatsMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1))
ciscoFipsStatsMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2))
cfipsStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1))
cfipsStatsGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1))
cfipsPostStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("running", 1), ("passed", 2), ("failed", 3), ("notAvailable", 4))).clone('notAvailable')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cfipsPostStatus.setStatus('current')
ciscoFipsStatsMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1))
ciscoFipsStatsMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2))
ciscoFipsStatsMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1, 1)).setObjects(("CISCO-FIPS-STATS-MIB", "ciscoFipsStatsMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoFipsStatsMIBCompliance = ciscoFipsStatsMIBCompliance.setStatus('current')
ciscoFipsStatsMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2, 1)).setObjects(("CISCO-FIPS-STATS-MIB", "cfipsPostStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoFipsStatsMIBGroup = ciscoFipsStatsMIBGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-FIPS-STATS-MIB", PYSNMP_MODULE_ID=ciscoFipsStatsMIB, ciscoFipsStatsMIBObjects=ciscoFipsStatsMIBObjects, ciscoFipsStatsMIB=ciscoFipsStatsMIB, ciscoFipsStatsMIBNotifs=ciscoFipsStatsMIBNotifs, ciscoFipsStatsMIBGroup=ciscoFipsStatsMIBGroup, cfipsPostStatus=cfipsPostStatus, ciscoFipsStatsMIBCompliance=ciscoFipsStatsMIBCompliance, ciscoFipsStatsMIBGroups=ciscoFipsStatsMIBGroups, ciscoFipsStatsMIBConform=ciscoFipsStatsMIBConform, ciscoFipsStatsMIBCompliances=ciscoFipsStatsMIBCompliances, cfipsStats=cfipsStats, cfipsStatsGlobal=cfipsStatsGlobal)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(notification_type, bits, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, integer32, ip_address, iso, gauge32, mib_identifier, module_identity, unsigned32, object_identity, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Bits', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'Integer32', 'IpAddress', 'iso', 'Gauge32', 'MibIdentifier', 'ModuleIdentity', 'Unsigned32', 'ObjectIdentity', 'Counter32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
cisco_fips_stats_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 999999))
ciscoFipsStatsMIB.setRevisions(('2003-03-10 00:00',))
if mibBuilder.loadTexts:
ciscoFipsStatsMIB.setLastUpdated('200303100000Z')
if mibBuilder.loadTexts:
ciscoFipsStatsMIB.setOrganization('Cisco Systems, Inc.')
cisco_fips_stats_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 0))
cisco_fips_stats_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1))
cisco_fips_stats_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2))
cfips_stats = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1))
cfips_stats_global = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1))
cfips_post_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('running', 1), ('passed', 2), ('failed', 3), ('notAvailable', 4))).clone('notAvailable')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cfipsPostStatus.setStatus('current')
cisco_fips_stats_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1))
cisco_fips_stats_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2))
cisco_fips_stats_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1, 1)).setObjects(('CISCO-FIPS-STATS-MIB', 'ciscoFipsStatsMIBGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_fips_stats_mib_compliance = ciscoFipsStatsMIBCompliance.setStatus('current')
cisco_fips_stats_mib_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2, 1)).setObjects(('CISCO-FIPS-STATS-MIB', 'cfipsPostStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_fips_stats_mib_group = ciscoFipsStatsMIBGroup.setStatus('current')
mibBuilder.exportSymbols('CISCO-FIPS-STATS-MIB', PYSNMP_MODULE_ID=ciscoFipsStatsMIB, ciscoFipsStatsMIBObjects=ciscoFipsStatsMIBObjects, ciscoFipsStatsMIB=ciscoFipsStatsMIB, ciscoFipsStatsMIBNotifs=ciscoFipsStatsMIBNotifs, ciscoFipsStatsMIBGroup=ciscoFipsStatsMIBGroup, cfipsPostStatus=cfipsPostStatus, ciscoFipsStatsMIBCompliance=ciscoFipsStatsMIBCompliance, ciscoFipsStatsMIBGroups=ciscoFipsStatsMIBGroups, ciscoFipsStatsMIBConform=ciscoFipsStatsMIBConform, ciscoFipsStatsMIBCompliances=ciscoFipsStatsMIBCompliances, cfipsStats=cfipsStats, cfipsStatsGlobal=cfipsStatsGlobal) |
N = int(input())
a = list(map(int, input().split()))
s = float("inf")
for i in range(min(a), max(a) + 1):
t = 0
for j in a:
t += (j - i) ** 2
s = min(s, t)
print(s)
| n = int(input())
a = list(map(int, input().split()))
s = float('inf')
for i in range(min(a), max(a) + 1):
t = 0
for j in a:
t += (j - i) ** 2
s = min(s, t)
print(s) |
class LoginBase():
freeTimeExpires = -1
def __init__(self, cr):
self.cr = cr
def sendLoginMsg(self, loginName, password, createFlag):
pass
def getErrorCode(self):
return 0
def needToSetParentPassword(self):
return 0 | class Loginbase:
free_time_expires = -1
def __init__(self, cr):
self.cr = cr
def send_login_msg(self, loginName, password, createFlag):
pass
def get_error_code(self):
return 0
def need_to_set_parent_password(self):
return 0 |
class RequiredClass:
pass
def main():
required = RequiredClass()
print(required)
if __name__ == '__main__':
main()
| class Requiredclass:
pass
def main():
required = required_class()
print(required)
if __name__ == '__main__':
main() |
def join_topic(part1: str, part2: str):
p1 = part1.rstrip('/')
p2 = part2.rstrip('/')
return p1 + '/' + p2
| def join_topic(part1: str, part2: str):
p1 = part1.rstrip('/')
p2 = part2.rstrip('/')
return p1 + '/' + p2 |
# encoding: utf-8
class DropShadowFilter(object):
def __init__(self, distance=4.0, angle=45.0, color=0, alpha=1.0,
blurX=4.0, blurY=4.0, strength=1.0, quality=1,
inner=False, knockout=False, hideObject=False):
self._type = 'DropShadowFilter'
self.distance = distance
self.angle = angle
self.color = color
self.alpha = alpha
self.blurX = blurX
self.blurY = blurY
self.strength = strength
self.quality = quality
self.inner = inner
self.knockout = knockout
self.hideObject = hideObject
def clone(self):
return DropShadowFilter(self.distance, self.angle, self.color,
self.alpha, self.blurX, self.blurY,
self.strength, self.quality,
self.inner, self.knockout,
self.hideObject) | class Dropshadowfilter(object):
def __init__(self, distance=4.0, angle=45.0, color=0, alpha=1.0, blurX=4.0, blurY=4.0, strength=1.0, quality=1, inner=False, knockout=False, hideObject=False):
self._type = 'DropShadowFilter'
self.distance = distance
self.angle = angle
self.color = color
self.alpha = alpha
self.blurX = blurX
self.blurY = blurY
self.strength = strength
self.quality = quality
self.inner = inner
self.knockout = knockout
self.hideObject = hideObject
def clone(self):
return drop_shadow_filter(self.distance, self.angle, self.color, self.alpha, self.blurX, self.blurY, self.strength, self.quality, self.inner, self.knockout, self.hideObject) |
#!/usr/bin/env python3
class Solution:
def setZeroes(self, matrix):
nrow, ncol = len(matrix), len(matrix[0])
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 0:
matrix[i][j] = 'X'
for k in range(ncol):
if matrix[i][k] != 0:
matrix[i][k] = 'X'
for k in range(nrow):
if matrix[k][j] != 0:
matrix[k][j] = 'X'
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 'X':
matrix[i][j] = 0
for i in range(nrow):
print(matrix[i])
matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
matrix = [[1,1,1],[1,0,1],[1,1,1]]
sol = Solution()
sol.setZeroes(matrix)
| class Solution:
def set_zeroes(self, matrix):
(nrow, ncol) = (len(matrix), len(matrix[0]))
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 0:
matrix[i][j] = 'X'
for k in range(ncol):
if matrix[i][k] != 0:
matrix[i][k] = 'X'
for k in range(nrow):
if matrix[k][j] != 0:
matrix[k][j] = 'X'
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 'X':
matrix[i][j] = 0
for i in range(nrow):
print(matrix[i])
matrix = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
sol = solution()
sol.setZeroes(matrix) |
# Parameters
BEHAVIORS = 'behaviors'
STIMULUS_ELEMENTS = 'stimulus_elements'
MECHANISM_NAME = 'mechanism'
START_V = 'start_v'
START_VSS = 'start_vss'
START_W = 'start_w'
ALPHA_V = 'alpha_v'
ALPHA_VSS = 'alpha_vss'
ALPHA_W = 'alpha_w'
BETA = 'beta'
MU = 'mu'
DISCOUNT = 'discount'
TRACE = 'trace'
BEHAVIOR_COST = 'behavior_cost'
U = 'u'
LAMBDA = 'lambda'
RESPONSE_REQUIREMENTS = 'response_requirements'
BIND_TRIALS = 'bind_trials'
N_SUBJECTS = 'n_subjects'
TITLE = 'title'
SUBPLOTTITLE = 'subplottitle'
RUNLABEL = 'runlabel'
SUBJECT = 'subject'
XSCALE = 'xscale'
XSCALE_MATCH = 'xscale_match'
PHASES = 'phases'
CUMULATIVE = 'cumulative'
MATCH = 'match'
FILENAME = 'filename'
# Commands
RUN = '@run'
VARIABLES = '@variables'
PHASE = '@phase'
FIGURE = '@figure'
SUBPLOT = '@subplot'
LEGEND = '@legend'
VPLOT = '@vplot'
VSSPLOT = '@vssplot'
WPLOT = '@wplot'
PPLOT = '@pplot'
NPLOT = '@nplot'
VEXPORT = '@vexport'
WEXPORT = '@wexport'
PEXPORT = '@pexport'
NEXPORT = '@nexport'
HEXPORT = '@hexport'
VSSEXPORT = '@vssexport'
# Other
DEFAULT = 'default'
RAND = 'rand'
CHOICE = 'choice'
COUNT = 'count'
COUNT_LINE = 'count_line'
KEYWORDS = (BEHAVIORS,
STIMULUS_ELEMENTS,
MECHANISM_NAME,
START_V,
START_VSS,
START_W,
ALPHA_V,
ALPHA_VSS,
ALPHA_W,
BETA,
MU,
DISCOUNT,
TRACE,
BEHAVIOR_COST,
U,
LAMBDA,
RESPONSE_REQUIREMENTS,
BIND_TRIALS,
N_SUBJECTS,
TITLE,
SUBPLOTTITLE,
RUNLABEL,
SUBJECT,
XSCALE,
XSCALE_MATCH,
PHASES,
CUMULATIVE,
MATCH,
FILENAME,
VARIABLES,
PHASE,
RUN,
FIGURE,
SUBPLOT,
LEGEND,
VPLOT,
VSSPLOT,
WPLOT,
PPLOT,
NPLOT,
VEXPORT,
WEXPORT,
PEXPORT,
NEXPORT,
DEFAULT,
RAND,
COUNT,
COUNT_LINE)
PHASEDIV = '|'
# Properties for evaluation
EVAL_SUBJECT = "subject"
EVAL_RUNLABEL = "runlabel"
# EVAL_EXACTSTEPS = "exact_steps"
EVAL_EXACT = "exact"
# EVAL_EXACTN = "exact_n"
EVAL_CUMULATIVE = "cumulative"
EVAL_PHASES = "phases"
EVAL_FILENAME = "filename"
# Property values for evaluation
EVAL_AVERAGE = "average"
EVAL_ON = "on"
EVAL_OFF = "off"
EVAL_ALL = "all"
| behaviors = 'behaviors'
stimulus_elements = 'stimulus_elements'
mechanism_name = 'mechanism'
start_v = 'start_v'
start_vss = 'start_vss'
start_w = 'start_w'
alpha_v = 'alpha_v'
alpha_vss = 'alpha_vss'
alpha_w = 'alpha_w'
beta = 'beta'
mu = 'mu'
discount = 'discount'
trace = 'trace'
behavior_cost = 'behavior_cost'
u = 'u'
lambda = 'lambda'
response_requirements = 'response_requirements'
bind_trials = 'bind_trials'
n_subjects = 'n_subjects'
title = 'title'
subplottitle = 'subplottitle'
runlabel = 'runlabel'
subject = 'subject'
xscale = 'xscale'
xscale_match = 'xscale_match'
phases = 'phases'
cumulative = 'cumulative'
match = 'match'
filename = 'filename'
run = '@run'
variables = '@variables'
phase = '@phase'
figure = '@figure'
subplot = '@subplot'
legend = '@legend'
vplot = '@vplot'
vssplot = '@vssplot'
wplot = '@wplot'
pplot = '@pplot'
nplot = '@nplot'
vexport = '@vexport'
wexport = '@wexport'
pexport = '@pexport'
nexport = '@nexport'
hexport = '@hexport'
vssexport = '@vssexport'
default = 'default'
rand = 'rand'
choice = 'choice'
count = 'count'
count_line = 'count_line'
keywords = (BEHAVIORS, STIMULUS_ELEMENTS, MECHANISM_NAME, START_V, START_VSS, START_W, ALPHA_V, ALPHA_VSS, ALPHA_W, BETA, MU, DISCOUNT, TRACE, BEHAVIOR_COST, U, LAMBDA, RESPONSE_REQUIREMENTS, BIND_TRIALS, N_SUBJECTS, TITLE, SUBPLOTTITLE, RUNLABEL, SUBJECT, XSCALE, XSCALE_MATCH, PHASES, CUMULATIVE, MATCH, FILENAME, VARIABLES, PHASE, RUN, FIGURE, SUBPLOT, LEGEND, VPLOT, VSSPLOT, WPLOT, PPLOT, NPLOT, VEXPORT, WEXPORT, PEXPORT, NEXPORT, DEFAULT, RAND, COUNT, COUNT_LINE)
phasediv = '|'
eval_subject = 'subject'
eval_runlabel = 'runlabel'
eval_exact = 'exact'
eval_cumulative = 'cumulative'
eval_phases = 'phases'
eval_filename = 'filename'
eval_average = 'average'
eval_on = 'on'
eval_off = 'off'
eval_all = 'all' |
nums_str = []
with open("dane/dane.txt") as f:
lines = []
for line in f:
sline = line.strip()
num = int(sline, 8)
num_str = str(num)
nums_str.append(num_str)
count = 0
for num_str in nums_str:
if num_str[0] == num_str[-1]:
count += 1
print(f"{count=}")
| nums_str = []
with open('dane/dane.txt') as f:
lines = []
for line in f:
sline = line.strip()
num = int(sline, 8)
num_str = str(num)
nums_str.append(num_str)
count = 0
for num_str in nums_str:
if num_str[0] == num_str[-1]:
count += 1
print(f'count={count!r}') |
'''
Provides utility functions for encoding and decoding linestrings using the
Google encoded polyline algorithm.
'''
def encode_coords(coords):
'''
Encodes a polyline using Google's polyline algorithm
See http://code.google.com/apis/maps/documentation/polylinealgorithm.html
for more information.
:param coords: list of Point objects
:type coords: list
:returns: Google-encoded polyline string.
:rtype: string
'''
result = []
prev_lat = 0
prev_lng = 0
for item in coords:
lat, lng = int(item.lat * 1e5), int(item.lng * 1e5)
d_lat = _encode_value(lat - prev_lat)
d_lng = _encode_value(lng - prev_lng)
prev_lat, prev_lng = lat, lng
result.append(d_lat)
result.append(d_lng)
return ''.join(c for r in result for c in r)
def _split_into_chunks(value):
while value >= 32: #2^5, while there are at least 5 bits
# first & with 2^5-1, zeros out all the bits other than the first five
# then OR with 0x20 if another bit chunk follows
yield (value & 31) | 0x20
value >>= 5
yield value
def _encode_value(value):
# Step 2 & 4
value = ~(value << 1) if value < 0 else (value << 1)
# Step 5 - 8
chunks = _split_into_chunks(value)
# Step 9-10
return (chr(chunk + 63) for chunk in chunks)
def decode(point_str):
'''Decodes a polyline that has been encoded using Google's algorithm
http://code.google.com/apis/maps/documentation/polylinealgorithm.html
This is a generic method that returns a list of (latitude, longitude)
tuples.
:param point_str: Encoded polyline string.
:type point_str: string
:returns: List of 2-tuples where each tuple is (latitude, longitude)
:rtype: list
'''
# sone coordinate offset is represented by 4 to 5 binary chunks
coord_chunks = [[]]
for char in point_str:
# convert each character to decimal from ascii
value = ord(char) - 63
# values that have a chunk following have an extra 1 on the left
split_after = not (value & 0x20)
value &= 0x1F
coord_chunks[-1].append(value)
if split_after:
coord_chunks.append([])
del coord_chunks[-1]
coords = []
for coord_chunk in coord_chunks:
coord = 0
for i, chunk in enumerate(coord_chunk):
coord |= chunk << (i * 5)
#there is a 1 on the right if the coord is negative
if coord & 0x1:
coord = ~coord #invert
coord >>= 1
coord /= 100000.0
coords.append(coord)
# convert the 1 dimensional list to a 2 dimensional list and offsets to
# actual values
points = []
prev_x = 0
prev_y = 0
for i in xrange(0, len(coords) - 1, 2):
if coords[i] == 0 and coords[i + 1] == 0:
continue
prev_x += coords[i + 1]
prev_y += coords[i]
# a round to 6 digits ensures that the floats are the same as when
# they were encoded
points.append((round(prev_x, 6), round(prev_y, 6)))
return points | """
Provides utility functions for encoding and decoding linestrings using the
Google encoded polyline algorithm.
"""
def encode_coords(coords):
"""
Encodes a polyline using Google's polyline algorithm
See http://code.google.com/apis/maps/documentation/polylinealgorithm.html
for more information.
:param coords: list of Point objects
:type coords: list
:returns: Google-encoded polyline string.
:rtype: string
"""
result = []
prev_lat = 0
prev_lng = 0
for item in coords:
(lat, lng) = (int(item.lat * 100000.0), int(item.lng * 100000.0))
d_lat = _encode_value(lat - prev_lat)
d_lng = _encode_value(lng - prev_lng)
(prev_lat, prev_lng) = (lat, lng)
result.append(d_lat)
result.append(d_lng)
return ''.join((c for r in result for c in r))
def _split_into_chunks(value):
while value >= 32:
yield (value & 31 | 32)
value >>= 5
yield value
def _encode_value(value):
value = ~(value << 1) if value < 0 else value << 1
chunks = _split_into_chunks(value)
return (chr(chunk + 63) for chunk in chunks)
def decode(point_str):
"""Decodes a polyline that has been encoded using Google's algorithm
http://code.google.com/apis/maps/documentation/polylinealgorithm.html
This is a generic method that returns a list of (latitude, longitude)
tuples.
:param point_str: Encoded polyline string.
:type point_str: string
:returns: List of 2-tuples where each tuple is (latitude, longitude)
:rtype: list
"""
coord_chunks = [[]]
for char in point_str:
value = ord(char) - 63
split_after = not value & 32
value &= 31
coord_chunks[-1].append(value)
if split_after:
coord_chunks.append([])
del coord_chunks[-1]
coords = []
for coord_chunk in coord_chunks:
coord = 0
for (i, chunk) in enumerate(coord_chunk):
coord |= chunk << i * 5
if coord & 1:
coord = ~coord
coord >>= 1
coord /= 100000.0
coords.append(coord)
points = []
prev_x = 0
prev_y = 0
for i in xrange(0, len(coords) - 1, 2):
if coords[i] == 0 and coords[i + 1] == 0:
continue
prev_x += coords[i + 1]
prev_y += coords[i]
points.append((round(prev_x, 6), round(prev_y, 6)))
return points |
router = {"host":"192.168.56.1",
"port":"830",
"username":"cisco",
"password":"cisco123!",
"hostkey_verify":"False"
} | router = {'host': '192.168.56.1', 'port': '830', 'username': 'cisco', 'password': 'cisco123!', 'hostkey_verify': 'False'} |
class Proxy:
def __init__(self, host, port):
self.host=host
self.port=port
self.succeed=0
self.fail=0
def markSucceed(self):
self.succeed +=1
def markFail(self):
self.fail +=1
def __str__(self):
return f'http://{self.host}:{self.port}'
| class Proxy:
def __init__(self, host, port):
self.host = host
self.port = port
self.succeed = 0
self.fail = 0
def mark_succeed(self):
self.succeed += 1
def mark_fail(self):
self.fail += 1
def __str__(self):
return f'http://{self.host}:{self.port}' |
lineitem_scheme = ["l_orderkey","l_partkey","l_suppkey","l_linenumber","l_quantity","l_extendedprice",
"l_discount","l_tax","l_returnflag","l_linestatus","l_shipdate","l_commitdate","l_receiptdate","l_shipinstruct",
"l_shipmode","l_comment", "null"]
order_scheme = ["o_orderkey", "o_custkey","o_orderstatus","o_totalprice","o_orderdate","o_orderpriority","o_clerk",
"o_shippriority","o_comment", "null"]
customer_scheme = ["c_custkey","c_name","c_address","c_nationkey","c_phone","c_acctbal","c_mktsegment","c_comment", "null"]
part_scheme = ["p_partkey","p_name","p_mfgr","p_brand","p_type","p_size","p_container","p_retailprice","p_comment","null"]
supplier_scheme = ["s_suppkey","s_name","s_address","s_nationkey","s_phone","s_acctbal","s_comment","null"]
partsupp_scheme = ["ps_partkey","ps_suppkey","ps_availqty","ps_supplycost","ps_comment","null"]
nation_scheme = ["n_nationkey","n_name","n_regionkey","n_comment","null"]
region_scheme = ["r_regionkey" ,"r_name","r_comment","null"]
schema_quotes = ["time","symbol","seq","bid","ask","bsize","asize","is_nbbo"]
schema_trades = ["time","symbol","size","price"] | lineitem_scheme = ['l_orderkey', 'l_partkey', 'l_suppkey', 'l_linenumber', 'l_quantity', 'l_extendedprice', 'l_discount', 'l_tax', 'l_returnflag', 'l_linestatus', 'l_shipdate', 'l_commitdate', 'l_receiptdate', 'l_shipinstruct', 'l_shipmode', 'l_comment', 'null']
order_scheme = ['o_orderkey', 'o_custkey', 'o_orderstatus', 'o_totalprice', 'o_orderdate', 'o_orderpriority', 'o_clerk', 'o_shippriority', 'o_comment', 'null']
customer_scheme = ['c_custkey', 'c_name', 'c_address', 'c_nationkey', 'c_phone', 'c_acctbal', 'c_mktsegment', 'c_comment', 'null']
part_scheme = ['p_partkey', 'p_name', 'p_mfgr', 'p_brand', 'p_type', 'p_size', 'p_container', 'p_retailprice', 'p_comment', 'null']
supplier_scheme = ['s_suppkey', 's_name', 's_address', 's_nationkey', 's_phone', 's_acctbal', 's_comment', 'null']
partsupp_scheme = ['ps_partkey', 'ps_suppkey', 'ps_availqty', 'ps_supplycost', 'ps_comment', 'null']
nation_scheme = ['n_nationkey', 'n_name', 'n_regionkey', 'n_comment', 'null']
region_scheme = ['r_regionkey', 'r_name', 'r_comment', 'null']
schema_quotes = ['time', 'symbol', 'seq', 'bid', 'ask', 'bsize', 'asize', 'is_nbbo']
schema_trades = ['time', 'symbol', 'size', 'price'] |
# https://github.com/adamsaparudin/python-datascience
# if (kondisi)
# if ("adam" == "adam") # True / False
# Task 1
# FIZZBUZZ
# print FIZZ jika bisa dibagi 3,
# print BUZZ jika bisa dibagi 5,
# print FIZZBUZZ jika bisa dibagi 15,
# print angka nya sendiri jika tidak bisa dibagi 3 atau 5
# input 6
# FIZZ
# input 10
# BUZZ
# input 30
# FIZZBUZZ
def print_fizzbuzz(numb):
if (numb % 15) == 0:
return "FIZZBUZZ"
elif (numb % 3) == 0:
print("FIZZ")
elif (numb % 5) == 0:
print("BUZZ")
else:
print( numb)
def tambahan(a, b):
return a + b
def main():
while True:
numb = int(input("Input bilangan bulat: "))
fizz = print_fizzbuzz(numb)
print(fizz)
main() | def print_fizzbuzz(numb):
if numb % 15 == 0:
return 'FIZZBUZZ'
elif numb % 3 == 0:
print('FIZZ')
elif numb % 5 == 0:
print('BUZZ')
else:
print(numb)
def tambahan(a, b):
return a + b
def main():
while True:
numb = int(input('Input bilangan bulat: '))
fizz = print_fizzbuzz(numb)
print(fizz)
main() |
def parse_list_ranges(s,sep='-'):
r = []
x = s.split(',')
for y in x:
z = y.split(sep)
if len(z)==1:
r += [int(z[0])]
else:
r += range(int(z[0]),int(z[1])+1)
return list(r)
def parse_list_floats(s):
x = s.split(',')
return list(map(float, x))
| def parse_list_ranges(s, sep='-'):
r = []
x = s.split(',')
for y in x:
z = y.split(sep)
if len(z) == 1:
r += [int(z[0])]
else:
r += range(int(z[0]), int(z[1]) + 1)
return list(r)
def parse_list_floats(s):
x = s.split(',')
return list(map(float, x)) |
def print_tree(mcts_obj, root_node):
fifo = []
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(
child_node,
mcts_obj.Q[child_node],
mcts_obj.visits[child_node],
q
)
fifo.append(child_node)
print("-")
while fifo:
root_node = fifo.pop()
print("(", root_node, ")")
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(
child_node,
mcts_obj.Q[child_node],
mcts_obj.visits[child_node],
q
)
fifo.append(child_node)
if root_node.children:
print(" ")
def gen_tree_graph(root_node, G):
fifo = []
root_id = str(root_node)
G.add_node(root_id)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node)
while fifo:
root_node = fifo.pop()
root_id = str(root_node)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node)
| def print_tree(mcts_obj, root_node):
fifo = []
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(child_node, mcts_obj.Q[child_node], mcts_obj.visits[child_node], q)
fifo.append(child_node)
print('-')
while fifo:
root_node = fifo.pop()
print('(', root_node, ')')
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(child_node, mcts_obj.Q[child_node], mcts_obj.visits[child_node], q)
fifo.append(child_node)
if root_node.children:
print(' ')
def gen_tree_graph(root_node, G):
fifo = []
root_id = str(root_node)
G.add_node(root_id)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node)
while fifo:
root_node = fifo.pop()
root_id = str(root_node)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node) |
class DataStructure(object):
def __init__(self):
self.name2id = {}
self.id2item = {}
def add_item(self, item_name, item_id, item):
self.name2id[item_name] = item_id
self.id2item[item_id] = item
def search_by_name(self, target_name):
target_id = self.name2id[target_name]
target_item = self.id2item[target_id]
return target_item
def search_by_id(self, target_id):
target_item = self.id2item[target_id]
return target_item
| class Datastructure(object):
def __init__(self):
self.name2id = {}
self.id2item = {}
def add_item(self, item_name, item_id, item):
self.name2id[item_name] = item_id
self.id2item[item_id] = item
def search_by_name(self, target_name):
target_id = self.name2id[target_name]
target_item = self.id2item[target_id]
return target_item
def search_by_id(self, target_id):
target_item = self.id2item[target_id]
return target_item |
class Calendar:
def __init__(self, day, month, year):
print("Clase Base - Calendar")
self.day = day
self.month = month
self.year = year
def __str__(self):
return "{}-{}-{}".format(self.day,
self.month,
self.year) | class Calendar:
def __init__(self, day, month, year):
print('Clase Base - Calendar')
self.day = day
self.month = month
self.year = year
def __str__(self):
return '{}-{}-{}'.format(self.day, self.month, self.year) |
#My favorite song described
#Genre, Artists and Album
Genre = "Bollywood Romance"
Composer = "Amit Trivedi"
Lyricist = "Amitabh Bhattacharya"
Singer_male = "Arijit Singh"
Singer_female = "Nikhita Gandhi"
Album = "Kedarnath"
#YearReleased
YearReleased = 2018
#Duration
DurationInSeconds = 351
print("My favorite song is from the Album " + Album + " and in the genre " + Genre)
print("The artists of this song are :")
print("Composer: " + Composer)
print("Lyricist: " + Lyricist)
print("Singer(Male): " + Singer_male)
print("Singer(Female): " + Singer_female)
print("It was released in the year" , YearReleased , "and has a duration of", DurationInSeconds , "seconds")
| genre = 'Bollywood Romance'
composer = 'Amit Trivedi'
lyricist = 'Amitabh Bhattacharya'
singer_male = 'Arijit Singh'
singer_female = 'Nikhita Gandhi'
album = 'Kedarnath'
year_released = 2018
duration_in_seconds = 351
print('My favorite song is from the Album ' + Album + ' and in the genre ' + Genre)
print('The artists of this song are :')
print('Composer: ' + Composer)
print('Lyricist: ' + Lyricist)
print('Singer(Male): ' + Singer_male)
print('Singer(Female): ' + Singer_female)
print('It was released in the year', YearReleased, 'and has a duration of', DurationInSeconds, 'seconds') |
#!/bin/python
#If player is X, I'm the first player.
#If player is O, I'm the second player.
player = raw_input()
#Read the board now. The board is a 3x3 array filled with X, O or _.
board = []
for i in xrange(0, 3):
board.append(raw_input())
#Proceed with processing and print 2 integers separated by a single space.
#Example: print random.randint(0, 2), random.randint(0, 2)
| player = raw_input()
board = []
for i in xrange(0, 3):
board.append(raw_input()) |
DEFAULT_ENV_NAME = "CartPole-v1"
DEFAULT_ALGORITHM = "random"
DEFAULT_MAX_EPISODES = 1000
DEFAULT_LEARNING_RATE = 0.001
DEFAULT_GAMMA = 0.95
DEFAULT_UPDATE_FREQUENCY = 20
| default_env_name = 'CartPole-v1'
default_algorithm = 'random'
default_max_episodes = 1000
default_learning_rate = 0.001
default_gamma = 0.95
default_update_frequency = 20 |
def initials(name):
parts = name.split(' ')
letters = ''
for part in parts:
letters += part[0]
return letters | def initials(name):
parts = name.split(' ')
letters = ''
for part in parts:
letters += part[0]
return letters |
# Q5. Write a program to implement OOPs concepts in python i.e. inheritance etc.
class Person:
def __init__(self, name, age, address): # constructor
self.name = name
self.age = age
self.address = address
def set_data(self, name, age, address):
self.name = name
self.age = age
self.address = address
def get_data(self):
print('Name : ', self.name)
print('Age : ', self.age)
print('Address : ', self.address)
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_address(self):
return self.address
class Student(Person):
def __init__(self, name, age, address, rollno, course, marksObtained, maximumMarks): # constructor
super().__init__(name, age, address)
self.rollno = rollno
self.course = course
self.marksObtained = marksObtained
self.maximumMarks = maximumMarks
def set_data(self, rollno, course, marksObtained, maximumMarks):
self.rollno = rollno
self.course = course
self.marksObtained = marksObtained
self.maximumMarks = maximumMarks
def get_data(self):
print('Name : ', super().get_name())
print('Age : ', super().get_age())
print('Address : ', super().get_address())
print('Rollno : ', self.rollno)
print('Course : ', self.course)
print('Marks Obtained : ', self.marksObtained)
print('Maximum Marks : ', self.maximumMarks)
print('Percentage : ', '{:.2f}'.format(self.get_percentage()), '%')
def get_rollno(self):
return self.rollno
def get_course(self):
return self.course
def get_marksObtained(self):
return self.marksObtained
def maximumMarks(self):
return self.maximumMarks
def get_percentage(self):
return marksObtained / maximumMarks * 100
print('PERSON DETAILS : ')
name = input('Enter Name of Person : ')
age = int(input('Enter Age of ' + name + ' : '))
address = input('Enter Address of ' + name +' : ')
p1 = Person(name, age, address) # Object of Person Class
print('\nSTUDENT DETAILS : ')
name = input('Enter Name of Student: ')
age = int(input('Enter Age of Student : '))
address = input('Enter Address of Student: ')
rollno = input('Enter Rollno of Student : ')
course = input('Enter Course of Student : ')
marksObtained = float(input('Enter Marks Obtained of Student : '))
maximumMarks = float(input('Enter Maximum Marks of Student : '))
s1 = Student(name, age, address, rollno, course, marksObtained, maximumMarks)
# Printing Person Details
print("\n\nPerson Details are as :")
p1.get_data();
#Printing Student Detatils
print("\n\nStudent Details are as :")
s1.get_data(); | class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def set_data(self, name, age, address):
self.name = name
self.age = age
self.address = address
def get_data(self):
print('Name : ', self.name)
print('Age : ', self.age)
print('Address : ', self.address)
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_address(self):
return self.address
class Student(Person):
def __init__(self, name, age, address, rollno, course, marksObtained, maximumMarks):
super().__init__(name, age, address)
self.rollno = rollno
self.course = course
self.marksObtained = marksObtained
self.maximumMarks = maximumMarks
def set_data(self, rollno, course, marksObtained, maximumMarks):
self.rollno = rollno
self.course = course
self.marksObtained = marksObtained
self.maximumMarks = maximumMarks
def get_data(self):
print('Name : ', super().get_name())
print('Age : ', super().get_age())
print('Address : ', super().get_address())
print('Rollno : ', self.rollno)
print('Course : ', self.course)
print('Marks Obtained : ', self.marksObtained)
print('Maximum Marks : ', self.maximumMarks)
print('Percentage : ', '{:.2f}'.format(self.get_percentage()), '%')
def get_rollno(self):
return self.rollno
def get_course(self):
return self.course
def get_marks_obtained(self):
return self.marksObtained
def maximum_marks(self):
return self.maximumMarks
def get_percentage(self):
return marksObtained / maximumMarks * 100
print('PERSON DETAILS : ')
name = input('Enter Name of Person : ')
age = int(input('Enter Age of ' + name + ' : '))
address = input('Enter Address of ' + name + ' : ')
p1 = person(name, age, address)
print('\nSTUDENT DETAILS : ')
name = input('Enter Name of Student: ')
age = int(input('Enter Age of Student : '))
address = input('Enter Address of Student: ')
rollno = input('Enter Rollno of Student : ')
course = input('Enter Course of Student : ')
marks_obtained = float(input('Enter Marks Obtained of Student : '))
maximum_marks = float(input('Enter Maximum Marks of Student : '))
s1 = student(name, age, address, rollno, course, marksObtained, maximumMarks)
print('\n\nPerson Details are as :')
p1.get_data()
print('\n\nStudent Details are as :')
s1.get_data() |
class PolarPoint():
def __init__(self, angle, radius):
self.angle = angle
self.radius = radius
| class Polarpoint:
def __init__(self, angle, radius):
self.angle = angle
self.radius = radius |
def mu(i, lo=0, hi=None):
hi = hi or len(i.has)
return sum([i.x(i.has[j]) for j in range(lo, hi)]) / (hi - lo)
class Some(o):
"Collect some examples, not all."
hi = 256 # max number of items to collect
def __init__(i, pos=0, txt=" ", inits=[]):
i.pos, i.txt, i.n, i._all, i.sorted = pos, txt, 0, [], False
i.w = -1 if txt[0] == Tab.less else 1
i.nump = txt[0] in Tab.nums
[i.add(x) for x in inits]
def add(i, x):
if x != Tab.skip:
if len(i._all) < Some.hi:
i.update(i._all.append(x))
elif random() < Some.hi / i.n:
i.update(i.replace(x))
return x
def update(i, ignore):
i.sorted = False
i.n += 1
def replace(i, x):
i._all[int(len(i._all) * random())] = x
def all(i):
if not i.sorted:
i._all = sorted(i._all)
i.sorted = True
return i._all
def per(i, p=None, lo=None, hi=None): return per(i.all(), p, lo, hi)
def sd(i, lo=None, hi=None): return sd(i.all(), lo, hi)
def nmusd(i):
return len(i._all), i.per(), i.sd()
def same(i, j):
xn, xmu, xsd = i.nmusd()
yn, ymu, ysd = j.nmusd()
return Ttest(xn, xmu, xsd, yn, ymu, ysd)
class Ttest(o):
small = 0.38 # medium = 1
d = {}
d[95] = [[3, 3.182], [6, 2.447], [12, 2.179],
[24, 2.064], [48, 2.011], [96, 1.985]]
d[99] = [[3, 5.841], [6, 3.707], [12, 3.055],
[24, 2.797], [48, 2.682], [96, 2.625]]
def __init__(i, *lst, conf=95):
xy = Ttest.d[conf]
i.result = i.hedges(Ttest.small, *lst) and i.ttest(xy, *lst)
def hedges(i, threshold, xn, xmu, xsd, yn, ymu, ysd):
# from https://goo.gl/w62iIL
nom = (xn - 1) * xsd ** 2 + (yn - 1) * ysd ** 2
denom = (xn - 1) + (yn - 1)
sp = (nom / denom)**0.5
g = abs(xmu - ymu) / sp
c = 1 - 3.0 / (4 * (xn + yn - 2) - 1)
return g * c > threshold
def ttest(i, xy, xn, xmu, xsd, yn, ymu, ysd, conf=95):
# debugged using https://goo.gl/CRl1Bz
t = (xmu - ymu) / max(10 ** -64, xsd**2 / xn + ysd**2 / yn)**0.5
a = xsd ** 2 / xn
b = ysd ** 2 / yn
df = (a + b)**2 / (10 ** -64 + a**2 / (xn - 1) + b**2 / (yn - 1))
c = i.critical(xy, int(df + 0.5))
return abs(t) > c
def critical(i, xy, df):
x1, y1 = xy[0]
if df < x1:
return y1
for x2, y2 in xy[1:]:
if x1 <= df < x2:
return y1 + (y2 - y1) * (df - x1) / (x2 - x1)
x1, y1 = x2, y2
return y2
| def mu(i, lo=0, hi=None):
hi = hi or len(i.has)
return sum([i.x(i.has[j]) for j in range(lo, hi)]) / (hi - lo)
class Some(o):
"""Collect some examples, not all."""
hi = 256
def __init__(i, pos=0, txt=' ', inits=[]):
(i.pos, i.txt, i.n, i._all, i.sorted) = (pos, txt, 0, [], False)
i.w = -1 if txt[0] == Tab.less else 1
i.nump = txt[0] in Tab.nums
[i.add(x) for x in inits]
def add(i, x):
if x != Tab.skip:
if len(i._all) < Some.hi:
i.update(i._all.append(x))
elif random() < Some.hi / i.n:
i.update(i.replace(x))
return x
def update(i, ignore):
i.sorted = False
i.n += 1
def replace(i, x):
i._all[int(len(i._all) * random())] = x
def all(i):
if not i.sorted:
i._all = sorted(i._all)
i.sorted = True
return i._all
def per(i, p=None, lo=None, hi=None):
return per(i.all(), p, lo, hi)
def sd(i, lo=None, hi=None):
return sd(i.all(), lo, hi)
def nmusd(i):
return (len(i._all), i.per(), i.sd())
def same(i, j):
(xn, xmu, xsd) = i.nmusd()
(yn, ymu, ysd) = j.nmusd()
return ttest(xn, xmu, xsd, yn, ymu, ysd)
class Ttest(o):
small = 0.38
d = {}
d[95] = [[3, 3.182], [6, 2.447], [12, 2.179], [24, 2.064], [48, 2.011], [96, 1.985]]
d[99] = [[3, 5.841], [6, 3.707], [12, 3.055], [24, 2.797], [48, 2.682], [96, 2.625]]
def __init__(i, *lst, conf=95):
xy = Ttest.d[conf]
i.result = i.hedges(Ttest.small, *lst) and i.ttest(xy, *lst)
def hedges(i, threshold, xn, xmu, xsd, yn, ymu, ysd):
nom = (xn - 1) * xsd ** 2 + (yn - 1) * ysd ** 2
denom = xn - 1 + (yn - 1)
sp = (nom / denom) ** 0.5
g = abs(xmu - ymu) / sp
c = 1 - 3.0 / (4 * (xn + yn - 2) - 1)
return g * c > threshold
def ttest(i, xy, xn, xmu, xsd, yn, ymu, ysd, conf=95):
t = (xmu - ymu) / max(10 ** (-64), xsd ** 2 / xn + ysd ** 2 / yn) ** 0.5
a = xsd ** 2 / xn
b = ysd ** 2 / yn
df = (a + b) ** 2 / (10 ** (-64) + a ** 2 / (xn - 1) + b ** 2 / (yn - 1))
c = i.critical(xy, int(df + 0.5))
return abs(t) > c
def critical(i, xy, df):
(x1, y1) = xy[0]
if df < x1:
return y1
for (x2, y2) in xy[1:]:
if x1 <= df < x2:
return y1 + (y2 - y1) * (df - x1) / (x2 - x1)
(x1, y1) = (x2, y2)
return y2 |
'''
Truth tables for logical expressions.
Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail).
A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)).
Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables.
Example:
* table(A,B,and(A,or(A,B))).
true true true
true fail true
fail true fail
fail fail fail
'''
# predicate funtion return true if any one is true or both A and B are true, oterwise return false
def predicateOr(A, B):
if A or B:
return True
else:
return False
# predicate function returns true if both A and B are False or one of them is False
def predicateNand(A, B):
if not(A and B):
return True
else:
return False
# predicate function return true only if both A and B are true,otherwise returns false
def predicateAnd(A, B):
if A and B:
return True
else:
return False
# for two input A and B inputs to predicate functions are
A = [True, True, False, False]
B = [True, False, True, False]
print('Result for: and(A,or(A,B))')
# finding output of given expression with all possible values of A and B
for i in range(len(A)):
print(f"{A[i]}\t{B[i]}\t{predicateAnd(A[i],predicateOr(A[i],B[i]))}")
print('\nResult for: and( or (A, B), nand(A, B))')
for i in range(len(A)):
output = predicateAnd(predicateOr(A[i], B[i]), predicateNand(A[i], B[i]))
print(f"{A[i]}\t{B[i]}\t{output}")
| """
Truth tables for logical expressions.
Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail).
A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)).
Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables.
Example:
* table(A,B,and(A,or(A,B))).
true true true
true fail true
fail true fail
fail fail fail
"""
def predicate_or(A, B):
if A or B:
return True
else:
return False
def predicate_nand(A, B):
if not (A and B):
return True
else:
return False
def predicate_and(A, B):
if A and B:
return True
else:
return False
a = [True, True, False, False]
b = [True, False, True, False]
print('Result for: and(A,or(A,B))')
for i in range(len(A)):
print(f'{A[i]}\t{B[i]}\t{predicate_and(A[i], predicate_or(A[i], B[i]))}')
print('\nResult for: and( or (A, B), nand(A, B))')
for i in range(len(A)):
output = predicate_and(predicate_or(A[i], B[i]), predicate_nand(A[i], B[i]))
print(f'{A[i]}\t{B[i]}\t{output}') |
'''
*000*000*
0*00*00*0
00*0*0*00
000***000
Utkarsh
'''
l=int(input())
b=int(input())
print("With for\n")
for i in range(1,b+1):
for j in range(1,l+1):
if j==(l+1)//2 or j==i or j==(l+1)-i:
print('*',end='')
else:
print('0',end='')
print()
i=1
j=1
print("\nWith while\n")
while i<=b:
while j<=l:
if j==(l+1)//2 or j==i or j==(l+1)-i:
print('*',end='')
else:
print('0',end='')
j+=1
j=1
print()
i+=1
| """
*000*000*
0*00*00*0
00*0*0*00
000***000
Utkarsh
"""
l = int(input())
b = int(input())
print('With for\n')
for i in range(1, b + 1):
for j in range(1, l + 1):
if j == (l + 1) // 2 or j == i or j == l + 1 - i:
print('*', end='')
else:
print('0', end='')
print()
i = 1
j = 1
print('\nWith while\n')
while i <= b:
while j <= l:
if j == (l + 1) // 2 or j == i or j == l + 1 - i:
print('*', end='')
else:
print('0', end='')
j += 1
j = 1
print()
i += 1 |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flat
class SeriesLengthOption(object):
Unlimited = 0
Three_Games = 1
Five_Games = 2
Seven_Games = 3
| class Serieslengthoption(object):
unlimited = 0
three__games = 1
five__games = 2
seven__games = 3 |
# coding: utf-8
__author__ = 'tack'
class Position(object):
'''
position
'''
def __init__(self, code, num, price, commission, date):
'''
Args:
code: stock code
price: cost price
commission: commission
num: num
date: date
'''
self.code = code
self.num = num
self.date = date
self.commission = commission
self.cost = price * self.num + commission
self.cost_price = self.cost / self.num
self.market_price = price
def add(self, position):
'''
buy some
'''
if position is None:
raise Exception('position is none')
if position.code != self.code:
raise Exception('add op can not apply on different stocks')
self.cost += position.cost
self.num += position.num
self.cost_price = self.cost / self.num
self.market_price = position.market_price
return True, 'buy'
def sub(self, sell_position=None):
'''
sell some
'''
if sell_position is None:
raise Exception('position is none')
if sell_position.code != self.code:
raise Exception('sub op can not apply on different stocks')
if sell_position.num <= self.num:
self.cost -= sell_position.get_market_value() # total cost - market value
self.num -= sell_position.num
self.update(market_price=sell_position.market_price)
if self.num == 0:
self.cost_price = 0.
return True, 'sell'
self.cost_price = self.cost / self.num
return True, 'sell'
else:
return False, 'no enough stocks to sell'
def update(self, market_price=None):
'''
update market price
'''
self.market_price = market_price
def get_cost_value(self):
'''
value
'''
# return self.cost_price * self.num
return self.cost
def get_market_value(self, market_price=None):
'''
get market value of the position
'''
if market_price is not None:
self.market_price = market_price
if self.market_price is None:
raise Exception('you need to update market price.')
return self.market_price * self.num
def get_profit(self):
'''
paper loss, paper gain
'''
return self.get_market_value() - self.cost
def get_profit_ratio(self):
return (self.get_market_value() - self.cost) / self.cost * 100
def __repr__(self):
return 'code=%s,cost=%f,cost_price=%f, market_price=%f,num=%d,value=%f,profit=%f,date=%s' % (self.code, self.cost, self.cost_price,self.market_price, self.num, self.get_market_value(), self.get_profit(), self.date)
def get(self):
return (self.code, self.num, self.cost_price, self.date)
class PosstionHistory(object):
'''
history of position
'''
def __init__(self):
self.phs = {}
def update(self, position):
'''
when the market close, update positions
:param position:
:return:
'''
if position.code in self.phs:
self.phs[position.code].append(position)
else:
self.phs[position.code] = [position]
def get_history(self, code):
return self.phs.get(code, None)
| __author__ = 'tack'
class Position(object):
"""
position
"""
def __init__(self, code, num, price, commission, date):
"""
Args:
code: stock code
price: cost price
commission: commission
num: num
date: date
"""
self.code = code
self.num = num
self.date = date
self.commission = commission
self.cost = price * self.num + commission
self.cost_price = self.cost / self.num
self.market_price = price
def add(self, position):
"""
buy some
"""
if position is None:
raise exception('position is none')
if position.code != self.code:
raise exception('add op can not apply on different stocks')
self.cost += position.cost
self.num += position.num
self.cost_price = self.cost / self.num
self.market_price = position.market_price
return (True, 'buy')
def sub(self, sell_position=None):
"""
sell some
"""
if sell_position is None:
raise exception('position is none')
if sell_position.code != self.code:
raise exception('sub op can not apply on different stocks')
if sell_position.num <= self.num:
self.cost -= sell_position.get_market_value()
self.num -= sell_position.num
self.update(market_price=sell_position.market_price)
if self.num == 0:
self.cost_price = 0.0
return (True, 'sell')
self.cost_price = self.cost / self.num
return (True, 'sell')
else:
return (False, 'no enough stocks to sell')
def update(self, market_price=None):
"""
update market price
"""
self.market_price = market_price
def get_cost_value(self):
"""
value
"""
return self.cost
def get_market_value(self, market_price=None):
"""
get market value of the position
"""
if market_price is not None:
self.market_price = market_price
if self.market_price is None:
raise exception('you need to update market price.')
return self.market_price * self.num
def get_profit(self):
"""
paper loss, paper gain
"""
return self.get_market_value() - self.cost
def get_profit_ratio(self):
return (self.get_market_value() - self.cost) / self.cost * 100
def __repr__(self):
return 'code=%s,cost=%f,cost_price=%f, market_price=%f,num=%d,value=%f,profit=%f,date=%s' % (self.code, self.cost, self.cost_price, self.market_price, self.num, self.get_market_value(), self.get_profit(), self.date)
def get(self):
return (self.code, self.num, self.cost_price, self.date)
class Posstionhistory(object):
"""
history of position
"""
def __init__(self):
self.phs = {}
def update(self, position):
"""
when the market close, update positions
:param position:
:return:
"""
if position.code in self.phs:
self.phs[position.code].append(position)
else:
self.phs[position.code] = [position]
def get_history(self, code):
return self.phs.get(code, None) |
with open("p022_names.txt","r") as names:
names = names.read().replace("\"","").split(",")
names.sort()
Sum = 0
length = len(names)
for position in range(length):
alphavalue=0
for j in names[position]:
alphavalue += (ord(j)-64)
Sum += (alphavalue * (position+1))
print(Sum) | with open('p022_names.txt', 'r') as names:
names = names.read().replace('"', '').split(',')
names.sort()
sum = 0
length = len(names)
for position in range(length):
alphavalue = 0
for j in names[position]:
alphavalue += ord(j) - 64
sum += alphavalue * (position + 1)
print(Sum) |
config = {
'population_size' : 100,
'mutation_probability' : .1,
'crossover_rate' : .9,
# maximum simulation runs before finishing
'max_runs' : 100,
# maximum timesteps per simulation
'max_timesteps' : 150,
# smoothness value of the line in [0, 1]
'line_smoothness' : .4,
# Bound for our gain parameters (p, i, d)
'max_gain_value' : 3,
# when set to 1, we create a new map this run. When set to 0, loads a new map
'new_map' : True,
'runs_per_screenshot' : 10,
'data_directory' : '/home/monk/genetic_pid_data',
'map_filename' : 'map.csv'
}
| config = {'population_size': 100, 'mutation_probability': 0.1, 'crossover_rate': 0.9, 'max_runs': 100, 'max_timesteps': 150, 'line_smoothness': 0.4, 'max_gain_value': 3, 'new_map': True, 'runs_per_screenshot': 10, 'data_directory': '/home/monk/genetic_pid_data', 'map_filename': 'map.csv'} |
expected_output = {
'mstp': {
'blocked-ports': {
'mst_instances': {
'0': {
'mst_id': '0',
'interfaces': {
'GigabitEthernet0/0/4/4': {
'name': 'GigabitEthernet0/0/4/4',
'cost': 200000,
'role': 'ALT',
'port_priority': 128,
'port_num': 196,
'port_state': 'BLK',
'designated_bridge_priority': 4097,
'designated_bridge_address': '0004.9bff.8078',
'designated_port_priority': 128,
'designated_port_num': 195,
},
},
},
},
},
},
}
| expected_output = {'mstp': {'blocked-ports': {'mst_instances': {'0': {'mst_id': '0', 'interfaces': {'GigabitEthernet0/0/4/4': {'name': 'GigabitEthernet0/0/4/4', 'cost': 200000, 'role': 'ALT', 'port_priority': 128, 'port_num': 196, 'port_state': 'BLK', 'designated_bridge_priority': 4097, 'designated_bridge_address': '0004.9bff.8078', 'designated_port_priority': 128, 'designated_port_num': 195}}}}}}} |
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
tup = [(ind, i) for ind, i in enumerate(nums)]
tup.sort(key=lambda x: x[1])
for i in range(len(tup)):
for j in range(i+1, len(tup)):
if abs(tup[i][1]-tup[j][1])>t:
break
if abs(tup[i][0]-tup[j][0])<=k:
return True
return False | class Solution:
def contains_nearby_almost_duplicate(self, nums: List[int], k: int, t: int) -> bool:
tup = [(ind, i) for (ind, i) in enumerate(nums)]
tup.sort(key=lambda x: x[1])
for i in range(len(tup)):
for j in range(i + 1, len(tup)):
if abs(tup[i][1] - tup[j][1]) > t:
break
if abs(tup[i][0] - tup[j][0]) <= k:
return True
return False |
del_items(0x80139F2C)
SetType(0x80139F2C, "void PresOnlyTestRoutine__Fv()")
del_items(0x80139F54)
SetType(0x80139F54, "void FeInitBuffer__Fv()")
del_items(0x80139F7C)
SetType(0x80139F7C, "void FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, unsigned short Str, struct FeTable *MenuPtr, struct CFont *Font)")
del_items(0x80139FF0)
SetType(0x80139FF0, "void FeAddTable__FP11FeMenuTablei(struct FeMenuTable *Table, int Count)")
del_items(0x8013A06C)
SetType(0x8013A06C, "void FeAddNameTable__FPUci(unsigned char *Table, int Count)")
del_items(0x8013A19C)
SetType(0x8013A19C, "void FeDrawBuffer__Fv()")
del_items(0x8013A5B0)
SetType(0x8013A5B0, "void FeNewMenu__FP7FeTable(struct FeTable *Menu)")
del_items(0x8013A630)
SetType(0x8013A630, "void FePrevMenu__Fv()")
del_items(0x8013A6DC)
SetType(0x8013A6DC, "void FeSelUp__Fi(int No)")
del_items(0x8013A7C4)
SetType(0x8013A7C4, "void FeSelDown__Fi(int No)")
del_items(0x8013A8A8)
SetType(0x8013A8A8, "int FeGetCursor__Fv()")
del_items(0x8013A8BC)
SetType(0x8013A8BC, "void FeSelect__Fv()")
del_items(0x8013A900)
SetType(0x8013A900, "void FeMainKeyCtrl__FP7CScreen(struct CScreen *FeScreen)")
del_items(0x8013AA98)
SetType(0x8013AA98, "void InitDummyMenu__Fv()")
del_items(0x8013AAA0)
SetType(0x8013AAA0, "void InitFrontEnd__FP9FE_CREATE(struct FE_CREATE *CreateStruct)")
del_items(0x8013AB60)
SetType(0x8013AB60, "void FeInitMainMenu__Fv()")
del_items(0x8013ABBC)
SetType(0x8013ABBC, "void FeInitNewGameMenu__Fv()")
del_items(0x8013AC0C)
SetType(0x8013AC0C, "void FeNewGameMenuCtrl__Fv()")
del_items(0x8013AD40)
SetType(0x8013AD40, "void FeInitPlayer1ClassMenu__Fv()")
del_items(0x8013ADB4)
SetType(0x8013ADB4, "void FeInitPlayer2ClassMenu__Fv()")
del_items(0x8013AE28)
SetType(0x8013AE28, "void FePlayerClassMenuCtrl__Fv()")
del_items(0x8013AE70)
SetType(0x8013AE70, "void FeDrawChrClass__Fv()")
del_items(0x8013B30C)
SetType(0x8013B30C, "void FeInitNewP1NameMenu__Fv()")
del_items(0x8013B354)
SetType(0x8013B354, "void FeInitNewP2NameMenu__Fv()")
del_items(0x8013B39C)
SetType(0x8013B39C, "void FeNewNameMenuCtrl__Fv()")
del_items(0x8013B92C)
SetType(0x8013B92C, "void FeCopyPlayerInfoForReturn__Fv()")
del_items(0x8013B9FC)
SetType(0x8013B9FC, "void FeEnterGame__Fv()")
del_items(0x8013BA24)
SetType(0x8013BA24, "void FeInitLoadMemcardSelect__Fv()")
del_items(0x8013BA8C)
SetType(0x8013BA8C, "void FeInitLoadChar1Menu__Fv()")
del_items(0x8013BAF8)
SetType(0x8013BAF8, "void FeInitLoadChar2Menu__Fv()")
del_items(0x8013BB64)
SetType(0x8013BB64, "void FeInitDifficultyMenu__Fv()")
del_items(0x8013BBAC)
SetType(0x8013BBAC, "void FeDifficultyMenuCtrl__Fv()")
del_items(0x8013BC64)
SetType(0x8013BC64, "void FeInitBackgroundMenu__Fv()")
del_items(0x8013BCAC)
SetType(0x8013BCAC, "void FeInitBook1Menu__Fv()")
del_items(0x8013BCF8)
SetType(0x8013BCF8, "void FeInitBook2Menu__Fv()")
del_items(0x8013BD44)
SetType(0x8013BD44, "void FeBackBookMenuCtrl__Fv()")
del_items(0x8013BF40)
SetType(0x8013BF40, "void PlayDemo__Fv()")
del_items(0x8013BF54)
SetType(0x8013BF54, "void FadeFEOut__Fv()")
del_items(0x8013C018)
SetType(0x8013C018, "void DrawBackTSK__FP4TASK(struct TASK *T)")
del_items(0x8013C110)
SetType(0x8013C110, "void FrontEndTask__FP4TASK(struct TASK *T)")
del_items(0x8013C488)
SetType(0x8013C488, "void McMainCharKeyCtrl__Fv()")
del_items(0x8013C890)
SetType(0x8013C890, "void DrawFeTwinkle__Fii(int SelX, int SelY)")
del_items(0x8013C950)
SetType(0x8013C950, "void ___6Dialog(struct Dialog *this, int __in_chrg)")
del_items(0x8013C978)
SetType(0x8013C978, "struct Dialog *__6Dialog(struct Dialog *this)")
del_items(0x8013C9D4)
SetType(0x8013C9D4, "void ___7CScreen(struct CScreen *this, int __in_chrg)")
del_items(0x8013C9F4)
SetType(0x8013C9F4, "unsigned char CheckActive__4CPad(struct CPad *this)")
del_items(0x8013D5A4)
SetType(0x8013D5A4, "void InitCredits__Fv()")
del_items(0x8013D5E0)
SetType(0x8013D5E0, "int PrintCredits__FPciiiii(char *Str, int Y, int CharFade, int RFlag, int GFlag, int BFlag)")
del_items(0x8013DE04)
SetType(0x8013DE04, "void DrawCreditsTitle__Fiiiii(int TitleNo, int TitleFade, int TitleMode, int NextTitleNo, int Y)")
del_items(0x8013DED0)
SetType(0x8013DED0, "void DrawCreditsSubTitle__Fiiiii(int SubTitleNo, int SubTitleFade, int SubTitleMode, int NextSubTitleNo, int Y)")
del_items(0x8013DFAC)
SetType(0x8013DFAC, "void DoCredits__Fv()")
del_items(0x8013E230)
SetType(0x8013E230, "void PRIM_GetPrim__FPP8POLY_FT4(struct POLY_FT4 **Prim)")
del_items(0x8013E2AC)
SetType(0x8013E2AC, "int GetCharHeight__5CFontc(struct CFont *this, char ch)")
del_items(0x8013E2EC)
SetType(0x8013E2EC, "int GetCharWidth__5CFontc(struct CFont *this, char ch)")
del_items(0x8013E344)
SetType(0x8013E344, "void ___7CScreen_addr_8013E344(struct CScreen *this, int __in_chrg)")
del_items(0x8013E364)
SetType(0x8013E364, "struct FRAME_HDR *GetFr__7TextDati(struct TextDat *this, int FrNum)")
del_items(0x80142920)
SetType(0x80142920, "void endian_swap__FPUci(unsigned char *b, int byts)")
del_items(0x80142954)
SetType(0x80142954, "unsigned short to_sjis__Fc(char asc)")
del_items(0x801429D4)
SetType(0x801429D4, "char to_ascii__FUs(unsigned short sjis)")
del_items(0x80142A54)
SetType(0x80142A54, "void ascii_to_sjis__FPcPUs(char *asc, unsigned short *sjis)")
del_items(0x80142AD8)
SetType(0x80142AD8, "void sjis_to_ascii__FPUsPc(unsigned short *sjis, char *asc)")
del_items(0x80142B50)
SetType(0x80142B50, "void read_card_directory__Fi(int card_number)")
del_items(0x80142D5C)
SetType(0x80142D5C, "int test_card_format__Fi(int card_number)")
del_items(0x80142E4C)
SetType(0x80142E4C, "int checksum_data__FPci(char *buf, int size)")
del_items(0x80142E88)
SetType(0x80142E88, "int delete_card_file__Fii(int card_number, int file)")
del_items(0x80142F80)
SetType(0x80142F80, "int read_card_file__FiiiPc(int card_number, int file, int id, char *buf)")
del_items(0x80143144)
SetType(0x80143144, "int format_card__Fi(int card_number)")
del_items(0x80143208)
SetType(0x80143208, "int write_card_file__FiiPcT2PUcPUsiT4(int card_number, int id, char *name, char *title, unsigned char *icon, unsigned short *clut, int size, unsigned char *buf)")
del_items(0x80143560)
SetType(0x80143560, "void new_card__Fi(int card_number)")
del_items(0x801435F4)
SetType(0x801435F4, "void service_card__Fi(int card_number)")
del_items(0x8015D834)
SetType(0x8015D834, "int GetFileNumber__FiPc(int side, char *file_name)")
del_items(0x8015D8F4)
SetType(0x8015D8F4, "int DoSaveOptions__Fv()")
del_items(0x8015D948)
SetType(0x8015D948, "int DoSaveCharacter__FPc(char *savefilename)")
del_items(0x8015DA18)
SetType(0x8015DA18, "int DoSaveGame__Fv()")
del_items(0x8015DAD8)
SetType(0x8015DAD8, "void DoLoadGame__Fv()")
del_items(0x8015DB68)
SetType(0x8015DB68, "int DoFrontEndLoadCharacter__FPc(char *loadfilenameptr)")
del_items(0x8015DBC4)
SetType(0x8015DBC4, "void McInitLoadCard1Menu__Fv()")
del_items(0x8015DC10)
SetType(0x8015DC10, "void McInitLoadCard2Menu__Fv()")
del_items(0x8015DC5C)
SetType(0x8015DC5C, "void ChooseCardLoad__Fv()")
del_items(0x8015DD10)
SetType(0x8015DD10, "void McInitLoadCharMenu__Fv()")
del_items(0x8015DD38)
SetType(0x8015DD38, "void McInitLoadGameMenu__Fv()")
del_items(0x8015DD94)
SetType(0x8015DD94, "void McMainKeyCtrl__Fv()")
del_items(0x8015DED0)
SetType(0x8015DED0, "void ShowAlertBox__Fv()")
del_items(0x8015E0A4)
SetType(0x8015E0A4, "void ShowCardActionText__FPc(char *Text)")
del_items(0x8015E1E8)
SetType(0x8015E1E8, "bool GetLoadStatusMessage__FPc(char *file_name)")
del_items(0x8015E28C)
SetType(0x8015E28C, "bool GetSaveStatusMessage__FiPc(int fileblocks, char *file_name)")
del_items(0x8015E364)
SetType(0x8015E364, "void ShowGameFiles__FPciiG4RECT(char *filename, int saveflag, int Spacing, struct RECT ORect)")
del_items(0x8015E4CC)
SetType(0x8015E4CC, "void SetRGB__6DialogUcUcUc(struct Dialog *this, unsigned char R, unsigned char G, unsigned char B)")
del_items(0x8015E4EC)
SetType(0x8015E4EC, "void SetBack__6Dialogi(struct Dialog *this, int Type)")
del_items(0x8015E4F4)
SetType(0x8015E4F4, "void SetBorder__6Dialogi(struct Dialog *this, int Type)")
del_items(0x8015E4FC)
SetType(0x8015E4FC, "int SetOTpos__6Dialogi(struct Dialog *this, int OT)")
del_items(0x8015E508)
SetType(0x8015E508, "void ___6Dialog_addr_8015E508(struct Dialog *this, int __in_chrg)")
del_items(0x8015E530)
SetType(0x8015E530, "struct Dialog *__6Dialog_addr_8015E530(struct Dialog *this)")
del_items(0x8015E58C)
SetType(0x8015E58C, "int ILoad__Fv()")
del_items(0x8015E5E0)
SetType(0x8015E5E0, "void LoadQuest__Fi(int i)")
del_items(0x8015E6A8)
SetType(0x8015E6A8, "void ISave__Fi(int v)")
del_items(0x8015E708)
SetType(0x8015E708, "void SaveQuest__Fi(int i)")
del_items(0x8015E7D4)
SetType(0x8015E7D4, "int PSX_GM_SaveGame__FiPcT1(int card_number, char *name, char *title)")
del_items(0x8015EA74)
SetType(0x8015EA74, "int PSX_GM_LoadGame__FUcii(unsigned char firstflag, int card_number, int file)")
del_items(0x8015ED60)
SetType(0x8015ED60, "int PSX_CH_LoadGame__Fii(int card_number, int file)")
del_items(0x8015EEC4)
SetType(0x8015EEC4, "int PSX_CH_SaveGame__FiPcT1(int card_number, char *name, char *title)")
del_items(0x8015F044)
SetType(0x8015F044, "void RestorePads__Fv()")
del_items(0x8015F104)
SetType(0x8015F104, "void StorePads__Fv()")
del_items(0x8015F1C0)
SetType(0x8015F1C0, "void GetIcon__Fv()")
del_items(0x8015F1FC)
SetType(0x8015F1FC, "int PSX_OPT_LoadGame__Fiib(int card_number, int file, bool KillHandler)")
del_items(0x8015F260)
SetType(0x8015F260, "int PSX_OPT_SaveGame__FiPc(int card_number, char *filename)")
del_items(0x8015F2F8)
SetType(0x8015F2F8, "void LoadOptions__Fv()")
del_items(0x8015F368)
SetType(0x8015F368, "void SaveOptions__Fv()")
| del_items(2148769580)
set_type(2148769580, 'void PresOnlyTestRoutine__Fv()')
del_items(2148769620)
set_type(2148769620, 'void FeInitBuffer__Fv()')
del_items(2148769660)
set_type(2148769660, 'void FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, unsigned short Str, struct FeTable *MenuPtr, struct CFont *Font)')
del_items(2148769776)
set_type(2148769776, 'void FeAddTable__FP11FeMenuTablei(struct FeMenuTable *Table, int Count)')
del_items(2148769900)
set_type(2148769900, 'void FeAddNameTable__FPUci(unsigned char *Table, int Count)')
del_items(2148770204)
set_type(2148770204, 'void FeDrawBuffer__Fv()')
del_items(2148771248)
set_type(2148771248, 'void FeNewMenu__FP7FeTable(struct FeTable *Menu)')
del_items(2148771376)
set_type(2148771376, 'void FePrevMenu__Fv()')
del_items(2148771548)
set_type(2148771548, 'void FeSelUp__Fi(int No)')
del_items(2148771780)
set_type(2148771780, 'void FeSelDown__Fi(int No)')
del_items(2148772008)
set_type(2148772008, 'int FeGetCursor__Fv()')
del_items(2148772028)
set_type(2148772028, 'void FeSelect__Fv()')
del_items(2148772096)
set_type(2148772096, 'void FeMainKeyCtrl__FP7CScreen(struct CScreen *FeScreen)')
del_items(2148772504)
set_type(2148772504, 'void InitDummyMenu__Fv()')
del_items(2148772512)
set_type(2148772512, 'void InitFrontEnd__FP9FE_CREATE(struct FE_CREATE *CreateStruct)')
del_items(2148772704)
set_type(2148772704, 'void FeInitMainMenu__Fv()')
del_items(2148772796)
set_type(2148772796, 'void FeInitNewGameMenu__Fv()')
del_items(2148772876)
set_type(2148772876, 'void FeNewGameMenuCtrl__Fv()')
del_items(2148773184)
set_type(2148773184, 'void FeInitPlayer1ClassMenu__Fv()')
del_items(2148773300)
set_type(2148773300, 'void FeInitPlayer2ClassMenu__Fv()')
del_items(2148773416)
set_type(2148773416, 'void FePlayerClassMenuCtrl__Fv()')
del_items(2148773488)
set_type(2148773488, 'void FeDrawChrClass__Fv()')
del_items(2148774668)
set_type(2148774668, 'void FeInitNewP1NameMenu__Fv()')
del_items(2148774740)
set_type(2148774740, 'void FeInitNewP2NameMenu__Fv()')
del_items(2148774812)
set_type(2148774812, 'void FeNewNameMenuCtrl__Fv()')
del_items(2148776236)
set_type(2148776236, 'void FeCopyPlayerInfoForReturn__Fv()')
del_items(2148776444)
set_type(2148776444, 'void FeEnterGame__Fv()')
del_items(2148776484)
set_type(2148776484, 'void FeInitLoadMemcardSelect__Fv()')
del_items(2148776588)
set_type(2148776588, 'void FeInitLoadChar1Menu__Fv()')
del_items(2148776696)
set_type(2148776696, 'void FeInitLoadChar2Menu__Fv()')
del_items(2148776804)
set_type(2148776804, 'void FeInitDifficultyMenu__Fv()')
del_items(2148776876)
set_type(2148776876, 'void FeDifficultyMenuCtrl__Fv()')
del_items(2148777060)
set_type(2148777060, 'void FeInitBackgroundMenu__Fv()')
del_items(2148777132)
set_type(2148777132, 'void FeInitBook1Menu__Fv()')
del_items(2148777208)
set_type(2148777208, 'void FeInitBook2Menu__Fv()')
del_items(2148777284)
set_type(2148777284, 'void FeBackBookMenuCtrl__Fv()')
del_items(2148777792)
set_type(2148777792, 'void PlayDemo__Fv()')
del_items(2148777812)
set_type(2148777812, 'void FadeFEOut__Fv()')
del_items(2148778008)
set_type(2148778008, 'void DrawBackTSK__FP4TASK(struct TASK *T)')
del_items(2148778256)
set_type(2148778256, 'void FrontEndTask__FP4TASK(struct TASK *T)')
del_items(2148779144)
set_type(2148779144, 'void McMainCharKeyCtrl__Fv()')
del_items(2148780176)
set_type(2148780176, 'void DrawFeTwinkle__Fii(int SelX, int SelY)')
del_items(2148780368)
set_type(2148780368, 'void ___6Dialog(struct Dialog *this, int __in_chrg)')
del_items(2148780408)
set_type(2148780408, 'struct Dialog *__6Dialog(struct Dialog *this)')
del_items(2148780500)
set_type(2148780500, 'void ___7CScreen(struct CScreen *this, int __in_chrg)')
del_items(2148780532)
set_type(2148780532, 'unsigned char CheckActive__4CPad(struct CPad *this)')
del_items(2148783524)
set_type(2148783524, 'void InitCredits__Fv()')
del_items(2148783584)
set_type(2148783584, 'int PrintCredits__FPciiiii(char *Str, int Y, int CharFade, int RFlag, int GFlag, int BFlag)')
del_items(2148785668)
set_type(2148785668, 'void DrawCreditsTitle__Fiiiii(int TitleNo, int TitleFade, int TitleMode, int NextTitleNo, int Y)')
del_items(2148785872)
set_type(2148785872, 'void DrawCreditsSubTitle__Fiiiii(int SubTitleNo, int SubTitleFade, int SubTitleMode, int NextSubTitleNo, int Y)')
del_items(2148786092)
set_type(2148786092, 'void DoCredits__Fv()')
del_items(2148786736)
set_type(2148786736, 'void PRIM_GetPrim__FPP8POLY_FT4(struct POLY_FT4 **Prim)')
del_items(2148786860)
set_type(2148786860, 'int GetCharHeight__5CFontc(struct CFont *this, char ch)')
del_items(2148786924)
set_type(2148786924, 'int GetCharWidth__5CFontc(struct CFont *this, char ch)')
del_items(2148787012)
set_type(2148787012, 'void ___7CScreen_addr_8013E344(struct CScreen *this, int __in_chrg)')
del_items(2148787044)
set_type(2148787044, 'struct FRAME_HDR *GetFr__7TextDati(struct TextDat *this, int FrNum)')
del_items(2148804896)
set_type(2148804896, 'void endian_swap__FPUci(unsigned char *b, int byts)')
del_items(2148804948)
set_type(2148804948, 'unsigned short to_sjis__Fc(char asc)')
del_items(2148805076)
set_type(2148805076, 'char to_ascii__FUs(unsigned short sjis)')
del_items(2148805204)
set_type(2148805204, 'void ascii_to_sjis__FPcPUs(char *asc, unsigned short *sjis)')
del_items(2148805336)
set_type(2148805336, 'void sjis_to_ascii__FPUsPc(unsigned short *sjis, char *asc)')
del_items(2148805456)
set_type(2148805456, 'void read_card_directory__Fi(int card_number)')
del_items(2148805980)
set_type(2148805980, 'int test_card_format__Fi(int card_number)')
del_items(2148806220)
set_type(2148806220, 'int checksum_data__FPci(char *buf, int size)')
del_items(2148806280)
set_type(2148806280, 'int delete_card_file__Fii(int card_number, int file)')
del_items(2148806528)
set_type(2148806528, 'int read_card_file__FiiiPc(int card_number, int file, int id, char *buf)')
del_items(2148806980)
set_type(2148806980, 'int format_card__Fi(int card_number)')
del_items(2148807176)
set_type(2148807176, 'int write_card_file__FiiPcT2PUcPUsiT4(int card_number, int id, char *name, char *title, unsigned char *icon, unsigned short *clut, int size, unsigned char *buf)')
del_items(2148808032)
set_type(2148808032, 'void new_card__Fi(int card_number)')
del_items(2148808180)
set_type(2148808180, 'void service_card__Fi(int card_number)')
del_items(2148915252)
set_type(2148915252, 'int GetFileNumber__FiPc(int side, char *file_name)')
del_items(2148915444)
set_type(2148915444, 'int DoSaveOptions__Fv()')
del_items(2148915528)
set_type(2148915528, 'int DoSaveCharacter__FPc(char *savefilename)')
del_items(2148915736)
set_type(2148915736, 'int DoSaveGame__Fv()')
del_items(2148915928)
set_type(2148915928, 'void DoLoadGame__Fv()')
del_items(2148916072)
set_type(2148916072, 'int DoFrontEndLoadCharacter__FPc(char *loadfilenameptr)')
del_items(2148916164)
set_type(2148916164, 'void McInitLoadCard1Menu__Fv()')
del_items(2148916240)
set_type(2148916240, 'void McInitLoadCard2Menu__Fv()')
del_items(2148916316)
set_type(2148916316, 'void ChooseCardLoad__Fv()')
del_items(2148916496)
set_type(2148916496, 'void McInitLoadCharMenu__Fv()')
del_items(2148916536)
set_type(2148916536, 'void McInitLoadGameMenu__Fv()')
del_items(2148916628)
set_type(2148916628, 'void McMainKeyCtrl__Fv()')
del_items(2148916944)
set_type(2148916944, 'void ShowAlertBox__Fv()')
del_items(2148917412)
set_type(2148917412, 'void ShowCardActionText__FPc(char *Text)')
del_items(2148917736)
set_type(2148917736, 'bool GetLoadStatusMessage__FPc(char *file_name)')
del_items(2148917900)
set_type(2148917900, 'bool GetSaveStatusMessage__FiPc(int fileblocks, char *file_name)')
del_items(2148918116)
set_type(2148918116, 'void ShowGameFiles__FPciiG4RECT(char *filename, int saveflag, int Spacing, struct RECT ORect)')
del_items(2148918476)
set_type(2148918476, 'void SetRGB__6DialogUcUcUc(struct Dialog *this, unsigned char R, unsigned char G, unsigned char B)')
del_items(2148918508)
set_type(2148918508, 'void SetBack__6Dialogi(struct Dialog *this, int Type)')
del_items(2148918516)
set_type(2148918516, 'void SetBorder__6Dialogi(struct Dialog *this, int Type)')
del_items(2148918524)
set_type(2148918524, 'int SetOTpos__6Dialogi(struct Dialog *this, int OT)')
del_items(2148918536)
set_type(2148918536, 'void ___6Dialog_addr_8015E508(struct Dialog *this, int __in_chrg)')
del_items(2148918576)
set_type(2148918576, 'struct Dialog *__6Dialog_addr_8015E530(struct Dialog *this)')
del_items(2148918668)
set_type(2148918668, 'int ILoad__Fv()')
del_items(2148918752)
set_type(2148918752, 'void LoadQuest__Fi(int i)')
del_items(2148918952)
set_type(2148918952, 'void ISave__Fi(int v)')
del_items(2148919048)
set_type(2148919048, 'void SaveQuest__Fi(int i)')
del_items(2148919252)
set_type(2148919252, 'int PSX_GM_SaveGame__FiPcT1(int card_number, char *name, char *title)')
del_items(2148919924)
set_type(2148919924, 'int PSX_GM_LoadGame__FUcii(unsigned char firstflag, int card_number, int file)')
del_items(2148920672)
set_type(2148920672, 'int PSX_CH_LoadGame__Fii(int card_number, int file)')
del_items(2148921028)
set_type(2148921028, 'int PSX_CH_SaveGame__FiPcT1(int card_number, char *name, char *title)')
del_items(2148921412)
set_type(2148921412, 'void RestorePads__Fv()')
del_items(2148921604)
set_type(2148921604, 'void StorePads__Fv()')
del_items(2148921792)
set_type(2148921792, 'void GetIcon__Fv()')
del_items(2148921852)
set_type(2148921852, 'int PSX_OPT_LoadGame__Fiib(int card_number, int file, bool KillHandler)')
del_items(2148921952)
set_type(2148921952, 'int PSX_OPT_SaveGame__FiPc(int card_number, char *filename)')
del_items(2148922104)
set_type(2148922104, 'void LoadOptions__Fv()')
del_items(2148922216)
set_type(2148922216, 'void SaveOptions__Fv()') |
# -*- coding: utf-8 -*-
# Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
# Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
# String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
# Nested way
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
| thisdict = {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
print(thisdict)
thisdict = {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'year': 2020}
print(thisdict)
thisdict = {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
child1 = {'name': 'Emil', 'year': 2004}
child2 = {'name': 'Tobias', 'year': 2007}
child3 = {'name': 'Linus', 'year': 2011}
myfamily = {'child1': child1, 'child2': child2, 'child3': child3}
print(myfamily) |
''' e. and use all methods '''
''' also try different exception like java file,array,string,numberformat '''
''' user define exception '''
try:
raise Exception('spam,','eggs')
except Exception as inst:
print("Type of instance : ",type(inst)) # the exception instance
print("Arguments of instance : ",inst.args) # arguments stored in .args
print("Instance print : ",inst) # __str__ allows args to be printed directly,but may be overridden in exception subclasses
a,b = inst.args # unpack args
print("a : ",a)
print("b : ",b) | """ e. and use all methods """
' also try different exception like java file,array,string,numberformat '
' user define exception '
try:
raise exception('spam,', 'eggs')
except Exception as inst:
print('Type of instance : ', type(inst))
print('Arguments of instance : ', inst.args)
print('Instance print : ', inst)
(a, b) = inst.args
print('a : ', a)
print('b : ', b) |
def is_palindrome_number(number):
return number == int(str(number)[::-1])
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for number in infinite_sequence():
if is_palindrome_number(number):
print(number)
def countdown_from(number):
print(f"Starting to count from {number}!")
while number > 0:
yield number
number -= 1
print("Done!")
def increment(start, stop):
yield from range(start, stop)
if __name__ == "__main__":
countdown = countdown_from(number=10)
for count in countdown:
print(count)
incremental = increment(start=1, stop=10)
for inc in incremental:
print(inc)
| def is_palindrome_number(number):
return number == int(str(number)[::-1])
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for number in infinite_sequence():
if is_palindrome_number(number):
print(number)
def countdown_from(number):
print(f'Starting to count from {number}!')
while number > 0:
yield number
number -= 1
print('Done!')
def increment(start, stop):
yield from range(start, stop)
if __name__ == '__main__':
countdown = countdown_from(number=10)
for count in countdown:
print(count)
incremental = increment(start=1, stop=10)
for inc in incremental:
print(inc) |
TEST_ROOT_TABLES = {
"tenders": ["/tender"],
"awards": ["/awards"],
"contracts": ["/contracts"],
"planning": ["/planning"],
"parties": ["/parties"],
}
TEST_COMBINED_TABLES = {
"documents": [
"/planning/documents",
"/tender/documents",
"/awards/documents",
"/contracts/documents",
"/contracts/implementation/documents",
],
"milestones": [
"/planning/milestones",
"/tender/milestones",
"/contracts/milestones",
"/contracts/implementation/milestones",
],
"amendments": [
"/planning/amendments",
"/tender/amendments",
"/awards/amendments",
"/contracts/amendments",
"/contracts/implementation/amendments",
],
}
tenders_columns = [
"/tender/id",
"/tender/title",
"/tender/description",
"/tender/status",
"/tender/procurementMethod",
"/tender/procurementMethodDetails",
"/tender/procurementMethodRationale",
"/tender/mainProcurementCategory",
"/tender/additionalProcurementCategories",
"/tender/awardCriteria",
"/tender/awardCriteriaDetails",
"/tender/submissionMethodDetails",
"/tender/submissionMethod",
"/tender/hasEnquiries",
"/tender/eligibilityCriteria",
"/tender/numberOfTenderers",
"/tender/contractPeriod/startDate",
"/tender/contractPeriod/endDate",
"/tender/contractPeriod/maxExtentDate",
"/tender/contractPeriod/durationInDays",
"/tender/awardPeriod/startDate",
"/tender/awardPeriod/endDate",
"/tender/awardPeriod/maxExtentDate",
"/tender/awardPeriod/durationInDays",
"/tender/enquiryPeriod/startDate",
"/tender/enquiryPeriod/endDate",
"/tender/enquiryPeriod/maxExtentDate",
"/tender/enquiryPeriod/durationInDays",
"/tender/tenderPeriod/startDate",
"/tender/tenderPeriod/endDate",
"/tender/tenderPeriod/maxExtentDate",
"/tender/tenderPeriod/durationInDays",
"/tender/minValue/amount",
"/tender/minValue/currency",
"/tender/value/amount",
"/tender/value/currency",
"/tender/procuringEntity/name",
"/tender/procuringEntity/id",
]
tenders_arrays = [
"/tender/items",
"/tender/tenderers",
"/tender/items/additionalClassifications",
]
tenders_combined_columns = [
"/tender/id",
"/tender/title",
"/tender/description",
"/tender/status",
"/tender/procurementMethod",
"/tender/procurementMethodDetails",
"/tender/procurementMethodRationale",
"/tender/mainProcurementCategory",
"/tender/additionalProcurementCategories",
"/tender/awardCriteria",
"/tender/awardCriteriaDetails",
"/tender/submissionMethod",
"/tender/submissionMethodDetails",
"/tender/hasEnquiries",
"/tender/eligibilityCriteria",
"/tender/numberOfTenderers",
"/tender/tenderers/0/name",
"/tender/tenderers/0/id",
"/tender/contractPeriod/startDate",
"/tender/contractPeriod/endDate",
"/tender/contractPeriod/maxExtentDate",
"/tender/contractPeriod/durationInDays",
"/tender/awardPeriod/startDate",
"/tender/awardPeriod/endDate",
"/tender/awardPeriod/maxExtentDate",
"/tender/awardPeriod/durationInDays",
"/tender/enquiryPeriod/startDate",
"/tender/enquiryPeriod/endDate",
"/tender/enquiryPeriod/maxExtentDate",
"/tender/enquiryPeriod/durationInDays",
"/tender/tenderPeriod/startDate",
"/tender/tenderPeriod/endDate",
"/tender/tenderPeriod/maxExtentDate",
"/tender/tenderPeriod/durationInDays",
"/tender/minValue/amount",
"/tender/minValue/currency",
"/tender/value/amount",
"/tender/value/currency",
"/tender/items/0/id",
"/tender/items/0/description",
"/tender/items/0/quantity",
"/tender/items/0/unit/scheme",
"/tender/items/0/unit/id",
"/tender/items/0/unit/name",
"/tender/items/0/unit/uri",
"/tender/items/0/unit/value/amount",
"/tender/items/0/unit/value/currency",
"/tender/items/0/additionalClassifications/0/scheme",
"/tender/items/0/additionalClassifications/0/id",
"/tender/items/0/additionalClassifications/0/description",
"/tender/items/0/additionalClassifications/0/uri",
"/tender/items/0/classification/scheme",
"/tender/items/0/classification/id",
"/tender/items/0/classification/description",
"/tender/items/0/classification/uri",
"/tender/procuringEntity/name",
"/tender/procuringEntity/id",
]
awards_columns = [
"/awards/id",
"/awards/title",
"/awards/description",
"/awards/status",
"/awards/date",
"/awards/contractPeriod/startDate",
"/awards/contractPeriod/endDate",
"/awards/contractPeriod/maxExtentDate",
"/awards/contractPeriod/durationInDays",
"/awards/value/amount",
"/awards/value/currency",
]
awards_combined_columns = [
"/awards/id",
"/awards/title",
"/awards/description",
"/awards/status",
"/awards/date",
"/awards/contractPeriod/startDate",
"/awards/contractPeriod/endDate",
"/awards/contractPeriod/maxExtentDate",
"/awards/contractPeriod/durationInDays",
"/awards/items/0/id",
"/awards/items/0/description",
"/awards/items/0/quantity",
"/awards/items/0/unit/scheme",
"/awards/items/0/unit/id",
"/awards/items/0/unit/name",
"/awards/items/0/unit/uri",
"/awards/items/0/unit/value/amount",
"/awards/items/0/unit/value/currency",
"/awards/items/0/additionalClassifications/0/scheme",
"/awards/items/0/additionalClassifications/0/id",
"/awards/items/0/additionalClassifications/0/description",
"/awards/items/0/additionalClassifications/0/uri",
"/awards/items/0/classification/scheme",
"/awards/items/0/classification/id",
"/awards/items/0/classification/description",
"/awards/items/0/classification/uri",
"/awards/suppliers/0/name",
"/awards/suppliers/0/id",
"/awards/value/amount",
"/awards/value/currency",
]
awards_arrays = [
"/awards/suppliers",
"/awards/items",
"/awards/items/additionalClassifications",
]
contracts_columns = [
"/contracts/id",
"/contracts/awardID",
"/contracts/title",
"/contracts/description",
"/contracts/status",
"/contracts/dateSigned",
"/contracts/value/amount",
"/contracts/value/currency",
"/contracts/period/startDate",
"/contracts/period/endDate",
"/contracts/period/maxExtentDate",
"/contracts/period/durationInDays",
]
contracts_arrays = [
"/contracts/items",
"/contracts/relatedProcesses",
"/contracts/implementation/transactions",
"/contracts/items/additionalClassifications",
]
contracts_combined_columns = [
"/contracts/id",
"/contracts/awardID",
"/contracts/title",
"/contracts/description",
"/contracts/status",
"/contracts/dateSigned",
"/contracts/relatedProcesses/0/id",
"/contracts/relatedProcesses/0/relationship",
"/contracts/relatedProcesses/0/title",
"/contracts/relatedProcesses/0/scheme",
"/contracts/relatedProcesses/0/identifier",
"/contracts/relatedProcesses/0/uri",
"/contracts/implementation/transactions/0/id",
"/contracts/implementation/transactions/0/source",
"/contracts/implementation/transactions/0/date",
"/contracts/implementation/transactions/0/uri",
"/contracts/implementation/transactions/0/payee/name",
"/contracts/implementation/transactions/0/payee/id",
"/contracts/implementation/transactions/0/payer/name",
"/contracts/implementation/transactions/0/payer/id",
"/contracts/implementation/transactions/0/value/amount",
"/contracts/implementation/transactions/0/value/currency",
"/contracts/items/0/id",
"/contracts/items/0/description",
"/contracts/items/0/quantity",
"/contracts/items/0/unit/scheme",
"/contracts/items/0/unit/id",
"/contracts/items/0/unit/name",
"/contracts/items/0/unit/uri",
"/contracts/items/0/unit/value/amount",
"/contracts/items/0/unit/value/currency",
"/contracts/items/0/additionalClassifications/0/scheme",
"/contracts/items/0/additionalClassifications/0/id",
"/contracts/items/0/additionalClassifications/0/description",
"/contracts/items/0/additionalClassifications/0/uri",
"/contracts/items/0/classification/scheme",
"/contracts/items/0/classification/id",
"/contracts/items/0/classification/description",
"/contracts/items/0/classification/uri",
"/contracts/value/amount",
"/contracts/value/currency",
"/contracts/period/startDate",
"/contracts/period/endDate",
"/contracts/period/maxExtentDate",
"/contracts/period/durationInDays",
]
planning_columns = [
"/planning/rationale",
"/planning/budget/id",
"/planning/budget/description",
"/planning/budget/project",
"/planning/budget/projectID",
"/planning/budget/uri",
"/planning/budget/amount/amount",
"/planning/budget/amount/currency",
]
planning_combined_columns = [
"/planning/rationale",
"/planning/budget/id",
"/planning/budget/description",
"/planning/budget/project",
"/planning/budget/projectID",
"/planning/budget/uri",
"/planning/budget/amount/amount",
"/planning/budget/amount/currency",
]
planning_arrays = []
parties_arrays = ["/parties/additionalIdentifiers"]
parties_columns = [
"/parties/name",
"/parties/id",
"/parties/roles",
"/parties/contactPoint/name",
"/parties/contactPoint/email",
"/parties/contactPoint/telephone",
"/parties/contactPoint/faxNumber",
"/parties/contactPoint/url",
"/parties/address/streetAddress",
"/parties/address/locality",
"/parties/address/region",
"/parties/address/postalCode",
"/parties/address/countryName",
"/parties/identifier/scheme",
"/parties/identifier/id",
"/parties/identifier/legalName",
"/parties/identifier/uri",
]
parties_combined_columns = [
"/parties/name",
"/parties/id",
"/parties/roles",
"/parties/roles",
"/parties/contactPoint/name",
"/parties/contactPoint/email",
"/parties/contactPoint/telephone",
"/parties/contactPoint/faxNumber",
"/parties/contactPoint/url",
"/parties/address/streetAddress",
"/parties/address/locality",
"/parties/address/region",
"/parties/address/postalCode",
"/parties/address/countryName",
"/parties/additionalIdentifiers/0/scheme",
"/parties/additionalIdentifiers/0/id",
"/parties/additionalIdentifiers/0/legalName",
"/parties/additionalIdentifiers/0/uri",
"/parties/identifier/scheme",
"/parties/identifier/id",
"/parties/identifier/legalName",
"/parties/identifier/uri",
]
| test_root_tables = {'tenders': ['/tender'], 'awards': ['/awards'], 'contracts': ['/contracts'], 'planning': ['/planning'], 'parties': ['/parties']}
test_combined_tables = {'documents': ['/planning/documents', '/tender/documents', '/awards/documents', '/contracts/documents', '/contracts/implementation/documents'], 'milestones': ['/planning/milestones', '/tender/milestones', '/contracts/milestones', '/contracts/implementation/milestones'], 'amendments': ['/planning/amendments', '/tender/amendments', '/awards/amendments', '/contracts/amendments', '/contracts/implementation/amendments']}
tenders_columns = ['/tender/id', '/tender/title', '/tender/description', '/tender/status', '/tender/procurementMethod', '/tender/procurementMethodDetails', '/tender/procurementMethodRationale', '/tender/mainProcurementCategory', '/tender/additionalProcurementCategories', '/tender/awardCriteria', '/tender/awardCriteriaDetails', '/tender/submissionMethodDetails', '/tender/submissionMethod', '/tender/hasEnquiries', '/tender/eligibilityCriteria', '/tender/numberOfTenderers', '/tender/contractPeriod/startDate', '/tender/contractPeriod/endDate', '/tender/contractPeriod/maxExtentDate', '/tender/contractPeriod/durationInDays', '/tender/awardPeriod/startDate', '/tender/awardPeriod/endDate', '/tender/awardPeriod/maxExtentDate', '/tender/awardPeriod/durationInDays', '/tender/enquiryPeriod/startDate', '/tender/enquiryPeriod/endDate', '/tender/enquiryPeriod/maxExtentDate', '/tender/enquiryPeriod/durationInDays', '/tender/tenderPeriod/startDate', '/tender/tenderPeriod/endDate', '/tender/tenderPeriod/maxExtentDate', '/tender/tenderPeriod/durationInDays', '/tender/minValue/amount', '/tender/minValue/currency', '/tender/value/amount', '/tender/value/currency', '/tender/procuringEntity/name', '/tender/procuringEntity/id']
tenders_arrays = ['/tender/items', '/tender/tenderers', '/tender/items/additionalClassifications']
tenders_combined_columns = ['/tender/id', '/tender/title', '/tender/description', '/tender/status', '/tender/procurementMethod', '/tender/procurementMethodDetails', '/tender/procurementMethodRationale', '/tender/mainProcurementCategory', '/tender/additionalProcurementCategories', '/tender/awardCriteria', '/tender/awardCriteriaDetails', '/tender/submissionMethod', '/tender/submissionMethodDetails', '/tender/hasEnquiries', '/tender/eligibilityCriteria', '/tender/numberOfTenderers', '/tender/tenderers/0/name', '/tender/tenderers/0/id', '/tender/contractPeriod/startDate', '/tender/contractPeriod/endDate', '/tender/contractPeriod/maxExtentDate', '/tender/contractPeriod/durationInDays', '/tender/awardPeriod/startDate', '/tender/awardPeriod/endDate', '/tender/awardPeriod/maxExtentDate', '/tender/awardPeriod/durationInDays', '/tender/enquiryPeriod/startDate', '/tender/enquiryPeriod/endDate', '/tender/enquiryPeriod/maxExtentDate', '/tender/enquiryPeriod/durationInDays', '/tender/tenderPeriod/startDate', '/tender/tenderPeriod/endDate', '/tender/tenderPeriod/maxExtentDate', '/tender/tenderPeriod/durationInDays', '/tender/minValue/amount', '/tender/minValue/currency', '/tender/value/amount', '/tender/value/currency', '/tender/items/0/id', '/tender/items/0/description', '/tender/items/0/quantity', '/tender/items/0/unit/scheme', '/tender/items/0/unit/id', '/tender/items/0/unit/name', '/tender/items/0/unit/uri', '/tender/items/0/unit/value/amount', '/tender/items/0/unit/value/currency', '/tender/items/0/additionalClassifications/0/scheme', '/tender/items/0/additionalClassifications/0/id', '/tender/items/0/additionalClassifications/0/description', '/tender/items/0/additionalClassifications/0/uri', '/tender/items/0/classification/scheme', '/tender/items/0/classification/id', '/tender/items/0/classification/description', '/tender/items/0/classification/uri', '/tender/procuringEntity/name', '/tender/procuringEntity/id']
awards_columns = ['/awards/id', '/awards/title', '/awards/description', '/awards/status', '/awards/date', '/awards/contractPeriod/startDate', '/awards/contractPeriod/endDate', '/awards/contractPeriod/maxExtentDate', '/awards/contractPeriod/durationInDays', '/awards/value/amount', '/awards/value/currency']
awards_combined_columns = ['/awards/id', '/awards/title', '/awards/description', '/awards/status', '/awards/date', '/awards/contractPeriod/startDate', '/awards/contractPeriod/endDate', '/awards/contractPeriod/maxExtentDate', '/awards/contractPeriod/durationInDays', '/awards/items/0/id', '/awards/items/0/description', '/awards/items/0/quantity', '/awards/items/0/unit/scheme', '/awards/items/0/unit/id', '/awards/items/0/unit/name', '/awards/items/0/unit/uri', '/awards/items/0/unit/value/amount', '/awards/items/0/unit/value/currency', '/awards/items/0/additionalClassifications/0/scheme', '/awards/items/0/additionalClassifications/0/id', '/awards/items/0/additionalClassifications/0/description', '/awards/items/0/additionalClassifications/0/uri', '/awards/items/0/classification/scheme', '/awards/items/0/classification/id', '/awards/items/0/classification/description', '/awards/items/0/classification/uri', '/awards/suppliers/0/name', '/awards/suppliers/0/id', '/awards/value/amount', '/awards/value/currency']
awards_arrays = ['/awards/suppliers', '/awards/items', '/awards/items/additionalClassifications']
contracts_columns = ['/contracts/id', '/contracts/awardID', '/contracts/title', '/contracts/description', '/contracts/status', '/contracts/dateSigned', '/contracts/value/amount', '/contracts/value/currency', '/contracts/period/startDate', '/contracts/period/endDate', '/contracts/period/maxExtentDate', '/contracts/period/durationInDays']
contracts_arrays = ['/contracts/items', '/contracts/relatedProcesses', '/contracts/implementation/transactions', '/contracts/items/additionalClassifications']
contracts_combined_columns = ['/contracts/id', '/contracts/awardID', '/contracts/title', '/contracts/description', '/contracts/status', '/contracts/dateSigned', '/contracts/relatedProcesses/0/id', '/contracts/relatedProcesses/0/relationship', '/contracts/relatedProcesses/0/title', '/contracts/relatedProcesses/0/scheme', '/contracts/relatedProcesses/0/identifier', '/contracts/relatedProcesses/0/uri', '/contracts/implementation/transactions/0/id', '/contracts/implementation/transactions/0/source', '/contracts/implementation/transactions/0/date', '/contracts/implementation/transactions/0/uri', '/contracts/implementation/transactions/0/payee/name', '/contracts/implementation/transactions/0/payee/id', '/contracts/implementation/transactions/0/payer/name', '/contracts/implementation/transactions/0/payer/id', '/contracts/implementation/transactions/0/value/amount', '/contracts/implementation/transactions/0/value/currency', '/contracts/items/0/id', '/contracts/items/0/description', '/contracts/items/0/quantity', '/contracts/items/0/unit/scheme', '/contracts/items/0/unit/id', '/contracts/items/0/unit/name', '/contracts/items/0/unit/uri', '/contracts/items/0/unit/value/amount', '/contracts/items/0/unit/value/currency', '/contracts/items/0/additionalClassifications/0/scheme', '/contracts/items/0/additionalClassifications/0/id', '/contracts/items/0/additionalClassifications/0/description', '/contracts/items/0/additionalClassifications/0/uri', '/contracts/items/0/classification/scheme', '/contracts/items/0/classification/id', '/contracts/items/0/classification/description', '/contracts/items/0/classification/uri', '/contracts/value/amount', '/contracts/value/currency', '/contracts/period/startDate', '/contracts/period/endDate', '/contracts/period/maxExtentDate', '/contracts/period/durationInDays']
planning_columns = ['/planning/rationale', '/planning/budget/id', '/planning/budget/description', '/planning/budget/project', '/planning/budget/projectID', '/planning/budget/uri', '/planning/budget/amount/amount', '/planning/budget/amount/currency']
planning_combined_columns = ['/planning/rationale', '/planning/budget/id', '/planning/budget/description', '/planning/budget/project', '/planning/budget/projectID', '/planning/budget/uri', '/planning/budget/amount/amount', '/planning/budget/amount/currency']
planning_arrays = []
parties_arrays = ['/parties/additionalIdentifiers']
parties_columns = ['/parties/name', '/parties/id', '/parties/roles', '/parties/contactPoint/name', '/parties/contactPoint/email', '/parties/contactPoint/telephone', '/parties/contactPoint/faxNumber', '/parties/contactPoint/url', '/parties/address/streetAddress', '/parties/address/locality', '/parties/address/region', '/parties/address/postalCode', '/parties/address/countryName', '/parties/identifier/scheme', '/parties/identifier/id', '/parties/identifier/legalName', '/parties/identifier/uri']
parties_combined_columns = ['/parties/name', '/parties/id', '/parties/roles', '/parties/roles', '/parties/contactPoint/name', '/parties/contactPoint/email', '/parties/contactPoint/telephone', '/parties/contactPoint/faxNumber', '/parties/contactPoint/url', '/parties/address/streetAddress', '/parties/address/locality', '/parties/address/region', '/parties/address/postalCode', '/parties/address/countryName', '/parties/additionalIdentifiers/0/scheme', '/parties/additionalIdentifiers/0/id', '/parties/additionalIdentifiers/0/legalName', '/parties/additionalIdentifiers/0/uri', '/parties/identifier/scheme', '/parties/identifier/id', '/parties/identifier/legalName', '/parties/identifier/uri'] |
def pattern_nineteen(steps):
''' Pattern nineteen
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
'''
for i in range(1, steps + 1):
num_list = []
for j in range(1, steps + 1):
num_list.append(str(i * j).ljust(4)) # Change 3 to different value if i * j is more than 3 digits
print(' '.join(num_list))
if __name__ == '__main__':
try:
pattern_nineteen(10)
except NameError:
print('Integer was expected')
| def pattern_nineteen(steps):
""" Pattern nineteen
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
"""
for i in range(1, steps + 1):
num_list = []
for j in range(1, steps + 1):
num_list.append(str(i * j).ljust(4))
print(' '.join(num_list))
if __name__ == '__main__':
try:
pattern_nineteen(10)
except NameError:
print('Integer was expected') |
n1 = float(input('qual a primeira nota? '))
n2 = float(input('qual a segunda nota? '))
soma = n1 + n2
media = (n1 + n2) / 2
print('a soma das notas foi {:.2f}, e a sua media foi de {:.2f}'.format(soma, media))
| n1 = float(input('qual a primeira nota? '))
n2 = float(input('qual a segunda nota? '))
soma = n1 + n2
media = (n1 + n2) / 2
print('a soma das notas foi {:.2f}, e a sua media foi de {:.2f}'.format(soma, media)) |
'''
02 - Creating dummy variables
As Andy discussed in the video, scikit-learn does not accept non-numerical features.
You saw in the previous exercise that the 'Region' feature contains very useful
information that can predict life expectancy.
For example: Sub-Saharan Africa has a lower life expectancy compared to Europe and
Central Asia. Therefore, if you are trying to predict life expectancy, it would be
preferable to retain the 'Region' feature. To do this, you need to binarize it by
creating dummy variables, which is what you will do in this exercise.
INSTRUCTIONS
- Use the pandas get_dummies() function to create dummy variables from the df DataFrame.
Store the result as df_region.
- Print the columns of df_region. This has been done for you.
- Use the get_dummies() function again, this time specifying drop_first=True to drop the
unneeded dummy variable (in this case, 'Region_America').
- Hit 'Submit Answer to print the new columns of df_region and take note of how one column
was dropped!
'''
# Create dummy variables: df_region
df_region = pd.get_dummies(df)
# Print the columns of df_region
print(df_region.columns)
# Create dummy variables with drop_first=True: df_region
df_region = pd.get_dummies(df, drop_first=True)
# Print the new columns of df_region
print(df_region.columns)
'''
Index(['population', 'fertility', 'HIV', 'CO2', 'BMI_male', 'GDP',
'BMI_female', 'life', 'child_mortality', 'Region_America',
'Region_East Asia & Pacific', 'Region_Europe & Central Asia',
'Region_Middle East & North Africa', 'Region_South Asia',
'Region_Sub-Saharan Africa'],
dtype='object')
Index(['population', 'fertility', 'HIV', 'CO2', 'BMI_male', 'GDP',
'BMI_female', 'life', 'child_mortality', 'Region_East Asia & Pacific',
'Region_Europe & Central Asia', 'Region_Middle East & North Africa',
'Region_South Asia', 'Region_Sub-Saharan Africa'],
dtype='object')
'''
| """
02 - Creating dummy variables
As Andy discussed in the video, scikit-learn does not accept non-numerical features.
You saw in the previous exercise that the 'Region' feature contains very useful
information that can predict life expectancy.
For example: Sub-Saharan Africa has a lower life expectancy compared to Europe and
Central Asia. Therefore, if you are trying to predict life expectancy, it would be
preferable to retain the 'Region' feature. To do this, you need to binarize it by
creating dummy variables, which is what you will do in this exercise.
INSTRUCTIONS
- Use the pandas get_dummies() function to create dummy variables from the df DataFrame.
Store the result as df_region.
- Print the columns of df_region. This has been done for you.
- Use the get_dummies() function again, this time specifying drop_first=True to drop the
unneeded dummy variable (in this case, 'Region_America').
- Hit 'Submit Answer to print the new columns of df_region and take note of how one column
was dropped!
"""
df_region = pd.get_dummies(df)
print(df_region.columns)
df_region = pd.get_dummies(df, drop_first=True)
print(df_region.columns)
"\nIndex(['population', 'fertility', 'HIV', 'CO2', 'BMI_male', 'GDP',\n 'BMI_female', 'life', 'child_mortality', 'Region_America',\n 'Region_East Asia & Pacific', 'Region_Europe & Central Asia',\n 'Region_Middle East & North Africa', 'Region_South Asia',\n 'Region_Sub-Saharan Africa'],\n dtype='object')\n \nIndex(['population', 'fertility', 'HIV', 'CO2', 'BMI_male', 'GDP',\n 'BMI_female', 'life', 'child_mortality', 'Region_East Asia & Pacific',\n 'Region_Europe & Central Asia', 'Region_Middle East & North Africa',\n 'Region_South Asia', 'Region_Sub-Saharan Africa'],\n dtype='object')\n" |
# Given three colinear points p, q, r, the function checks if
# point q lies on line segment 'pr'
def onSegment(p, q, r):
if ( (q.position[0] <= max(p.position[0], r.position[0])) and (q.position[0] >= min(p.position[0], r.position[0])) and
(q.position[1] <= max(p.position[1], r.position[1])) and (q.position[1] >= min(p.position[1], r.position[1]))):
return True
return False
def orientation(p, q, r):
# to find the orientation of an ordered triplet (p,q,r)
# function returns the following values:
# 0 : Colinear points
# 1 : Clockwise points
# 2 : Counterclockwise
# See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/
# for details of below formula.
val = (float(q.position[1] - p.position[1]) * (r.position[0] - q.position[0])) - (float(q.position[0] - p.position[0]) * (r.position[1] - q.position[1]))
if (val > 0):
# Clockwise orientation
return 1
elif (val < 0):
# Counterclockwise orientation
return 2
else:
# Colinear orientation
return 0
# The main function that returns true if
# the line segment 'p1q1' and 'p2q2' intersect.
def doIntersect(p1,q1,p2,q2):
if (p1.position == p2.position
or p1.position == q2.position
or q1.position == p2.position
or q1.position == q2.position):
return False
# Find the 4 orientations required for
# the general and special cases
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
# General case
if ((o1 != o2) and (o3 != o4)):
return True
# Special Cases
# p1 , q1 and p2 are colinear and p2 lies on segment p1q1
if ((o1 == 0) and onSegment(p1, p2, q1)):
return True
# p1 , q1 and q2 are colinear and q2 lies on segment p1q1
if ((o2 == 0) and onSegment(p1, q2, q1)):
return True
# p2 , q2 and p1 are colinear and p1 lies on segment p2q2
if ((o3 == 0) and onSegment(p2, p1, q2)):
return True
# p2 , q2 and q1 are colinear and q1 lies on segment p2q2
if ((o4 == 0) and onSegment(p2, q1, q2)):
return True
# If none of the cases
return False
# # Driver program to test above functions:
# p1 = Point(1, 1)
# q1 = Point(10, 1)
# p2 = Point(1, 2)
# q2 = Point(10, 2)
# if doIntersect(p1, q1, p2, q2):
# print("Yes")
# else:
# print("No")
# p1 = Point(10, 0)
# q1 = Point(0, 10)
# p2 = Point(0, 0)
# q2 = Point(10,10)
# if doIntersect(p1, q1, p2, q2):
# print("Yes")
# else:
# print("No")
# p1 = Point(-5,-5)
# q1 = Point(0, 0)
# p2 = Point(1, 1)
# q2 = Point(10, 10)
# if doIntersect(p1, q1, p2, q2):
# print("Yes")
# else:
# print("No") | def on_segment(p, q, r):
if q.position[0] <= max(p.position[0], r.position[0]) and q.position[0] >= min(p.position[0], r.position[0]) and (q.position[1] <= max(p.position[1], r.position[1])) and (q.position[1] >= min(p.position[1], r.position[1])):
return True
return False
def orientation(p, q, r):
val = float(q.position[1] - p.position[1]) * (r.position[0] - q.position[0]) - float(q.position[0] - p.position[0]) * (r.position[1] - q.position[1])
if val > 0:
return 1
elif val < 0:
return 2
else:
return 0
def do_intersect(p1, q1, p2, q2):
if p1.position == p2.position or p1.position == q2.position or q1.position == p2.position or (q1.position == q2.position):
return False
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
if o1 != o2 and o3 != o4:
return True
if o1 == 0 and on_segment(p1, p2, q1):
return True
if o2 == 0 and on_segment(p1, q2, q1):
return True
if o3 == 0 and on_segment(p2, p1, q2):
return True
if o4 == 0 and on_segment(p2, q1, q2):
return True
return False |
class SystemCallFault(Exception):
def __init__(self):
pass
def __str__(self):
return 'System not give expect response.'
class NecessaryLibraryNotFound(Exception):
def __init__(self,value = '?'):
self.value = value
def __str__(self):
return 'Necessary library \'%s\' not found.'%self.value | class Systemcallfault(Exception):
def __init__(self):
pass
def __str__(self):
return 'System not give expect response.'
class Necessarylibrarynotfound(Exception):
def __init__(self, value='?'):
self.value = value
def __str__(self):
return "Necessary library '%s' not found." % self.value |
string = "Character"
print(string[2])
# string[2] = 'A' not change it
# string.replace('a','A') we can replace it but it cannot change the our string variables.
new_string = string.replace('a','A')
print(new_string) | string = 'Character'
print(string[2])
new_string = string.replace('a', 'A')
print(new_string) |
## CvAltRoot
##
## Tells BUG where to locate its files when it cannot find them normally.
## This is common when using the /AltRoot Civ4 feature or sometimes on
## non-English operating systems and Windows Vista.
##
## HOW TO USE
##
## 1. Change the text in the quotes below to match the full path to the
## "Beyond the Sword" folder that contains the CivilizationIV.ini file.
## Make sure to use forward slashes (/), even for Windows paths.
##
## Windows XP: "C:/Documents and Settings/[UserName]/My Documents/My Games/Beyond the Sword"
##
## Windows Vista: "C:/Users/[UserName]/Documents/My Games/Beyond the Sword"
##
## MacOS: "/home/[UserName]/Documents/Beyond the Sword"
##
## 2. Copy this file to the "Python" folder.
## When BUG is installed as a mod, the folder is "Assets/Python".
## When BUG is installed normally, the folder is "CustomAssets/Python".
##
## Copyright (c) 2008 The BUG Mod.
##
## Author: EmperorFool
rootDir = "C:/Documents and Settings/[UserName]/My Documents/My Games/Beyond the Sword"
| root_dir = 'C:/Documents and Settings/[UserName]/My Documents/My Games/Beyond the Sword' |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
class Config:
q_target = 0
expected_sarsa_target = 1
def __init__(self):
self.task_fn = None
self.optimizer_fn = None
self.actor_optimizer_fn = None
self.critic_optimizer_fn = None
self.network_fn = None
self.actor_network_fn = None
self.critic_network_fn = None
self.policy_fn = None
self.replay_fn = None
self.random_process_fn = None
self.discount = 0.99
self.target_network_update_freq = 0
self.max_episode_length = 0
self.exploration_steps = 0
self.logger = None
self.history_length = 1
self.test_interval = 100
self.test_repetitions = 50
self.double_q = False
self.tag = 'vanilla'
self.num_workers = 1
self.worker = None
self.update_interval = 1
self.gradient_clip = 40
self.entropy_weight = 0.01
self.use_gae = True
self.gae_tau = 1.0
self.noise_decay_interval = 0
self.target_network_mix = 0.001
self.action_shift_fn = lambda a: a
self.reward_shift_fn = lambda r: r
self.reward_weight = 1
self.hybrid_reward = False
self.target_type = self.q_target
self.episode_limit = 0
self.min_memory_size = 200
self.master_fn = None
self.master_optimizer_fn = None
self.num_heads = 10
self.min_epsilon = 0
self.save_interval = 0
self.max_steps = 0
self.success_threshold = float('inf')
self.render_episode_freq = 0
self.rollout_length = None
self.value_loss_weight = 1.0
self.iteration_log_interval = 30
self.categorical_v_min = -10
self.categorical_v_max = 10
self.categorical_n_atoms = 51
| class Config:
q_target = 0
expected_sarsa_target = 1
def __init__(self):
self.task_fn = None
self.optimizer_fn = None
self.actor_optimizer_fn = None
self.critic_optimizer_fn = None
self.network_fn = None
self.actor_network_fn = None
self.critic_network_fn = None
self.policy_fn = None
self.replay_fn = None
self.random_process_fn = None
self.discount = 0.99
self.target_network_update_freq = 0
self.max_episode_length = 0
self.exploration_steps = 0
self.logger = None
self.history_length = 1
self.test_interval = 100
self.test_repetitions = 50
self.double_q = False
self.tag = 'vanilla'
self.num_workers = 1
self.worker = None
self.update_interval = 1
self.gradient_clip = 40
self.entropy_weight = 0.01
self.use_gae = True
self.gae_tau = 1.0
self.noise_decay_interval = 0
self.target_network_mix = 0.001
self.action_shift_fn = lambda a: a
self.reward_shift_fn = lambda r: r
self.reward_weight = 1
self.hybrid_reward = False
self.target_type = self.q_target
self.episode_limit = 0
self.min_memory_size = 200
self.master_fn = None
self.master_optimizer_fn = None
self.num_heads = 10
self.min_epsilon = 0
self.save_interval = 0
self.max_steps = 0
self.success_threshold = float('inf')
self.render_episode_freq = 0
self.rollout_length = None
self.value_loss_weight = 1.0
self.iteration_log_interval = 30
self.categorical_v_min = -10
self.categorical_v_max = 10
self.categorical_n_atoms = 51 |
# question 1
A = 3
B = 3
C = (-5)
X = 8.8
Y = 3.5
Z = (-5.2)
print(A % C)
print(A * B / C)
print((A * C) % C)
print(X / Y)
print(X / (X + Y))
print(int(X) % int(Y))
# question 2
A = float(input("the number you want to round off:"))
print(round(A))
# question 3
A = float(input("length in CM:"))
B = float(input("length in CM:"))
C = (A / (12 * 5 / 2))
D = (B * 5 / 2)
print(C, D)
# question 4
A = int(input("enter the radius:"))
print(4 / 3 * 3.14 * A * A * A)
# question 5
F = float(input("enter the Teamprature in Celsius:"))
C = (F * 9 / 5) + 32
print(C)
# question 6
L = float(input("enter the lenght of rectangle:"))
B = float(input("enter the width of rectangle:"))
P = 2 * (L + B)
print(P)
# question 7
A = float(input("enter the first number"))
B = float(input("enter the second number:"))
C = float(input("enter the third number:"))
M = float((A + B + C) / 2)
print(M)
'''
A=str(input("enter the pattern:"))
print(A[0])
print((A[0]+A[1])*2)
print((A[0]+A[1]+A[2])*2)
'''
A = int(input("enter a integer"))
B = int(input("enter a integer"))
c = A + B - A % B
print(c)
AGE = int(input("enter you age"))
if 15 <= AGE < 46:
print("you are eligible ti ride roller coaster")
else:
print("you are eligible ti ride roller coaster")
A = int(input("enter the number"))
if (A % 5 == 0) and (A % 7 == 0):
print("its divisible by 7 and 5")
else:
print("ts not divisible by 7 and 5")
# vowels problem in school
name = input("enter your name :")
vowels = ["a", "e", "i", "o", "u"]
if name[0] in vowels:
print("name starts with vowels")
else:
print("name does not starts with vowels")
| a = 3
b = 3
c = -5
x = 8.8
y = 3.5
z = -5.2
print(A % C)
print(A * B / C)
print(A * C % C)
print(X / Y)
print(X / (X + Y))
print(int(X) % int(Y))
a = float(input('the number you want to round off:'))
print(round(A))
a = float(input('length in CM:'))
b = float(input('length in CM:'))
c = A / (12 * 5 / 2)
d = B * 5 / 2
print(C, D)
a = int(input('enter the radius:'))
print(4 / 3 * 3.14 * A * A * A)
f = float(input('enter the Teamprature in Celsius:'))
c = F * 9 / 5 + 32
print(C)
l = float(input('enter the lenght of rectangle:'))
b = float(input('enter the width of rectangle:'))
p = 2 * (L + B)
print(P)
a = float(input('enter the first number'))
b = float(input('enter the second number:'))
c = float(input('enter the third number:'))
m = float((A + B + C) / 2)
print(M)
'\nA=str(input("enter the pattern:"))\nprint(A[0])\nprint((A[0]+A[1])*2)\nprint((A[0]+A[1]+A[2])*2)\n'
a = int(input('enter a integer'))
b = int(input('enter a integer'))
c = A + B - A % B
print(c)
age = int(input('enter you age'))
if 15 <= AGE < 46:
print('you are eligible ti ride roller coaster')
else:
print('you are eligible ti ride roller coaster')
a = int(input('enter the number'))
if A % 5 == 0 and A % 7 == 0:
print('its divisible by 7 and 5')
else:
print('ts not divisible by 7 and 5')
name = input('enter your name :')
vowels = ['a', 'e', 'i', 'o', 'u']
if name[0] in vowels:
print('name starts with vowels')
else:
print('name does not starts with vowels') |
# coding=utf-8
setThrowException(True)
class Nautilus:
REMOTE = 0
LOCAL = 1
_tab = None
_dirs = {}
def __init__(self):
self._dirs = {self.LOCAL: [], self.REMOTE: []}
self._startNautilus()
self._initWebdav()
sleep(1)
self._initLocal()
def _startNautilus(self):
openApp("/usr/bin/nautilus")
wait(Pattern("1265282313623.png").similar(0.70).firstN(1))
def _initWebdav(self):
click("1265202229746.png")
click("1265202325039.png")
click("1265202559414.png")
click("1265278752490.png")
type("1265278810480.png", "webdav")
type(Pattern("1266393612873.png").similar(0.80).firstN(1), "secure_collection")
type("1266320552496.png", "some")
click("1265279597052.png")
setThrowException(False)
pwField = wait(Pattern("1266321197328.png").similar(0.70).firstN(1), 6000)
# Nautilus stores password until user logs out
if len(pwField) != 0:
type(pwField.inside().find("1266321225325.png"), "thing")
checkBoxes = find(Pattern("1266321321797.png").similar(0.70).firstN(1))
click(checkBoxes.inside().find(Pattern("1266321357040.png").similar(0.70).firstN(1)))
click(Pattern("1266321387258.png").similar(0.70).firstN(1))
setThrowException(True)
self._tab = self.REMOTE
self._dirs[self.REMOTE].append("/")
self._dirs[self.REMOTE].append("secure_collection")
def _initLocal(self):
type("t", KEY_CTRL)
sleep(1)
self._tab = self.LOCAL
click("1265313336023.png")
self._dirs[self.LOCAL].append("/")
self.openLocal("1265314310481.png", "down")
def switchRemote(self):
if (self._tab == self.LOCAL):
type(Key.PAGE_UP, KEY_CTRL)
self._tab = self.REMOTE
sleep(0.4)
def switchLocal(self):
if (self._tab == self.REMOTE):
type(Key.PAGE_DOWN, KEY_CTRL)
self._tab = self.LOCAL
sleep(0.4)
def openLocal(self, dirImg, dirName):
self.switchLocal()
self._open(dirImg, dirName)
def _open(self, dirImg, dirName):
doubleClick(dirImg)
self._dirs[self._tab].append(dirName)
def openRemote(self, dirImg, dirName):
self.switchRemote()
self._open(dirImg, dirName)
def upRemote(self, dirName=None):
self.switchRemote()
sleep(1)
self.goUp(dirName)
def upLocal(self, dirName=None):
self.switchLocal()
sleep(1)
self.goUp(dirName)
def goUp(self, dirName):
if dirName == None:
click(Pattern("1266259183958.png").similar(0.90).firstN(1))
self._dirs[self._tab].pop()
return
while self._dirs[self._tab][-1] != dirName:
click(Pattern("1266259183958.png").similar(0.90).firstN(1))
self._dirs[self._tab].pop()
def copy(self):
type("c", KEY_CTRL)
def paste(self):
type("v", KEY_CTRL)
def rename(self, fileImg, newName, newFileImg):
click(fileImg)
sleep(0.2)
type(Key.F2)
sleep(0.5)
type("a", KEY_CTRL)
sleep(0.2)
paste(newName)
sleep(0.1)
type(Key.ENTER)
wait(newFileImg)
class NautilusWebdavTest:
_nautilus = None
def __init__(self, nautilus):
self._nautilus = nautilus
def run(self):
# secure_collection opened initially
# self.testInitial()
self.testListCollection()
self.testDownloadSingle()
self.testListSubdir()
self.testDownloadMultiple()
self.testCreateNewdir()
self.testListNewdir()
self.testUploadSingle()
self.testCreateNewsubdir()
self.testListNewsubdir()
self.testUploadSingleOverwrite()
self.testDeleteNewdir()
self.testUploadNew()
self.testDownloadUploaded()
self.testRenameFiles()
self.testCopyFilesRemote()
self.testRenameCollection()
def testInitial(self):
self._nautilus.switchRemote()
find(Pattern("1265793342336.png").similar(0.70).firstN(1))
def testListCollection(self):
# secure_collection opened on init
# self._nautilus.openRemote("1265279909203.png", "collection")
self._nautilus.switchRemote()
find(Pattern("1265793562509.png").similar(0.70).firstN(1))
def testDownloadSingle(self):
self._nautilus.switchRemote()
click(Pattern("1265314613379.png").similar(0.95).firstN(1))
self._nautilus.copy()
self._nautilus.switchLocal()
sleep(1)
self._nautilus.paste()
sleep(1)
find(Pattern("1266397437910.png").similar(0.80).firstN(1))
def testListSubdir(self):
self._nautilus.openRemote("1265315881723.png", "subdir")
find("1265315899109.png")
def testDownloadMultiple(self):
self._nautilus.switchRemote()
click(Pattern("1265795508414.png").similar(0.70).firstN(1))
type(Key.DOWN, KEY_SHIFT)
self._nautilus.copy()
sleep(1)
self._nautilus.switchLocal()
sleep(1)
self._nautilus.paste()
sleep(1)
find(Pattern("1265822372031.png").similar(0.90).firstN(1))
def testCreateNewdir(self):
self._nautilus.switchRemote()
type("n", KEY_CTRL | KEY_SHIFT)
sleep(1)
type("newdir")
type("\n")
find(Pattern("1266256110323.png").similar(0.90).firstN(1))
def testListNewdir(self):
self._nautilus.openRemote("1266256707500.png", "newdir")
find(Pattern("1266256773322.png").similar(0.90).firstN(1))
def testUploadSingle(self):
self._nautilus.switchLocal()
click(Pattern("1266256870724.png").similar(0.90).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
find(Pattern("1266256969255.png").similar(0.90).firstN(1))
def testCreateNewsubdir(self):
self._nautilus.switchRemote()
type("n", KEY_CTRL | KEY_SHIFT)
sleep(1)
type("newsubdir")
type("\n")
find(Pattern("1266257989662.png").similar(0.90).firstN(1))
def testListNewsubdir(self):
self._nautilus.openRemote("1266256707500.png", "newdir")
find(Pattern("1266258293601.png").similar(0.90).firstN(1))
def testUploadSingleOverwrite(self):
self._nautilus.switchLocal()
click(Pattern("1266257097775.png").similar(0.90).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
find(Pattern("1266258371198.png").similar(0.78).firstN(1))
self._nautilus.switchLocal()
click(Pattern("1266257097775.png").similar(0.90).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
wait(Pattern("1266397752968.png").similar(0.80).firstN(1))
dialog = find(Pattern("1266397783288.png").similar(0.80).firstN(1))
click(dialog.inside().find(Pattern("1266257459272.png").similar(0.90).firstN(1)))
find(Pattern("1266258834123.png").similar(0.90).firstN(1))
def testDeleteNewdir(self):
self._nautilus.upRemote("secure_collection")
click(Pattern("1266259247619.png").similar(0.90).firstN(1))
type(Key.DELETE)
wait(Pattern("1266259486059.png").similar(0.55).firstN(1))
dialog = find(Pattern("1266259486059.png").similar(0.55).firstN(1))
click(dialog.inside().find(Pattern("1266259533961.png").similar(0.90).firstN(1)))
sleep(1)
find(Pattern("1266398284223.png").similar(0.80).firstN(1))
def testUploadNew(self):
self._nautilus.upLocal("/")
self._nautilus.openLocal(Pattern("1266259890975.png").similar(0.90).firstN(1), "up")
type("a", KEY_CTRL)
sleep(0.5)
self._nautilus.copy()
self._nautilus.switchRemote()
sleep(1)
self._nautilus.paste()
find(Pattern("1266398512093.png").similar(0.70).firstN(1))
find(Pattern("1266398764125.png").similar(0.80).firstN(1))
def testDownloadUploaded(self):
self._nautilus.switchRemote()
# downloading dirs is broken in Nautilus
click(Pattern("1266269427884.png").similar(0.90).firstN(1))
type(Key.DOWN, KEY_SHIFT)
type(Key.DOWN, KEY_SHIFT)
type(Key.DOWN, KEY_SHIFT)
self._nautilus.copy()
self._nautilus.upLocal("/")
self._nautilus.openLocal("1265314310481.png", "down")
self._nautilus.paste()
def testRenameFiles(self):
self._nautilus.switchRemote()
self._nautilus.rename("1266270237742.png", u"put_test_renamed.xml", Pattern("1266270332525.png").similar(0.90).firstN(1))
self._nautilus.rename("1266270356862.png", u"put_test_utf8_\u00f6\u00e4\u00fc\u00df.txt", Pattern("1266274332854.png").similar(0.80).firstN(1))
self._nautilus.rename(Pattern("1266270558156.png").similar(0.90).firstN(1), u"put_non_utf8_test.txt", Pattern("1266270602424.png").similar(0.90).firstN(1))
def testCopyFilesRemote(self):
self._nautilus.switchRemote()
click(Pattern("1266274684143.png").similar(0.80).firstN(1))
# invert selection
type("i", KEY_CTRL | KEY_SHIFT)
sleep(1)
self._nautilus.copy()
self._nautilus.openRemote(Pattern("1266274684143.png").similar(0.80).firstN(1), "collection")
sleep(1)
self._nautilus.paste()
wait(Pattern("1266311546228.png").similar(0.70).firstN(1))
find(Pattern("1266311574320.png").similar(0.70).firstN(1))
find(Pattern("1266311712385.png").similar(0.70).firstN(1))
def testRenameCollection(self):
self._nautilus.upRemote()
self._nautilus.rename(Pattern("1266310197088.png").similar(0.90).firstN(1), "renamed_collection", Pattern("1266310220931.png").similar(0.90).firstN(1))
nautilus = Nautilus()
test = NautilusWebdavTest(nautilus)
test.run()
| set_throw_exception(True)
class Nautilus:
remote = 0
local = 1
_tab = None
_dirs = {}
def __init__(self):
self._dirs = {self.LOCAL: [], self.REMOTE: []}
self._startNautilus()
self._initWebdav()
sleep(1)
self._initLocal()
def _start_nautilus(self):
open_app('/usr/bin/nautilus')
wait(pattern('1265282313623.png').similar(0.7).firstN(1))
def _init_webdav(self):
click('1265202229746.png')
click('1265202325039.png')
click('1265202559414.png')
click('1265278752490.png')
type('1265278810480.png', 'webdav')
type(pattern('1266393612873.png').similar(0.8).firstN(1), 'secure_collection')
type('1266320552496.png', 'some')
click('1265279597052.png')
set_throw_exception(False)
pw_field = wait(pattern('1266321197328.png').similar(0.7).firstN(1), 6000)
if len(pwField) != 0:
type(pwField.inside().find('1266321225325.png'), 'thing')
check_boxes = find(pattern('1266321321797.png').similar(0.7).firstN(1))
click(checkBoxes.inside().find(pattern('1266321357040.png').similar(0.7).firstN(1)))
click(pattern('1266321387258.png').similar(0.7).firstN(1))
set_throw_exception(True)
self._tab = self.REMOTE
self._dirs[self.REMOTE].append('/')
self._dirs[self.REMOTE].append('secure_collection')
def _init_local(self):
type('t', KEY_CTRL)
sleep(1)
self._tab = self.LOCAL
click('1265313336023.png')
self._dirs[self.LOCAL].append('/')
self.openLocal('1265314310481.png', 'down')
def switch_remote(self):
if self._tab == self.LOCAL:
type(Key.PAGE_UP, KEY_CTRL)
self._tab = self.REMOTE
sleep(0.4)
def switch_local(self):
if self._tab == self.REMOTE:
type(Key.PAGE_DOWN, KEY_CTRL)
self._tab = self.LOCAL
sleep(0.4)
def open_local(self, dirImg, dirName):
self.switchLocal()
self._open(dirImg, dirName)
def _open(self, dirImg, dirName):
double_click(dirImg)
self._dirs[self._tab].append(dirName)
def open_remote(self, dirImg, dirName):
self.switchRemote()
self._open(dirImg, dirName)
def up_remote(self, dirName=None):
self.switchRemote()
sleep(1)
self.goUp(dirName)
def up_local(self, dirName=None):
self.switchLocal()
sleep(1)
self.goUp(dirName)
def go_up(self, dirName):
if dirName == None:
click(pattern('1266259183958.png').similar(0.9).firstN(1))
self._dirs[self._tab].pop()
return
while self._dirs[self._tab][-1] != dirName:
click(pattern('1266259183958.png').similar(0.9).firstN(1))
self._dirs[self._tab].pop()
def copy(self):
type('c', KEY_CTRL)
def paste(self):
type('v', KEY_CTRL)
def rename(self, fileImg, newName, newFileImg):
click(fileImg)
sleep(0.2)
type(Key.F2)
sleep(0.5)
type('a', KEY_CTRL)
sleep(0.2)
paste(newName)
sleep(0.1)
type(Key.ENTER)
wait(newFileImg)
class Nautiluswebdavtest:
_nautilus = None
def __init__(self, nautilus):
self._nautilus = nautilus
def run(self):
self.testListCollection()
self.testDownloadSingle()
self.testListSubdir()
self.testDownloadMultiple()
self.testCreateNewdir()
self.testListNewdir()
self.testUploadSingle()
self.testCreateNewsubdir()
self.testListNewsubdir()
self.testUploadSingleOverwrite()
self.testDeleteNewdir()
self.testUploadNew()
self.testDownloadUploaded()
self.testRenameFiles()
self.testCopyFilesRemote()
self.testRenameCollection()
def test_initial(self):
self._nautilus.switchRemote()
find(pattern('1265793342336.png').similar(0.7).firstN(1))
def test_list_collection(self):
self._nautilus.switchRemote()
find(pattern('1265793562509.png').similar(0.7).firstN(1))
def test_download_single(self):
self._nautilus.switchRemote()
click(pattern('1265314613379.png').similar(0.95).firstN(1))
self._nautilus.copy()
self._nautilus.switchLocal()
sleep(1)
self._nautilus.paste()
sleep(1)
find(pattern('1266397437910.png').similar(0.8).firstN(1))
def test_list_subdir(self):
self._nautilus.openRemote('1265315881723.png', 'subdir')
find('1265315899109.png')
def test_download_multiple(self):
self._nautilus.switchRemote()
click(pattern('1265795508414.png').similar(0.7).firstN(1))
type(Key.DOWN, KEY_SHIFT)
self._nautilus.copy()
sleep(1)
self._nautilus.switchLocal()
sleep(1)
self._nautilus.paste()
sleep(1)
find(pattern('1265822372031.png').similar(0.9).firstN(1))
def test_create_newdir(self):
self._nautilus.switchRemote()
type('n', KEY_CTRL | KEY_SHIFT)
sleep(1)
type('newdir')
type('\n')
find(pattern('1266256110323.png').similar(0.9).firstN(1))
def test_list_newdir(self):
self._nautilus.openRemote('1266256707500.png', 'newdir')
find(pattern('1266256773322.png').similar(0.9).firstN(1))
def test_upload_single(self):
self._nautilus.switchLocal()
click(pattern('1266256870724.png').similar(0.9).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
find(pattern('1266256969255.png').similar(0.9).firstN(1))
def test_create_newsubdir(self):
self._nautilus.switchRemote()
type('n', KEY_CTRL | KEY_SHIFT)
sleep(1)
type('newsubdir')
type('\n')
find(pattern('1266257989662.png').similar(0.9).firstN(1))
def test_list_newsubdir(self):
self._nautilus.openRemote('1266256707500.png', 'newdir')
find(pattern('1266258293601.png').similar(0.9).firstN(1))
def test_upload_single_overwrite(self):
self._nautilus.switchLocal()
click(pattern('1266257097775.png').similar(0.9).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
find(pattern('1266258371198.png').similar(0.78).firstN(1))
self._nautilus.switchLocal()
click(pattern('1266257097775.png').similar(0.9).firstN(1))
self._nautilus.copy()
self._nautilus.switchRemote()
self._nautilus.paste()
wait(pattern('1266397752968.png').similar(0.8).firstN(1))
dialog = find(pattern('1266397783288.png').similar(0.8).firstN(1))
click(dialog.inside().find(pattern('1266257459272.png').similar(0.9).firstN(1)))
find(pattern('1266258834123.png').similar(0.9).firstN(1))
def test_delete_newdir(self):
self._nautilus.upRemote('secure_collection')
click(pattern('1266259247619.png').similar(0.9).firstN(1))
type(Key.DELETE)
wait(pattern('1266259486059.png').similar(0.55).firstN(1))
dialog = find(pattern('1266259486059.png').similar(0.55).firstN(1))
click(dialog.inside().find(pattern('1266259533961.png').similar(0.9).firstN(1)))
sleep(1)
find(pattern('1266398284223.png').similar(0.8).firstN(1))
def test_upload_new(self):
self._nautilus.upLocal('/')
self._nautilus.openLocal(pattern('1266259890975.png').similar(0.9).firstN(1), 'up')
type('a', KEY_CTRL)
sleep(0.5)
self._nautilus.copy()
self._nautilus.switchRemote()
sleep(1)
self._nautilus.paste()
find(pattern('1266398512093.png').similar(0.7).firstN(1))
find(pattern('1266398764125.png').similar(0.8).firstN(1))
def test_download_uploaded(self):
self._nautilus.switchRemote()
click(pattern('1266269427884.png').similar(0.9).firstN(1))
type(Key.DOWN, KEY_SHIFT)
type(Key.DOWN, KEY_SHIFT)
type(Key.DOWN, KEY_SHIFT)
self._nautilus.copy()
self._nautilus.upLocal('/')
self._nautilus.openLocal('1265314310481.png', 'down')
self._nautilus.paste()
def test_rename_files(self):
self._nautilus.switchRemote()
self._nautilus.rename('1266270237742.png', u'put_test_renamed.xml', pattern('1266270332525.png').similar(0.9).firstN(1))
self._nautilus.rename('1266270356862.png', u'put_test_utf8_öäüß.txt', pattern('1266274332854.png').similar(0.8).firstN(1))
self._nautilus.rename(pattern('1266270558156.png').similar(0.9).firstN(1), u'put_non_utf8_test.txt', pattern('1266270602424.png').similar(0.9).firstN(1))
def test_copy_files_remote(self):
self._nautilus.switchRemote()
click(pattern('1266274684143.png').similar(0.8).firstN(1))
type('i', KEY_CTRL | KEY_SHIFT)
sleep(1)
self._nautilus.copy()
self._nautilus.openRemote(pattern('1266274684143.png').similar(0.8).firstN(1), 'collection')
sleep(1)
self._nautilus.paste()
wait(pattern('1266311546228.png').similar(0.7).firstN(1))
find(pattern('1266311574320.png').similar(0.7).firstN(1))
find(pattern('1266311712385.png').similar(0.7).firstN(1))
def test_rename_collection(self):
self._nautilus.upRemote()
self._nautilus.rename(pattern('1266310197088.png').similar(0.9).firstN(1), 'renamed_collection', pattern('1266310220931.png').similar(0.9).firstN(1))
nautilus = nautilus()
test = nautilus_webdav_test(nautilus)
test.run() |
print((2**64).to_bytes(9, "little",signed=False))
#signed shall be False by default
print((2**64).to_bytes(9, "little"))
# test min/max signed value
for i in [10]:
v = 2**(i*8 - 1) - 1
print(v)
vbytes = v.to_bytes(i, "little")
print(vbytes)
print(int.from_bytes(vbytes,"little"))
v = - (2**(i*8 - 1))
print(v)
vbytes = v.to_bytes(i, "little",signed=True)
print(vbytes)
print(int.from_bytes(vbytes,"little",signed=True))
# negative number should raise an error if signed=False
try:
(- (2**64)).to_bytes(9, "little",signed=False)
except OverflowError:
print("OverflowError")
| print((2 ** 64).to_bytes(9, 'little', signed=False))
print((2 ** 64).to_bytes(9, 'little'))
for i in [10]:
v = 2 ** (i * 8 - 1) - 1
print(v)
vbytes = v.to_bytes(i, 'little')
print(vbytes)
print(int.from_bytes(vbytes, 'little'))
v = -2 ** (i * 8 - 1)
print(v)
vbytes = v.to_bytes(i, 'little', signed=True)
print(vbytes)
print(int.from_bytes(vbytes, 'little', signed=True))
try:
(-2 ** 64).to_bytes(9, 'little', signed=False)
except OverflowError:
print('OverflowError') |
x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
print()
print(x%y)
print(y%x)
print()
print(x//y)
print(y//x) | x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
print()
print(x % y)
print(y % x)
print()
print(x // y)
print(y // x) |
SEAL_CHECKER = 9300535
SEAL_OF_TIME_1 = 2159363
SEAL_OF_TIME_2 = 2159364
SEAL_OF_TIME_3 = 2159365
SEAL_OF_TIME_4 = 2159366
sm.giveSkill(20041222)
sm.setFuncKeyByScript(True, 20041222, 42)
sm.spawnMob(SEAL_CHECKER, 550, -298, False)
sm.spawnMob(SEAL_CHECKER, 107, -508, False)
sm.spawnMob(SEAL_CHECKER, -195, -508, False)
sm.spawnMob(SEAL_CHECKER, -625, -298, False)
sm.spawnNpc(SEAL_OF_TIME_1, 550, -310)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_1, "summon", 0)
sm.spawnNpc(SEAL_OF_TIME_2, 107, -520)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_2, "summon", 0)
sm.spawnNpc(SEAL_OF_TIME_3, -195, -520)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_3, "summon", 0)
sm.spawnNpc(SEAL_OF_TIME_4, -625, -310)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_4, "summon", 0)
sm.showFieldEffect("lightning/screenMsg/4")
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("Time is frozen. I must activate the seals before the Black Mage notices.")
sm.sendSay("I must reach the light on the platform to the right. I can #b<Flash Blink>#k there if I press #r[Shift]#k.")
sm.showFieldEffect("lightning/screenMsg/5")
| seal_checker = 9300535
seal_of_time_1 = 2159363
seal_of_time_2 = 2159364
seal_of_time_3 = 2159365
seal_of_time_4 = 2159366
sm.giveSkill(20041222)
sm.setFuncKeyByScript(True, 20041222, 42)
sm.spawnMob(SEAL_CHECKER, 550, -298, False)
sm.spawnMob(SEAL_CHECKER, 107, -508, False)
sm.spawnMob(SEAL_CHECKER, -195, -508, False)
sm.spawnMob(SEAL_CHECKER, -625, -298, False)
sm.spawnNpc(SEAL_OF_TIME_1, 550, -310)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_1, 'summon', 0)
sm.spawnNpc(SEAL_OF_TIME_2, 107, -520)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_2, 'summon', 0)
sm.spawnNpc(SEAL_OF_TIME_3, -195, -520)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_3, 'summon', 0)
sm.spawnNpc(SEAL_OF_TIME_4, -625, -310)
sm.showNpcSpecialActionByTemplateId(SEAL_OF_TIME_4, 'summon', 0)
sm.showFieldEffect('lightning/screenMsg/4')
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext('Time is frozen. I must activate the seals before the Black Mage notices.')
sm.sendSay('I must reach the light on the platform to the right. I can #b<Flash Blink>#k there if I press #r[Shift]#k.')
sm.showFieldEffect('lightning/screenMsg/5') |
description = 'minimal NICOS startup setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'tofhw.toftof.frm2:14869',
)
| description = 'minimal NICOS startup setup'
group = 'lowlevel'
sysconfig = dict(cache='tofhw.toftof.frm2:14869') |
class BaseStrategy(object):
def get_next_move(self, board):
raise NotImplementedError
class MoveFirst(BaseStrategy):
pass
| class Basestrategy(object):
def get_next_move(self, board):
raise NotImplementedError
class Movefirst(BaseStrategy):
pass |
VERSION = "1.0.0-beta.15"
LANGUAGE = "python"
PROJECT = "versionhelper"
_p = "versionhelper.libvh."
API = {_p + "version_helper" : {"arguments" : ("filename str", ),
"keywords" : {"directory" : "directory str",
"version" : "str",
"prerelease" : "str",
"build_metadata" : "str",
"db" : "filename str",
"checker" : "filename str",
"source_types" : "iterable of str",
"no_invariant_check" : "bool",
"dry_run" : "bool",
"silent" : "bool"},
"returns" : None,
"exceptions" : ("ValueError", "Missing_Api_Function",
"Mismatched_Api_Argument",
"Missing_Api_Info"),
"side_effects" : ("Modifies api VERSION",
"Modifies database",
"Overwrites apichangelog.txt")},
_p + "parse_version" : {"arguments" : ("version str", ),
"returns" : ("str", "str", "str", "str", "str")}
}
| version = '1.0.0-beta.15'
language = 'python'
project = 'versionhelper'
_p = 'versionhelper.libvh.'
api = {_p + 'version_helper': {'arguments': ('filename str',), 'keywords': {'directory': 'directory str', 'version': 'str', 'prerelease': 'str', 'build_metadata': 'str', 'db': 'filename str', 'checker': 'filename str', 'source_types': 'iterable of str', 'no_invariant_check': 'bool', 'dry_run': 'bool', 'silent': 'bool'}, 'returns': None, 'exceptions': ('ValueError', 'Missing_Api_Function', 'Mismatched_Api_Argument', 'Missing_Api_Info'), 'side_effects': ('Modifies api VERSION', 'Modifies database', 'Overwrites apichangelog.txt')}, _p + 'parse_version': {'arguments': ('version str',), 'returns': ('str', 'str', 'str', 'str', 'str')}} |
#Build a Bus/Air/Rail Booking System where the user can choose a source and destination from the list given and enter the information passenger wise, depending on the distance cost shall be computed.
#Bus,Rail and Air systems will have different fares for different classes.You should be able to think of the system as how would he/she use it as a user.
mode=input("Hello! Welcome to the automated ticket system. Please enter a method how you would like to travel (Bus, Air or Rail): ").lower()
transport = {"bus":500,"air":4000,"rail":1500}
cost = 0
place = {"mumbai":1000,"hydrabad":900,"chennai":1200,"bangalore":950}
if mode=="bus" or mode=="air" or mode=="rail":
print(f"You chose to travel by {mode.title()}")
start=input(f"\n\nPlease select starting point from the following list:\nDelhi\nMumbai\nHydrabad\nChennai\nBangalore\nStaring Point: ").lower()
cost+=transport[mode]
if start=="mumbai" or start=="hydrabad" or start=="chennai" or start=="bangalore":
print(f"You have set your starting point to {start.title()}")
else:
print("Please enter a valid starting point")
destination=input(f"\nPlease select a destination from the following list\n(Please note that your destination can not be the same as your start point):\nDelhi\nMumbai\nHydrabad\nChennai\nBangalore\nDestination: ").lower()
if destination==start:
print("Your destination can not be the same as your starting point")
elif destination=="delhi" or destination=="mumbai" or destination=="hydrabad" or destination=="chennai" or destination=="bangalore":
print(f"You have set your destination to {destination}")
cost+= place[destination]
print(f"\n\nYou chose to travel by {mode}. From {start} to {destination} in {cost} rupees. Have a safe trip!")
else:
print("Please enter a valid destination")
else:
print("Please enter a valid mode of transport")
| mode = input('Hello! Welcome to the automated ticket system. Please enter a method how you would like to travel (Bus, Air or Rail): ').lower()
transport = {'bus': 500, 'air': 4000, 'rail': 1500}
cost = 0
place = {'mumbai': 1000, 'hydrabad': 900, 'chennai': 1200, 'bangalore': 950}
if mode == 'bus' or mode == 'air' or mode == 'rail':
print(f'You chose to travel by {mode.title()}')
start = input(f'\n\nPlease select starting point from the following list:\nDelhi\nMumbai\nHydrabad\nChennai\nBangalore\nStaring Point: ').lower()
cost += transport[mode]
if start == 'mumbai' or start == 'hydrabad' or start == 'chennai' or (start == 'bangalore'):
print(f'You have set your starting point to {start.title()}')
else:
print('Please enter a valid starting point')
destination = input(f'\nPlease select a destination from the following list\n(Please note that your destination can not be the same as your start point):\nDelhi\nMumbai\nHydrabad\nChennai\nBangalore\nDestination: ').lower()
if destination == start:
print('Your destination can not be the same as your starting point')
elif destination == 'delhi' or destination == 'mumbai' or destination == 'hydrabad' or (destination == 'chennai') or (destination == 'bangalore'):
print(f'You have set your destination to {destination}')
cost += place[destination]
print(f'\n\nYou chose to travel by {mode}. From {start} to {destination} in {cost} rupees. Have a safe trip!')
else:
print('Please enter a valid destination')
else:
print('Please enter a valid mode of transport') |
'''
Author: Shuailin Chen
Created Date: 2021-08-17
Last Modified: 2021-08-17
content:
'''
_base_= [
'../_base_/models/bit_pos_s4_dd8.py',
'../_base_/datasets/s2looking.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_80k.py'
]
data = dict(
samples_per_gpu=8,
workers_per_gpu=8,
)
evaluation = dict(metric=['mFscore', 'mFscoreCD'])
| """
Author: Shuailin Chen
Created Date: 2021-08-17
Last Modified: 2021-08-17
content:
"""
_base_ = ['../_base_/models/bit_pos_s4_dd8.py', '../_base_/datasets/s2looking.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py']
data = dict(samples_per_gpu=8, workers_per_gpu=8)
evaluation = dict(metric=['mFscore', 'mFscoreCD']) |
#need prompt for pet type
#build pet dictionary
#give toys, feed pet, let game loop, while printing menu
pet = {"name":"", "type": "", "age": 0, "hunger": 0, "playfulness" : 0, "toys": []}
pettoys = {"cat": ["String", "Cardboard Box", "Scratching Post"], "dog": ["Frisbee","Tennis Ball", "Stick"], "fish": ["Undersea Castle", "Buried Treasure", "Coral"]}
def quitsim():
print("That's the end of the game! Thank you for playing the pet simulator!")
def feedpet():
newHunger = pet["hunger"] - 10
if newHunger < 0:
newHunger = 0
pet["hunger"] = newHunger
print("Fed pet, their hunger is getting out of control")
def gettoy():
toyChoices = pettoys[pet["type"]]
toyNum = -1
while toyNum < 0 or toyNum >= len(pettoys):
print("Here are your toy choices: ")
for i in range(len(toyChoices)):
print(str(i) + ": " + toyChoices[i])
toyNum = int(input("Please input your choice of pet toy: "))
chosenToy = toyChoices[toyNum]
pet["toys"].append(chosenToy)
print("Nice! You chose: " + chosenToy + " for " + pet["name"] + ". Great pick!")
def playtoys():
print("Yay! Let's play with our toys.")
pet["playfulness"] += 10
def virtpet (pettoys):
pettype = ""
petops = list(pettoys.keys())
while pettype not in petops:
print("Please input pet you would like to have:")
for option in petops:
print(option)
pettype = input("Please select from one of these pets: ")
pet["type"] = pettype
pet["name"] = input("What would you like to name your " + pet["type"] + "? ")
#this initializes the pet game
#then it should ask you to choose and name your pet if its working correctly
#Not only write a while loop but lets the user quit by hitting the q key
def printmenu(menuops):
print()
print("Here are your options: ")
print("----------")
for key in menuops:
print(key + ":\t" + menuops[key]["text"])
print()
#bug fix, not only was feedpet and quitsim not defined but once I defined it I could not get printmenu to show, just getting a long string of letters and numbers
def printstats():
print()
print("Your " + pet["type"] + " named " + pet["name"] + " had a great time playing with you!")
print(pet["name"] + " is " + str(pet["age"]) + " days old")
print(pet["name"] + " is currently at a hunger level of " + str(pet["hunger"]) + " out of 100!")
print("You have " + str(len(pet["toys"])) + " toys! They are: ")
for toy in pet["toys"]:
print(toy)
print()
#added stats, pushed pass earlier error, will work on that later once I find a solution
def main():
virtpet(pettoys)
menuops = {"Q": { "function": quitsim, "text": "Quit the game"}, "F": { "function": feedpet, "text": "Feed " + pet["name"] + "!"}, "G": { "function": gettoy, "text": "Get a toy for " + pet["name"] + "!"}, "P": { "function": playtoys, "text": "Play with " + pet["name"] + " and your toys!"} }
keepplaying = True
while keepplaying:
menuselect = ""
menuopskeys = list(menuops.keys())
while menuselect not in menuopskeys:
printmenu(menuops)
menuselect = input("Which of thesee menu options would you like to use? ").upper()
print()
if menuselect == "Q":
keepplaying = False
pet["hunger"] += 3
pet["age"] += 1
menuops[menuselect]["function"]()
printstats()
main() | pet = {'name': '', 'type': '', 'age': 0, 'hunger': 0, 'playfulness': 0, 'toys': []}
pettoys = {'cat': ['String', 'Cardboard Box', 'Scratching Post'], 'dog': ['Frisbee', 'Tennis Ball', 'Stick'], 'fish': ['Undersea Castle', 'Buried Treasure', 'Coral']}
def quitsim():
print("That's the end of the game! Thank you for playing the pet simulator!")
def feedpet():
new_hunger = pet['hunger'] - 10
if newHunger < 0:
new_hunger = 0
pet['hunger'] = newHunger
print('Fed pet, their hunger is getting out of control')
def gettoy():
toy_choices = pettoys[pet['type']]
toy_num = -1
while toyNum < 0 or toyNum >= len(pettoys):
print('Here are your toy choices: ')
for i in range(len(toyChoices)):
print(str(i) + ': ' + toyChoices[i])
toy_num = int(input('Please input your choice of pet toy: '))
chosen_toy = toyChoices[toyNum]
pet['toys'].append(chosenToy)
print('Nice! You chose: ' + chosenToy + ' for ' + pet['name'] + '. Great pick!')
def playtoys():
print("Yay! Let's play with our toys.")
pet['playfulness'] += 10
def virtpet(pettoys):
pettype = ''
petops = list(pettoys.keys())
while pettype not in petops:
print('Please input pet you would like to have:')
for option in petops:
print(option)
pettype = input('Please select from one of these pets: ')
pet['type'] = pettype
pet['name'] = input('What would you like to name your ' + pet['type'] + '? ')
def printmenu(menuops):
print()
print('Here are your options: ')
print('----------')
for key in menuops:
print(key + ':\t' + menuops[key]['text'])
print()
def printstats():
print()
print('Your ' + pet['type'] + ' named ' + pet['name'] + ' had a great time playing with you!')
print(pet['name'] + ' is ' + str(pet['age']) + ' days old')
print(pet['name'] + ' is currently at a hunger level of ' + str(pet['hunger']) + ' out of 100!')
print('You have ' + str(len(pet['toys'])) + ' toys! They are: ')
for toy in pet['toys']:
print(toy)
print()
def main():
virtpet(pettoys)
menuops = {'Q': {'function': quitsim, 'text': 'Quit the game'}, 'F': {'function': feedpet, 'text': 'Feed ' + pet['name'] + '!'}, 'G': {'function': gettoy, 'text': 'Get a toy for ' + pet['name'] + '!'}, 'P': {'function': playtoys, 'text': 'Play with ' + pet['name'] + ' and your toys!'}}
keepplaying = True
while keepplaying:
menuselect = ''
menuopskeys = list(menuops.keys())
while menuselect not in menuopskeys:
printmenu(menuops)
menuselect = input('Which of thesee menu options would you like to use? ').upper()
print()
if menuselect == 'Q':
keepplaying = False
pet['hunger'] += 3
pet['age'] += 1
menuops[menuselect]['function']()
printstats()
main() |
RAWDATA_DIR = '/staging/as/skchoudh/rna-seq-datasets/single/gallus_gallus/SRP007412'
OUT_DIR = '/staging/as/skchoudh/rna-seq-output/gallus_gallus/SRP007412'
CDNA_FA_GZ = '/home/cmb-panasas2/skchoudh/genomes/gallus_gallus/cdna/Gallus_gallus.Gallus_gallus-5.0.cdna.all.fa.gz'
CDNA_IDX = '/home/cmb-panasas2/skchoudh/genomes/gallus_gallus/cdna/Gallus_gallus.Gallus_gallus-5.0.cdna.all.kallisto.index'
| rawdata_dir = '/staging/as/skchoudh/rna-seq-datasets/single/gallus_gallus/SRP007412'
out_dir = '/staging/as/skchoudh/rna-seq-output/gallus_gallus/SRP007412'
cdna_fa_gz = '/home/cmb-panasas2/skchoudh/genomes/gallus_gallus/cdna/Gallus_gallus.Gallus_gallus-5.0.cdna.all.fa.gz'
cdna_idx = '/home/cmb-panasas2/skchoudh/genomes/gallus_gallus/cdna/Gallus_gallus.Gallus_gallus-5.0.cdna.all.kallisto.index' |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
TIME_WINDOW = u"Microsoft.TimeWindow"
PERCENTAGE = u"Microsoft.Percentage"
TARGETING = u"Microsoft.Targeting"
| time_window = u'Microsoft.TimeWindow'
percentage = u'Microsoft.Percentage'
targeting = u'Microsoft.Targeting' |
n, min_val, max_val = int(input('n=')), int(input('minimum=')), int(input('maximum='))
c = i = 0
while True:
i, sq = i+1, i**n
if sq in range(min_val, max_val+1): c += 1
if sq > max_val: break
print(f'{c} values raised to the power {n} lie in the range {min_val}, {max_val}')
| (n, min_val, max_val) = (int(input('n=')), int(input('minimum=')), int(input('maximum=')))
c = i = 0
while True:
(i, sq) = (i + 1, i ** n)
if sq in range(min_val, max_val + 1):
c += 1
if sq > max_val:
break
print(f'{c} values raised to the power {n} lie in the range {min_val}, {max_val}') |
_base_ = [
'../_base_/models/fpn_r50.py', '../_base_/datasets/FoodSeg103.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
model = dict(pretrained='./pretrained_model/R50_ReLeM.pth',
backbone=dict(type='ResNet'),
decode_head=dict(num_classes=104))
optimizer_config = dict()
runner = dict(type='IterBasedRunner', max_iters=80000)
checkpoint_config = dict(by_epoch=False, interval=4000)
evaluation = dict(interval=4000, metric='mIoU')
| _base_ = ['../_base_/models/fpn_r50.py', '../_base_/datasets/FoodSeg103.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py']
model = dict(pretrained='./pretrained_model/R50_ReLeM.pth', backbone=dict(type='ResNet'), decode_head=dict(num_classes=104))
optimizer_config = dict()
runner = dict(type='IterBasedRunner', max_iters=80000)
checkpoint_config = dict(by_epoch=False, interval=4000)
evaluation = dict(interval=4000, metric='mIoU') |
def me(**kwargs):
for key, value in kwargs.items():
print("{0}=={1}". format(key, value))
me(name="Rahim", ID=18)
me(name="Ariful", age=109)
me(age=10)
| def me(**kwargs):
for (key, value) in kwargs.items():
print('{0}=={1}'.format(key, value))
me(name='Rahim', ID=18)
me(name='Ariful', age=109)
me(age=10) |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Adekunle Oliver Adebajo\n",
"### 20120612016\n",
"### adekunle.adebajo@pau.edu.ng\n",
"### the following codes consist of class exercises involving problem solving"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"26\n",
"7\n"
]
}
],
"source": [
"def difference(n):\n",
" if n <= 17:\n",
" return 17 - n\n",
" else:\n",
" return (n - 17) * 2 \n",
"\n",
"print(difference(30))\n",
"print(difference(10))\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12\n",
"45\n"
]
}
],
"source": [
"def sum_thrice(x, y, z):\n",
" \n",
" sum = x + y + z\n",
" \n",
" if x == y == z:\n",
" sum = sum * 3\n",
" return sum\n",
" \n",
"print(sum_thrice(3, 4, 5))\n",
"print(sum_thrice(5, 5, 5))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n",
"True\n"
]
}
],
"source": [
"def test_number5(x, y):\n",
" if x == y or abs(x-y) == 5 or (x+y) == 5:\n",
" return True\n",
" else:\n",
" return False\n",
"\n",
"print(test_number5(10, 5))\n",
"print(test_number5(3, 4))\n",
"print(test_number5(2, 3))\n"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-22-30a5df4de358>, line 1)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-22-30a5df4de358>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m if (a > c)\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"if (a > c)\n",
" swap(a, c);\n",
"\n",
"if (a > b)\n",
" swap(a, b);\n",
"\n",
"//Now the smallest element is the 1st one. Just check the 2nd and 3rd\n",
"\n",
"if (b > c)\n",
" swap(b, c);\n",
" (a, b, c) == (2, 5, 1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sum_of_cubes(n):\n",
" n = 5\n",
" total = 0\n",
" while n > 0:\n",
" total += n * n * n\n",
" n = 5\n",
" return total\n",
"print(\"Sum of cubes: \",sum_of_cubes(3))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
| {'cells': [{'cell_type': 'markdown', 'metadata': {}, 'source': ['### Adekunle Oliver Adebajo\n', '### 20120612016\n', '### adekunle.adebajo@pau.edu.ng\n', '### the following codes consist of class exercises involving problem solving']}, {'cell_type': 'code', 'execution_count': 17, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['26\n', '7\n']}], 'source': ['def difference(n):\n', ' if n <= 17:\n', ' return 17 - n\n', ' else:\n', ' return (n - 17) * 2 \n', '\n', 'print(difference(30))\n', 'print(difference(10))\n', '\n']}, {'cell_type': 'code', 'execution_count': 18, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['12\n', '45\n']}], 'source': ['def sum_thrice(x, y, z):\n', ' \n', ' sum = x + y + z\n', ' \n', ' if x == y == z:\n', ' sum = sum * 3\n', ' return sum\n', ' \n', 'print(sum_thrice(3, 4, 5))\n', 'print(sum_thrice(5, 5, 5))']}, {'cell_type': 'code', 'execution_count': 19, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['True\n', 'False\n', 'True\n']}], 'source': ['def test_number5(x, y):\n', ' if x == y or abs(x-y) == 5 or (x+y) == 5:\n', ' return True\n', ' else:\n', ' return False\n', '\n', 'print(test_number5(10, 5))\n', 'print(test_number5(3, 4))\n', 'print(test_number5(2, 3))\n']}, {'cell_type': 'code', 'execution_count': 22, 'metadata': {}, 'outputs': [{'ename': 'SyntaxError', 'evalue': 'invalid syntax (<ipython-input-22-30a5df4de358>, line 1)', 'output_type': 'error', 'traceback': ['\x1b[1;36m File \x1b[1;32m"<ipython-input-22-30a5df4de358>"\x1b[1;36m, line \x1b[1;32m1\x1b[0m\n\x1b[1;33m if (a > c)\x1b[0m\n\x1b[1;37m ^\x1b[0m\n\x1b[1;31mSyntaxError\x1b[0m\x1b[1;31m:\x1b[0m invalid syntax\n']}], 'source': ['if (a > c)\n', ' swap(a, c);\n', '\n', 'if (a > b)\n', ' swap(a, b);\n', '\n', '//Now the smallest element is the 1st one. Just check the 2nd and 3rd\n', '\n', 'if (b > c)\n', ' swap(b, c);\n', ' (a, b, c) == (2, 5, 1)']}, {'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['def sum_of_cubes(n):\n', ' n = 5\n', ' total = 0\n', ' while n > 0:\n', ' total += n * n * n\n', ' n = 5\n', ' return total\n', 'print("Sum of cubes: ",sum_of_cubes(3))']}, {'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': []}], 'metadata': {'kernelspec': {'display_name': 'Python 3', 'language': 'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.8.5'}}, 'nbformat': 4, 'nbformat_minor': 4} |
#divide 2 numbers
x = int(input("Enter first number :"))
y = int(input("Enter second number :"))
answer = int(x/y)
remainder = x % y
print("{} divided by {} is {} with a remainder of {}".format(x,y,answer,remainder))
| x = int(input('Enter first number :'))
y = int(input('Enter second number :'))
answer = int(x / y)
remainder = x % y
print('{} divided by {} is {} with a remainder of {}'.format(x, y, answer, remainder)) |
def return_true():
return True
if __name__ == "__main__":
print("shipit") | def return_true():
return True
if __name__ == '__main__':
print('shipit') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.