content
stringlengths 7
1.05M
|
---|
BASE_FILES = "C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\"
BASE_FILES_GENERAL = BASE_FILES + "general\\"
G1 = BASE_FILES + "t_graph_1.ttl"
G1_NT = BASE_FILES + "t_graph_1.nt"
G1_TSVO_SPO = BASE_FILES + "t_graph_1.tsv"
G1_JSON_LD = BASE_FILES + "t_graph_1.json"
G1_XML = BASE_FILES + "t_graph_1.xml"
G1_N3 = BASE_FILES + "t_graph_1.n3"
G1_ALL_CLASSES_NO_COMMENTS = BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex"
# PREFIX xml: <http://www.w3.org/XML/1998/namespace/>
# PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
# PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
# PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
# PREFIX foaf: <http://xmlns.com/foaf/0.1/>
# NAMESPACES_WITH_FOAF_AND_EX = {"http://example.org/" : "ex",
# "http://www.w3.org/XML/1998/namespace/" : "xml",
# "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
# "http://www.w3.org/2000/01/rdf-schema#" : "rdfs",
# "http://www.w3.org/2001/XMLSchema#": "xsd",
# "http://xmlns.com/foaf/0.1/": "foaf"
# }
def default_namespaces():
return {"http://example.org/": "ex",
"http://www.w3.org/XML/1998/namespace/": "xml",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
"http://www.w3.org/2000/01/rdf-schema#": "rdfs",
"http://www.w3.org/2001/XMLSchema#": "xsd",
"http://xmlns.com/foaf/0.1/": "foaf"
}
|
val = int(input("Valor:"))
soma = val
maior = val
menor = val
for i in range(0,9):
val = int(input("Valor:"))
if val>maior:
maior = val
if val<menor:
menor=val
soma+=val
print("O maior valor é:",maior)
print("O menor valor é:",menor)
print("A média é:",(soma/10))
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def deps():
excludes = native.existing_rules().keys()
if "bazel_installer" not in excludes:
http_file(
name = "bazel_installer",
downloaded_file_path = "bazel-installer.sh",
sha256 = "bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2",
urls = [
"https://releases.bazel.build/4.0.0/release/bazel-4.0.0-installer-linux-x86_64.sh",
"https://github.com/bazelbuild/bazel/releases/download/4.0.0/bazel-4.0.0-installer-linux-x86_64.sh",
],
)
|
#!/usr/bin/python
def test_vars():
"""test variables in python"""
int_var = 5
string_var = "hah"
assert int_var == 5
assert string_var == 'hah'
print("test vars is done")
if __name__ == "__main__":
test_vars()
|
class Programmer:
def __init__(self, name, language, skills):
self.name = name
self.language = language
self.skills = skills
def watch_course(self, course_name, language, skills_earned):
if not self.language == language:
return f"{self.name} does not know {language}"
self.skills += skills_earned
return f"{self.name} watched {course_name}"
def change_language(self, new_language, skills_needed):
if not skills_needed <= self.skills:
needed_skills = skills_needed - self.skills
return f"{self.name} needs {needed_skills} more skills"
if self.language == new_language:
return f"{self.name} already knows {self.language}"
previous_language = self.language
self.language = new_language
return f"{self.name} switched from {previous_language} to {new_language}"
|
#returns the value to the variable #
x = 900
print(x)
#print will take the argument x as the value in the variable #
|
def add(tree, x):
if not tree:
tree.extend([x, None, None])
print('DONE')
return
key = tree[0]
if x == key:
print('ALREADY')
elif x < key:
left = tree[1]
if left == None:
tree[1] = [x, None, None]
print('DONE')
else:
add(left, x)
elif x > key:
right = tree[2]
if right == None:
tree[2] = [x, None, None]
print('DONE')
else:
add(right, x)
def find(tree, x):
if not tree:
return False
key = tree[0]
if x == key:
return True
elif x < key:
left = tree[1]
if left == None:
return False
else:
return find(left, x)
elif x > key:
right = tree[2]
if right == None:
return False
else:
return find(right, x)
def printtree(tree, count=0):
# if not tree:
# return
if tree[1]:
printtree(tree[1], count + 1)
print(f"{''.join('.' * count)}{tree[0]}")
if tree[2]:
printtree(tree[2], count + 1)
tree = []
with open('input.txt', 'r', encoding='utf-8') as file:
string = file.readline().strip()
while string != '':
line = [i for i in string.split()]
if line[0] == 'ADD':
add(tree, int(line[1]))
elif line[0] == 'SEARCH':
if find(tree, int(line[1])):
print('YES')
else:
print('NO')
elif line[0] == 'PRINTTREE':
printtree(tree)
string = file.readline().strip()
|
batch_size, num_samples, sample_rate = 32, 32000, 16000.0
# A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1].
pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32)
# A 1024-point STFT with frames of 64 ms and 75% overlap.
stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256,
fft_length=1024)
spectrograms = tf.abs(stfts)
# Warp the linear scale spectrograms into the mel-scale.
num_spectrogram_bins = stfts.shape[-1].value
lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80
linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(
num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz,
upper_edge_hertz)
mel_spectrograms = tf.tensordot(
spectrograms, linear_to_mel_weight_matrix, 1)
mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate(
linear_to_mel_weight_matrix.shape[-1:]))
# Compute a stabilized log to get log-magnitude mel-scale spectrograms.
log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6)
# Compute MFCCs from log_mel_spectrograms and take the first 13.
mfccs = tf.signal.mfccs_from_log_mel_spectrograms(
log_mel_spectrograms)[..., :13]
|
"""Top-level package for mynlp."""
__author__ = """Suneel Dondapati"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
"""
User Get Key Value Input Dictionary Start
"""
dic = {
"google": "google is provide job and internship.",
"amezon": "amezon is e-commerce store and cloud computing provider.",
"zoom": "zoom is provide video call system to connecting meeating.",
"microsoft": "microsoft is owner of windows and office software.."
}
# For beginner
print("google")
print("amezon")
print("zoom")
print("microsoft")
key = input("search detail of dectionary! \n")
print(dic[key.lower()])
# For advance
while True:
for index, item in dic.items():
print(index)
key = input("search detail of dectionary! \n")
print(dic[key.lower()])
if int(input("Press 1 to exit 0 to continue \n")):
break
"""
User Get Key Value Input Dictionary End
"""
|
# Copyright 2016 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
sample_product = {
"title": "Test",
"us_url": "http://us.test.com",
"uk_url": "http://uk.test.com",
"active": True,
"db_name": "test",
"require_region": True,
"doc_url": "http://doc.test.com",
"pitchfork_url": "https://pitchfork/url"
}
sample_limit = {
"product": "test",
"title": "Test",
"uri": "/limits",
"slug": "test",
"active": True,
"absolute_path": "test/path",
"absolute_type": "list",
"limit_key": "test_limit",
"value_key": "test_value"
}
sample_log = {
"queried": ["dns"],
"queried_by": "skeletor",
"region": "dfw",
"ddi": "123456",
'query_results': []
}
sample_auth_failure = {
'message': (
'<strong>Error!</strong> Authentication has failed due to'
' incorrect token or DDI. Please check the token and DDI '
'and try again.'
)
}
""" DNS Tests """
dns = {
"title": "DNS",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "dns",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
dns_limit = {
"product": "dns",
"title": "Domains",
"uri": "/limits",
"slug": "domains",
"active": True,
"absolute_path": "limits.absolute",
"absolute_type": "dict",
"value_key": "",
"limit_key": "domains"
}
dns_limit_return = {
"limits": {
"rate": [
{
"regex": ".*/v\\d+\\.\\d+/(\\d+/domains/search).*",
"limit": [
{
"value": 20,
"verb": "GET",
"next-available": "2016-01-12T13:56:11.450Z",
"remaining": 20,
"unit": "MINUTE"
}
],
"uri": "*/domains/search*"
}
],
"absolute": {
"domains": 500,
"records per domain": 500
}
}
}
dns_list_return = {
"domains": [
{
"comment": "Test",
"updated": "2015-12-08T20:47:02.000+0000",
"name": "test.net",
"created": "2015-04-09T15:42:49.000+0000",
"emailAddress": "[email protected]",
"id": 123465798,
"accountId": 1234567
}
],
"totalEntries": 1
}
dns_full_return = {
'dns': {
'values': {'Domains': 1},
'limits': {'Domains': 500}
}
}
""" Autoscale """
autoscale = {
"title": "Autoscale",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "autoscale",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
autoscale_limit = {
"product": "autoscale",
"title": "Max Groups",
"absolute_path": "limits.absolute",
"uri": "/v1.0/{ddi}/limits",
"slug": "max_groups",
"value_key": "",
"absolute_type": "dict",
"active": True,
"limit_key": "maxGroups"
}
autoscale_limit_return = {
"limits": {
"rate": [
{
"regex": "/v1\\.0/execute/(.*)",
"limit": [
{
"value": 10,
"verb": "ALL",
"next-available": "2016-01-12T14:51:13.402Z",
"remaining": 10,
"unit": "SECOND"
}
],
"uri": "/v1.0/execute/*"
}
],
"absolute": {
"maxGroups": 1000,
"maxPoliciesPerGroup": 100,
"maxWebhooksPerPolicy": 25
}
}
}
autoscale_list_return = {
"groups": [
{
"state": {
"status": "ACTIVE",
"desiredCapacity": 0,
"paused": False,
"active": [],
"pendingCapacity": 0,
"activeCapacity": 0,
"name": "test"
},
"id": "d446f3c2-612f-41b8-92dc-4d6e1422bde2",
"links": [
{
"href": (
'https://dfw.autoscale.api.rackspacecloud.com/v1.0'
'/1234567/groups/d446f3c2-612f-41b8-92dc-4d6e1422bde2/'
),
"rel": "self"
}
]
}
],
"groups_links": []
}
autoscale_full_return = {
'autoscale': {
'values': {'Max Groups': 1},
'limits': {'Max Groups': 1000}
}
}
""" Big Data """
big_data = {
"title": "Big Data",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "big_data",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
big_data_limit = [
{
"product": "big_data",
"title": "Node Count",
"absolute_path": "limits.absolute.node_count",
"uri": "/v2/{ddi}/limits",
"slug": "node_count",
"value_key": "remaining",
"absolute_type": "dict",
"active": True,
"limit_key": "limit"
}, {
"product": "big_data",
"title": "Disk - MB",
"absolute_path": "limits.absolute.disk",
"uri": "/v2/{ddi}/limits",
"slug": "disk_-_mb",
"value_key": "remaining",
"absolute_type": "dict",
"active": True,
"limit_key": "limit"
}
]
big_data_limit_return = {
"limits": {
"absolute": {
"node_count": {
"limit": 15,
"remaining": 8
},
"disk": {
"limit": 50000,
"remaining": 25000
},
"ram": {
"limit": 655360,
"remaining": 555360
},
"vcpus": {
"limit": 200,
"remaining": 120
}
}
}
}
big_data_full_return = {
'big_data': {
'values': {'Node Count': 7, 'Disk - MB': 25000},
'limits': {'Node Count': 15, 'Disk - MB': 50000}
}
}
""" CBS """
cbs = {
"title": "CBS",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "cbs",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
cbs_limit = {
"product": "cbs",
"title": "SATA - GB",
"absolute_path": "quota_set.gigabytes_SATA",
"uri": "/v1/{ddi}/os-quota-sets/{ddi}?usage=True",
"slug": "sata_-_gb",
"value_key": "in_use",
"absolute_type": "dict",
"active": True,
"limit_key": "limit"
}
cbs_limit_return = {
"quota_set": {
"volumes": {
"limit": -1,
"reserved": 0,
"in_use": 3
},
"gigabytes_SATA": {
"limit": 10240,
"reserved": 0,
"in_use": 325
},
"gigabytes_SSD": {
"limit": 10240,
"reserved": 0,
"in_use": 50
}
}
}
cbs_full_return = {
'cbs': {
'values': {'SATA - GB': 9915},
'limits': {'SATA - GB': 10240}
}
}
""" Load Balancers """
clb = {
"title": "Load Balancers",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "load_balancers",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
clb_limit = [
{
"product": "load_balancers",
"title": "Total Load Balancers",
"uri": "/v1.0/{ddi}/loadbalancers/absolutelimits",
"slug": "total_load_balancers",
"active": True,
"path": "absolute['LOADBALANCER_LIMIT']",
"absolute_path": "absolute",
"value_key": "",
"absolute_type": "list",
"limit_key": "LOADBALANCER_LIMIT"
}, {
"product": "load_balancers",
"title": "Nodes per LB",
"uri": "/v1.0/{ddi}/loadbalancers/absolutelimits",
"slug": "nodes_per_lb",
"active": True,
"path": "absolute['NODE_LIMIT']",
"absolute_path": "absolute",
"value_key": "",
"absolute_type": "list",
"limit_key": "NODE_LIMIT"
}
]
clb_limit_return = {
"absolute": [
{
"name": "IPV6_LIMIT",
"value": 25
}, {
"name": "LOADBALANCER_LIMIT",
"value": 25
}, {
"name": "BATCH_DELETE_LIMIT",
"value": 10
}, {
"name": "ACCESS_LIST_LIMIT",
"value": 100
}, {
"name": "NODE_LIMIT",
"value": 25
}, {
"name": "NODE_META_LIMIT",
"value": 25
}, {
"name": "LOADBALANCER_META_LIMIT",
"value": 25
}, {
"name": "CERTIFICATE_MAPPING_LIMIT",
"value": 20
}
]
}
clb_list_return = {
"loadBalancers": [
{
"status": "ACTIVE",
"updated": {
"time": "2016-01-12T16:04:44Z"
},
"protocol": "HTTP",
"name": "test",
"algorithm": "LEAST_CONNECTIONS",
"created": {
"time": "2016-01-12T16:04:44Z"
},
"virtualIps": [
{
"ipVersion": "IPV4",
"type": "PUBLIC",
"id": 19875,
"address": "148.62.0.226"
}, {
"ipVersion": "IPV6",
"type": "PUBLIC",
"id": 9318325,
"address": "2001:4800:7904:0100:f46f:211b:0000:0001"
}
],
"id": 506497,
"timeout": 30,
"nodeCount": 0,
"port": 80
}
]
}
clb_full_return = {
'load_balancers': {
'values': {'Total Load Balancers': 1},
'limits': {'Total Load Balancers': 25, 'Nodes per LB': 25}
}
}
""" Servers """
server = {
"title": "Servers",
"us_url": "https://us.test.com",
"uk_url": "https://uk.test.com",
"active": True,
"db_name": "servers",
"require_region": True,
"doc_url": "https://doc.test.com",
"pitchfork_url": "https://pitchfork.url",
"limit_maps": []
}
server_limit = [
{
"product": "servers",
"title": "Servers",
"uri": "/v2/{ddi}/limits",
"slug": "servers",
"active": True,
"path": "absolute['maxTotalInstances']",
"absolute_path": "limits.absolute",
"value_key": "",
"absolute_type": "dict",
"limit_key": "maxTotalInstances"
}, {
"product": "servers",
"title": "Private Networks",
"uri": "/v2/{ddi}/limits",
"slug": "private_networks",
"active": True,
"path": "absolute['maxTotalPrivateNetworks']",
"absolute_path": "limits.absolute",
"value_key": "",
"absolute_type": "dict",
"limit_key": "maxTotalPrivateNetworks"
}, {
"product": "servers",
"title": "Ram - MB",
"uri": "/v2/{ddi}/limits",
"slug": "ram_-_mb",
"active": True,
"path": "absolute['maxTotalRAMSize']",
"absolute_path": "limits.absolute",
"value_key": "",
"absolute_type": "dict",
"limit_key": "maxTotalRAMSize"
}
]
server_limit_return = {
"limits": {
"rate": [
{
"regex": "/[^/]*/?$",
"limit": [
{
"next-available": "2016-01-12T16:14:47.624Z",
"unit": "MINUTE",
"verb": "GET",
"remaining": 2200,
"value": 2200
}
],
"uri": "*"
}, {
"regex": (
"/v[^/]+/[^/]+/servers/([^/]+)/rax-si-image-schedule"
),
"limit": [
{
"next-available": "2016-01-12T16:14:47.624Z",
"unit": "SECOND",
"verb": "POST",
"remaining": 10,
"value": 10
}
],
"uri": "/servers/{id}/rax-si-image-schedule"
}
],
"absolute": {
"maxPersonalitySize": 1000,
"maxTotalCores": -1,
"maxPersonality": 5,
"totalPrivateNetworksUsed": 1,
"maxImageMeta": 40,
"maxTotalPrivateNetworks": 10,
"maxSecurityGroupRules": -1,
"maxTotalKeypairs": 100,
"totalRAMUsed": 4096,
"maxSecurityGroups": -1,
"totalFloatingIpsUsed": 0,
"totalInstancesUsed": 3,
"totalSecurityGroupsUsed": 0,
"maxServerMeta": 40,
"maxTotalFloatingIps": -1,
"maxTotalInstances": 200,
"totalCoresUsed": 4,
"maxTotalRAMSize": 256000
}
}
}
server_list_return = {
"servers": [
{
"OS-EXT-STS:task_state": None,
"addresses": {
"public": [
{
"version": 4,
"addr": "104.130.28.32"
}, {
"version": 6,
"addr": "2001:4802:7803:104:be76:4eff:fe21:51b7"
}
],
"private": [
{
"version": 4,
"addr": "10.176.205.68"
}
]
},
"flavor": {
"id": "general1-1",
"links": [
{
"href": (
"https://iad.servers.api.rackspacecloud.com"
"/766030/flavors/general1-1"
),
"rel": "bookmark"
}
]
},
"id": "3290e50d-888f-4500-a934-16c10f3b8a10",
"user_id": "284275",
"OS-DCF:diskConfig": "MANUAL",
"accessIPv4": "104.130.28.32",
"accessIPv6": "2001:4802:7803:104:be76:4eff:fe21:51b7",
"progress": 100,
"OS-EXT-STS:power_state": 1,
"config_drive": "",
"status": "ACTIVE",
"updated": "2016-01-12T15:16:37Z",
"name": "test-server",
"created": "2016-01-12T15:15:39Z",
"tenant_id": "1234567",
"metadata": {
"build_config": "",
"rax_service_level_automation": "Complete"
}
}
]
}
server_list_processed_return = [
{
'status': 'ACTIVE',
'updated': '2016-01-12T15:16:37Z',
'OS-EXT-STS:task_state': None,
'user_id': '284275',
'addresses': {
'public': [
{
'version': 4,
'addr': '104.130.28.32'
}, {
'version': 6,
'addr': '2001:4802:7803:104:be76:4eff:fe21:51b7'
}
],
'private': [
{
'version': 4,
'addr': '10.176.205.68'
}
]
},
'created': '2016-01-12T15:15:39Z',
'tenant_id': '1234567',
'OS-DCF:diskConfig': 'MANUAL',
'id': '3290e50d-888f-4500-a934-16c10f3b8a10',
'accessIPv4': '104.130.28.32',
'accessIPv6': '2001:4802:7803:104:be76:4eff:fe21:51b7',
'config_drive': '',
'progress': 100,
'OS-EXT-STS:power_state': 1,
'metadata': {
'build_config': '',
'rax_service_level_automation': 'Complete'
},
'flavor': {
'id': 'general1-1',
'links': [
{
'href': (
'https://iad.servers.api.rackspacecloud.com'
'/766030/flavors/general1-1'
),
'rel': 'bookmark'
}
]
},
'name': 'test-server'
}
]
network_list_return = {
"networks": [
{
"status": "ACTIVE",
"subnets": [
"879ff280-6f17-4fd8-b684-19237d88fc45"
],
"name": "test-network",
"admin_state_up": True,
"tenant_id": "1234567",
"shared": False,
"id": "e737483a-00d7-4517-afc3-bd1fbbbd4cd3"
}
]
}
network_processed_list = [
{
'status': 'ACTIVE',
'subnets': [
'879ff280-6f17-4fd8-b684-19237d88fc45'
],
'name': 'test-network',
'admin_state_up': True,
'tenant_id': '1234567',
'shared': False,
'id': 'e737483a-00d7-4517-afc3-bd1fbbbd4cd3'
}
]
server_flavor_return = {
"flavor": {
"ram": 1024,
"name": "1 GB General Purpose v1",
"OS-FLV-WITH-EXT-SPECS:extra_specs": {
"number_of_data_disks": "0",
"class": "general1",
"disk_io_index": "40",
"policy_class": "general_flavor"
},
"vcpus": 1,
"swap": "",
"rxtx_factor": 200.0,
"OS-FLV-EXT-DATA:ephemeral": 0,
"disk": 20,
"id": "general1-1"
}
}
server_full_return = {
'servers': {
'values': {
'Private Networks': 1,
'Ram - MB': 1024,
'Servers': 1
},
'limits': {
'Private Networks': 10,
'Ram - MB': 256000,
'Servers': 200
}
}
}
|
class Element:
dependencies = []
def __init__(self, name):
self.name = name
def add_dependencies(self, *elements):
for element in elements:
if not self.dependencies.__contains__(element):
self.dependencies.append(element)
def remove_dependencies(self, *elements):
for element in elements:
if self.dependencies.__contains__(element):
self.dependencies.remove(element)
|
# known contracts from protocol
CONTRACTS = [
# NFT - Meteor Dust
"terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7",
# NFT - Eggs
"terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg",
# NFT - Dragons
"terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6",
# NFT - Loot
"terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el",
]
def handle(exporter, elem, txinfo, contract):
print(f"Levana! {contract}")
#print(elem)
|
def isPalindrome(string, i = 0):
j = len(string) - 1 -i
return True if i > j else string[i] == string[j] and isPalindrome(string, i+1)
def isPalindrome(string):
return string == string[::-1]
def isPalindromeUsingIndexes(string):
lIx = 0
rIdx = len(string) -1
while lIx < rIdx:
if(string[lIx] != string [rIdx]):
return False
else:
lIx += 1
rIdx -=1
return True
|
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"access_modes": "accessModes",
"api_group": "apiGroup",
"api_version": "apiVersion",
"app_protocol": "appProtocol",
"association_status": "associationStatus",
"available_nodes": "availableNodes",
"change_budget": "changeBudget",
"client_ip": "clientIP",
"cluster_ip": "clusterIP",
"config_ref": "configRef",
"daemon_set": "daemonSet",
"data_source": "dataSource",
"elasticsearch_association_status": "elasticsearchAssociationStatus",
"elasticsearch_ref": "elasticsearchRef",
"expected_nodes": "expectedNodes",
"external_i_ps": "externalIPs",
"external_name": "externalName",
"external_traffic_policy": "externalTrafficPolicy",
"file_realm": "fileRealm",
"health_check_node_port": "healthCheckNodePort",
"ip_family": "ipFamily",
"kibana_association_status": "kibanaAssociationStatus",
"kibana_ref": "kibanaRef",
"last_probe_time": "lastProbeTime",
"last_transition_time": "lastTransitionTime",
"load_balancer_ip": "loadBalancerIP",
"load_balancer_source_ranges": "loadBalancerSourceRanges",
"match_expressions": "matchExpressions",
"match_labels": "matchLabels",
"max_surge": "maxSurge",
"max_unavailable": "maxUnavailable",
"min_available": "minAvailable",
"node_port": "nodePort",
"node_sets": "nodeSets",
"pod_disruption_budget": "podDisruptionBudget",
"pod_template": "podTemplate",
"publish_not_ready_addresses": "publishNotReadyAddresses",
"remote_clusters": "remoteClusters",
"rolling_update": "rollingUpdate",
"secret_name": "secretName",
"secret_token_secret": "secretTokenSecret",
"secure_settings": "secureSettings",
"self_signed_certificate": "selfSignedCertificate",
"service_account_name": "serviceAccountName",
"session_affinity": "sessionAffinity",
"session_affinity_config": "sessionAffinityConfig",
"storage_class_name": "storageClassName",
"subject_alt_names": "subjectAltNames",
"target_port": "targetPort",
"timeout_seconds": "timeoutSeconds",
"topology_keys": "topologyKeys",
"update_strategy": "updateStrategy",
"volume_claim_templates": "volumeClaimTemplates",
"volume_mode": "volumeMode",
"volume_name": "volumeName",
}
CAMEL_TO_SNAKE_CASE_TABLE = {
"accessModes": "access_modes",
"apiGroup": "api_group",
"apiVersion": "api_version",
"appProtocol": "app_protocol",
"associationStatus": "association_status",
"availableNodes": "available_nodes",
"changeBudget": "change_budget",
"clientIP": "client_ip",
"clusterIP": "cluster_ip",
"configRef": "config_ref",
"daemonSet": "daemon_set",
"dataSource": "data_source",
"elasticsearchAssociationStatus": "elasticsearch_association_status",
"elasticsearchRef": "elasticsearch_ref",
"expectedNodes": "expected_nodes",
"externalIPs": "external_i_ps",
"externalName": "external_name",
"externalTrafficPolicy": "external_traffic_policy",
"fileRealm": "file_realm",
"healthCheckNodePort": "health_check_node_port",
"ipFamily": "ip_family",
"kibanaAssociationStatus": "kibana_association_status",
"kibanaRef": "kibana_ref",
"lastProbeTime": "last_probe_time",
"lastTransitionTime": "last_transition_time",
"loadBalancerIP": "load_balancer_ip",
"loadBalancerSourceRanges": "load_balancer_source_ranges",
"matchExpressions": "match_expressions",
"matchLabels": "match_labels",
"maxSurge": "max_surge",
"maxUnavailable": "max_unavailable",
"minAvailable": "min_available",
"nodePort": "node_port",
"nodeSets": "node_sets",
"podDisruptionBudget": "pod_disruption_budget",
"podTemplate": "pod_template",
"publishNotReadyAddresses": "publish_not_ready_addresses",
"remoteClusters": "remote_clusters",
"rollingUpdate": "rolling_update",
"secretName": "secret_name",
"secretTokenSecret": "secret_token_secret",
"secureSettings": "secure_settings",
"selfSignedCertificate": "self_signed_certificate",
"serviceAccountName": "service_account_name",
"sessionAffinity": "session_affinity",
"sessionAffinityConfig": "session_affinity_config",
"storageClassName": "storage_class_name",
"subjectAltNames": "subject_alt_names",
"targetPort": "target_port",
"timeoutSeconds": "timeout_seconds",
"topologyKeys": "topology_keys",
"updateStrategy": "update_strategy",
"volumeClaimTemplates": "volume_claim_templates",
"volumeMode": "volume_mode",
"volumeName": "volume_name",
}
|
# -*- coding: utf-8 -*-
# Importing Libraries
"""
# Commented out IPython magic to ensure Python compatibility.
import torch
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import torch.nn as nn
from tqdm import tqdm_notebook
from sklearn.preprocessing import MinMaxScaler
# %matplotlib inline
torch.manual_seed(0)
"""# Loading Dataset"""
sns.get_dataset_names()
flight_data = sns.load_dataset("flights")
flight_data.head()
"""# Preprocessing"""
# Changing the plot size
figsize = plt.rcParams["figure.figsize"]
figsize[0] = 15
figsize[1] = 5
plt.rcParams["figure.figsize"] = figsize
# Plotting the data
plt.title("Time Series Representation of Data")
plt.xlabel("Months")
plt.ylabel("Passengers")
plt.grid(True)
plt.autoscale(axis = "x",tight=True)
plt.plot(flight_data["passengers"])
#Please note that this is univariate time series data : consisting of one variable passengers
#
data = flight_data["passengers"].values.astype(float)
print(data)
print(len(data))
# Train-Test Split
# Consider the last the 12 months data as evaluation data for testing the model's behaviour
train_window = 12
train_data = data[:-train_window]
test_data = data[-train_window:]
print(len(train_data))
print(len(test_data))
# Normalizing the train-data
scaler = MinMaxScaler(feature_range=(-1,1))
train_data_normalized = scaler.fit_transform(train_data.reshape(-1,1))
print(train_data_normalized[:10])
# Converting to Torch Tensor
train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1)
print(train_data_normalized)
# Final step is creating sequences of length 12 (12 months data) from the train-data and
# the label for each sequence is the passenger_data for the (12+1)th Month
def create_in_sequences(input_data,tw):
in_seq = []
L = len(input_data)
for i in range(L-tw):
train_seq = input_data[i:i+tw]
train_label = input_data[i+tw:i+tw+1]
in_seq.append((train_seq,train_label))
return in_seq
# Therefore, we get 120 train sequences along with the label value
train_in_seq = create_in_sequences(train_data_normalized,train_window)
print(len(train_in_seq))
print(train_in_seq[:5])
"""# The Model
Please note that the model considered here is:
1. LSTM layer with a univariate input sequence of length 12 and LSTM's previous hidden cell consisting of previous hidden state and previous cell state of length 100 and also , the size of LSTM's output is 100
2. The second layer is a Linear layer of 100 inputs from the LSTM's output and a single output size
"""
class LSTM(nn.Module): #LSTM Class inheriting the inbuilt nn.Module class for neural networks
def __init__(self,input_size = 1,hidden_layer_size = 100, output_size = 1):
super().__init__() #Calls the init function of the nn.Module superclass for being able to access its features
self.hidden_layer_size = hidden_layer_size # Defines the size of h(t-1) [Previous hidden output] and c(t-1) [previous cell state]
self.lstm = nn.LSTM(input_size,hidden_layer_size,dropout = 0.45) # definining the LSTM with univariate input,output and with a dropout regularization of 0.45
self.linear = nn.Linear(hidden_layer_size,output_size) # Linear layer which returns the weighted sum of 100 outputs from the LSTM
self.hidden_cell = (torch.ones(1,1,self.hidden_layer_size), # This is the previous hidden state
torch.ones(1,1,self.hidden_layer_size)) # This is the previous cell state
def forward(self,input_seq):
lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq),1,-1),self.hidden_cell) #returns 1200 outputs from each of the 100 output neurons for the 12 valued sequence
predictions = self.linear(lstm_out.view(len(input_seq),-1)) # Reshaped to make it compatible as an input to the linear layer
return predictions[-1] # The last element contains the prediction
model = LSTM()
print(model)
"""# Loss Function and Learning Algorithm (Optimizer)
Please note that for this simple model ,
* Loss Function considered is *Mean Squared Error* and
* Optimization Function used is Stochastic Version of **Adam** *Optimizer*.
"""
loss_fn = nn.MSELoss() # Mean Squared Error Loss Function
optimizer = torch.optim.Adam(model.parameters(),lr = 0.0002) # Adam Learning Algorithm
"""# Training"""
epochs = 450
loss_plot = []
for epoch in tqdm_notebook(range(epochs), total=epochs, unit="epoch"):
for seq,label in train_in_seq:
optimizer.zero_grad() # makes the gradients zero for each new sequence
model.hidden_cell = (torch.zeros(1,1,model.hidden_layer_size), # Initialising the previous hidden state and cell state for each new sequence
torch.zeros(1,1,model.hidden_layer_size))
y_pred = model(seq) # Automatically calls the forward pass
loss = loss_fn(y_pred,label) # Determining the loss
loss.backward() # Backpropagation of loss and gradients computation
optimizer.step() # Weights and Bias Updation
loss_plot.append(loss.item()) # Some Bookkeeping
plt.plot(loss_plot,'r-')
plt.xlabel("Epochs")
plt.ylabel("Loss : MSE")
plt.show()
print(loss_plot[-1])
"""# Making Prediction
Please note that for comparison purpose we use the training data's values and predicted data values to predict the number of passengers for the test data months and then compare them
"""
fut_pred = 12
test_inputs = train_data_normalized[-train_window: ].tolist()
print(test_inputs)
print(len(test_inputs))
model.eval() # Makes the model ready for evaluation
for i in range(fut_pred):
seq = torch.FloatTensor(test_inputs[-train_window: ]) # Converting to a tensor
with torch.no_grad(): # Stops adding to the computational flow graph (stops being prepared for backpropagation)
model.hidden_cell = (torch.zeros(1,1,model.hidden_layer_size),
torch.zeros(1,1,model.hidden_layer_size))
test_inputs.append(model(seq).item())
predicted_outputs_normalized = []
predicted_outputs_normalized = test_inputs[-train_window: ]
print(predicted_outputs_normalized)
print(len(predicted_outputs_normalized))
"""# Postprocessing"""
predicted_outputs = scaler.inverse_transform(np.array(predicted_outputs_normalized).reshape(-1,1))
print(predicted_outputs)
x = np.arange(132, 144, 1)
print(x)
"""# Final Output"""
figsize = plt.rcParams["figure.figsize"]
figsize[0] = 15
figsize[1] = 5
plt.rcParams["figure.figsize"] = figsize
plt.title('Month vs Passenger')
plt.ylabel('Total Passengers')
plt.grid(True)
plt.autoscale(axis='x', tight=True)
plt.plot(flight_data['passengers'])
plt.plot(x,predicted_outputs)
plt.show()
figsize = plt.rcParams["figure.figsize"]
figsize[0] = 15
figsize[1] = 5
plt.rcParams["figure.figsize"] = figsize
plt.title('Month vs Passenger')
plt.ylabel('Total Passengers')
plt.grid(True)
plt.autoscale(axis='x', tight=True)
plt.plot(flight_data['passengers'][-train_window-5: ])
plt.plot(x,predicted_outputs)
plt.show()
"""**Please observe that the model is able to get the trend of the passengers but it can be further fine-tuned by adding appropriate regularization methods**"""
|
ad1 = input(f"Adjective1: ")
ad2 = input(f"Adjective2: ")
part1 = input(f"body part: ")
dish = input(f"Dish: ")
madlib=f"One day, a {ad1} fox invited a stork for dinner. \
Stork was very {ad2} with the invitation – she reached the fox’s home on time and knocked at the door with her {part1}.\
The fox took her to the dinner table and served some {dish} in shallow bowls for both of them.\
As the bowl was too shallow for the stork, she couldn’t have soup at all. But, the fox licked up his soup quickly."
print(f"{madlib}")
|
# List of addresses within the Battle Animation Scripts for the following commands which cause screen flashes:
# B0 - Set background palette color addition (absolute)
# B5 - Add color to background palette (relative)
# AF - Set background palette color subtraction (absolute)
# B6 - Subtract color from background palette (relative)
# By changing address + 1 to E0 (for absolute) or F0 (for relative), it causes no change to the background color (that is, no flash)
BATTLE_ANIMATION_FLASHES = {
"Goner": [
0x100088, # AF E0 - set background color subtraction to 0 (black)
0x10008C, # B6 61 - increase background color subtraction by 1 (red)
0x100092, # B6 31 - decrease background color subtraction by 1 (yellow)
0x100098, # B6 81 - increase background color subtraction by 1 (cyan)
0x1000A1, # B6 91 - decrease background color subtraction by 1 (cyan)
0x1000A3, # B6 21 - increase background color subtraction by 1 (yellow)
0x1000D3, # B6 8F - increase background color subtraction by 15 (cyan)
0x1000DF, # B0 FF - set background color addition to 31 (white)
0x100172, # B5 F2 - decrease background color addition by 2 (white)
],
"Final KEFKA Death": [
0x10023A, # B0 FF - set background color addition to 31 (white)
0x100240, # B5 F4 - decrease background color addition by 4 (white)
0x100248, # B0 FF - set background color addition to 31 (white)
0x10024E, # B5 F4 - decrease background color addition by 4 (white)
],
"Atom Edge": [ # Also True Edge
0x1003D0, # AF E0 - set background color subtraction to 0 (black)
0x1003DD, # B6 E1 - increase background color subtraction by 1 (black)
0x1003E6, # B6 E1 - increase background color subtraction by 1 (black)
0x10044B, # B6 F1 - decrease background color subtraction by 1 (black)
0x100457, # B6 F1 - decrease background color subtraction by 1 (black)
],
"Boss Death": [
0x100476, # B0 FF - set background color addition to 31 (white)
0x10047C, # B5 F4 - decrease background color addition by 4 (white)
0x100484, # B0 FF - set background color addition to 31 (white)
0x100497, # B5 F4 - decrease background color addition by 4 (white)
],
"Transform into Magicite": [
0x100F30, # B0 FF - set background color addition to 31 (white)
0x100F3F, # B5 F2 - decrease background color addition by 2 (white)
0x100F4E, # B5 F2 - decrease background color addition by 2 (white)
],
"Purifier": [
0x101340, # AF E0 - set background color subtraction to 0 (black)
0x101348, # B6 62 - increase background color subtraction by 2 (red)
0x101380, # B6 81 - increase background color subtraction by 1 (cyan)
0x10138A, # B6 F1 - decrease background color subtraction by 1 (black)
],
"Wall": [
0x10177B, # AF E0 - set background color subtraction to 0 (black)
0x10177F, # B6 61 - increase background color subtraction by 1 (red)
0x101788, # B6 51 - decrease background color subtraction by 1 (magenta)
0x101791, # B6 81 - increase background color subtraction by 1 (cyan)
0x10179A, # B6 31 - decrease background color subtraction by 1 (yellow)
0x1017A3, # B6 41 - increase background color subtraction by 1 (magenta)
0x1017AC, # B6 91 - decrease background color subtraction by 1 (cyan)
0x1017B5, # B6 51 - decrease background color subtraction by 1 (magenta)
],
"Pearl": [
0x10190E, # B0 E0 - set background color addition to 0 (white)
0x101913, # B5 E2 - increase background color addition by 2 (white)
0x10191E, # B5 F1 - decrease background color addition by 1 (white)
0x10193E, # B6 C2 - increase background color subtraction by 2 (blue)
],
"Ice 3": [
0x101978, # B0 FF - set background color addition to 31 (white)
0x10197B, # B5 F4 - decrease background color addition by 4 (white)
0x10197E, # B5 F4 - decrease background color addition by 4 (white)
0x101981, # B5 F4 - decrease background color addition by 4 (white)
0x101984, # B5 F4 - decrease background color addition by 4 (white)
0x101987, # B5 F4 - decrease background color addition by 4 (white)
0x10198A, # B5 F4 - decrease background color addition by 4 (white)
0x10198D, # B5 F4 - decrease background color addition by 4 (white)
0x101990, # B5 F4 - decrease background color addition by 4 (white)
],
"Fire 3": [
0x1019FA, # B0 9F - set background color addition to 31 (red)
0x101A1C, # B5 94 - decrease background color addition by 4 (red)
],
"Sleep": [
0x101A23, # AF E0 - set background color subtraction to 0 (black)
0x101A29, # B6 E1 - increase background color subtraction by 1 (black)
0x101A33, # B6 F1 - decrease background color subtraction by 1 (black)
],
"7-Flush": [
0x101B43, # AF E0 - set background color subtraction to 0 (black)
0x101B47, # B6 61 - increase background color subtraction by 1 (red)
0x101B4D, # B6 51 - decrease background color subtraction by 1 (magenta)
0x101B53, # B6 81 - increase background color subtraction by 1 (cyan)
0x101B59, # B6 31 - decrease background color subtraction by 1 (yellow)
0x101B5F, # B6 41 - increase background color subtraction by 1 (magenta)
0x101B65, # B6 91 - decrease background color subtraction by 1 (cyan)
0x101B6B, # B6 51 - decrease background color subtraction by 1 (magenta)
],
"H-Bomb": [
0x101BC5, # B0 E0 - set background color addition to 0 (white)
0x101BC9, # B5 E1 - increase background color addition by 1 (white)
0x101C13, # B5 F1 - decrease background color addition by 1 (white)
],
"Revenger": [
0x101C62, # AF E0 - set background color subtraction to 0 (black)
0x101C66, # B6 81 - increase background color subtraction by 1 (cyan)
0x101C6C, # B6 41 - increase background color subtraction by 1 (magenta)
0x101C72, # B6 91 - decrease background color subtraction by 1 (cyan)
0x101C78, # B6 21 - increase background color subtraction by 1 (yellow)
0x101C7E, # B6 51 - decrease background color subtraction by 1 (magenta)
0x101C84, # B6 81 - increase background color subtraction by 1 (cyan)
0x101C86, # B6 31 - decrease background color subtraction by 1 (yellow)
0x101C8C, # B6 91 - decrease background color subtraction by 1 (cyan)
],
"Phantasm": [
0x101DFD, # AF E0 - set background color subtraction to 0 (black)
0x101E03, # B6 E1 - increase background color subtraction by 1 (black)
0x101E07, # B0 FF - set background color addition to 31 (white)
0x101E0D, # B5 F4 - decrease background color addition by 4 (white)
0x101E15, # B6 E2 - increase background color subtraction by 2 (black)
0x101E1F, # B0 FF - set background color addition to 31 (white)
0x101E27, # B5 F4 - decrease background color addition by 4 (white)
0x101E2F, # B6 E2 - increase background color subtraction by 2 (black)
0x101E3B, # B6 F1 - decrease background color subtraction by 1 (black)
],
"TigerBreak": [
0x10240D, # B0 FF - set background color addition to 31 (white)
0x102411, # B5 F2 - decrease background color addition by 2 (white)
0x102416, # B5 F2 - decrease background color addition by 2 (white)
],
"Metamorph": [
0x102595, # AF E0 - set background color subtraction to 0 (black)
0x102599, # B6 61 - increase background color subtraction by 1 (red)
0x1025AF, # B6 71 - decrease background color subtraction by 1 (red)
],
"Cat Rain": [
0x102677, # B0 FF - set background color addition to 31 (white)
0x10267B, # B5 F1 - decrease background color addition by 1 (white)
],
"Charm": [
0x1026EE, # B0 FF - set background color addition to 31 (white)
0x1026FB, # B5 F1 - decrease background color addition by 1 (white)
],
"Mirager": [
0x102791, # B0 FF - set background color addition to 31 (white)
0x102795, # B5 F2 - decrease background color addition by 2 (white)
],
"SabreSoul": [
0x1027D3, # B0 FF - set background color addition to 31 (white)
0x1027DA, # B5 F2 - decrease background color addition by 2 (white)
],
"Back Blade": [
0x1028D3, # AF FF - set background color subtraction to 31 (black)
0x1028DF, # B6 F4 - decrease background color subtraction by 4 (black)
],
"RoyalShock": [
0x102967, # B0 FF - set background color addition to 31 (white)
0x10296B, # B5 F2 - decrease background color addition by 2 (white)
0x102973, # B5 F2 - decrease background color addition by 2 (white)
],
"Overcast": [
0x102C3A, # AF E0 - set background color subtraction to 0 (black)
0x102C55, # B6 E1 - increase background color subtraction by 1 (black)
0x102C8D, # B6 F1 - decrease background color subtraction by 1 (black)
0x102C91, # B6 F1 - decrease background color subtraction by 1 (black)
],
"Disaster": [
0x102CEE, # AF E0 - set background color subtraction to 0 (black)
0x102CF2, # B6 E1 - increase background color subtraction by 1 (black)
0x102D19, # B6 F1 - decrease background color subtraction by 1 (black)
],
"ForceField": [
0x102D3A, # B0 E0 - set background color addition to 0 (white)
0x102D48, # B5 E1 - increase background color addition by 1 (white)
0x102D64, # B5 F1 - decrease background color addition by 1 (white)
],
"Terra/Tritoch Lightning": [
0x102E05, # B0 E0 - set background color addition to 0 (white)
0x102E09, # B5 81 - increase background color addition by 1 (red)
0x102E24, # B5 61 - increase background color addition by 1 (cyan)
],
"S. Cross": [
0x102EDA, # AF E0 - set background color subtraction to 0 (black)
0x102EDE, # B6 E2 - increase background color subtraction by 2 (black)
0x102FA8, # B6 F2 - decrease background color subtraction by 2 (black)
0x102FB1, # B0 E0 - set background color addition to 0 (white)
0x102FBE, # B5 E2 - increase background color addition by 2 (white)
0x102FD9, # B5 F2 - decrease background color addition by 2 (white)
],
"Mind Blast": [
0x102FED, # B0 E0 - set background color addition to 0 (white)
0x102FF1, # B5 81 - increase background color addition by 1 (red)
0x102FF7, # B5 91 - decrease background color addition by 1 (red)
0x102FF9, # B5 21 - increase background color addition by 1 (blue)
0x102FFF, # B5 31 - decrease background color addition by 1 (blue)
0x103001, # B5 C1 - increase background color addition by 1 (yellow)
0x103007, # B5 91 - decrease background color addition by 1 (red)
0x10300D, # B5 51 - decrease background color addition by 1 (green)
0x103015, # B5 E2 - increase background color addition by 2 (white)
0x10301F, # B5 F1 - decrease background color addition by 1 (white)
],
"Flare Star": [
0x1030F5, # B0 E0 - set background color addition to 0 (white)
0x103106, # B5 81 - increase background color addition by 1 (red)
0x10310D, # B5 E2 - increase background color addition by 2 (white)
0x103123, # B5 71 - decrease background color addition by 1 (cyan)
0x10312E, # B5 91 - decrease background color addition by 1 (red)
],
"Quasar": [
0x1031D2, # AF E0 - set background color subtraction to 0 (black)
0x1031D6, # B6 E1 - increase background color subtraction by 1 (black)
0x1031FA, # B6 F1 - decrease background color subtraction by 1 (black)
],
"R.Polarity": [
0x10328B, # B0 FF - set background color addition to 31 (white)
0x103292, # B5 F1 - decrease background color addition by 1 (white)
],
"Rippler": [
0x1033C6, # B0 FF - set background color addition to 31 (white)
0x1033CA, # B5 F1 - decrease background color addition by 1 (white)
],
"Step Mine": [
0x1034D9, # B0 FF - set background color addition to 31 (white)
0x1034E0, # B5 F4 - decrease background color addition by 4 (white)
],
"L.5 Doom": [
0x1035E6, # B0 FF - set background color addition to 31 (white)
0x1035F6, # B5 F4 - decrease background color addition by 4 (white)
],
"Megazerk": [
0x103757, # B0 80 - set background color addition to 0 (red)
0x103761, # B5 82 - increase background color addition by 2 (red)
0x10378F, # B5 92 - decrease background color addition by 2 (red)
0x103795, # B5 92 - decrease background color addition by 2 (red)
0x10379B, # B5 92 - decrease background color addition by 2 (red)
0x1037A1, # B5 92 - decrease background color addition by 2 (red)
0x1037A7, # B5 92 - decrease background color addition by 2 (red)
0x1037AD, # B5 92 - decrease background color addition by 2 (red)
0x1037B3, # B5 92 - decrease background color addition by 2 (red)
0x1037B9, # B5 92 - decrease background color addition by 2 (red)
0x1037C0, # B5 92 - decrease background color addition by 2 (red)
],
"Schiller": [
0x103819, # B0 FF - set background color addition to 31 (white)
0x10381D, # B5 F4 - decrease background color addition by 4 (white)
],
"WallChange": [
0x10399E, # B0 FF - set background color addition to 31 (white)
0x1039A3, # B5 F2 - decrease background color addition by 2 (white)
0x1039A9, # B5 F2 - decrease background color addition by 2 (white)
0x1039AF, # B5 F2 - decrease background color addition by 2 (white)
0x1039B5, # B5 F2 - decrease background color addition by 2 (white)
0x1039BB, # B5 F2 - decrease background color addition by 2 (white)
0x1039C1, # B5 F2 - decrease background color addition by 2 (white)
0x1039C7, # B5 F2 - decrease background color addition by 2 (white)
0x1039CD, # B5 F2 - decrease background color addition by 2 (white)
0x1039D4, # B5 F2 - decrease background color addition by 2 (white)
],
"Ultima": [
0x1056CB, # AF 60 - set background color subtraction to 0 (red)
0x1056CF, # B6 C2 - increase background color subtraction by 2 (blue)
0x1056ED, # B0 FF - set background color addition to 31 (white)
0x1056F5, # B5 F1 - decrease background color addition by 1 (white)
],
"Bolt 3": [ # Also Giga Volt
0x10588E, # B0 FF - set background color addition to 31 (white)
0x105893, # B5 F4 - decrease background color addition by 4 (white)
0x105896, # B5 F4 - decrease background color addition by 4 (white)
0x105899, # B5 F4 - decrease background color addition by 4 (white)
0x10589C, # B5 F4 - decrease background color addition by 4 (white)
0x1058A1, # B5 F4 - decrease background color addition by 4 (white)
0x1058A6, # B5 F4 - decrease background color addition by 4 (white)
0x1058AB, # B5 F4 - decrease background color addition by 4 (white)
0x1058B0, # B5 F4 - decrease background color addition by 4 (white)
],
"X-Zone": [
0x105A5D, # B0 FF - set background color addition to 31 (white)
0x105A6A, # B5 F2 - decrease background color addition by 2 (white)
0x105A79, # B5 F2 - decrease background color addition by 2 (white)
],
"Dispel": [
0x105DC2, # B0 FF - set background color addition to 31 (white)
0x105DC9, # B5 F1 - decrease background color addition by 1 (white)
0x105DD2, # B5 F1 - decrease background color addition by 1 (white)
0x105DDB, # B5 F1 - decrease background color addition by 1 (white)
0x105DE4, # B5 F1 - decrease background color addition by 1 (white)
0x105DED, # B5 F1 - decrease background color addition by 1 (white)
],
"Muddle": [ # Also L.3 Muddle, Confusion
0x1060EA, # B0 FF - set background color addition to 31 (white)
0x1060EE, # B5 F1 - decrease background color addition by 1 (white)
],
"Shock": [
0x1068BE, # B0 FF - set background color addition to 31 (white)
0x1068D0, # B5 F1 - decrease background color addition by 1 (white)
],
"Bum Rush": [
0x106C3E, # B0 E0 - set background color addition to 0 (white)
0x106C47, # B0 E0 - set background color addition to 0 (white)
0x106C53, # B0 E0 - set background color addition to 0 (white)
0x106C7E, # B0 FF - set background color addition to 31 (white)
0x106C87, # B0 E0 - set background color addition to 0 (white)
0x106C95, # B0 FF - set background color addition to 31 (white)
0x106C9E, # B0 E0 - set background color addition to 0 (white)
],
"Stunner": [
0x1071BA, # B0 20 - set background color addition to 0 (blue)
0x1071C1, # B5 24 - increase background color addition by 4 (blue)
0x1071CA, # B5 24 - increase background color addition by 4 (blue)
0x1071D5, # B5 24 - increase background color addition by 4 (blue)
0x1071DE, # B5 24 - increase background color addition by 4 (blue)
0x1071E9, # B5 24 - increase background color addition by 4 (blue)
0x1071F2, # B5 24 - increase background color addition by 4 (blue)
0x1071FD, # B5 24 - increase background color addition by 4 (blue)
0x107206, # B5 24 - increase background color addition by 4 (blue)
0x107211, # B5 24 - increase background color addition by 4 (blue)
0x10721A, # B5 24 - increase background color addition by 4 (blue)
0x10725A, # B5 32 - decrease background color addition by 2 (blue)
],
"Quadra Slam": [ # Also Quadra Slice
0x1073DC, # B0 FF - set background color addition to 31 (white)
0x1073EE, # B5 F2 - decrease background color addition by 2 (white)
0x1073F3, # B5 F2 - decrease background color addition by 2 (white)
0x107402, # B0 5F - set background color addition to 31 (green)
0x107424, # B5 54 - decrease background color addition by 4 (green)
0x107429, # B5 54 - decrease background color addition by 4 (green)
0x107436, # B0 3F - set background color addition to 31 (blue)
0x107458, # B5 34 - decrease background color addition by 4 (blue)
0x10745D, # B5 34 - decrease background color addition by 4 (blue)
0x107490, # B0 9F - set background color addition to 31 (red)
0x1074B2, # B5 94 - decrease background color addition by 4 (red)
0x1074B7, # B5 94 - decrease background color addition by 4 (red)
],
"Slash": [
0x1074F4, # B0 FF - set background color addition to 31 (white)
0x1074FD, # B5 F2 - decrease background color addition by 2 (white)
0x107507, # B5 F2 - decrease background color addition by 2 (white)
],
"Flash": [
0x107850, # B0 FF - set background color addition to 31 (white)
0x10785C, # B5 F1 - decrease background color addition by 1 (white)
]
}
|
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if not envelopes:
return 0
pairs = sorted(envelopes, key=lambda x: (x[0], -x[1]))
result = []
for pair in pairs:
height = pair[1]
if len(result) == 0 or height > result[-1]:
result.append(height)
else:
index = bisect.bisect_left(result, height)
result[index] = height
return len(result)
|
class Dog:
def __init__(self, newColor):
self.color = newColor
def bark(self):
print("---旺旺叫----")
def printColor(self):
print("颜色为:%s"%self.color)
def test(AAA):
AAA.printColor()
wangcai = Dog("白")
#wangcai.printColor()
xiaoqiang = Dog("黑")
#xiaoqiang.printColor()
test(wangcai)
|
# -*- coding: utf-8 -*-
# This file is made to configure every file number at one place
# Choose the place you are training at
# AWS : 0, Own PC : 1
PC = 1
path_list = ["/jet/prs/workspace/", "."]
url = path_list[PC]
clothes = ['shirt',
'jeans',
'blazer',
'chino-pants',
'jacket',
'coat',
'hoody',
'training-pants',
't-shirt',
'polo-shirt',
'knit',
'slacks',
'sweat-shirt']
schedule = ['party',
'trip',
'sport',
'work',
'speech',
'daily',
'school',
'date']
weather = ['snow',
'sunny',
'cloudy',
'rain']
|
def test_rm_long_opt_help(pycred):
pycred('rm --help')
def test_rm_short_opt_help(pycred):
pycred('rm -h')
def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace):
with workspace():
pycred('rm non-existing-store user', expected_exit_code=2)
|
# Calcula a quantidade de notas de cada valor a serem sacadas em uma caixa eletrônico
print('=' * 30)
print('{:^30}'.format('CAIXA ELETRÔNICO'))
print('=' * 30)
valor = int(input('Valor a ser sacado: R$ '))
# notas de real (R$) existentes
tot200 = valor // 200
tot100 = (valor % 200) // 100
tot50 = ((valor % 200) % 100) // 50
tot20 = (((valor % 200) % 100) % 50) // 20
tot10 = ((((valor % 200) % 100) % 50) % 20) //10
tot5 = (((((valor % 200) % 100) % 50) % 20) % 10) // 5
tot2 = ((((((valor % 200) % 100) % 50) % 20) % 10) % 5) // 2
while True:
if tot200 > 0:
print(f'Total de {tot200} cédula(s) de R$ 200,00.')
if tot100 > 0:
print(f'Total de {tot100} cédula(s) de R$ 100,00.')
if tot50 > 0:
print(f'Total de {tot50} cédula(s) de R$ 50,00.')
if tot20 > 0:
print(f'Total de {tot20} cédula(s) de R$ 20,00.')
if tot10 > 0:
print(f'Total de {tot10} cédula(s) de R$ 10,00.')
if tot5 > 0:
print(f'Total de {tot5} cédula(s) de R$ 5,00.')
if tot2 > 0:
print(f'Total de {tot2} cédula(s) de R$ 2,00.')
break
|
# Application definition
INSTALLED_APPS = [
'django.contrib.staticfiles',
'django.contrib.sessions',
'authenticate',
]
ROOT_URLCONF = 'auth_service.urls'
WSGI_APPLICATION = 'auth_service.wsgi.application'
# Use a non database session engine
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_SECURE = False
|
s=[]
for i in range(int(input())):
s.append(input())
cnt=0
while s:
flag=True
for i in range(len(s)//2):
if s[i]<s[-(i+1)]:
print(s[0],end='')
s.pop(0)
flag=False
break
elif s[-(i+1)]<s[i]:
print(s[-1],end='')
s.pop()
flag=False
break
if flag:
print(s[-1],end='')
s.pop()
cnt+=1
if cnt%80==0: print()
|
cars=100
cars_in_space=5
drivers=20
pasengers=70
car_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_percar=passengers/cars_driven
print("There are", cars,"cars availble")
print("There are only",drivers,"drivers availble")
print("There will be",car_not_driven,"empty cars today")
print("There are",cars_in_space,"space availble in car")
print("We can transport",carpool_capacity,"peopletoday.")
print("We have", passengers,"to carpool today.")
print("We need to put about", average_passengers_per_car,"in each car.")
|
# Definição de função
def soma(a2, b2): # Os parâmetros aqui precisam ter outro nome
print(f'A = {a2} e B = {b2}')
s = a2 + b2
print(f'A soma vale A + B = {s}')
# Programa principal
a = int(input('Digite um valor para A: '))
b = int(input('Digite um valor para B: '))
soma(a, b)
|
# Your code goes here
tab=[]
for i in range(1000) :
tab.append(i)
tab2=[]
for i in range(len(tab)):
if sum([ int(c) for c in str(tab[i]) ]) <= 10:
tab2.append(tab[i])
tab3=[]
for i in range(len(tab2)):
a=str(tab2[i])
if a[len(a)-2] == '4':
tab3.append(tab2[i])
tab4=[]
for i in range(len(tab3)):
if len(str(tab3[i]))>=2 :
tab4.append(tab3[i])
tab5=[]
for i in range(len(tab4)):
a=str(tab4[i])
if a.find('7')==-1 and a.find('1')==-1:
tab5.append(tab4[i])
tab6=[]
for i in range(len(tab5)):
a=str(tab5[i])
if ((int(a[0])+int(a[1]))%2) != 0:
tab6.append(tab5[i])
tab7=[]
for i in range(len(tab6)):
a=str(tab6[i])
if str(len(a)) == a[len(a)-1]:
tab7.append(tab6[i])
print(tab7)
mystery_number=tab7[0]
print(f'Le nombre mystère est le : {mystery_number}')
|
# 대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.
# 첫째 줄에는 테스트 케이스의 개수 C가 주어진다.
# 둘째 줄부터 각 테스트 케이스마다 학생의 수 N(1 ≤ N ≤ 1000, N은 정수)이 첫 수로 주어지고, 이어서 N명의 점수가 주어진다. 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다.
# 각 케이스마다 한 줄씩 평균을 넘는 학생들의 비율을 반올림하여 소수점 셋째 자리까지 출력한다.
def avg(l):
s=0
for i in l:
s+=i
return((s-l[0])/l[0])
t=int(input())
for _ in range(t):
a=list(map(int,input().split()))
c=0
for j in range(1,a[0]+1):
if a[j]>avg(a):
c+=1
print(str('{:,.3f}'.format(round(c/a[0]*100,3)))+"%")
|
# AUTOGENERATED! DO NOT EDIT! File to edit: dataset.ipynb (unless otherwise specified).
__all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size',
'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim']
# Cell
def load_mp3(file):
sample = tf.io.read_file(file)
sample_audio = tfio.audio.decode_mp3(sample)
return sample_audio
# Cell
def get_sample_label(file):
sample = load_mp3(file)
label = tf.argmax(tf.strings.split(file, '/')[1] == np.array(ebirds))
return sample, label
# Cell
def preprocess_file(sample_audio, label):
# Only look at the first channel
sample_audio = sample_audio[:,0]
sample_audio_scaled = (sample_audio - tf.math.reduce_min(sample_audio))/(tf.math.reduce_max(sample_audio) - tf.math.reduce_min(sample_audio))
sample_audio_scaled = 2*(sample_audio_scaled - 0.5)
return sample_audio_scaled, label
# Cell
def pad_by_zeros(sample, min_file_size, last_sample_size):
padding_size = min_file_size - last_sample_size
sample_padded = tf.pad(sample, paddings=[[tf.constant(0), padding_size]])
return sample_padded
# Cell
def split_file_by_window_size(sample, label):
# number of subsamples given none overlapping window size.
subsample_count = int(np.round(sample.shape[0]/min_file_size))
# ignore extremely long files for now
subsample_limit = 75
if subsample_count <= subsample_limit:
# if the last sample is at least half the window size, then pad it, if not, clip it.
last_sample_size = sample.shape[0]%min_file_size
if last_sample_size/min_file_size > 0.5:
sample = pad_by_zeros(sample, min_file_size, last_sample_size)
else:
sample = sample[:subsample_count*min_file_size]
sample = tf.reshape(sample, shape=[subsample_count, min_file_size])
label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, subsample_count-1]], constant_values=label.numpy())
else:
sample = tf.reshape(sample[:subsample_limit*min_file_size], shape=[subsample_limit, min_file_size])
label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, 74]], constant_values=label.numpy())
return sample, label
# Cell
def wrapper_split_file_by_window_size(sample, label):
sample, label = tf.py_function(split_file_by_window_size, inp=(sample, label),
Tout=(sample.dtype, label.dtype))
return sample, label
# Cell
def create_dataset_fixed_size(ds):
iterator = iter(ds)
sample, label = iterator.next()
samples_all = tf.unstack(sample)
labels_all = tf.unstack(label)
while True:
try:
sample, label = iterator.next()
sample = tf.unstack(sample)
label = tf.unstack(label)
samples_all = tf.concat([samples_all, sample], axis=0)
labels_all = tf.concat([labels_all, label], axis=0)
except:
break
return samples_all, labels_all
# Cell
def get_spectrogram(sample, label):
spectrogram = tfio.experimental.audio.spectrogram(sample, nfft=512, window=512, stride=256)
return spectrogram, label
# Cell
def add_channel_dim(sample, label):
sample = tf.expand_dims(sample, axis=-1)
return sample, label
|
# Exercício 066
soma = total = 0
while True:
n = int(input('Digite um valor [999 para parar]: '))
if n == 999:
break
soma += n
total += 1
print(f'O total de números digitados foi {total} e a soma deles vale {soma}')
|
# coding=utf-8
DEBUG = True
TESTING = True
SECRET_KEY = 'secret_key for test'
# mongodb
MONGODB_SETTINGS = {
'db': 'firefly_test',
'username': '',
'password': '',
'host': '127.0.0.1',
'port': 27017
}
# redis cache
CACHE_TYPE = 'redis'
CACHE_REDIS_HOST = '127.0.0.1'
CACHE_REDIS_PORT = 6379
CACHE_REDIS_DB = 9
CACHE_REDIS_PASSWORD = ''
# mail sender
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = 'MAIL_USERNAME'
MAIL_PASSWORD = 'MAIL_PASSWORD'
MAIL_DEFAULT_SENDER = '[email protected]'
SECURITY_PASSWORD_SALT = "abc"
SECURITY_PASSWORD_HASH = "bcrypt"
# SECURITY_PASSWORD_HASH = "pbkdf2_sha512"
SECURITY_EMAIL_SENDER = "[email protected]"
SECURITY_CONFIRM_SALT = "570be5f24e690ce5af208244f3e539a93b6e4f05"
SECURITY_REMEMBER_SALT = "de154140385c591ea771dcb3b33f374383e6ea47"
# Set secret keys for CSRF protection
CSRF_ENABLED = False
WTF_CSRF_ENABLED = False
SERVER_EMAIL = 'Python-China <[email protected]>'
# Flask-SocialBlueprint
SOCIAL_BLUEPRINT = {
# https://developers.facebook.com/apps/
"flask_social_blueprint.providers.Facebook": {
# App ID
'consumer_key': '197…',
# App Secret
'consumer_secret': 'c956c1…'
},
# https://apps.twitter.com/app/new
"flask_social_blueprint.providers.Twitter": {
# Your access token from API Keys tab
'consumer_key': 'bkp…',
# access token secret
'consumer_secret': 'pHUx…'
},
# https://console.developers.google.com/project
"flask_social_blueprint.providers.Google": {
# Client ID
'consumer_key': '797….apps.googleusercontent.com',
# Client secret
'consumer_secret': 'bDG…'
},
# https://github.com/settings/applications/new
"flask_social_blueprint.providers.Github": {
# Client ID
'consumer_key': '6f6…',
# Client Secret
'consumer_secret': '1a9…'
},
}
|
# Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
class mockData:
"""dictionary of mocking data for the mocking tests"""
# dictionary to hold the mock data
_data={}
# function to add mock data to the _mock_data dictionary
def _add(self,uri,status,payload):
self._data[uri] = {"status":status,
"payload":payload
}
return
def getPayload(self,input):
return self._data[input]['payload']
def getStatusCode(self,input):
return self._data[input]['status']
# initialize the _mock_data dictionary with all the appropriate mocking data
def __init__(self):
self._add( uri="limits", status=200,
payload='{"transaction-quota":10000,"transaction-count":259,"endpoint-quota":100,"endpoint-count":1}')
self._add( uri="connectorVersion", status=200,
payload='DeviceServer v3.0.0-520\nREST version = v2')
self._add( uri="apiVersion", status=200,
payload='["v1","v2"]')
self._add( uri="endpoints", status=200,
payload='[{"name":"51f540a2-3113-46e2-aef4-96e94a637b31","type":"test","status":"ACTIVE"}]')
self._add( uri="resources", status=200,
payload='[{"uri":"/Test/0/S","rt":"Static","obs":false,"type":""},{"uri":"/Test/0/D","rt":"Dynamic","obs":true,"type":""},{"uri":"/3/0/2","obs":false,"type":""},{"uri":"/3/0/1","obs":false,"type":""},{"uri":"/3/0/17","obs":false,"type":""},{"uri":"/3/0/0","obs":false,"type":""},{"uri":"/3/0/16","obs":false,"type":""},{"uri":"/3/0/11","obs":false,"type":""},{"uri":"/3/0/11/0","obs":false,"type":""},{"uri":"/3/0/4","obs":false,"type":""}]')
#self._add( uri="", status=200,
# payload="")
#self._add( uri="", status=200,
# payload="")
#self._add( uri="", status=200,
# payload="")
|
a = int(input())
b = int(input())
if a >=b*12:
print("Buy it!")
else:
print("Try again")
|
# [weight, value]
I = [[4, 8], [4, 7], [6, 14]]
k = 8
def knapRecursive(I, k):
return knapRecursiveAux(I, k, len(I) - 1)
def knapRecursiveAux(I, k, hi):
# final element
if hi == 0:
# too big for sack
if I[hi][0] > k:
return 0
# fits
else:
return I[hi][1]
else:
# too big for sack
if I[hi][0] > k:
return knapRecursiveAux(I, k, hi - 1)
# fits
else:
# don't include it
s1 = knapRecursiveAux(I, k, hi - 1)
# include it
s2 = I[hi][1] + knapRecursiveAux(I, k - I[hi][0], hi - 1)
return max(s1, s2)
print(knapRecursive(I, k))
|
class Piece(object):
def __init__(self,
is_tall: bool = True,
is_dark: bool = True,
is_square: bool = True,
is_solid: bool = True,
string: str = None):
if string:
self.is_tall = (string[0] == "1")
self.is_dark = (string[1] == "1")
self.is_square = (string[2] == "1")
self.is_solid = (string[3] == "1")
else:
self.is_tall = is_tall
self.is_dark = is_dark
self.is_square = is_square
self.is_solid = is_solid
def __str__(self):
return "{0}{1}{2}{3}".format(
'1' if self.is_tall else '0',
'1' if self.is_dark else '0',
'1' if self.is_square else '0',
'1' if self.is_solid else '0'
)
def __hash__(self):
res = 0
res += 1 if self.is_tall else 0
res += 2 if self.is_dark else 0
res += 4 if self.is_square else 0
res += 8 if self.is_solid else 0
return res
def __eq__(self, other_piece):
if not isinstance(other_piece, type(self)):
return False
return self.__hash__() == other_piece.__hash__()
def has_in_common_with(self, *other_pieces):
all_pieces_are_as_tall = True
all_pieces_are_as_dark = True
all_pieces_are_as_square = True
all_pieces_are_as_solid = True
for p in other_pieces:
if not(self.is_tall == p.is_tall):
all_pieces_are_as_tall = False
if not(self.is_dark == p.is_dark):
all_pieces_are_as_dark = False
if not(self.is_square == p.is_square):
all_pieces_are_as_square = False
if not(self.is_solid == p.is_solid):
all_pieces_are_as_solid = False
return (all_pieces_are_as_tall
or all_pieces_are_as_dark
or all_pieces_are_as_square
or all_pieces_are_as_solid)
if __name__ == "__main__":
pass
|
"""
# Utilities for interacting with NCBI EUtilities relating to PubMed
"""
__version__ = "0.0.1"
|
# Crie um programa que leia uma frase qualquer e diga se ele é um palíndromo, desconsiderando os espaços.
frase = str(input('Digite uma frase: ')).strip()
palavras = frase.split()
junto = ''.join(palavras)
inverso = ''
for c in range( len(junto)-1, -1, -1):
inverso += junto[c]
if inverso == junto:
print('A frase é um PALINDROMO')
else:
print('A frase NÃO é um PALINDROMO')
|
inp = input().split(" ")
adult = int(inp[0])
child = int(inp[1])
if adult == 0 and child == 0:
print("0 0")
quit()
if adult == 0:
print("Impossible")
quit()
min = 0
# К каждому взрослому один бесплатный ребенок =>
# "Платные дети" это разница между взрослыми и всеми детьми
not_free_child = child - adult
# Если детей было меньше, то может оказаться отриц. ответ
if not_free_child < 0:
not_free_child = 0
min = adult + not_free_child
max = 0
# К одному взрослому приписывает всех детей,
# кроме одного "бесплатного".
if child == 0:
# Если нет детей, то не нужно и отнимать "бесплатного"
max = adult
else:
max = adult + child - 1
print("{} {}".format(min, max))
|
'''
杨氏矩阵查找
在一个m行n列二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下
递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
def get_value(l, r, c):
return l[r][c]
def find(l, x):
m = len(l) - 1
n = len(l[0]) - 1
r = 0
c = n
while c >= 0 and r <= m:
value = get_value(l, r, c)
if value == x:
return True
elif value > x:
c = c - 1
elif value < x:
r = r + 1
return False
|
x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
z = int(input('Podaj trzecia liczbe calkowita: '))
print()
if x > 10:
print(x)
if y > 10:
print(y)
if z > 10:
print(z)
|
while True:
try:
dados = []
matriz = []
n = int(input())
for linha in range(0, n):
for coluna in range(0, n):
dados.append(0)
matriz.append(dados[:])
dados.clear()
# Numeros na diagonal
for diagonal_principal in range(0, n):
matriz[diagonal_principal][diagonal_principal] = 2
for diagonal_secundaria in range(0, n):
matriz[diagonal_secundaria][n - 1 - diagonal_secundaria] = 3
# Matriz do numero 1
for linha in range(n // 3, n - n // 3):
for coluna in range(n // 3, n - n // 3):
matriz[linha][coluna] = 1
# Matriz do numero 4
matriz[n // 2][n // 2] = 4
# Print da Matriz completa
for linha in range(0, len(matriz)):
for coluna in range(0, len(matriz)):
if coluna == 0:
print(f"{matriz[linha][coluna]}", end="")
else:
print(f"{matriz[linha][coluna]}", end="")
print()
print()
except EOFError:
break
|
'''
http://pythontutor.ru/lessons/ifelse/problems/minimum/
Даны два целых числа. Выведите значение наименьшего из них.
'''
val_01 = int(input())
val_02 = int(input())
if val_01 > val_02:
print(val_02)
else:
print(val_01)
|
# query_strings.py
'''
Since Sqlite queries are inserted as string in Python code,
the queries can be stored here to save space in the modules
where they are used.
'''
delete_color_scheme = '''
DELETE FROM color_scheme
WHERE color_scheme_id = ?
'''
insert_color_scheme = '''
INSERT INTO color_scheme
VALUES (null, ?, ?, ?, ?, 0, 0)
'''
select_all_color_schemes = '''
SELECT bg, highlight_bg, head_bg, fg
FROM color_scheme
'''
select_all_color_schemes_plus = '''
SELECT bg, highlight_bg, head_bg, fg, built_in, color_scheme_id
FROM color_scheme
'''
select_color_scheme_current = '''
SELECT bg, highlight_bg, head_bg, fg
FROM format
WHERE format_id = 1
'''
select_current_database = '''
SELECT current_database
FROM closing_state
WHERE closing_state_id = 1
'''
select_font_scheme = '''
SELECT font_size, output_font, input_font
FROM format
WHERE format_id = 1
'''
select_opening_settings = '''
SELECT
bg,
highlight_bg,
head_bg,
fg,
output_font,
input_font,
font_size,
default_bg,
default_highlight_bg,
default_head_bg,
default_fg,
default_output_font,
default_input_font,
default_font_size
FROM format
WHERE format_id = 1
'''
update_color_scheme_null = '''
UPDATE format
SET (bg, highlight_bg, head_bg, fg) =
(null, null, null, null)
WHERE format_id = 1
'''
update_current_database = '''
UPDATE closing_state
SET current_database = ?
WHERE closing_state_id = 1
'''
update_format_color_scheme = '''
UPDATE format
SET (bg, highlight_bg, head_bg, fg) = (?, ?, ?, ?)
WHERE format_id = 1
'''
update_format_fonts = '''
UPDATE format
SET (font_size, output_font, input_font) = (?, ?, ?)
WHERE format_id = 1
'''
|
"""
HackerRank :: Reverse a singly-linked list
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
Complete the reverse function below.
For your reference:
SinglyLinkedListNode:
int data
SinglyLinkedListNode next
"""
def reverse(head):
# head node value can be null
# Keep track of previous node
prev_node = None
cur_node = head
# Loop through - while node.next
while cur_node:
# Save node for overwriting cur_node
next_node = cur_node.next
# Set current node's next to prev_node
cur_node.next = prev_node
# Pass previous node to next iteration
prev_node = cur_node
cur_node = next_node
return prev_node
|
# Copyright (c) 2013 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.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'gfx',
'type': '<(component)',
'dependencies': [
'<(DEPTH)/base/base.gyp:base',
'<(DEPTH)/base/base.gyp:base_i18n',
'<(DEPTH)/base/base.gyp:base_static',
'<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
'<(DEPTH)/net/net.gyp:net',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/icu/icu.gyp:icui18n',
'<(DEPTH)/third_party/icu/icu.gyp:icuuc',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/zlib/zlib.gyp:zlib',
'<(DEPTH)/url/url.gyp:url_lib',
],
# text_elider.h includes ICU headers.
'export_dependent_settings': [
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/icu/icu.gyp:icui18n',
'<(DEPTH)/third_party/icu/icu.gyp:icuuc',
],
'defines': [
'GFX_IMPLEMENTATION',
],
'sources': [
'android/device_display_info.cc',
'android/device_display_info.h',
'android/gfx_jni_registrar.cc',
'android/gfx_jni_registrar.h',
'android/java_bitmap.cc',
'android/java_bitmap.h',
'android/shared_device_display_info.cc',
'android/shared_device_display_info.h',
'animation/animation.cc',
'animation/animation.h',
'animation/animation_container.cc',
'animation/animation_container.h',
'animation/animation_container_element.h',
'animation/animation_container_observer.h',
'animation/animation_delegate.h',
'animation/linear_animation.cc',
'animation/linear_animation.h',
'animation/multi_animation.cc',
'animation/multi_animation.h',
'animation/slide_animation.cc',
'animation/slide_animation.h',
'animation/throb_animation.cc',
'animation/throb_animation.h',
'animation/tween.cc',
'animation/tween.h',
'blit.cc',
'blit.h',
'box_f.cc',
'box_f.h',
'break_list.h',
'canvas.cc',
'canvas.h',
'canvas_android.cc',
'canvas_paint_gtk.cc',
'canvas_paint_gtk.h',
'canvas_paint_mac.h',
'canvas_paint_mac.mm',
'canvas_paint_win.cc',
'canvas_paint_win.h',
'canvas_skia.cc',
'canvas_skia_paint.h',
'codec/jpeg_codec.cc',
'codec/jpeg_codec.h',
'codec/png_codec.cc',
'codec/png_codec.h',
'color_analysis.cc',
'color_analysis.h',
'color_profile.cc',
'color_profile.h',
'color_profile_mac.cc',
'color_profile_win.cc',
'color_utils.cc',
'color_utils.h',
'display.cc',
'display.h',
'display_observer.cc',
'display_observer.h',
'favicon_size.cc',
'favicon_size.h',
'frame_time.h',
'font.cc',
'font.h',
'font_fallback_win.cc',
'font_fallback_win.h',
'font_list.cc',
'font_list.h',
'font_render_params_android.cc',
'font_render_params_linux.cc',
'font_render_params_linux.h',
'font_smoothing_win.cc',
'font_smoothing_win.h',
'gfx_export.h',
'gfx_paths.cc',
'gfx_paths.h',
'gpu_memory_buffer.cc',
'gpu_memory_buffer.h',
'image/canvas_image_source.cc',
'image/canvas_image_source.h',
'image/image.cc',
'image/image.h',
'image/image_family.cc',
'image/image_family.h',
'image/image_ios.mm',
'image/image_mac.mm',
'image/image_png_rep.cc',
'image/image_png_rep.h',
'image/image_skia.cc',
'image/image_skia.h',
'image/image_skia_operations.cc',
'image/image_skia_operations.h',
'image/image_skia_rep.cc',
'image/image_skia_rep.h',
'image/image_skia_source.h',
'image/image_skia_util_ios.h',
'image/image_skia_util_ios.mm',
'image/image_skia_util_mac.h',
'image/image_skia_util_mac.mm',
'image/image_util.cc',
'image/image_util.h',
'image/image_util_ios.mm',
'insets.cc',
'insets.h',
'insets_base.h',
'insets_f.cc',
'insets_f.h',
'interpolated_transform.cc',
'interpolated_transform.h',
'mac/scoped_ns_disable_screen_updates.h',
'matrix3_f.cc',
'matrix3_f.h',
'native_widget_types.h',
'ozone/dri/dri_skbitmap.cc',
'ozone/dri/dri_skbitmap.h',
'ozone/dri/dri_surface.cc',
'ozone/dri/dri_surface.h',
'ozone/dri/dri_surface_factory.cc',
'ozone/dri/dri_surface_factory.h',
'ozone/dri/dri_wrapper.cc',
'ozone/dri/dri_wrapper.h',
'ozone/dri/hardware_display_controller.cc',
'ozone/dri/hardware_display_controller.h',
'ozone/impl/file_surface_factory.cc',
'ozone/impl/file_surface_factory.h',
'ozone/surface_factory_ozone.cc',
'ozone/surface_factory_ozone.h',
'pango_util.cc',
'pango_util.h',
'path.cc',
'path.h',
'path_aura.cc',
'path_gtk.cc',
'path_win.cc',
'path_win.h',
'path_x11.cc',
'path_x11.h',
'platform_font.h',
'platform_font_android.cc',
'platform_font_ios.h',
'platform_font_ios.mm',
'platform_font_mac.h',
'platform_font_mac.mm',
'platform_font_ozone.cc',
'platform_font_pango.cc',
'platform_font_pango.h',
'platform_font_win.cc',
'platform_font_win.h',
'point.cc',
'point.h',
'point3_f.cc',
'point3_f.h',
'point_base.h',
'point_conversions.cc',
'point_conversions.h',
'point_f.cc',
'point_f.h',
'quad_f.cc',
'quad_f.h',
'range/range.cc',
'range/range.h',
'range/range_mac.mm',
'range/range_win.cc',
'rect.cc',
'rect.h',
'rect_base.h',
'rect_base_impl.h',
'rect_conversions.cc',
'rect_conversions.h',
'rect_f.cc',
'rect_f.h',
'render_text.cc',
'render_text.h',
'render_text_mac.cc',
'render_text_mac.h',
'render_text_ozone.cc',
'render_text_pango.cc',
'render_text_pango.h',
'render_text_win.cc',
'render_text_win.h',
'safe_integer_conversions.h',
'scoped_canvas.h',
'scoped_cg_context_save_gstate_mac.h',
'scoped_ns_graphics_context_save_gstate_mac.h',
'scoped_ns_graphics_context_save_gstate_mac.mm',
'scoped_ui_graphics_push_context_ios.h',
'scoped_ui_graphics_push_context_ios.mm',
'screen.cc',
'screen.h',
'screen_android.cc',
'screen_aura.cc',
'screen_gtk.cc',
'screen_ios.mm',
'screen_mac.mm',
'screen_win.cc',
'screen_win.h',
'scrollbar_size.cc',
'scrollbar_size.h',
'selection_model.cc',
'selection_model.h',
'sequential_id_generator.cc',
'sequential_id_generator.h',
'shadow_value.cc',
'shadow_value.h',
'size.cc',
'size.h',
'size_base.h',
'size_conversions.cc',
'size_conversions.h',
'size_f.cc',
'size_f.h',
'skbitmap_operations.cc',
'skbitmap_operations.h',
'skia_util.cc',
'skia_util.h',
'skia_utils_gtk.cc',
'skia_utils_gtk.h',
'switches.cc',
'switches.h',
'sys_color_change_listener.cc',
'sys_color_change_listener.h',
'text_constants.h',
'text_elider.cc',
'text_elider.h',
'text_utils.cc',
'text_utils.h',
'text_utils_android.cc',
'text_utils_ios.mm',
'text_utils_skia.cc',
'transform.cc',
'transform.h',
'transform_util.cc',
'transform_util.h',
'utf16_indexing.cc',
'utf16_indexing.h',
'vector2d.cc',
'vector2d.h',
'vector2d_conversions.cc',
'vector2d_conversions.h',
'vector2d_f.cc',
'vector2d_f.h',
'vector3d_f.cc',
'vector3d_f.h',
'win/dpi.cc',
'win/dpi.h',
'win/hwnd_util.cc',
'win/hwnd_util.h',
'win/scoped_set_map_mode.h',
'win/singleton_hwnd.cc',
'win/singleton_hwnd.h',
'win/window_impl.cc',
'win/window_impl.h',
'x/x11_atom_cache.cc',
'x/x11_atom_cache.h',
'x/x11_types.cc',
'x/x11_types.h',
],
'conditions': [
['OS=="ios"', {
# iOS only uses a subset of UI.
'sources/': [
['exclude', '^codec/jpeg_codec\\.cc$'],
],
}, {
'dependencies': [
'<(libjpeg_gyp_path):libjpeg',
],
}],
# TODO(asvitkine): Switch all platforms to use canvas_skia.cc.
# http://crbug.com/105550
['use_canvas_skia==1', {
'sources!': [
'canvas_android.cc',
],
}, { # use_canvas_skia!=1
'sources!': [
'canvas_skia.cc',
],
}],
['toolkit_uses_gtk == 1', {
'dependencies': [
'<(DEPTH)/build/linux/system.gyp:gtk',
],
'sources': [
'gtk_native_view_id_manager.cc',
'gtk_native_view_id_manager.h',
'gtk_preserve_window.cc',
'gtk_preserve_window.h',
'gdk_compat.h',
'gtk_compat.h',
'gtk_util.cc',
'gtk_util.h',
'image/cairo_cached_surface.cc',
'image/cairo_cached_surface.h',
'scoped_gobject.h',
],
}],
['OS=="win"', {
'sources': [
'gdi_util.cc',
'gdi_util.h',
'icon_util.cc',
'icon_util.h',
],
# TODO(jschuh): C4267: http://crbug.com/167187 size_t -> int
# C4324 is structure was padded due to __declspec(align()), which is
# uninteresting.
'msvs_disabled_warnings': [ 4267, 4324 ],
}],
['OS=="android"', {
'sources!': [
'animation/throb_animation.cc',
'display_observer.cc',
'path.cc',
'selection_model.cc',
],
'dependencies': [
'gfx_jni_headers',
],
'link_settings': {
'libraries': [
'-landroid',
'-ljnigraphics',
],
},
}],
['OS=="android" and android_webview_build==0', {
'dependencies': [
'<(DEPTH)/base/base.gyp:base_java',
],
}],
['OS=="android" or OS=="ios"', {
'sources!': [
'render_text.cc',
'render_text.h',
'text_utils_skia.cc',
],
}],
['use_pango==1', {
'dependencies': [
'<(DEPTH)/build/linux/system.gyp:pangocairo',
],
}],
['ozone_platform_dri==1', {
'dependencies': [
'<(DEPTH)/build/linux/system.gyp:dridrm',
],
}],
],
'target_conditions': [
# Need 'target_conditions' to override default filename_rules to include
# the file on iOS.
['OS == "ios"', {
'sources/': [
['include', '^scoped_cg_context_save_gstate_mac\\.h$'],
],
}],
],
}
],
'conditions': [
['OS=="android"' , {
'targets': [
{
'target_name': 'gfx_jni_headers',
'type': 'none',
'direct_dependent_settings': {
'include_dirs': [
'<(SHARED_INTERMEDIATE_DIR)/ui/gfx',
],
},
'sources': [
'../android/java/src/org/chromium/ui/gfx/BitmapHelper.java',
'../android/java/src/org/chromium/ui/gfx/DeviceDisplayInfo.java',
],
'variables': {
'jni_gen_package': 'ui/gfx',
'jni_generator_ptr_type': 'long',
},
'includes': [ '../../build/jni_generator.gypi' ],
},
],
}],
],
}
|
"""
113 / 113 test cases passed.
Runtime: 92 ms
Memory Usage: 16.4 MB
"""
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
def dfs(used, x, y):
used[x][y] = True
for xx, yy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if 0 <= xx < m and 0 <= yy < n and not used[xx][yy] and heights[xx][yy] >= heights[x][y]:
dfs(used, xx, yy)
pacific_used = [[False] * n for _ in range(m)]
atlantic_used = [[False] * n for _ in range(m)]
for i in range(m):
dfs(pacific_used, i, 0)
dfs(atlantic_used, i, n - 1)
for i in range(n):
dfs(pacific_used, 0, i)
dfs(atlantic_used, m - 1, i)
ans = []
for i in range(m):
for j in range(n):
if pacific_used[i][j] and atlantic_used[i][j]:
ans.append([i, j])
return ans
|
__all__ = (
'LIST',
'GET',
'CREATE',
'UPDATE',
'REPLACE',
'DELETE',
'ALL',
'get_http_methods'
)
LIST = 'list'
GET = 'get'
CREATE = 'create'
REPLACE = 'replace'
UPDATE = 'update'
DELETE = 'delete'
ALL = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE)
_http_methods = {
LIST: ('get',),
GET: ('get',),
CREATE: ('post',),
REPLACE: ('put',),
UPDATE: ('patch',),
DELETE: ('delete',)
}
def get_http_methods(method):
return _http_methods[method]
|
# -*- coding: utf-8 -*-
"""
Created on 2017/11/18
@author: MG
"""
|
"""
Rackspace Cloud Backup API
Test Suite
"""
|
def test():
assert "spacy.load" in __solution__, "Rufst du spacy.load auf?"
assert nlp.meta["lang"] == "de", "Lädst du das korrekte Modell?"
assert nlp.meta["name"] == "core_news_sm", "Lädst du das korrekte Modell?"
assert "nlp(text)" in __solution__, "Verarbeitest du den Text korrekt?"
assert "print(doc.text)" in __solution__, "Druckst du den Text des Doc?"
__msg__.good(
"Gut gemacht! Jetzt wo du das Laden von Modellen geübt hast, lass uns "
"mal ein paar ihrer Vorhersagen anschauen."
)
|
NFSW_Texts = [
'سکس'
,'گایید'
,' کص'
,'جنده'
,'کیر'
,'jnde'
,'jende'
,'kos'
,'pussy'
,'kir'
,'lashi'
,'لاشی'
,'jakesh'
,'جاکش'
,'مادر خراب'
,'madar kharab'
,'mde kharab'
,'khar kose'
,'fuck'
,'bitch'
,'haroomzade'
,'حرومی'
,'حرامزاده'
,'حرومزاده'
,'جندس'
,'کصه '
]
NFSW_Names=[
'خاله'
,'جنده'
,"کص"
,"کیر"
,"ساعتی"
,"اوف"
,"💦💦💦💦"
,"سوپر"
,"فیلم"
,"بیو"
,"حضوری"
,"مکان"
]
Porn={'dick':'Male Genitalia - Exposed',
'pussy':'Female Genitalia - Exposed',
'coveredpossy':'Female Genitalia - Covered',
'fboobs':'Female Breast - Exposed',
'mboobs':'Male Breast - Exposed',
'coveredboobs':'Female Breast - Covered',
'stomack':'Male Breast - Covered',
'baghal':'Male Breast - Exposed',
'ass':'Buttocks - Exposed',
'feet':'404NotFound',
'coveredass':'Buttocks - Covered'}
|
#!/usr/bin/env python3
if __name__ == '__main__':
# Python can represent integers. Here are a couple of ways to create an integer variable. Notice the truncation,
# rather than rounding, in the assignment of d.
a = 5
b = int()
c = int(4)
d = int(3.84)
print(a, b, c, d)
# Integers have the usual math operations. Note that division will return a float, but others will preserve the
# integer type. The type() function can tell you the type of a variable. You should try to avoid using this
# function in your code.
print('\ndivision')
a = 10
b = 10 / 5
print(b, type(b))
# We can force integer division with //. Note that this will truncate results.
print('\nInteger division')
a = 10
b = 10 // 5
print(b, type(b))
a = 10
b = 10 // 3
print(b, type(b))
# We can also calculate the remainder
n = 10
m = 3
div = n // m
rem = n % m
print('\n{0} = {1} * {2} + {3}'.format(n, div, m, rem))
|
def test():
obj = { 'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123 }
i = 0
while i < 1e7:
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
i += 1
test()
|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
"""
__author__ = 'joscha'
__date__ = '03.08.12'
|
counter_name = 'I0_PIN'
Size = wx.Size(1007, 726)
logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log'
average_count = 1
max_value = 11
min_value = 0
start_fraction = 0.401
reject_outliers = False
outlier_cutoff = 2.5
show_statistics = True
time_window = 172800
|
print("I will now count my chickens:")
print ("Hens",25+30/6)
print ("Roosters",100-25*3%4)
print("How I will count the eggs:")
print(3+2+1-5+4%2-1/4+6)
print("Is it true that 3+2<5-7?")
print(3+2<5-7)
print("What is 3+2?", 3+2)
print("What is 5-7?", 5-7)
print("Oh,that's why it's false")
print("How about some more.")
print("Is it greater?",5>-2)
print("Is it greater or equal?",5>=-2)
print("Is it less or equal?",5<=-2)
|
class Cpf:
def __init__(self, documento):
documento = str(documento)
if self.cpf_eh_valido(documento):
self.cpf = documento
else:
raise ValueError("CPF inválido!")
def cpf_eh_valido(self, documento):
if len(documento) == 11:
return True
else:
return False
def cpf_formato(self):
fatia_um = self.cpf[:3]
fatia_dois = self.cpf[3:6]
fatia_tres = self.cpf[6:9]
fatia_quatro = self.cpf[9:]
return(
"{}.{}.{}-{}".format(
fatia_um,
fatia_dois,
fatia_tres,
fatia_quatro
)
)
|
#! /usr/bin/env python
"""
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 2
Author: Hank Preston <[email protected]>
common_vars.py
Illustrate the following concepts:
- Code reuse
imported into other examples
"""
shapes = ["square", "triangle", "circle"]
books = [
{
"title": "War and Peace",
"shelf": 3,
"available": True
},
{
"title": "Hamlet",
"shelf": 1,
"available": False
},
{
"title": "Harold and the Purple Crayon",
"shelf": 2,
"available": True
}
]
colors = ["blue", "green", "red"]
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 18:48:24 2020
@author: Christopher Cheng
"""
class Stack(object):
def __init__ (self):
self.stack = []
def get_stack_elements(self):
return self.stack.copy()
def add_one(self, item):
self.stack.append(item)
def add_many(self,item,n): # item is still a single string, n times
for i in range (n):
self.stack.append(item)
def remove_one(self):
self.stack.pop()
def remove_many(self,n):
for i in range(n):
self.stack.pop()
def size(self):
return len(self.stack)
def prettyprint(self):
for thing in self.stack[::-1]:
print("|_", thing,"_|")
def add_list(self, L):
for e in L:
self.stack.append(e)
def __str__ (self):
ret = ""
for thing in self.stack[::-1]:
ret += ("|_" + str(thing) + "_|\n")
return ret
class Circle (object):
def __init__(self):
self.radius = 0
def change_radius(self, radius):
self.radius = radius
def get_radius (self):
return self.radius
def __str__(self):
return "circle: " + str(self.radius)
circles = Stack()
one_circle = Circle()
one_circle.change_radius(1)
circles.add_one(one_circle)
two_circle = Circle()
two_circle.change_radius(2)
circles.add_one(two_circle)
print(circles)
|
def wordPower(word):
num = dict(zip(string.ascii_lowercase, range(1,27)))
return sum([num[ch] for ch in word])
|
'''
剑指 Offer 10- II. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
提示:
0 <= n <= 100
'''
'''
思路:递归
'''
class Solution:
def numWays(self, n: int) -> int:
if n == 0:
return 1
if n == 1:
return 1
if n == 2:
return 2
return (self.numWays(n - 1) + self.numWays(n - 2)) % 1000000007
s = Solution()
print(s.numWays(2))
print(s.numWays(5))
print(s.numWays(0))
print(s.numWays(7))
|
"""
Profile ../profile-datasets-py/div83/027.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/027.py"
self["Q"] = numpy.array([ 1.51831800e+00, 2.02599600e+00, 2.94787100e+00,
3.99669400e+00, 4.71653800e+00, 4.89106600e+00,
5.14399400e+00, 5.67274800e+00, 6.02338400e+00,
6.09836300e+00, 6.08376300e+00, 6.01126400e+00,
5.91866500e+00, 5.77584700e+00, 5.59481900e+00,
5.41637100e+00, 5.26750200e+00, 5.10689400e+00,
4.98576500e+00, 4.90039600e+00, 4.80689700e+00,
4.63989800e+00, 4.46443000e+00, 4.30135100e+00,
4.16606300e+00, 4.06766300e+00, 4.01361400e+00,
3.95640400e+00, 3.87825500e+00, 3.79394600e+00,
3.73623600e+00, 3.72919600e+00, 3.74067600e+00,
3.78187600e+00, 3.81900500e+00, 3.85233500e+00,
3.88512500e+00, 3.91148500e+00, 3.92466500e+00,
3.92849500e+00, 3.93905400e+00, 3.97355400e+00,
4.02951400e+00, 4.05710400e+00, 4.04558400e+00,
4.02228400e+00, 4.01040400e+00, 4.00572400e+00,
4.00641400e+00, 4.08608300e+00, 4.44130000e+00,
5.00126500e+00, 5.73600700e+00, 6.83860300e+00,
8.34002000e+00, 9.95999100e+00, 1.13537700e+01,
1.24435500e+01, 1.36048100e+01, 1.55239600e+01,
1.77784800e+01, 1.93991200e+01, 2.00516000e+01,
1.97941100e+01, 1.89638400e+01, 1.84148600e+01,
1.82331700e+01, 1.84861600e+01, 2.02668900e+01,
3.24805400e+01, 6.31028200e+01, 1.09865900e+02,
1.71694500e+02, 2.41407700e+02, 3.05073900e+02,
3.60772800e+02, 4.04902000e+02, 4.16543400e+02,
4.04623200e+02, 3.59892400e+02, 3.06567000e+02,
3.03443900e+02, 4.25764600e+02, 8.75110500e+02,
1.60701300e+03, 2.52645100e+03, 3.50894400e+03,
4.39830900e+03, 5.05090900e+03, 5.40195000e+03,
5.54486300e+03, 5.86218200e+03, 6.10752900e+03,
6.83105600e+03, 6.63557500e+03, 6.44820100e+03,
6.26853800e+03, 6.09616900e+03, 5.93072700e+03,
5.77187200e+03, 5.61926500e+03])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56505000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61260000e+01, 6.09895000e+01, 6.61253000e+01,
7.15398000e+01, 7.72396000e+01, 8.32310000e+01,
8.95204000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17778000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23442000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90893000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53628000e+02, 7.77790000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31524000e+02, 9.58591000e+02,
9.86067000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 375.9234, 375.9232, 375.9219, 375.9195, 375.9172, 375.9142,
375.9041, 375.8819, 375.8607, 375.8617, 375.8997, 375.9717,
376.0398, 376.0858, 376.1489, 376.212 , 376.224 , 376.2321,
376.2481, 376.2772, 376.3252, 376.3663, 376.4023, 376.4224,
376.4504, 376.4865, 376.5545, 376.6335, 376.7605, 376.8966,
377.0446, 377.2036, 377.3766, 377.5606, 377.7106, 377.8485,
378.0765, 378.4945, 378.9365, 379.6475, 380.4225, 381.0245,
381.4085, 381.8025, 381.8315, 381.8625, 381.8985, 381.9405,
381.9845, 382.0364, 382.0903, 382.5651, 383.1618, 383.8894,
384.7668, 385.5962, 386.1156, 386.6532, 386.7607, 386.854 ,
386.8701, 386.8645, 386.8732, 386.8913, 386.9157, 386.9449,
386.9669, 386.9788, 386.9602, 386.9034, 386.8186, 386.7075,
386.6086, 386.5187, 386.4681, 386.4315, 386.4595, 386.5189,
386.6375, 386.8447, 387.1073, 387.3124, 387.433 , 387.3937,
387.2297, 386.9659, 386.6525, 386.3522, 386.1188, 385.9826,
385.9361, 385.8209, 385.7317, 385.4548, 385.5337, 385.6074,
385.6771, 385.744 , 385.8082, 385.8699, 385.9291])
self["CO"] = numpy.array([ 0.2205447 , 0.2185316 , 0.2145434 , 0.2078282 , 0.1977631 ,
0.1839901 , 0.1511932 , 0.09891954, 0.0827345 , 0.05454007,
0.02926452, 0.01534331, 0.01021024, 0.00922827, 0.00895567,
0.00841368, 0.00791632, 0.0076217 , 0.00749041, 0.00745301,
0.00740799, 0.00741502, 0.00746624, 0.00760092, 0.00775626,
0.00793258, 0.0081303 , 0.00834271, 0.00844155, 0.00854593,
0.00861921, 0.00869836, 0.00895125, 0.009236 , 0.00956421,
0.00993273, 0.01050776, 0.01155325, 0.01277055, 0.01483604,
0.01745463, 0.02009092, 0.02248201, 0.0252159 , 0.0250677 ,
0.0249136 , 0.0248554 , 0.0248671 , 0.0248747 , 0.0248604 ,
0.02484549, 0.02830606, 0.03349511, 0.03954063, 0.04649641,
0.05393566, 0.05777834, 0.06203953, 0.06291754, 0.06367061,
0.06376177, 0.06365417, 0.06355173, 0.06345124, 0.063449 ,
0.06353453, 0.06376724, 0.06416551, 0.06445159, 0.0646028 ,
0.06451203, 0.06417925, 0.06369376, 0.06310236, 0.06261609,
0.06216137, 0.06196 , 0.06180874, 0.06178709, 0.06208905,
0.06263239, 0.06350083, 0.06423774, 0.06476787, 0.06481747,
0.06471838, 0.06458966, 0.06447546, 0.06438733, 0.06432344,
0.06428367, 0.06423741, 0.0641983 , 0.06589368, 0.07015209,
0.07475692, 0.0797395 , 0.08513432, 0.09097941, 0.09731644,
0.1041912 ])
self["T"] = numpy.array([ 189.265, 197.336, 211.688, 227.871, 242.446, 252.765,
259.432, 262.908, 263.411, 262.202, 261.422, 259.368,
255.095, 250.075, 244.792, 239.205, 235.817, 231.46 ,
227.966, 225.935, 225.115, 222.382, 219.723, 218.152,
217.875, 218.211, 218.288, 218.294, 217.949, 217.202,
216.158, 214.964, 215.259, 215.053, 215.409, 216.081,
216.441, 216.152, 215.427, 215.082, 216.198, 217.247,
217.006, 216.373, 216.342, 217.088, 218.419, 219.839,
220.797, 220.946, 221.423, 222.504, 223.822, 225.134,
226.221, 226.93 , 227.275, 227.405, 227.434, 227.346,
227.212, 227.246, 227.566, 228.2 , 229.083, 230.094,
231.117, 232.121, 233.086, 234.01 , 235.064, 236.351,
237.928, 239.892, 242.039, 244.306, 246.651, 249.025,
251.415, 253.802, 256.16 , 258.448, 260.591, 262.445,
264.071, 265.349, 266.233, 266.969, 267.78 , 268.72 ,
269.42 , 270.502, 271.421, 273.317, 273.317, 273.317,
273.317, 273.317, 273.317, 273.317, 273.317])
self["N2O"] = numpy.array([ 0.00161 , 0.00187 , 0.00205999, 0.00220999, 0.00233999,
0.00235999, 0.00157999, 0.00186999, 0.00519997, 0.00870995,
0.00838995, 0.00955994, 0.01208993, 0.01432992, 0.0171399 ,
0.02172988, 0.02788985, 0.03756981, 0.04630977, 0.05168975,
0.05680973, 0.05922973, 0.06028973, 0.06131974, 0.07010971,
0.07957968, 0.08867964, 0.09929961, 0.1101496 , 0.1206295 ,
0.1301795 , 0.1371795 , 0.1439595 , 0.1505294 , 0.1651494 ,
0.1848693 , 0.2034792 , 0.2285391 , 0.252299 , 0.2748389 ,
0.2840589 , 0.2926288 , 0.3004188 , 0.3072488 , 0.3129187 ,
0.3172487 , 0.3200187 , 0.3209987 , 0.3209987 , 0.3209987 ,
0.3209986 , 0.3209984 , 0.3209982 , 0.3209978 , 0.3209973 ,
0.3209968 , 0.3209964 , 0.320996 , 0.3209956 , 0.320995 ,
0.3209943 , 0.3209938 , 0.3209936 , 0.3209936 , 0.3209939 ,
0.3209941 , 0.3209941 , 0.3209941 , 0.3209935 , 0.3209896 ,
0.3209797 , 0.3209647 , 0.3209449 , 0.3209225 , 0.3209021 ,
0.3208842 , 0.32087 , 0.3208663 , 0.3208701 , 0.3208845 ,
0.3209016 , 0.3209026 , 0.3208633 , 0.3207191 , 0.3204841 ,
0.320189 , 0.3198736 , 0.3195881 , 0.3193787 , 0.319266 ,
0.3192201 , 0.3191182 , 0.3190395 , 0.3188072 , 0.31887 ,
0.3189301 , 0.3189878 , 0.3190431 , 0.3190962 , 0.3191472 ,
0.3191962 ])
self["O3"] = numpy.array([ 0.1903137 , 0.2192386 , 0.3077081 , 0.5440408 , 0.8590299 ,
1.170854 , 1.499102 , 1.864289 , 2.273556 , 2.805293 ,
3.409769 , 4.028786 , 4.806182 , 5.619898 , 6.411164 ,
7.147361 , 7.51202 , 7.648961 , 7.644362 , 7.556123 ,
7.446574 , 7.281136 , 6.952659 , 6.604492 , 6.296854 ,
6.008776 , 5.751387 , 5.520268 , 5.311749 , 5.111921 ,
4.890092 , 4.593293 , 4.298724 , 3.882905 , 3.380027 ,
2.799559 , 2.288161 , 2.031152 , 2.018272 , 2.047542 ,
1.969722 , 1.685453 , 1.220825 , 0.9176053 , 0.8929574 ,
0.9542592 , 1.004996 , 1.034796 , 1.031726 , 1.019046 ,
0.8797071 , 0.6484178 , 0.4105526 , 0.2529783 , 0.1943934 ,
0.201197 , 0.2459162 , 0.322179 , 0.3977806 , 0.4292413 ,
0.4255834 , 0.3930204 , 0.3461121 , 0.2989281 , 0.2606191 ,
0.2321107 , 0.2069452 , 0.1838146 , 0.1618567 , 0.1410414 ,
0.1225313 , 0.1061913 , 0.09214328, 0.08133816, 0.07293074,
0.06636085, 0.06143102, 0.05859298, 0.05740586, 0.05732126,
0.05783027, 0.05809797, 0.05651443, 0.05019414, 0.0404447 ,
0.03280082, 0.02944741, 0.02902179, 0.02945348, 0.02918976,
0.02836743, 0.02750451, 0.02608958, 0.02225294, 0.02225732,
0.02226152, 0.02226555, 0.02226941, 0.02227312, 0.02227668,
0.02228009])
self["CH4"] = numpy.array([ 0.1059488, 0.1201298, 0.1306706, 0.1417254, 0.1691352,
0.209023 , 0.2345078, 0.2578465, 0.2845033, 0.328699 ,
0.3987896, 0.4800421, 0.5668716, 0.6510682, 0.7280449,
0.7954147, 0.8518465, 0.8903115, 0.9281374, 0.9731752,
1.016085 , 1.071595 , 1.131985 , 1.189835 , 1.247015 ,
1.302185 , 1.355285 , 1.400504 , 1.442154 , 1.464494 ,
1.488464 , 1.514124 , 1.541544 , 1.560774 , 1.579304 ,
1.596804 , 1.612894 , 1.627174 , 1.638294 , 1.650024 ,
1.662373 , 1.675353 , 1.688973 , 1.722213 , 1.729283 ,
1.736683 , 1.741733 , 1.745103 , 1.749093 , 1.755483 ,
1.762122 , 1.770021 , 1.77847 , 1.785498 , 1.790785 ,
1.795642 , 1.79793 , 1.800308 , 1.800506 , 1.800632 ,
1.800498 , 1.800295 , 1.800414 , 1.800704 , 1.800856 ,
1.800867 , 1.800517 , 1.799787 , 1.798434 , 1.796372 ,
1.794017 , 1.791393 , 1.789133 , 1.787118 , 1.785875 ,
1.784886 , 1.784827 , 1.785476 , 1.788046 , 1.791395 ,
1.795229 , 1.798224 , 1.800263 , 1.801052 , 1.800931 ,
1.80036 , 1.799234 , 1.797877 , 1.796739 , 1.796035 ,
1.795827 , 1.795294 , 1.79488 , 1.793604 , 1.793966 ,
1.794315 , 1.794639 , 1.794951 , 1.795249 , 1.795536 ,
1.795812 ])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 273.317
self["S2M"]["Q"] = 5619.26541873
self["S2M"]["O"] = 0.022280094739
self["S2M"]["P"] = 905.85559
self["S2M"]["U"] = 0.0
self["S2M"]["V"] = 0.0
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 0
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 273.317
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 0.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 45.309
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([2007, 4, 1])
self["TIME"] = numpy.array([0, 0, 0])
|
s = input().strip()
res = [c for c in set(s.lower()) if c.isalpha()]
if len(res) == 26:
print("pangram")
else:
print("not pangram")
|
class DataStream:
async def create_private_listen_key(self) -> dict:
"""**Create a ListenKey (USER_STREAM)**
Notes:
``POST /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream
"""
return await self._fetch(
'POST',
'create_private_listen_key',
'/fapi/v1/listenKey'
)
async def update_private_listen_key(self) -> dict:
"""**Ping/Keep-alive a ListenKey (USER_STREAM)**
Notes:
``PUT /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#keepalive-user-data-stream-user_stream
"""
return await self._fetch(
'PUT',
'update_private_listen_key',
'/fapi/v1/listenKey'
)
async def delete_private_listen_key(self) -> dict:
"""**Close a ListenKey (USER_STREAM)**
Notes:
``DELETE /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#close-user-data-stream-user_stream
"""
return await self._fetch(
'DELETE',
'delete_private_listen_key',
'/fapi/v1/listenKey'
)
|
x = input("Enter sentence: ")
count={"Uppercase":0, "Lowercase":0}
for i in x:
if i.isupper():
count["Uppercase"]+=1
elif i.islower():
count["Lowercase"]+=1
else:
pass
print ("There is:", count["Uppercase"], "uppercases.")
print ("There is:", count["Lowercase"], "lowercases.")
|
input = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
output = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
|
file = open("13")
sum = 0
for numbers in file:
#print(numbers.rstrip())
numbers = int(numbers)
sum += numbers;
print(sum)
sum = str(sum)
print(sum[:10])
|
variable1 = "variable original"
def variable_global():
global variable1
variable1 = "variable global modificada"
print(variable1)
#variable original
variable_global()
print(variable1)
#variable global modificada
|
TIMEOUT=100
def GenerateWriteCommand(i2cAddress, ID, writeLocation, data):
i = 0
TIMEOUT = 100
command = bytearray(len(data)+15)
while (i < 4):
command[i] = 255
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ID
command[7] = 2
command[8] = writeLocation
command[9] = len(data)
command[(10 + len(data))] = 255
i = 0
while (i < len(data)):
command[(10 + i)] = data[i]
i += 1
i = 0
while (i < 4):
command[(11 + i) + len(data)] = 254
i += 1
return command
def GenerateReadCommand(i2cAddress, ID, readLocation, numToRead):
command = bytearray(16)
i = 0
TIMEOUT = 100
while (i < 4):
command[i] = 0xFF
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ID
command[7] = 0x01
command[8] = readLocation
command[9] = numToRead
command[10] = 0xFF
i = 0
while (i < 4):
command[(11 + i)] = 0xFE
i += 1
return command
def GenerateToggleCommand(i2cAddress, ID, writeLocation, data):
i = 0
command = bytearray(16 + 15)
while (i < 4):
command[i] = 255
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ID
command[7] = 3
command[8] = data
command[9] = 16
command[(10 + 16)] = 255
i = 0
while (i < 16):
command[(10 + i)] = 7
i += 1
i = 0
while (i < 4):
command[((11 + i) + 16)] = 254
i += 1
return command
|
class AveragingBucketUpkeep:
def __init__(self):
self.numer = 0.0
self.denom = 0
def add_cost(self, cost):
self.numer += cost
self.denom += 1
return self.numer / self.denom
def rem_cost(self, cost):
self.numer -= cost
self.denom -= 1
if self.denom == 0:
return 0
return self.numer / self.denom
|
#--- Exercício 2 - Variáveis
#--- Crie um menu para um sistema de cadastro de funcionários
#--- O menu deve ser impresso com a função format()
#--- As opções devem ser variáveis do tipo inteiro
#--- As descrições das opções serão:
#--- Cadastrar funcionário
#--- Listar funcionários
#--- Editar funcionário
#--- Deletar funcionário
#--- Sair
#--- Além das opções o menu deve conter um cabeçalho e um rodapé
#--- Entre o cabeçalho e o menu e entre o menu e o rodapé deverá ter espaçamento de 3 linhas
#--- Deve ser utilizado os caracteres especiais de quebra de linha e de tabulação
opcao = int(input("""
SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n
{} - Cadastrar Funcionário
{} - Listar Funcinários
{} - Editar Funcionário
{} - Deletar Funcionário
{} - Sair\n\n\n
Escolha uma opção: """.format(1,2,3,4,5)))
if opcao == 1:
print("A opção escolhida foi 'Cadastrar funcionário'")
elif opcao == 2:
print("A opção escolhida foi 'Listar funcionários'")
elif opcao == 3:
print("A opção escolhida foi 'Editar funcionário'")
elif opcao == 4:
print("A opção escolhida foi 'Deletar funcionário'")
elif opcao == 5:
print("A opção escolhida foi 'Sair'")
else:
pass
|
__version__ = "2.18"
def version():
"""Returns the version number of the installed workflows package."""
return __version__
class Error(Exception):
"""Common class for exceptions deliberately raised by workflows package."""
class Disconnected(Error):
"""Indicates the connection could not be established or has been lost."""
|
#!/usr/bin/env python3
class UnionFind():
def __init__(self, n):
self.parent = [-1 for _ in range(n)]
# 正==子: 根の頂点番号 / 負==根: 連結頂点数
def find(self, x):
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def unite(self, x, y):
x, y = self.find(x), self.find(y)
if x == y:
return False
else:
if self.size(x) < self.size(y):
x, y = y, x
self.parent[x] += self.parent[y]
self.parent[y] = x
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
x = self.find(x)
return -self.parent[x]
def is_root(self, x):
return self.parent[x] < 0
def main():
n, m = map(int, input().split())
count = 0
pair_list = []
uf = UnionFind(n)
for i in range(m):
array = list(map(int,input().split()))
array[0] -=1 ; array[1] -= 1
pair_list.append(array)
print(uf.unite(n-1,m-1))
main()
|
sqlqueries = {
'WeatherForecast':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity) humidity from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(f.forecasted_timestamp, 'YY'), to_char(f.forecasted_timestamp, 'MON'), to_char(f.forecasted_timestamp, 'DD'), f.zipcode;",
'WeatherActDesc':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, o.weather_description descripion from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON'), to_char(o.observation_timestamp, 'DD'), o.zipcode, o.weather_description order by fiscal_yr, fiscal_mth, fiscal_day, zip;",
'WeatherActual':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, min(o.temp_avg) low, max(o.temp_avg) high, max(o.wind_speed) wind, max(o.humidity) humidity from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON') , to_char(o.observation_timestamp, 'DD') , o.zipcode order by fiscal_yr, fiscal_mth, fiscal_day, zip;",
'WeatherDescription':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr , to_char(f.forecasted_timestamp, 'MON') Fiscal_mth , concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day , f.zipcode zip , f.weather_description descripion from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(forecasted_timestamp, 'YY') , to_char(f.forecasted_timestamp, 'MON') , to_char(f.forecasted_timestamp, 'DD') , f.zipcode , f.weather_description;"
}
|
mock_dbcli_config = {
'exports_from': {
'lpass': {
'pull_lastpass_from': "{{ lastpass_entry }}",
},
'lpass_user_and_pass_only': {
'pull_lastpass_username_password_from': "{{ lastpass_entry }}",
},
'my-json-script': {
'json_script': [
'some-custom-json-script'
]
},
'invalid-method': {
},
},
'dbs': {
'baz': {
'exports_from': 'my-json-script',
},
'bing': {
'exports_from': 'invalid-method',
},
'bazzle': {
'exports_from': 'lpass',
'lastpass_entry': 'lpass entry name'
},
'bazzle-bing': {
'exports_from': 'lpass',
'lastpass_entry': 'different lpass entry name'
},
'frazzle': {
'exports_from': 'lpass',
'lastpass_entry': 'lpass entry name'
},
'frink': {
'exports_from': 'lpass_user_and_pass_only',
'lastpass_entry': 'lpass entry name',
'jinja_context_name': 'standard',
'exports': {
'some_additional': 'export',
'a_numbered_export': 123
},
},
'gaggle': {
'jinja_context_name': [
'env',
'base64',
],
'exports': {
'type': 'bigquery',
'protocol': 'bigquery',
'bq_account': 'bq_itest',
'bq_service_account_json':
"{{ env('ITEST_BIGQUERY_SERVICE_ACCOUNT_JSON_BASE64') | b64decode }}",
'bq_default_project_id': 'bluelabs-tools-dev',
'bq_default_dataset_id': 'bq_itest',
},
},
},
'orgs': {
'myorg': {
'full_name': 'MyOrg',
},
},
}
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:dabai time:2019/2/24
class GameStats():
"""跟踪游戏的统计信息"""
def __init__(self,ai_settings):
"""初始化统计信息"""
self.ai_settings=ai_settings
self.reset_stats()
# 让游戏一开始处于非活动状态
self.game_active=False
# 在任何情况下都不应重置最高得分
self.high_score=0
def reset_stats(self):
"""初始化在游戏运行期间可能变化的统计信息"""
self.ships_left=self.ai_settings.ship_limit
self.score=0
self.level=1
|
# Practica de funciones
#! /usr/bin/python
# -*- coding: iso-8859-15
def f(x):
y = 2 * x ** 2 + 1
return y
# Programa que usa la funcion f
n = int(input("Ingrese número: "))
for i in range(n):
y = f(i)
print (i,y)
|
class Samples:
def __init__(self):
#COMMANDS
self.PP = ('Für [https://osu.ppy.sh/b/{} {} [{}]{}] (OD {}, AR {}, '
'CS {}, {}★, {}:{}) wirst du {} {}')
self.PP_FOR = ('| {}pp bekommen für {}% ')
self.PP_PRED = ('Für [https://osu.ppy.sh/b/{} {} [{}]{}] (OD {}, AR {}, '
'CS {}, {}★, {}:{}) wirst du {} {} # {}')
self.PP_PRED_IMPOSSIBLE = ('Unmöglich zu FC für dich')
self.PP_PRED_FUTURE = ('Es erwarten dich: {}pp')
self.INFO = ('Sie kannst Quelle und Information '
'[https://suroryz.github.io/surbot-osu/ hier] finden')
self.LANG_CHANGED = ('Sprache erfolgreich geändert. '
'Localizer: some HiNative guy')
#ERRORS
self.ERROR_SYNTAX = ('Sie hast etwas falsches eingegeben. '
'Kontrollieren Sie die Hilfeseite -> .info')
self.ERROR_NP_NEED = ('Sie müssen /np vorher verwenden')
self.ERROR_NO_LANGUAGE = ('Entschuldigung, aber ich kann deine/Ihre Sprache nicht in meiner Datenbank finden. '
'Versuchen Sie den ISO 639-1 Sprachen-Code zu nutzen. '
'Wenn Ihre dort nicht vorzufinden ist, können Sie das '
'[https://suroryz.github.io/surbot-osu/lang/langs hier] melden')
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def minDistance(self, height, width, tree, squirrel, nuts):
"""
:type height: int
:type width: int
:type tree: List[int]
:type squirrel: List[int]
:type nuts: List[List[int]]
:rtype: int
"""
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
result = 0
d = float("inf")
for nut in nuts:
result += (distance(nut, tree) * 2)
d = min(d, distance(nut, squirrel) - distance(nut, tree))
return result + d
|
# Copyright 2000-2004 Michael Hudson [email protected]
#
# All Rights Reserved
#
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
#
# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
class Event:
"""An Event. `evt' is 'key' or somesuch."""
def __init__(self, evt, data, raw=''):
self.evt = evt
self.data = data
self.raw = raw
def __repr__(self):
return 'Event(%r, %r)'%(self.evt, self.data)
class Console:
"""Attributes:
screen,
height,
width,
"""
def refresh(self, screen, xy):
pass
def prepare(self):
pass
def restore(self):
pass
def move_cursor(self, x, y):
pass
def set_cursor_vis(self, vis):
pass
def getheightwidth(self):
"""Return (height, width) where height and width are the height
and width of the terminal window in characters."""
pass
def get_event(self, block=1):
"""Return an Event instance. Returns None if |block| is false
and there is no event pending, otherwise waits for the
completion of an event."""
pass
def beep(self):
pass
def clear(self):
"""Wipe the screen"""
pass
def finish(self):
"""Move the cursor to the end of the display and otherwise get
ready for end. XXX could be merged with restore? Hmm."""
pass
def flushoutput(self):
"""Flush all output to the screen (assuming there's some
buffering going on somewhere)."""
pass
def forgetinput(self):
"""Forget all pending, but not yet processed input."""
pass
def getpending(self):
"""Return the characters that have been typed but not yet
processed."""
pass
def wait(self):
"""Wait for an event."""
pass
|
with open('./8/input_a.txt', 'r') as f:
input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f]
num = sum([sum([1 if len(a) in {2,3,4,7} else 0 for a in o[1]]) for o in input ])
print(f'Part A: Number of 1,4,7 or 8s in output - {num}')
def getoutput(i):
nums = ['0','1','2','3','4','5','6','7','8','9']
nums[1] = [a for a in i[0] if len(a) == 2][0]
nums[4] = [a for a in i[0] if len(a) == 4][0]
nums[7] = [a for a in i[0] if len(a) == 3][0]
nums[8] = [a for a in i[0] if len(a) == 7][0]
nums[9] = [a for a in i[0] if len(a) == 6 and set(nums[4]).issubset(set(a))][0]
nums[0] = [a for a in i[0] if len(a) == 6 and set(nums[1]).issubset(set(a)) and a not in nums][0]
nums[6] = [a for a in i[0] if len(a) == 6 and a not in nums][0]
nums[3] = [a for a in i[0] if len(a) == 5 and set(nums[1]).issubset(set(a))][0]
nums[5] = [a for a in i[0] if len(a) == 5 and (set(nums[4]) - set(nums[1])).issubset(set(a)) and a not in nums][0]
nums[2] = [a for a in i[0] if len(a) == 5 and a not in nums][0]
return int(''.join([str(nums.index([n for n in nums if set(n) == set(a)][0])) for a in i[1]]))
print(f'Part B: total output sum value - {sum([getoutput(a) for a in input])}')
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def sumLinkedListNodes(list1, list2):
value1, value2 = "", ""
head1, head2 = list1, list2
while head1:
value1 += str(head1.data)
head1 = head1.next
while head2:
value2 += str(head2.data)
head2 = head2.next
total = str(int(value1) + int(value2))
totalList = list(total)
list3 = {"head": Node(int(totalList[0]))}
current = list3["head"]
for i in range(1, len(totalList)):
current.next = Node(int(totalList[i]))
current = current.next
return list3
list1 = Node(5)
list1.next = Node(6)
list1.next.next = Node(3)
list2 = Node(8)
list2.next = Node(4)
list2.next.next = Node(2)
sumLinkedListNodes(list1, list2)
|
class Stack:
def __init__(self):
self.array = []
self.top = -1
self.max = 100
def isEmpty(self):
if(self.top == -1):
return True
else:
return False
def isFull(self):
if(self.top == self.max -1):
return True
else:
return False
def push(self, data):
if(self.isFull()):
print("Stack Overflow")
return
else:
self.top += 1
self.array.append(data)
def pop(self):
if(self.isEmpty()):
print("Stack Underflow")
return
else:
self.top -= 1
return(self.array.pop())
class SpecialStack(Stack):
def __init__(self):
super().__init__()
self.Min = Stack()
def push(self, x):
if(self.isEmpty):
super().push(x)
self.Min.push(x)
else:
super().push(x)
y = self.Min.pop()
self.Min.push(y)
if(x <= y):
self.Min.push(x)
else:
self.Min.push(y)
def pop(self):
x = super().pop()
self.Min.pop()
return x
def getMin(self):
x = self.Min.pop()
self.Min.push(x)
return x
if __name__ == "__main__":
s = SpecialStack()
s.push(10)
s.push(20)
s.push(30)
print(s.getMin())
s.push(5)
print(s.getMin())
|
#----------------------------------------------------------------------
# Basis Set Exchange
# Version v0.8.13
# https://www.basissetexchange.org
#----------------------------------------------------------------------
# Basis set: STO-3G
# Description: STO-3G Minimal Basis (3 functions/AO)
# Role: orbital
# Version: 1 (Data from Gaussian09)
#----------------------------------------------------------------------
# BASIS "ao basis" PRINT
# #BASIS SET: (3s) -> [1s]
# H S
# 0.3425250914E+01 0.1543289673E+00
# 0.6239137298E+00 0.5353281423E+00
# 0.1688554040E+00 0.4446345422E+00
# END
A_LIST = [3.425250914 , 0.6239137298, 0.1688554040]
D_LIST = [0.1543289673, 0.5353281423, 0.4446345422]
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "001887f2",
"metadata": {},
"outputs": [],
"source": [
"# import os modules to create path across operating system to load csv file\n",
"import os\n",
"# module for reading csv files\n",
"import csv"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "77c0f7d8",
"metadata": {},
"outputs": [],
"source": [
"# read csv data and load to budgetDB\n",
"csvpath = os.path.join(\"Resources\",\"budget_data.csv\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b2da0e1e",
"metadata": {},
"outputs": [],
"source": [
"# creat a txt file to hold the analysis\n",
"outputfile = os.path.join(\"Analysis\",\"budget_analysis.txt\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f3c0fd89",
"metadata": {},
"outputs": [],
"source": [
"# set var and initialize to zero\n",
"totalMonths = 0 \n",
"totalBudget = 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f807576",
"metadata": {},
"outputs": [],
"source": [
"# set list to store all of the monthly changes\n",
"monthChange = [] \n",
"months = []"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad264653",
"metadata": {},
"outputs": [],
"source": [
"# use csvreader object to import the csv library with csvreader object\n",
"with open(csvpath, newline = \"\") as csvfile:\n",
"# # create a csv reader object\n",
" csvreader = csv.reader(csvfile, delimiter=\",\")\n",
" \n",
" # skip the first row since it has all of the column information\n",
" #next(csvreader)\n",
" \n",
"#header: date, profit/losses\n",
"print(csvreader)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "27fc81c1",
"metadata": {},
"outputs": [],
"source": [
"for p in csvreader:\n",
" print(\"date: \" + p[0])\n",
" print(\"profit: \" + p[1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "83749f03",
"metadata": {},
"outputs": [],
"source": [
"# read the header row\n",
"header = next(csvreader)\n",
"print(f\"csv header:{header}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3b441a20",
"metadata": {},
"outputs": [],
"source": [
"# move to the next row (first row)\n",
"firstRow = next(csvreader)\n",
"totalMonths = (len(f\"[csvfile.index(months)][csvfile]\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a815e200",
"metadata": {},
"outputs": [],
"source": [
"output = (\n",
" f\"Financial Anaylsis \\n\"\n",
" f\"------------------------- \\n\"\n",
" f\"Total Months: {totalMonths} \\n\")\n",
"print(output)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6bf35c14",
"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.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|
class Solution:
"""
@param A : an integer array
@return : a integer
"""
def singleNumber(self, A):
# write your code here
return reduce(lambda x, y: x ^ y, A) if A != [] else 0
|
# Copyright 2018 Luddite Labs Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Block Quotes
------------
Line blocks are groups of lines beginning with vertical bar ("|") prefixes.
Each vertical bar prefix indicates a new line, so line breaks are preserved.
Initial indents are also significant, resulting in a nested structure.
Inline markup is supported. Continuation lines are wrapped portions
of long lines; they begin with a space in place of the vertical bar.
The left edge of a continuation line must be indented, but need not be aligned
with the left edge of the text above it. A line block ends with a blank line.
Syntax diagram:
+------------------------------+
| (current level of |
| indentation) |
+------------------------------+
+---------------------------+
| block quote |
| (body elements)+ |
| |
| -- attribution text |
| (optional) |
+---------------------------+
http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#block-quotes
"""
class BlockQuoteMixin:
def visit_block_quote(self, node):
self.open_block(indent=self.options['indent'], top_margin=1,
bottom_margin=1)
def depart_block_quote(self, node):
self.close_block()
def visit_attribution(self, node):
self.block.add_text(u'-- ')
def depart_attribution(self, node):
pass
|
# https://www.beecrowd.com.br/judge/en/problems/view/1017
car_efficiency = 12 # Km/L
time = int(input())
average_speed = int(input())
liters = (time * average_speed) / car_efficiency
print(f"{liters:.3f}")
|
"""
Copyright (c) College of Mechatronics and Control Engineering, Shenzhen University.
All rights reserved.
Description :
Author:Team Li
"""
"""
13. Roman to Integer
Easy
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
"""
def romanToInt(s):
"""
:type s: str
:rtype: int
"""
c2num_normal = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
c2num_sp = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
def sub_roman2int(s_index, num):
if s_index == len(s):
return num
for sp in list(c2num_sp.keys()):
if s.startswith(sp, s_index):
num += c2num_sp[sp]
return sub_roman2int(s_index + 2, num)
num += c2num_normal[s[s_index]]
return sub_roman2int(s_index + 1, num)
return sub_roman2int(0, 0)
|
preference_list_of_user=[]
def give(def_list):
Def=def_list
global preference_list_of_user
preference_list_of_user=Def
return Def
def give_to_model():
return preference_list_of_user
|
UNIVERSAL_POS_TAGS = {
'VERB': 'verbo',
'NOUN': 'nombre',
'PRON': 'pronombre',
'ADJ' : 'adjetivo',
'ADV' : 'adverbio',
'ADP' : 'aposición',
'CONJ': 'conjunción',
'DET' : 'determinante',
'NUM' : 'numeral',
'PRT' : 'partícula gramatical',
'X' : 'desconocido',
'.' : 'signo de puntuación',
}
BABEL = {
'v': 'verbo',
'n': 'nombre',
'a': 'adjetivo',
'r': 'adverbio',
}
|
def is_leap(year):
leap = False
# Write your logic here
# The year can be evenly divided by 4, is a leap year, unless:
# The year can be evenly divided by 100, it is NOT a leap year, unless:
# The year is also evenly divisible by 400. Then it is a leap year.
leap = (year % 4 == 0 and (year % 400 == 0 or year % 100 != 0))
return leap
year = int(input())
print(is_leap(year))
|
# Set random number generator
np.random.seed(2020)
# Initialize step_end, n, t_range, v and i
step_end = int(t_max / dt)
n = 50
t_range = np.linspace(0, t_max, num=step_end)
v_n = el * np.ones([n, step_end])
i = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random([n, step_end]) - 1))
# Loop for step_end - 1 steps
for step in range(1, step_end):
# Compute v_n
v_n[:, step] = v_n[:, step - 1] + (dt / tau) * (el - v_n[:, step - 1] + r * i[:, step])
# Plot figure
with plt.xkcd():
plt.figure()
plt.title('Multiple realizations of $V_m$')
plt.xlabel('time (s)')
plt.ylabel('$V_m$ (V)')
plt.plot(t_range, v_n.T, 'k', alpha=0.3)
plt.show()
|
# ------------------------------
# 78. Subsets
#
# Description:
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
#
# For example,
# If nums = [1,2,3], a solution is:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
# Version: 1.0
# 01/20/18 by Jianfa
# ------------------------------
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
result = []
for i in range(len(nums) + 1):
result += self.combine(nums, i)
return result
def combine(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[List[int]]
"""
res = []
currlist = []
self.backtrack(nums, k, currlist, 0, res)
return res
def backtrack(self, nums, k, currlist, start, res):
if len(currlist) == k:
temp = [x for x in currlist]
res.append(temp)
elif len(nums) - start + len(currlist) < k:
return
else:
for i in range(start, len(nums)):
currlist.append(nums[i])
self.backtrack(nums, k, currlist, i+1, res)
currlist.pop()
# Used for testing
if __name__ == "__main__":
test = Solution()
nums = [1,3,5]
test.subsets(nums)
# ------------------------------
# Summary:
# Borrow the combine idea from 77.py. The major difference is here a number list is provided.
# The number list may include discontinuous integers. So the parameter "start" here means index
# rather than number itself.
|
class CompressedFastq( CompressedArchive ):
"""
Class describing an compressed fastq file
This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py.
"""
file_ext = "fq.gz"
def set_peek( self, dataset, is_multi_byte=False ):
if not dataset.dataset.purged:
dataset.peek = "Compressed fastq file"
dataset.blurb = nice_size( dataset.get_size() )
else:
dataset.peek = 'file does not exist'
dataset.blurb = 'file purged from disk'
def display_peek( self, dataset ):
try:
return dataset.peek
except:
return "Compressed fastq file (%s)" % ( nice_size( dataset.get_size() ) )
Binary.register_unsniffable_binary_ext("fq.gz")
|
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module containing the InsertableString class."""
class InsertableString(object):
"""Class that accumulates insert and replace operations for a string and
later performs them all at once so that positions in the original string
can be used in all of the operations.
"""
def __init__(self, input_string):
self.input_string = input_string
self.to_insert = []
def insert_at(self, pos, s):
"""Add an insert operation at given position."""
self.to_insert.append((pos, pos, s))
def replace_range(self, start, end, s):
"""Add a replace operation for given range. Assume that all
replace_range operations are disjoint, otherwise undefined behavior.
"""
self.to_insert.append((start, end, s))
def apply_insertions(self):
"""Return a string obtained by performing all accumulated operations."""
to_insert = reversed(sorted(self.to_insert))
result = self.input_string
for start, end, s in to_insert:
result = result[:start] + s + result[end:]
return result
|
class PaginatorOptions:
def __init__(
self,
page_number: int,
page_size: int,
sort_column: str = None,
sort_descending: bool = None
):
self.sort_column = sort_column
self.sort_descending = sort_descending
self.page_number = page_number
self.page_size = page_size
assert (page_number is not None and page_size) \
or (page_number is not None and not page_size), \
'Specify both page_number and page_size'
if not sort_column:
self.sort_column = 'id'
self.sort_descending = True
__all__ = ['PaginatorOptions']
|
property_setter = {
"dt": "Property Setter",
"filters": [
["name", "in", [
'Purchase Order-read_only_onload',
'Purchase Order-default_print_format',
'Purchase Invoice-naming_series-options',
'Purchase Invoice-naming_series-default',
'Delivery Note-naming_series-options',
'Delivery Note-naming_series-default',
'Sales Order-naming_series-options',
'Sales Order-naming_series-default',
'Purchase Receipt-naming_series-options',
'Purchase Receipt-naming_series-default',
'Production Order-naming_series-options',
'Production Order-naming_series-default',
'Stock Entry-naming_series-options',
'Stock Entry-naming_series-default',
'Purchase Order-naming_series-options',
'Purchase Order-naming_series-default',
'Sales Invoice-naming_series-options',
'Sales Invoice-naming_series-default',
'Purchase Invoice-read_only_onload',
'Stock Reconciliation-read_only_onload',
'Delivery Note-read_only_onload',
'Stock Entry-read_only_onload',
'Sales Invoice-po_no-read_only',
'Sales Invoice-read_only_onload',
'Purchase Receipt Item-read_only_onload',
'Custom Field-fieldname-width',
'Custom Field-dt-width',
'Sales Invoice Item-read_only_onload',
'Sales Invoice Item-warehouse-default',
'Sales Order-po_no-read_only',
'Sales Order-read_only_onload',
'Item-read_only_onload',
'User-read_only_onload',
'User-sort_field',
'Asset Maintenance Task-periodicity-options',
'Asset Maintenance Task-read_only_onload',
'Asset-read_only_onload',
'Sales Invoice Item-customer_item_code-print_hide',
'Sales Invoice Item-customer_item_code-hidden',
'Sales Order Item-read_only_onload',
'BOM-with_operations-default',
'BOM-read_only_onload',
'Stock Entry-default_print_format',
'Purchase Receipt-read_only_onload',
'Production Order-skip_transfer-default',
'Production Order-skip_transfer-read_only',
'Production Order-use_multi_level_bom-default',
'Production Order-use_multi_level_bom-read_only',
'Production Order-read_only_onload',
'Purchase Order Item-amount-precision',
'Purchase Order Item-read_only_onload',
'Purchase Order Item-rate-precision',
'Stock Entry-use_multi_level_bom-default',
'Stock Entry-use_multi_level_bom-read_only',
'Stock Entry-from_bom-read_only',
'Stock Entry-from_bom-default',
'Stock Entry Detail-barcode-read_only',
'Stock Entry Detail-read_only_onload',
'Stock Entry-to_warehouse-read_only',
'Stock Entry-from_warehouse-read_only',
'Stock Entry-remarks-reqd',
'Purchase Receipt-in_words-print_hide',
'Purchase Receipt-in_words-hidden',
'Purchase Invoice-in_words-print_hide',
'Purchase Invoice-in_words-hidden',
'Purchase Order-in_words-print_hide',
'Purchase Order-in_words-hidden',
'Supplier Quotation-in_words-print_hide',
'Supplier Quotation-in_words-hidden',
'Delivery Note-in_words-print_hide',
'Delivery Note-in_words-hidden',
'Sales Invoice-in_words-print_hide',
'Sales Invoice-in_words-hidden',
'Sales Order-in_words-print_hide',
'Sales Order-in_words-hidden',
'Quotation-in_words-print_hide',
'Quotation-in_words-hidden',
'Purchase Order-rounded_total-print_hide',
'Purchase Order-rounded_total-hidden',
'Purchase Order-base_rounded_total-print_hide',
'Purchase Order-base_rounded_total-hidden',
'Supplier Quotation-rounded_total-print_hide',
'Supplier Quotation-rounded_total-hidden',
'Supplier Quotation-base_rounded_total-print_hide',
'Supplier Quotation-base_rounded_total-hidden',
'Delivery Note-rounded_total-print_hide',
'Delivery Note-rounded_total-hidden',
'Delivery Note-base_rounded_total-print_hide',
'Delivery Note-base_rounded_total-hidden',
'Sales Invoice-rounded_total-print_hide',
'Sales Invoice-rounded_total-hidden',
'Sales Invoice-base_rounded_total-print_hide',
'Sales Invoice-base_rounded_total-hidden',
'Sales Order-rounded_total-print_hide',
'Sales Order-rounded_total-hidden',
'Sales Order-base_rounded_total-print_hide',
'Sales Order-base_rounded_total-hidden',
'Quotation-rounded_total-print_hide',
'Quotation-rounded_total-hidden',
'Quotation-base_rounded_total-print_hide',
'Quotation-base_rounded_total-hidden',
'Dropbox Settings-dropbox_setup_via_site_config-hidden',
'Dropbox Settings-read_only_onload',
'Dropbox Settings-dropbox_access_token-hidden',
'Activity Log-subject-width',
'Employee-employee_number-hidden',
'Employee-employee_number-reqd',
'Employee-naming_series-reqd',
'Employee-naming_series-hidden',
'Supplier-naming_series-hidden',
'Supplier-naming_series-reqd',
'Delivery Note-tax_id-print_hide',
'Delivery Note-tax_id-hidden',
'Sales Invoice-tax_id-print_hide',
'Sales Invoice-tax_id-hidden',
'Sales Order-tax_id-print_hide',
'Sales Order-tax_id-hidden',
'Customer-naming_series-hidden',
'Customer-naming_series-reqd',
'Stock Entry Detail-barcode-hidden',
'Stock Reconciliation Item-barcode-hidden',
'Item-barcode-hidden',
'Delivery Note Item-barcode-hidden',
'Sales Invoice Item-barcode-hidden',
'Purchase Receipt Item-barcode-hidden',
'Item-item_code-reqd',
'Item-item_code-hidden',
'Item-naming_series-hidden',
'Item-naming_series-reqd',
'Item-manufacturing-collapsible_depends_on',
'Purchase Invoice-payment_schedule-print_hide',
'Purchase Invoice-due_date-print_hide',
'Purchase Order-payment_schedule-print_hide',
'Purchase Order-due_date-print_hide',
'Sales Invoice-payment_schedule-print_hide',
'Sales Invoice-due_date-print_hide',
'Sales Order-payment_schedule-print_hide',
'Sales Order-due_date-print_hide',
'Journal Entry Account-sort_order',
'Journal Entry Account-account_currency-print_hide',
'Sales Invoice-taxes_and_charges-reqd',
'Sales Taxes and Charges-sort_order',
'Sales Invoice Item-customer_item_code-label',
'Sales Invoice-default_print_format',
'Purchase Taxes and Charges Template-sort_order',
'Serial No-company-in_standard_filter',
'Serial No-amc_expiry_date-in_standard_filter',
'Serial No-warranty_expiry_date-in_standard_filter',
'Serial No-maintenance_status-in_standard_filter',
'Serial No-customer_name-in_standard_filter',
'Serial No-customer_name-bold',
'Serial No-customer-in_standard_filter',
'Serial No-delivery_document_no-in_standard_filter',
'Serial No-delivery_document_type-in_standard_filter',
'Serial No-supplier_name-bold',
'Serial No-supplier_name-in_standard_filter',
'Serial No-supplier-in_standard_filter',
'Serial No-purchase_date-in_standard_filter',
'Serial No-description-in_standard_filter',
'Delivery Note-section_break1-hidden',
'Delivery Note-sales_team_section_break-hidden',
'Delivery Note-project-hidden',
'Delivery Note-taxes-hidden',
'Delivery Note-taxes_and_charges-hidden',
'Delivery Note-taxes_section-hidden',
'Delivery Note-posting_time-print_hide',
'Delivery Note-posting_time-description',
'Delivery Note Item-warehouse-default',
'Item-income_account-default',
'Item-income_account-depends_on',
'Purchase Receipt-remarks-reqd',
'Purchase Receipt-taxes-hidden',
'Purchase Receipt-taxes_and_charges-hidden',
'Purchase Receipt Item-base_rate-fieldtype',
'Purchase Receipt Item-amount-in_list_view',
'Purchase Receipt Item-rate-fieldtype',
'Purchase Receipt Item-base_price_list_rate-fieldtype',
'Purchase Receipt Item-price_list_rate-fieldtype',
'Purchase Receipt Item-qty-in_list_view',
'Stock Entry-title_field',
'Stock Entry-search_fields',
'Stock Entry-project-hidden',
'Stock Entry-supplier-in_list_view',
'Stock Entry-from_warehouse-in_list_view',
'Stock Entry-to_warehouse-in_list_view',
'Stock Entry-purpose-default',
'ToDo-sort_order',
'Currency Exchange-sort_order',
'Company-abbr-in_list_view',
'Stock Reconciliation-expense_account-in_standard_filter',
'Stock Reconciliation-expense_account-depends_on',
'Sales Order-taxes-hidden',
'Warehouse-sort_order',
'Address-fax-hidden',
'Address-fax-read_only',
'Address-phone-hidden',
'Address-email_id-hidden',
'Address-city-reqd',
'BOM Operation-sort_order',
'BOM Item-scrap-read_only',
'BOM-operations_section-read_only',
'BOM-operations-read_only',
'BOM-rm_cost_as_per-reqd',
'Journal Entry-pay_to_recd_from-allow_on_submit',
'Journal Entry-remark-in_global_search',
'Journal Entry-total_amount-bold',
'Journal Entry-total_amount-print_hide',
'Journal Entry-total_amount-in_list_view',
'Journal Entry-total_credit-print_hide',
'Journal Entry-total_debit-print_hide',
'Journal Entry-total_debit-in_list_view',
'Journal Entry-user_remark-print_hide',
'Stock Entry-to_warehouse-hidden',
'Purchase Order Item-rate-fieldtype',
'Journal Entry Account-exchange_rate-print_hide',
'Sales Invoice Item-item_code-label',
'BOM-rm_cost_as_per-options',
'Purchase Order Item-price_list_rate-fieldtype',
'Reconciliation-expense_account-read_only',
'Customer-tax_id-read_only',
'Purchase Order Item-amount-fieldtype',
'Stock Entry-project-hidden'
]
]
]
}
|
# -*- encoding: utf-8 -*-
"""
@File : metadata.py
@Time : 2020/1/1
@Author : flack
@Email : [email protected]
@ide : PyCharm
@project : faketranslate
@description : 描述
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.