blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8b1321f9162b7074137a5c527555ccaad201f2b | 7203877828aebb80f5a5809451d10da39c307e6a | /test/distributed/algorithms/test_join.py | 6ed8345f365e3a8d85d8e749d8533f392874ee7e | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
]
| permissive | minitu/pytorch | 37361e9041437ce29682821b70fbf4136e715baf | 5ed6e4429e2a75cb3d0d573e007bc3417939e9bd | refs/heads/master | 2021-08-12T02:18:24.317899 | 2021-08-10T00:53:11 | 2021-08-10T00:54:43 | 170,204,590 | 0 | 0 | NOASSERTION | 2019-02-11T21:23:41 | 2019-02-11T21:23:41 | null | UTF-8 | Python | false | false | 16,873 | py | import contextlib
import os
import sys
from typing import Any, Optional
import torch
import torch.distributed as dist
if not dist.is_available():
print("Distributed not available, skipping tests", file=sys.stderr)
sys.exit(0)
from torch.distributed.algorithms.join import Join, Joinable, JoinHook
from torch.testing._internal.common_distributed import (
MultiProcessTestCase,
require_n_gpus_for_nccl_backend,
)
from torch.testing._internal.common_utils import TEST_WITH_ASAN, run_tests
BACKEND = dist.Backend.NCCL if torch.cuda.is_available() else dist.Backend.GLOO
WORLD_SIZE = min(4, max(2, torch.cuda.device_count()))
# Constants used for testing post-hooks
BEFORE_CONSTANT = 41
AFTER_CONSTANT = 42
class AllReducerJoinHook(JoinHook):
r"""
Join hook for :class:`AllReducer`.
Arguments:
allreducer (AllReducer): the :class:`AllReducer` object using this
hook.
num_allreduces (int): the number of all-reduces to shadow per
iteration.
run_post_hook (bool): a flag enabling the post-hook logic.
"""
def __init__(
self,
allreducer,
num_allreduces,
run_post_hook
):
self.allreducer = allreducer
self.num_allreduces = num_allreduces
self.run_post_hook = run_post_hook
def main_hook(self):
r"""
Shadows each all-reduce; the number of all-reduces is passed into the
constructor as ``num_allreduces``.
"""
device = self.allreducer.device
for _ in range(self.num_allreduces):
t = torch.zeros(1, device=device)
dist.all_reduce(t)
def post_hook(self, is_last_joiner: bool):
r"""
Broadcasts a tensor containing a magic constant ``AFTER_CONSTANT`` from
the last joiner to all other processes.
"""
if not self.run_post_hook:
return
rank = dist.get_rank(self.allreducer.process_group)
common_rank = self.allreducer.find_common_rank(rank, is_last_joiner)
device = self.allreducer.device
if rank == common_rank:
self.allreducer.post_hook_tensor = torch.tensor([AFTER_CONSTANT], device=device)
dist.broadcast(self.allreducer.post_hook_tensor, src=common_rank)
class AllReducer(Joinable):
r"""
Example :class:`Joinable` that performs some number of all-reduces as its
per-iteration collective communication.
"""
def __init__(self, device, process_group):
super(AllReducer, self).__init__()
self.device = device
self.process_group = process_group
self.post_hook_tensor = torch.tensor([BEFORE_CONSTANT], device=self.device)
def __call__(self, num_allreduces=1):
r"""
All-reduces a dim-1 one tensor ``num_allreduces``-many times, and
returns the total result.
"""
Join.notify_join_context(self)
device = self.device
total = 0
for _ in range(num_allreduces):
t = torch.ones(1, device=device)
dist.all_reduce(t)
total += t.item()
return total
def join_hook(self, **kwargs) -> JoinHook:
r"""
Returns a join hook that shadows some number of all-reduces; by default,
this number is 1.
"""
num_allreduces = kwargs.get("num_allreduces", 1)
run_post_hook = kwargs.get("run_post_hooks", False)
return AllReducerJoinHook(
self,
num_allreduces,
run_post_hook
)
@property
def join_device(self) -> torch.device:
return self.device
@property
def join_process_group(self) -> Any:
return self.process_group
def find_common_rank(self, rank, to_consider):
r"""
Returns the max rank of the ones to consider over the process group.
"""
common_rank = torch.tensor(
[rank if to_consider else -1],
device=self.device
)
dist.all_reduce(common_rank, op=dist.ReduceOp.MAX, group=self.process_group)
common_rank = common_rank.item()
assert common_rank >= 0
return common_rank
class TestJoin(MultiProcessTestCase):
r"""Test cases for the generic join context."""
def setUp(self):
super(TestJoin, self).setUp()
os.environ["WORLD_SIZE"] = str(self.world_size)
os.environ["BACKEND"] = BACKEND
# torch and spawn have known issues with ASAN, so use fork instead
if TEST_WITH_ASAN:
self._fork_processes()
else:
self._spawn_processes()
@property
def device(self):
return torch.device(self.rank) if BACKEND == dist.Backend.NCCL \
else torch.device("cpu")
@property
def world_size(self):
return WORLD_SIZE
@property
def process_group(self):
return dist.group.WORLD
def tearDown(self):
try:
dist.destroy_process_group()
except AssertionError:
pass
try:
os.remove(self.file_name)
except OSError:
pass
def dist_init(self, rank, world_size, backend=BACKEND):
store = dist.FileStore(self.file_name, world_size)
return dist.init_process_group(
backend=backend,
store=store,
rank=rank,
world_size=world_size
)
def construct_uneven_inputs(self, base, offset, device=None):
r"""
Returns uneven inputs: rank i gets ``base`` + i * ``offset`` inputs.
"""
if device is None:
device = self.device
return [torch.zeros(1, device=device) for _ in range(base + self.rank * offset)]
def construct_even_inputs(self, base, device=None):
r"""Returns even inputs: each rank gets ``base`` inputs."""
if device is None:
device = self.device
return [torch.zeros(1, device=device) for _ in range(base)]
@property
def base_num_inputs(self):
r"""Base number of inputs to be used by all ranks."""
return 3
@property
def offset(self):
r"""Rank i gets i * ``offset`` additional inputs."""
return 1
def _test_join_base(
self,
uneven_inputs: bool,
num_joinables: int,
enable: bool,
throw_on_early_termination: bool,
num_allreduces: int,
run_post_hooks: bool,
expected_total: Optional[int] = None,
):
r"""
Skeleton for all :class:`Join` tests.
Arguments:
uneven_inputs (bool): ``True`` to use uneven inputs; ``False``
otherwise.
num_joinables (int): number of :class:`AllReducer` s to construct.
enable (bool): ``True`` to enable the join context manager;
``False`` otherwise.
throw_on_early_termination (bool): ``True`` to raise an exception
upon detecting uneven inputs; ``False`` otherwise.
num_allreduces (int): number of all-reduces to perform per input.
run_post_hooks (bool): ``True`` to run post-hooks; ``False``
otherwise.
expected_total (Optional[int]): ``None`` to not check the expected
all-reduce total; otherwise, the expected total; default is
``None``.
"""
self.dist_init(self.rank, self.world_size)
allreducers = [
AllReducer(self.device, self.process_group)
for _ in range(num_joinables)
]
for allreducer in allreducers:
self.assertEqual(allreducer.post_hook_tensor.item(), BEFORE_CONSTANT)
inputs = self.construct_uneven_inputs(self.base_num_inputs, self.offset) \
if uneven_inputs \
else self.construct_even_inputs(self.base_num_inputs)
allreduce_total = 0
# Expect a `RuntimeError` if `throw_on_early_termination=True`
# Rank 0 exhausts its inputs first
expected_msg = "Rank 0 exhausted all inputs." if self.rank == 0 \
else "Detected at least one rank that exhausted inputs. " \
"Throwing across all ranks."
with self.assertRaisesRegex(
RuntimeError,
expected_msg
) if throw_on_early_termination else contextlib.suppress():
with Join(
allreducers,
enable=enable,
throw_on_early_termination=throw_on_early_termination,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks
):
for _ in inputs:
for allreducer in allreducers:
allreduce_total += allreducer(num_allreduces)
if throw_on_early_termination:
return
# Check `expected_total` if not `None`
if expected_total:
self.assertEqual(allreduce_total, expected_total)
# All `AllReduce` instances should receive the updated
# `post_hook_tensor` from the last-joined process
if run_post_hooks:
for allreducer in allreducers:
self.assertEqual(allreducer.post_hook_tensor.item(), AFTER_CONSTANT)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_single_joinable_main_hooks(self):
r"""Tests the main hooks of a single :class:`Joinable`."""
num_joinables = 1
num_allreduces = 1
run_post_hooks = False
# Non-joined processes all-reduce a 1, so this rank's all-reduce total
# should be precisely equal to the total number of inputs processed
# before it joined
expected_total = self.world_size * self.base_num_inputs
# Rank i runs for i additional iterations
for num_joined in range(1, self.rank + 1):
expected_total += (self.world_size - num_joined) * self.offset
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_single_joinable_post_hooks(self):
r"""Tests the post-hooks of a single :class:`Joinable`."""
num_joinables = 1
num_allreduces = 0 # set to 0 to skip the main hooks
run_post_hooks = False
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=None
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_single_joinable(self):
r"""
Tests the main hooks and post-hooks of a single :class:`Joinable`
together.
This combines ``test_single_joinable_main_hooks()`` and
``test_single_joinable_post_hooks()`` into a single test to ensure that
main hooks and post-hooks operate correctly together.
"""
num_joinables = 1
num_allreduces = 1
run_post_hooks = True
expected_total = self.world_size * self.base_num_inputs
for num_joined in range(1, self.rank + 1):
expected_total += (self.world_size - num_joined) * self.offset
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_multiple_joinables(self):
r"""
Tests the main hooks and post-hooks of multiple :class:`Joinable` s
together.
This generalizes ``test_single_joinable()`` to multiple
:class:`Joinable` s.
"""
num_joinables = 3
num_allreduces = 1
run_post_hooks = True
expected_total = self.world_size * self.base_num_inputs
for num_joined in range(1, self.rank + 1):
expected_total += (self.world_size - num_joined) * self.offset
# The expected total is now multiplied by a factor of `NUM_JOINABLES`
expected_total *= num_joinables
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_single_joinable_disable(self):
r"""Tests ``enable=False`` for a single :class:`Joinable`."""
num_joinables = 1
num_allreduces = 1
uneven_inputs = False
enable = False
run_post_hooks = False
expected_total = self.world_size * self.base_num_inputs
self._test_join_base(
uneven_inputs=uneven_inputs,
num_joinables=num_joinables,
enable=enable,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_multiple_joinable_disable(self):
r"""
Tests ``enable=False`` for multiple :class:`Joinable` s.
This generalizes ``test_single_joinable_disable`` to multiple
:class:`Joinable` s.
"""
num_joinables = 3
num_allreduces = 1
uneven_inputs = False
enable = False
run_post_hooks = False
expected_total = self.world_size * self.base_num_inputs * num_joinables
self._test_join_base(
uneven_inputs=uneven_inputs,
num_joinables=num_joinables,
enable=enable,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_single_joinable_throw(self):
r"""
Tests ``throw_on_early_termination=True`` for a single
:class:`Joinable`.
"""
num_joinables = 1
num_allreduces = 1
throw_on_early_termination = True
run_post_hooks = False
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=throw_on_early_termination,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=None
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_multiple_joinables_throw(self):
r"""
Tests ``throw_on_early_termination=True`` for multiple
:class:`Joinable` s together.
This generalizes ``test_single_joinable_throw`` to multiple
:class:`Joinable` s.
"""
num_joinables = 3
num_allreduces = 1
throw_on_early_termination = True
run_post_hooks = False
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=throw_on_early_termination,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=None
)
@require_n_gpus_for_nccl_backend(
WORLD_SIZE, BACKEND
)
def test_join_kwargs(self):
r"""
Tests passing keyword arguments to the context manager.
"""
num_joinables = 1
num_allreduces = 2
run_post_hooks = False
expected_total = self.world_size * self.base_num_inputs
for num_joined in range(1, self.rank + 1):
expected_total += (self.world_size - num_joined) * self.offset
# The expected total is now multiplied by a factor of `NUM_ALLREDUCES`
expected_total *= num_allreduces
self._test_join_base(
uneven_inputs=True,
num_joinables=num_joinables,
enable=True,
throw_on_early_termination=False,
num_allreduces=num_allreduces,
run_post_hooks=run_post_hooks,
expected_total=expected_total
)
if __name__ == "__main__":
run_tests()
| [
"[email protected]"
]
| |
610d5cdc267e4a54433d81daedad04c0f8fa26c0 | c5fb49af6c4de5e5dde2981224dce8d39243d8c1 | /Pdf_Merging/apps.py | 8c0ad80f9835068107c554c70593b1e30fda2ff1 | []
| no_license | Ashish2831/TEXT-UTILS | 1631d5dcaea4ff11eb7b5fa323ff2ad13c8a57f1 | 6a905731269988001364648e46590a7a04496c8b | refs/heads/main | 2023-08-16T16:11:31.436503 | 2021-09-14T10:22:49 | 2021-09-14T10:22:49 | 374,950,398 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | from django.apps import AppConfig
class PdfMergingConfig(AppConfig):
name = 'Pdf_Merging'
| [
"[email protected]"
]
| |
7ca4eecfe2397f0d485aeda40315a32a0818623e | 8a9dbfd7c2213652265269838ca9c15aad66a66f | /class-20161005/report/정동휘_식품생명공학과/grade_calculator.py | 9b0a53ccdbdcbbbbfb0588a42552fc3dd5fb7f8c | []
| no_license | askdjango/snu-web-2016-09 | 48ba3b0301be1e0f05f1e630dcfecac51827e779 | eaf703cc3ff7ddf3795a636ad1631624a87a9b70 | refs/heads/master | 2020-02-26T14:23:00.495594 | 2016-12-19T11:51:45 | 2016-12-19T11:51:45 | 68,677,254 | 6 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,370 | py | result = {}
for i in range(1, 4):
name = input('{} 번째 학생 이름은? '.format(i))
ko_score = int(input('{}님의 국어 시험 점수는? '.format(name)))
en_score = int(input('{}님의 영어 시험 점수는? '.format(name)))
math_score = int(input('{}님의 수학 시험 점수는? '.format(name)))
result[name] = {
'ko_score': ko_score,
'en_score': en_score,
'math_score': math_score,
}
print('개별 평균점수')
for name in result:
total = result[name]['ko_score'] + result[name]['en_score'] + result[name]['math_score']
average = total / 3
print('[{}] 국어: {}, 영어: {}, 수학: {}, 평균: {}'.format(
name, result[name]['ko_score'], result[name]['en_score'],
result[name]['math_score'], average,
))
print('전체 국어 평균점수는?')
ko_total = 0
for name in result:
ko_total += result[name]['ko_score']
ko_average = ko_total / len(result)
print(ko_average)
print('전체 영어 평균점수는?')
en_total = 0
for name in result:
en_total += result[name]['en_score']
en_average = en_total / len(result)
print(en_average)
print('전체 수학 평균점수는?')
math_total = 0
for name in result:
math_total += result[name]['math_score']
math_average = math_total / len(result)
print(math_average) | [
"[email protected]"
]
| |
a718fb9f186e8c294058abca07778ec93045f6d0 | af9268e1ead8cdb491868c14a2240d9e44fb3b56 | /last-minute-env/lib/python2.7/site-packages/django/db/migrations/utils.py | 7ce4ca8663c3ddcf8da046cd7f1629f47a953275 | []
| no_license | frosqh/Cousinade2017 | d5154c24c93ca8089eeba26b53c594e92cb6bd82 | c34d5707af02402bf2bb7405eddc91297da399ff | refs/heads/master | 2021-01-20T07:57:34.586476 | 2017-10-22T18:42:45 | 2017-10-22T18:42:45 | 90,074,802 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | import datetime
import re
COMPILED_REGEX_TYPE = type(re.compile(''))
class RegexObject(object):
def __init__(self, obj):
self.pattern = obj.pattern
self.flags = obj.flags
def __eq__(self, other):
return self.pattern == other.pattern and self.flags == other.flags
def get_migration_name_timestamp():
return datetime.datetime.now().strftime("%Y%m%d_%H%M")
| [
"[email protected]"
]
| |
267fe8149bb5d82e174ccbfe25ade2e158bcf6bc | e6dab5aa1754ff13755a1f74a28a201681ab7e1c | /.parts/lib/django-1.3/django/core/cache/backends/base.py | 074649a88f7f37492bf36becbb4864804ec40414 | []
| no_license | ronkagan/Euler_1 | 67679203a9510147320f7c6513eefd391630703e | 022633cc298475c4f3fd0c6e2bde4f4728713995 | refs/heads/master | 2021-01-06T20:45:52.901025 | 2014-09-06T22:34:16 | 2014-09-06T22:34:16 | 23,744,842 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 100 | py | /home/action/.parts/packages/googleappengine/1.9.4/lib/django-1.3/django/core/cache/backends/base.py | [
"[email protected]"
]
| |
21496f14d0eeb0b566cc136a8393c58736bbaa3a | 63272ccdc6b0e7739e79dd66a309a55fd8e987ae | /hola.py | 0aa50053a99f80c100baabd940488eae6a70afce | []
| no_license | jcromerohdz/myProject | 93324061ddd4f4ca492d2c6b2d5a206c3d7a02d8 | 964286202cae5c0443ada55e0d467c2ada406966 | refs/heads/master | 2021-01-22T20:54:10.027553 | 2013-04-23T03:36:56 | 2013-04-23T03:36:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 37 | py | __author__ = 'user'
print "Hola git"
| [
"[email protected]"
]
| |
990cf362c52b0604321d688b88a3fbe9bf48bbd7 | acb8e84e3b9c987fcab341f799f41d5a5ec4d587 | /langs/3/gM4.py | fdb0064b8a489e72ae3a97d6d7c4a39405c21402 | []
| no_license | G4te-Keep3r/HowdyHackers | 46bfad63eafe5ac515da363e1c75fa6f4b9bca32 | fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2 | refs/heads/master | 2020-08-01T12:08:10.782018 | 2016-11-13T20:45:50 | 2016-11-13T20:45:50 | 73,624,224 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import sys
def printFunction(lineRemaining):
if lineRemaining[0] == '"' and lineRemaining[-1] == '"':
if len(lineRemaining) > 2:
#data to print
lineRemaining = lineRemaining[1:-1]
print ' '.join(lineRemaining)
else:
print
def main(fileName):
with open(fileName) as f:
for line in f:
data = line.split()
if data[0] == 'gM4':
printFunction(data[1:])
else:
print 'ERROR'
return
if __name__ == '__main__':
main(sys.argv[1]) | [
"[email protected]"
]
| |
5b4643859114311f8d6323277fd4ffada3146b81 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/sieve-big-6089.py | aa9c35099e39105f7021024fcb8c84c40e2a2142 | []
| no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 31,698 | py | # A resizable list of integers
class Vector(object):
items: [int] = None
size: int = 0
def __init__(self:"Vector"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector", idx: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector") -> int:
return self.size
# A resizable list of integers
class Vector2(object):
items: [int] = None
items2: [int] = None
size: int = 0
size2: int = 0
def __init__(self:"Vector2"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector2") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector2") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector2") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector2") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector2", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector2", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector2", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector2", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector2", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector2", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector2", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector2", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector2") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector2") -> int:
return self.size
# A resizable list of integers
class Vector3(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
def __init__(self:"Vector3"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector3") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector3") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector3") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector3", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector3", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector3", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector3", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector3", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector3", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector3", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector3", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector3", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector3", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector3", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector3", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector3") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector3") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector3") -> int:
return self.size
# A resizable list of integers
class Vector4(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
items4: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
size4: int = 0
def __init__(self:"Vector4"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity4(self:"Vector4") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity4(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector4", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector4", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector4", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append4(self:"Vector4", item: int, item2: int, item3: int, item4: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector4", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector4", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all4(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector4", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector4", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector4", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector4", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector4", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector4", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length4(self:"Vector4") -> int:
return self.size
# A resizable list of integers
class Vector5(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
items4: [int] = None
items5: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
size4: int = 0
size5: int = 0
def __init__(self:"Vector5"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity4(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity5(self:"Vector5") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity4(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity5(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector5", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector5", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector5", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append4(self:"Vector5", item: int, item2: int, item3: int, item4: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append5(self:"Vector5", item: int, item2: int, item3: int, item4: int, item5: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector5", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector5", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all4(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all5(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int], new_items5: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
item5:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector5", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector5", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector5", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
$Block
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector5", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector5", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector5", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length4(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length5(self:"Vector5") -> int:
return self.size
# A faster (but more memory-consuming) implementation of vector
class DoublingVector(Vector):
doubling_limit:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector2(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector2") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector2") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector3(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector4(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
doubling_limit4:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity4(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector5(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
doubling_limit4:int = 1000
doubling_limit5:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity4(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity5(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Makes a vector in the range [i, j)
def vrange(i:int, j:int) -> Vector:
v:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange2(i:int, j:int, i2:int, j2:int) -> Vector:
v:Vector = None
v2:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange3(i:int, j:int, i2:int, j2:int, i3:int, j3:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange4(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange5(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int, i5:int, j5:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v5:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
# Sieve of Eratosthenes (not really)
def sieve(v:Vector) -> object:
i:int = 0
j:int = 0
k:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve2(v:Vector, v2:Vector) -> object:
i:int = 0
i2:int = 0
j:int = 0
j2:int = 0
k:int = 0
k2:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve3(v:Vector, v2:Vector, v3:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
j:int = 0
j2:int = 0
j3:int = 0
k:int = 0
k2:int = 0
k3:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve4(v:Vector, v2:Vector, v3:Vector, v4:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
j:int = 0
j2:int = 0
j3:int = 0
j4:int = 0
k:int = 0
k2:int = 0
k3:int = 0
k4:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve5(v:Vector, v2:Vector, v3:Vector, v4:Vector, v5:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
j:int = 0
j2:int = 0
j3:int = 0
j4:int = 0
j5:int = 0
k:int = 0
k2:int = 0
k3:int = 0
k4:int = 0
k5:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
# Input parameter
n:int = 50
n2:int = 50
n3:int = 50
n4:int = 50
n5:int = 50
# Data
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v5:Vector = None
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
# Crunch
v = vrange(2, n)
v2 = vrange(2, n)
v3 = vrange(2, n)
v4 = vrange(2, n)
v5 = vrange(2, n)
sieve(v)
# Print
while i < v.length():
print(v.get(i))
i = i + 1
| [
"[email protected]"
]
| |
f3259a87df330e939839e295315c2a730bbcd3a1 | 221cada2354556fbb969f25ddd3079542904ef5d | /Leetcode/53.py | 542846f48674eb52b129579efcd4ee597d7cdaf6 | []
| no_license | syzdemonhunter/Coding_Exercises | 4b09e1a7dad7d1e3d4d4ae27e6e006732ffdcb1d | ca71572677d2b2a2aed94bb60d6ec88cc486a7f3 | refs/heads/master | 2020-05-24T11:19:35.019543 | 2019-11-22T20:08:32 | 2019-11-22T20:08:32 | 187,245,394 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 765 | py | # https://leetcode.com/problems/maximum-subarray/
'''
# T: O(n)
# S: O(n)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0]*len(nums)
dp[0] = nums[0]
result = dp[0]
for i in range(1, len(nums)):
if dp[i - 1] < 0:
dp[i] = nums[i]
else:
dp[i] = nums[i] + dp[i - 1]
result = max(result, dp[i])
return result
'''
# T: O(n)
# S: O(1)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
result = nums[0]
max_end = nums[0]
for num in nums[1:]:
max_end = max(num, max_end + num)
result = max(result, max_end)
return result
| [
"[email protected]"
]
| |
425c558f56bc92363d78905ea0157a314eb024a5 | 07539ecbcee0488ce4a0eb779583da3149cfac7b | /amonone/mail/models.py | 0c56dda41c125c637c4a429143771a2b70ceaf09 | [
"MIT"
]
| permissive | outbounder/amonone | e151584ac38222b40c314d586ebadc4e0f43fce1 | 985fa147c1d98a4f57ff33ebd37ca0d938fe674d | refs/heads/master | 2020-12-25T13:33:46.425826 | 2013-07-11T08:54:32 | 2013-07-11T08:54:32 | 11,389,227 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 624 | py | from amonone.web.apps.core.basemodel import BaseModel
class EmailModel(BaseModel):
def __init__(self):
super(EmailModel, self).__init__()
self.collection = self.mongo.get_collection('email_settings')
def save_email_details(self, data=None):
self.collection.remove()
self.collection.insert(data)
def get_email_details(self):
return self.collection.find_one()
class EmailRecepientModel(BaseModel):
def __init__(self):
super(EmailRecepientModel, self).__init__()
self.collection = self.mongo.get_collection('email_recepients')
email_model = EmailModel()
email_recepient_model = EmailRecepientModel()
| [
"[email protected]"
]
| |
94af3fbd4e6a1462d62229b90fc50b45d0115762 | 747f759311d404af31c0f80029e88098193f6269 | /addons/point_of_sale/wizard/wizard_pos_payment.py | 1404f4ff6d2ea1fdf9c774108e011d3bb45b25d1 | []
| no_license | sgeerish/sirr_production | 9b0d0f7804a928c0c582ddb4ccb7fcc084469a18 | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | refs/heads/master | 2020-05-19T07:21:37.047958 | 2013-09-15T13:03:36 | 2013-09-15T13:03:36 | 9,648,444 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 80 | py | /home/openerp/production/extra-addons/point_of_sale/wizard/wizard_pos_payment.py | [
"[email protected]"
]
| |
1ee375c9ad6c64d94fa46b81938f9ace48c32246 | 83277e8b959de61b655f614b7e072394a99d77ae | /venv/lib/python3.7/site-packages/graphql/validation/rules/__init__.py | 056a530de90b0f265b8512ca66debc4458dbc8f6 | [
"MIT"
]
| permissive | hskang9/scalable-django | b3ed144670c3d5b244168fdd38f33e1f596253c0 | 162e0f4a3d49f164af1d33298fa9a47b66508cbf | refs/heads/master | 2023-04-29T05:33:23.460640 | 2020-03-27T00:55:28 | 2020-03-27T00:55:28 | 247,036,359 | 2 | 1 | MIT | 2023-04-21T20:53:08 | 2020-03-13T09:40:37 | Python | UTF-8 | Python | false | false | 2,910 | py | from .arguments_of_correct_type import ArgumentsOfCorrectType
from .default_values_of_correct_type import DefaultValuesOfCorrectType
from .fields_on_correct_type import FieldsOnCorrectType
from .fragments_on_composite_types import FragmentsOnCompositeTypes
from .known_argument_names import KnownArgumentNames
from .known_directives import KnownDirectives
from .known_fragment_names import KnownFragmentNames
from .known_type_names import KnownTypeNames
from .lone_anonymous_operation import LoneAnonymousOperation
from .no_fragment_cycles import NoFragmentCycles
from .no_undefined_variables import NoUndefinedVariables
from .no_unused_fragments import NoUnusedFragments
from .no_unused_variables import NoUnusedVariables
from .overlapping_fields_can_be_merged import OverlappingFieldsCanBeMerged
from .possible_fragment_spreads import PossibleFragmentSpreads
from .provided_non_null_arguments import ProvidedNonNullArguments
from .scalar_leafs import ScalarLeafs
from .unique_argument_names import UniqueArgumentNames
from .unique_fragment_names import UniqueFragmentNames
from .unique_input_field_names import UniqueInputFieldNames
from .unique_operation_names import UniqueOperationNames
from .unique_variable_names import UniqueVariableNames
from .variables_are_input_types import VariablesAreInputTypes
from .variables_in_allowed_position import VariablesInAllowedPosition
# Necessary for static type checking
if False: # flake8: noqa
from typing import List, Type
from .base import ValidationRule
specified_rules = [
UniqueOperationNames,
LoneAnonymousOperation,
KnownTypeNames,
FragmentsOnCompositeTypes,
VariablesAreInputTypes,
ScalarLeafs,
FieldsOnCorrectType,
UniqueFragmentNames,
KnownFragmentNames,
NoUnusedFragments,
PossibleFragmentSpreads,
NoFragmentCycles,
NoUndefinedVariables,
NoUnusedVariables,
KnownDirectives,
KnownArgumentNames,
UniqueArgumentNames,
ArgumentsOfCorrectType,
ProvidedNonNullArguments,
DefaultValuesOfCorrectType,
VariablesInAllowedPosition,
OverlappingFieldsCanBeMerged,
UniqueInputFieldNames,
UniqueVariableNames,
] # type: List[Type[ValidationRule]]
__all__ = [
"ArgumentsOfCorrectType",
"DefaultValuesOfCorrectType",
"FieldsOnCorrectType",
"FragmentsOnCompositeTypes",
"KnownArgumentNames",
"KnownDirectives",
"KnownFragmentNames",
"KnownTypeNames",
"LoneAnonymousOperation",
"NoFragmentCycles",
"UniqueVariableNames",
"NoUndefinedVariables",
"NoUnusedFragments",
"NoUnusedVariables",
"OverlappingFieldsCanBeMerged",
"PossibleFragmentSpreads",
"ProvidedNonNullArguments",
"ScalarLeafs",
"UniqueArgumentNames",
"UniqueFragmentNames",
"UniqueInputFieldNames",
"UniqueOperationNames",
"VariablesAreInputTypes",
"VariablesInAllowedPosition",
"specified_rules",
]
| [
"[email protected]"
]
| |
00b09bb07ee546d00b56dca37a774c559f81dda9 | 6982c3c54ee9199d93fb89c61cfdcba15b9b7012 | /exercise/git_exercises/visitors_book/visitors_book/wsgi.py | 20d31dac8eebd8eb05a5e3d496a59265370e9973 | []
| no_license | gzgdouru/python_study | a640e1097ebc27d12049ded53fb1af3ba9729bac | e24b39e82e39ee5a5e54566781457e18c90a122a | refs/heads/master | 2020-03-29T11:33:13.150869 | 2019-03-08T09:24:29 | 2019-03-08T09:24:29 | 149,858,658 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 404 | py | """
WSGI config for visitors_book project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "visitors_book.settings")
application = get_wsgi_application()
| [
"[email protected]"
]
| |
8fd124b553f30e34b2daea187d61f7717b22fa81 | 3c000380cbb7e8deb6abf9c6f3e29e8e89784830 | /venv/Lib/site-packages/cobra/modelimpl/vns/range.py | ebba918f860a70b9f9534be38894aba409af3ada | []
| no_license | bkhoward/aciDOM | 91b0406f00da7aac413a81c8db2129b4bfc5497b | f2674456ecb19cf7299ef0c5a0887560b8b315d0 | refs/heads/master | 2023-03-27T23:37:02.836904 | 2021-03-26T22:07:54 | 2021-03-26T22:07:54 | 351,855,399 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,551 | py | # coding=UTF-8
# **********************************************************************
# Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved
# written by zen warriors, do not modify!
# **********************************************************************
from cobra.mit.meta import ClassMeta
from cobra.mit.meta import StatsClassMeta
from cobra.mit.meta import CounterMeta
from cobra.mit.meta import PropMeta
from cobra.mit.meta import Category
from cobra.mit.meta import SourceRelationMeta
from cobra.mit.meta import NamedSourceRelationMeta
from cobra.mit.meta import TargetRelationMeta
from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory
from cobra.model.category import MoCategory, PropCategory, CounterCategory
from cobra.mit.mo import Mo
# ##################################################
class Range(Mo):
"""
A range assertion.
"""
meta = ClassMeta("cobra.model.vns.Range")
meta.moClassName = "vnsRange"
meta.rnFormat = "range-%(name)s"
meta.category = MoCategory.REGULAR
meta.label = "Range Assertion"
meta.writeAccessMask = 0x1
meta.readAccessMask = 0x1
meta.isDomainable = False
meta.isReadOnly = True
meta.isConfigurable = False
meta.isDeletable = False
meta.isContextRoot = False
meta.parentClasses.add("cobra.model.vns.MDev")
meta.parentClasses.add("cobra.model.vns.MParam")
meta.parentClasses.add("cobra.model.vns.MFolder")
meta.parentClasses.add("cobra.model.vns.Composite")
meta.parentClasses.add("cobra.model.vns.MFunc")
meta.superClasses.add("cobra.model.naming.NamedObject")
meta.superClasses.add("cobra.model.vns.Assertion")
meta.rnPrefixes = [
('range-', True),
]
prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("deleteAll", "deleteall", 16384)
prop._addConstant("deleteNonPresent", "deletenonpresent", 8192)
prop._addConstant("ignore", "ignore", 4096)
meta.props.add("childAction", prop)
prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN)
prop.label = "None"
prop.isDn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("dn", prop)
prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "local"
prop._addConstant("implicit", "implicit", 4)
prop._addConstant("local", "local", 0)
prop._addConstant("policy", "policy", 1)
prop._addConstant("replica", "replica", 2)
prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3)
meta.props.add("lcOwn", prop)
prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "never"
prop._addConstant("never", "never", 0)
meta.props.add("modTs", prop)
prop = PropMeta("str", "name", "name", 7373, PropCategory.REGULAR)
prop.label = "Name"
prop.isConfig = True
prop.isAdmin = True
prop.isCreateOnly = True
prop.isNaming = True
prop.range = [(1, 16)]
prop.regex = ['[a-zA-Z0-9_.:-]+']
prop.defaultValue = "schema"
prop.defaultValueStr = "schema"
meta.props.add("name", prop)
prop = PropMeta("str", "nameAlias", "nameAlias", 28417, PropCategory.REGULAR)
prop.label = "Name alias"
prop.isConfig = True
prop.isAdmin = True
prop.range = [(0, 63)]
prop.regex = ['[a-zA-Z0-9_.-]+']
meta.props.add("nameAlias", prop)
prop = PropMeta("str", "not", "not", 5085, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = False
prop.defaultValueStr = "no"
prop._addConstant("no", None, False)
prop._addConstant("yes", None, True)
meta.props.add("not", prop)
prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN)
prop.label = "None"
prop.isRn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("rn", prop)
prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("created", "created", 2)
prop._addConstant("deleted", "deleted", 8)
prop._addConstant("modified", "modified", 4)
meta.props.add("status", prop)
prop = PropMeta("str", "value1", "value1", 5088, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.range = [(0, 512)]
meta.props.add("value1", prop)
prop = PropMeta("str", "value2", "value2", 5089, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.range = [(0, 512)]
meta.props.add("value2", prop)
meta.namingProps.append(getattr(meta.props, "name"))
# Deployment Meta
meta.deploymentQuery = True
meta.deploymentType = "Ancestor"
meta.deploymentQueryPaths.append(DeploymentPathMeta("MDevToGraphInst", "Graph Instances", "cobra.model.vns.GraphInst"))
def __init__(self, parentMoOrDn, name, markDirty=True, **creationProps):
namingVals = [name]
Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)
# End of package file
# ##################################################
| [
"[email protected]"
]
| |
7a585e2db5523b1ba1a9cca50833de40373101ac | cdbd54f19b28c651e1945f4514a2a2a5431d4753 | /myspider/myspider/settings.py | fe55396cdd58a2b20c9a62c340c9ed8b6be7bf33 | []
| no_license | Knowledgeofitselfisriches/spider | 8ccc7e928da00dc7b53159fb53d6f38b16316ee9 | 797736b6ac850532efe42d9e60524d612d99ad02 | refs/heads/master | 2020-03-27T08:41:06.005591 | 2018-09-11T05:48:10 | 2018-09-11T05:48:10 | 146,277,449 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,380 | py | # -*- coding: utf-8 -*-
# Scrapy settings for myspider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
import os
BOT_NAME = 'myspider'
SPIDER_MODULES = ['myspider.spiders']
NEWSPIDER_MODULE = 'myspider.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'myspider (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
# COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
# 'myspider.middlewares.MyspiderSpiderMiddleware': 543,
# }
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
# 'myspider.middlewares.MyspiderDownloaderMiddleware': 543,
# }
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
# }
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'myspider.pipelines.MyspiderPipeline': 301,
'myspider.pipelines.ShangGuiGuImagePipelines': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
# HTTPCACHE_ENABLED = True
# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = 'httpcache'
# HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
IMAGES_STORE = os.path.dirname(os.path.realpath("__file__")) + "/images/" | [
"[email protected]"
]
| |
ba822ac4287b075913e8805e28bb41c076b5d62e | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03543/s810389255.py | adf2bbfd787f4f2481953d91af3b2e9c140db7fd | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 54 | py | a,b,c,d=input()
print('NYoe s'[a==b==c or b==c==d::2]) | [
"[email protected]"
]
| |
5f36f7b5a2f455751488b2ddc7cfe19638b20074 | 7913bf8dee268d0ed0a96b6ef359abac24f4e613 | /code/backend/billing/migrations/0002_auto_20200512_1158.py | 34b08f9bf77070850a866489ba0306dbd6f8e330 | [
"MIT"
]
| permissive | dorinapall/noe | 724236813fc130be550b80bb1701293c4d2775eb | 6d5682ab00a2cdc5cb419ecab57804c9f70d7b3a | refs/heads/master | 2022-11-11T17:29:22.365369 | 2020-06-18T09:12:58 | 2020-06-18T09:12:58 | 273,198,257 | 1 | 0 | MIT | 2020-06-18T09:35:22 | 2020-06-18T09:35:21 | null | UTF-8 | Python | false | false | 567 | py | # Generated by Django 3.0.5 on 2020-05-12 09:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('appointments', '0003_seat_doctor_name'),
('billing', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='billingdetail',
name='appointment',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='billing_detail', to='appointments.Appointment'),
),
]
| [
"[email protected]"
]
| |
1f3a93ff2a1c44f7c16ced6b39a02975fae54761 | 3ba2d4091332b9d0a2b053f15a4d4ce4ae1c1ef0 | /中等148. 排序链表.py | 91439c6553ea5b008723b9dca4e9aafa03ea40cd | []
| no_license | ganhan999/ForLeetcode | 126272d34250035abda6c2d67222c2c186a3f80b | 9980a9e4bf448b2cf3fed98891a54b6d202a64db | refs/heads/master | 2023-05-01T14:21:49.883692 | 2021-05-12T08:59:51 | 2021-05-12T08:59:51 | 348,708,572 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,684 | py | """
给你链表的头结点head,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在O(nlogn) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
"""
"""
合并排序,利用递归,自上而下
"""
#大神做法1
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def sortFunc(head: ListNode, tail: ListNode) -> ListNode:#用快慢指针找到中点,分成两个链表
if not head:
return head
if head.next == tail:
head.next = None
return head
slow = fast = head
while fast != tail:
slow = slow.next
fast = fast.next
if fast != tail:
fast = fast.next
mid = slow
return merge(sortFunc(head, mid), sortFunc(mid, tail))
def merge(head1: ListNode, head2: ListNode) -> ListNode:
dummyHead = ListNode(0)
temp, temp1, temp2 = dummyHead, head1, head2
while temp1 and temp2:
if temp1.val <= temp2.val:
temp.next = temp1
temp1 = temp1.next
else:
temp.next = temp2
temp2 = temp2.next
temp = temp.next
if temp1:
temp.next = temp1
elif temp2:
temp.next = temp2
return dummyHead.next
return sortFunc(head, None)#一开始是以None作为fast的最后一个节点的判断条件
"""
合并排序,自底向上,先1后2再4以此类推
"""
#大神做法1
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def merge(head1: ListNode, head2: ListNode) -> ListNode:
dummyHead = ListNode(0)
temp, temp1, temp2 = dummyHead, head1, head2
while temp1 and temp2:
if temp1.val <= temp2.val:
temp.next = temp1
temp1 = temp1.next
else:
temp.next = temp2
temp2 = temp2.next
temp = temp.next
if temp1:
temp.next = temp1
elif temp2:
temp.next = temp2
return dummyHead.next
if not head:
return head
length = 0
node = head
while node:
length += 1
node = node.next
dummyHead = ListNode(0, head)
subLength = 1
while subLength < length:
prev, curr = dummyHead, dummyHead.next
while curr:
head1 = curr
for i in range(1, subLength):
if curr.next:
curr = curr.next
else:
break
head2 = curr.next
curr.next = None
curr = head2
for i in range(1, subLength):
if curr and curr.next:
curr = curr.next
else:
break
succ = None
if curr:
succ = curr.next
curr.next = None
merged = merge(head1, head2)
prev.next = merged
while prev.next:
prev = prev.next
curr = succ
subLength <<= 1
return dummyHead.next
| [
"[email protected]"
]
| |
d8921437c42a694886143020ac2eb19bdc858564 | cefd6c17774b5c94240d57adccef57d9bba4a2e9 | /WebKit/Tools/Scripts/webkitpy/port/mock_drt.py | a9040250e0a998a072821655e74f06cd4edbb054 | [
"BSL-1.0"
]
| permissive | adzhou/oragle | 9c054c25b24ff0a65cb9639bafd02aac2bcdce8b | 5442d418b87d0da161429ffa5cb83777e9b38e4d | refs/heads/master | 2022-11-01T05:04:59.368831 | 2014-03-12T15:50:08 | 2014-03-12T15:50:08 | 17,238,063 | 0 | 1 | BSL-1.0 | 2022-10-18T04:23:53 | 2014-02-27T05:39:44 | C++ | UTF-8 | Python | false | false | 10,044 | py | # Copyright (c) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the Google name nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
This is an implementation of the Port interface that overrides other
ports and changes the Driver binary to "MockDRT".
The MockDRT objects emulate what a real DRT would do. In particular, they
return the output a real DRT would return for a given test, assuming that
test actually passes (except for reftests, which currently cause the
MockDRT to crash).
"""
import base64
import logging
import optparse
import os
import sys
# Since we execute this script directly as part of the unit tests, we need to ensure
# that Tools/Scripts is in sys.path for the next imports to work correctly.
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
if script_dir not in sys.path:
sys.path.append(script_dir)
from webkitpy.common.system.systemhost import SystemHost
from webkitpy.port.driver import DriverInput, DriverOutput, DriverProxy
from webkitpy.port.factory import PortFactory
_log = logging.getLogger(__name__)
class MockDRTPort(object):
port_name = 'mock'
@classmethod
def determine_full_port_name(cls, host, options, port_name):
return port_name
def __init__(self, host, port_name, **kwargs):
self.__delegate = PortFactory(host).get(port_name.replace('mock-', ''), **kwargs)
def __getattr__(self, name):
return getattr(self.__delegate, name)
def check_build(self, needs_http):
return True
def check_sys_deps(self, needs_http):
return True
def create_driver(self, worker_number, no_timeout=False):
# The magic of the MockDRTPort is that we create a driver that has a
# cmd_line() method monkey-patched to invoke this script instead of DRT.
return DriverProxy(self, worker_number, self._mocked_driver_maker, pixel_tests=self.get_option('pixel_tests'), no_timeout=no_timeout)
@staticmethod
def _mocked_driver_maker(port, worker_number, pixel_tests, no_timeout=False):
path_to_this_file = port.host.filesystem.abspath(__file__.replace('.pyc', '.py'))
driver = port.__delegate._driver_class()(port, worker_number, pixel_tests, no_timeout)
driver.cmd_line = port._overriding_cmd_line(driver.cmd_line,
port.__delegate._path_to_driver(),
sys.executable,
path_to_this_file,
port.__delegate.name())
return driver
@staticmethod
def _overriding_cmd_line(original_cmd_line, driver_path, python_exe, this_file, port_name):
def new_cmd_line(pixel_tests, per_test_args):
cmd_line = original_cmd_line(pixel_tests, per_test_args)
index = cmd_line.index(driver_path)
cmd_line[index:index + 1] = [python_exe, this_file, '--platform', port_name]
return cmd_line
return new_cmd_line
def start_helper(self, pixel_tests=False):
pass
def start_http_server(self, number_of_servers):
pass
def start_websocket_server(self):
pass
def acquire_http_lock(self):
pass
def stop_helper(self):
pass
def stop_http_server(self):
pass
def stop_websocket_server(self):
pass
def release_http_lock(self):
pass
def show_results_html_file(self, results_filename):
pass
def main(argv, host, stdin, stdout, stderr):
"""Run the tests."""
options, args = parse_options(argv)
drt = MockDRT(options, args, host, stdin, stdout, stderr)
return drt.run()
def parse_options(argv):
# FIXME: We have to do custom arg parsing instead of using the optparse
# module. First, Chromium and non-Chromium DRTs have a different argument
# syntax. Chromium uses --pixel-tests=<path>, and non-Chromium uses
# --pixel-tests as a boolean flag. Second, we don't want to have to list
# every command line flag DRT accepts, but optparse complains about
# unrecognized flags. At some point it might be good to share a common
# DRT options class between this file and webkit.py and chromium.py
# just to get better type checking.
platform_index = argv.index('--platform')
platform = argv[platform_index + 1]
pixel_tests = '--pixel-tests' in argv
return (optparse.Values({'platform': platform, 'pixel_tests': pixel_tests}), argv)
class MockDRT(object):
def __init__(self, options, args, host, stdin, stdout, stderr):
self._options = options
self._args = args
self._host = host
self._stdout = stdout
self._stdin = stdin
self._stderr = stderr
port_name = None
if options.platform:
port_name = options.platform
self._port = PortFactory(host).get(port_name=port_name, options=options)
self._driver = self._port.create_driver(0)
def run(self):
while True:
line = self._stdin.readline()
if not line:
return 0
driver_input = self.input_from_line(line)
dirname, basename = self._port.split_test(driver_input.test_name)
is_reftest = (self._port.reference_files(driver_input.test_name) or
self._port.is_reference_html_file(self._port._filesystem, dirname, basename))
output = self.output_for_test(driver_input, is_reftest)
self.write_test_output(driver_input, output, is_reftest)
def input_from_line(self, line):
vals = line.strip().split("'")
if len(vals) == 1:
uri = vals[0]
checksum = None
else:
uri = vals[0]
checksum = vals[1]
if uri.startswith('http://') or uri.startswith('https://'):
test_name = self._driver.uri_to_test(uri)
else:
test_name = self._port.relative_test_filename(uri)
return DriverInput(test_name, 0, checksum, self._options.pixel_tests)
def output_for_test(self, test_input, is_reftest):
port = self._port
actual_text = port.expected_text(test_input.test_name)
actual_audio = port.expected_audio(test_input.test_name)
actual_image = None
actual_checksum = None
if is_reftest:
# Make up some output for reftests.
actual_text = 'reference text\n'
actual_checksum = 'mock-checksum'
actual_image = 'blank'
if test_input.test_name.endswith('-mismatch.html'):
actual_text = 'not reference text\n'
actual_checksum = 'not-mock-checksum'
actual_image = 'not blank'
elif self._options.pixel_tests and test_input.image_hash:
actual_checksum = port.expected_checksum(test_input.test_name)
actual_image = port.expected_image(test_input.test_name)
return DriverOutput(actual_text, actual_image, actual_checksum, actual_audio)
def write_test_output(self, test_input, output, is_reftest):
if output.audio:
self._stdout.write('Content-Type: audio/wav\n')
self._stdout.write('Content-Transfer-Encoding: base64\n')
self._stdout.write(base64.b64encode(output.audio))
else:
self._stdout.write('Content-Type: text/plain\n')
# FIXME: Note that we don't ensure there is a trailing newline!
# This mirrors actual (Mac) DRT behavior but is a bug.
if output.text:
self._stdout.write(output.text)
self._stdout.write('#EOF\n')
if self._options.pixel_tests and output.image_hash:
self._stdout.write('\n')
self._stdout.write('ActualHash: %s\n' % output.image_hash)
self._stdout.write('ExpectedHash: %s\n' % test_input.image_hash)
if output.image_hash != test_input.image_hash:
self._stdout.write('Content-Type: image/png\n')
self._stdout.write('Content-Length: %s\n' % len(output.image))
self._stdout.write(output.image)
self._stdout.write('#EOF\n')
self._stdout.flush()
self._stderr.write('#EOF\n')
self._stderr.flush()
if __name__ == '__main__':
# Note that the Mock in MockDRT refers to the fact that it is emulating a
# real DRT, and as such, it needs access to a real SystemHost, not a MockSystemHost.
sys.exit(main(sys.argv[1:], SystemHost(), sys.stdin, sys.stdout, sys.stderr))
| [
"[email protected]"
]
| |
68ed6d9f89c9286e62ae56f6b282e9a8bcd5a948 | 1ab7b3f2aa63de8488ce7c466a67d367771aa1f2 | /Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/pygame/tests/event_test.py | d77479a7f229cb98e9bb038a0d0fde958fd29cd1 | [
"MIT"
]
| permissive | icl-rocketry/Avionics | 9d39aeb11aba11115826fd73357b415026a7adad | 95b7a061eabd6f2b607fba79e007186030f02720 | refs/heads/master | 2022-07-30T07:54:10.642930 | 2022-07-10T12:19:10 | 2022-07-10T12:19:10 | 216,184,670 | 9 | 1 | MIT | 2022-06-27T10:17:06 | 2019-10-19T09:57:07 | C++ | UTF-8 | Python | false | false | 27,813 | py | import os
import sys
import unittest
import collections
import pygame
from pygame.compat import as_unicode
PY3 = sys.version_info >= (3, 0, 0)
SDL1 = pygame.get_sdl_version()[0] < 2
################################################################################
EVENT_TYPES = (
# pygame.NOEVENT,
# pygame.ACTIVEEVENT,
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
pygame.JOYAXISMOTION,
pygame.JOYBALLMOTION,
pygame.JOYHATMOTION,
pygame.JOYBUTTONDOWN,
pygame.JOYBUTTONUP,
pygame.VIDEORESIZE,
pygame.VIDEOEXPOSE,
pygame.QUIT,
pygame.SYSWMEVENT,
pygame.USEREVENT,
# pygame.NUMEVENTS,
)
EVENT_TEST_PARAMS = collections.defaultdict(dict)
EVENT_TEST_PARAMS.update({
pygame.KEYDOWN:{'key': pygame.K_SPACE},
pygame.KEYUP:{'key': pygame.K_SPACE},
pygame.MOUSEMOTION:dict(),
pygame.MOUSEBUTTONDOWN:dict(button=1),
pygame.MOUSEBUTTONUP:dict(button=1),
})
NAMES_AND_EVENTS = (
("NoEvent", pygame.NOEVENT),
("ActiveEvent", pygame.ACTIVEEVENT),
("KeyDown", pygame.KEYDOWN),
("KeyUp", pygame.KEYUP),
("MouseMotion", pygame.MOUSEMOTION),
("MouseButtonDown", pygame.MOUSEBUTTONDOWN),
("MouseButtonUp", pygame.MOUSEBUTTONUP),
("JoyAxisMotion", pygame.JOYAXISMOTION),
("JoyBallMotion", pygame.JOYBALLMOTION),
("JoyHatMotion", pygame.JOYHATMOTION),
("JoyButtonDown", pygame.JOYBUTTONDOWN),
("JoyButtonUp", pygame.JOYBUTTONUP),
("VideoResize", pygame.VIDEORESIZE),
("VideoExpose", pygame.VIDEOEXPOSE),
("Quit", pygame.QUIT),
("SysWMEvent", pygame.SYSWMEVENT),
("MidiIn", pygame.MIDIIN),
("MidiOut", pygame.MIDIOUT),
("UserEvent", pygame.USEREVENT),
("Unknown", 0xFFFF),
)
# Add in any SDL 2 specific events.
if pygame.get_sdl_version()[0] >= 2:
NAMES_AND_EVENTS += (
("FingerMotion", pygame.FINGERMOTION),
("FingerDown", pygame.FINGERDOWN),
("FingerUp", pygame.FINGERUP),
("MultiGesture", pygame.MULTIGESTURE),
("MouseWheel", pygame.MOUSEWHEEL),
("TextInput", pygame.TEXTINPUT),
("TextEditing", pygame.TEXTEDITING),
("ControllerAxisMotion", pygame.CONTROLLERAXISMOTION),
("ControllerButtonDown", pygame.CONTROLLERBUTTONDOWN),
("ControllerButtonUp", pygame.CONTROLLERBUTTONUP),
("ControllerDeviceAdded", pygame.CONTROLLERDEVICEADDED),
("ControllerDeviceRemoved", pygame.CONTROLLERDEVICEREMOVED),
("ControllerDeviceMapped", pygame.CONTROLLERDEVICEREMAPPED),
("DropFile", pygame.DROPFILE),
)
# Add in any SDL 2.0.4 specific events.
if pygame.get_sdl_version() >= (2, 0, 4):
NAMES_AND_EVENTS += (
("AudioDeviceAdded", pygame.AUDIODEVICEADDED),
("AudioDeviceRemoved", pygame.AUDIODEVICEREMOVED),
)
# Add in any SDL 2.0.5 specific events.
if pygame.get_sdl_version() >= (2, 0, 5):
NAMES_AND_EVENTS += (
("DropText", pygame.DROPTEXT),
("DropBegin", pygame.DROPBEGIN),
("DropComplete", pygame.DROPCOMPLETE),
)
class EventTypeTest(unittest.TestCase):
def test_Event(self):
"""Ensure an Event object can be created."""
e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr="1")
self.assertEqual(e.some_attr, 1)
self.assertEqual(e.other_attr, "1")
# Event now uses tp_dictoffset and tp_members: request 62
# on Motherhamster Bugzilla.
self.assertEqual(e.type, pygame.USEREVENT)
self.assertIs(e.dict, e.__dict__)
e.some_attr = 12
self.assertEqual(e.some_attr, 12)
e.new_attr = 15
self.assertEqual(e.new_attr, 15)
# For Python 2.x a TypeError is raised for a readonly member;
# for Python 3.x it is an AttributeError.
self.assertRaises((TypeError, AttributeError), setattr, e, "type", 0)
self.assertRaises((TypeError, AttributeError), setattr, e, "dict", None)
# Ensure attributes are visible to dir(), part of the original
# posted request.
d = dir(e)
attrs = ("type", "dict", "__dict__", "some_attr", "other_attr", "new_attr")
for attr in attrs:
self.assertIn(attr, d)
def test_as_str(self):
# Bug reported on Pygame mailing list July 24, 2011:
# For Python 3.x str(event) to raises an UnicodeEncodeError when
# an event attribute is a string with a non-ascii character.
try:
str(pygame.event.Event(EVENT_TYPES[0], a=as_unicode(r"\xed")))
except UnicodeEncodeError:
self.fail("Event object raised exception for non-ascii character")
# Passed.
race_condition_notification = """
This test is dependent on timing. The event queue is cleared in preparation for
tests. There is a small window where outside events from the OS may have effected
results. Try running the test again.
"""
class EventModuleArgsTest(unittest.TestCase):
def setUp(self):
pygame.display.init()
pygame.event.clear()
def tearDown(self):
pygame.display.quit()
def test_get(self):
pygame.event.get()
pygame.event.get(None)
pygame.event.get(None, True)
pygame.event.get(pump=False)
pygame.event.get(pump=True)
pygame.event.get(eventtype=None)
pygame.event.get(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.get(eventtype=pygame.USEREVENT, pump=False)
def test_clear(self):
pygame.event.clear()
pygame.event.clear(None)
pygame.event.clear(None, True)
pygame.event.clear(pump=False)
pygame.event.clear(pump=True)
pygame.event.clear(eventtype=None)
pygame.event.clear(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.clear(eventtype=pygame.USEREVENT, pump=False)
def test_peek(self):
pygame.event.peek()
pygame.event.peek(None)
pygame.event.peek(None, True)
pygame.event.peek(pump=False)
pygame.event.peek(pump=True)
pygame.event.peek(eventtype=None)
pygame.event.peek(eventtype=[pygame.KEYUP, pygame.KEYDOWN])
pygame.event.peek(eventtype=pygame.USEREVENT, pump=False)
class EventCustomTypeTest(unittest.TestCase):
"""Those tests are special in that they need the _custom_event counter to
be reset before and/or after being run."""
def setUp(self):
pygame.quit()
pygame.init()
pygame.display.init()
def tearDown(self):
pygame.quit()
def test_custom_type(self):
self.assertEqual(pygame.event.custom_type(), pygame.USEREVENT + 1)
atype = pygame.event.custom_type()
atype2 = pygame.event.custom_type()
self.assertEqual(atype, atype2 - 1)
ev = pygame.event.Event(atype)
pygame.event.post(ev)
queue = pygame.event.get(atype)
self.assertEqual(len(queue), 1)
self.assertEqual(queue[0].type, atype)
def test_custom_type__end_boundary(self):
"""Ensure custom_type() raises error when no more custom types.
The last allowed custom type number should be (pygame.NUMEVENTS - 1).
"""
start = pygame.event.custom_type() + 1
for i in range(start, pygame.NUMEVENTS):
last = pygame.event.custom_type()
self.assertEqual(last, pygame.NUMEVENTS - 1)
with self.assertRaises(pygame.error):
pygame.event.custom_type()
def test_custom_type__reset(self):
"""Ensure custom events get 'deregistered' by quit().
"""
before = pygame.event.custom_type()
self.assertEqual(before, pygame.event.custom_type() - 1)
pygame.quit()
pygame.init()
pygame.display.init()
self.assertEqual(before, pygame.event.custom_type())
class EventModuleTest(unittest.TestCase):
def _assertCountEqual(self, *args, **kwargs):
# Handle method name differences between Python versions.
if PY3:
self.assertCountEqual(*args, **kwargs)
else:
self.assertItemsEqual(*args, **kwargs)
def _assertExpectedEvents(self, expected, got):
"""Find events like expected events, raise on unexpected or missing,
ignore additional event properties if expected properties are present."""
# This does greedy matching, don't encode an NP-hard problem
# into your input data, *please*
items_left=got[:]
for expected_element in expected:
for item in items_left:
for key in expected_element.__dict__:
if item.__dict__[key]!=expected_element.__dict__[key]:
break
else:
#found item!
items_left.remove(item)
break
else:
raise AssertionError("Expected "+str(expected_element)+" among remaining events "+str(items_left)+" out of "+str(got))
if len(items_left)>0:
raise AssertionError("Unexpected Events: "+str(items_left))
def setUp(self):
pygame.display.init()
pygame.event.clear() # flush events
def tearDown(self):
pygame.event.clear() # flush events
pygame.display.quit()
def test_event_numevents(self):
"""Ensures NUMEVENTS does not exceed the maximum SDL number of events.
"""
# Ref: https://www.libsdl.org/tmp/SDL/include/SDL_events.h
MAX_SDL_EVENTS = 0xFFFF # SDL_LASTEVENT = 0xFFFF
self.assertLessEqual(pygame.NUMEVENTS, MAX_SDL_EVENTS)
def test_event_attribute(self):
e1 = pygame.event.Event(pygame.USEREVENT, attr1="attr1")
self.assertEqual(e1.attr1, "attr1")
def test_set_blocked(self):
"""Ensure events can be blocked from the queue."""
event = EVENT_TYPES[0]
pygame.event.set_blocked(event)
self.assertTrue(pygame.event.get_blocked(event))
pygame.event.post(pygame.event.Event(event, **EVENT_TEST_PARAMS[EVENT_TYPES[0]]))
ret = pygame.event.get()
should_be_blocked = [e for e in ret if e.type == event]
self.assertEqual(should_be_blocked, [])
def test_set_blocked__event_sequence(self):
"""Ensure a sequence of event types can be blocked."""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
pygame.event.set_blocked(event_types)
for etype in event_types:
self.assertTrue(pygame.event.get_blocked(etype))
def test_set_blocked_all(self):
"""Ensure all events can be unblocked at once."""
pygame.event.set_blocked(None)
for e in EVENT_TYPES:
self.assertTrue(pygame.event.get_blocked(e))
def test_post__and_poll(self):
"""Ensure events can be posted to the queue."""
e1 = pygame.event.Event(pygame.USEREVENT, attr1="attr1")
pygame.event.post(e1)
posted_event = pygame.event.poll()
self.assertEqual(e1.attr1, posted_event.attr1, race_condition_notification)
# fuzzing event types
for i in range(1, 13):
pygame.event.post(pygame.event.Event(EVENT_TYPES[i], **EVENT_TEST_PARAMS[EVENT_TYPES[i]]))
self.assertEqual(
pygame.event.poll().type, EVENT_TYPES[i], race_condition_notification
)
def test_post_and_get_keydown(self):
"""Ensure keydown events can be posted to the queue."""
activemodkeys = pygame.key.get_mods()
events = [
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_p),
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_y, mod=activemodkeys),
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_g, unicode="g"),
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_a, unicode=None),
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_m, mod=None, window=None),
pygame.event.Event(pygame.KEYDOWN, key=pygame.K_e, mod=activemodkeys, unicode="e")
]
for e in events:
pygame.event.post(e)
posted_event = pygame.event.poll()
self.assertEqual(e, posted_event, race_condition_notification)
def test_post_large_user_event(self):
pygame.event.post(pygame.event.Event(pygame.USEREVENT, {"a": "a" * 1024}))
e = pygame.event.poll()
self.assertEqual(e.type, pygame.USEREVENT)
self.assertEqual(e.a, "a" * 1024)
def test_post_blocked(self):
"""
Test blocked events are not posted. Also test whether post()
returns a boolean correctly
"""
pygame.event.set_blocked(pygame.USEREVENT)
self.assertFalse(pygame.event.post(pygame.event.Event(pygame.USEREVENT)))
self.assertFalse(pygame.event.poll())
pygame.event.set_allowed(pygame.USEREVENT)
self.assertTrue(pygame.event.post(pygame.event.Event(pygame.USEREVENT)))
self.assertEqual(pygame.event.poll(), pygame.event.Event(pygame.USEREVENT))
def test_get(self):
"""Ensure get() retrieves all the events on the queue."""
event_cnt = 10
for _ in range(event_cnt):
pygame.event.post(pygame.event.Event(pygame.USEREVENT))
queue = pygame.event.get()
self.assertEqual(len(queue), event_cnt)
self.assertTrue(all(e.type == pygame.USEREVENT for e in queue))
def test_get_type(self):
ev = pygame.event.Event(pygame.USEREVENT)
pygame.event.post(ev)
queue = pygame.event.get(pygame.USEREVENT)
self.assertEqual(len(queue), 1)
self.assertEqual(queue[0].type, pygame.USEREVENT)
TESTEVENTS = 10
for _ in range(TESTEVENTS):
pygame.event.post(ev)
q = pygame.event.get([pygame.USEREVENT])
self.assertEqual(len(q), TESTEVENTS)
for event in q:
self.assertEqual(event, ev)
def test_get__empty_queue(self):
"""Ensure get() works correctly on an empty queue."""
expected_events = []
pygame.event.clear()
# Ensure all events can be checked.
retrieved_events = pygame.event.get()
self.assertListEqual(retrieved_events, expected_events)
# Ensure events can be checked individually.
for event_type in EVENT_TYPES:
retrieved_events = pygame.event.get(event_type)
self.assertListEqual(retrieved_events, expected_events)
# Ensure events can be checked as a sequence.
retrieved_events = pygame.event.get(EVENT_TYPES)
self.assertListEqual(retrieved_events, expected_events)
def test_get__event_sequence(self):
"""Ensure get() can handle a sequence of event types."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
other_event_type = pygame.MOUSEBUTTONUP
# Test when no events in the queue.
expected_events = []
pygame.event.clear()
retrieved_events = pygame.event.get(event_types)
# don't use self._assertCountEqual here. This checks for
# expected properties in events, and ignores unexpected ones, for
# forward compatibility with SDL2.
self._assertExpectedEvents(expected=expected_events, got=retrieved_events)
# Test when an event type not in the list is in the queue.
expected_events = []
pygame.event.clear()
pygame.event.post(pygame.event.Event(other_event_type, **EVENT_TEST_PARAMS[other_event_type]))
retrieved_events = pygame.event.get(event_types)
self._assertExpectedEvents(expected=expected_events, got=retrieved_events)
# Test when 1 event type in the list is in the queue.
expected_events = [pygame.event.Event(event_types[0], **EVENT_TEST_PARAMS[event_types[0]])]
pygame.event.clear()
pygame.event.post(expected_events[0])
retrieved_events = pygame.event.get(event_types)
self._assertExpectedEvents(expected=expected_events, got=retrieved_events)
# Test all events in the list are in the queue.
pygame.event.clear()
expected_events = []
for etype in event_types:
expected_events.append(pygame.event.Event(etype, **EVENT_TEST_PARAMS[etype]))
pygame.event.post(expected_events[-1])
retrieved_events = pygame.event.get(event_types)
self._assertExpectedEvents(expected=expected_events, got=retrieved_events)
def test_clear(self):
"""Ensure clear() removes all the events on the queue."""
for e in EVENT_TYPES:
pygame.event.post(pygame.event.Event(e, **EVENT_TEST_PARAMS[e]))
poll_event = pygame.event.poll()
self.assertNotEqual(poll_event.type, pygame.NOEVENT)
pygame.event.clear()
poll_event = pygame.event.poll()
self.assertEqual(poll_event.type, pygame.NOEVENT, race_condition_notification)
def test_clear__empty_queue(self):
"""Ensure clear() works correctly on an empty queue."""
expected_events = []
pygame.event.clear()
# Test calling clear() on an already empty queue.
pygame.event.clear()
retrieved_events = pygame.event.get()
self.assertListEqual(retrieved_events, expected_events)
def test_clear__event_sequence(self):
"""Ensure a sequence of event types can be cleared from the queue."""
cleared_event_types = EVENT_TYPES[:5]
expected_event_types = EVENT_TYPES[5:10]
expected_events = []
# Add the events to the queue.
for etype in cleared_event_types:
pygame.event.post(pygame.event.Event(etype, **EVENT_TEST_PARAMS[etype]))
for etype in expected_events:
expected_events.append(pygame.event.Event(etype, **EVENT_TEST_PARAMS[etype]))
pygame.event.post(expected_events[-1])
# Clear the cleared_events from the queue.
pygame.event.clear(cleared_event_types)
# Check the rest of the events in the queue.
remaining_events = pygame.event.get()
self._assertCountEqual(remaining_events, expected_events)
def test_event_name(self):
"""Ensure event_name() returns the correct event name."""
for expected_name, event in NAMES_AND_EVENTS:
self.assertEqual(
pygame.event.event_name(event), expected_name, "0x{:X}".format(event)
)
def test_event_name__userevent_range(self):
"""Ensures event_name() returns the correct name for user events.
Tests the full range of user events.
"""
expected_name = "UserEvent"
for event in range(pygame.USEREVENT, pygame.NUMEVENTS):
self.assertEqual(
pygame.event.event_name(event), expected_name, "0x{:X}".format(event)
)
def test_event_name__userevent_boundary(self):
"""Ensures event_name() does not return 'UserEvent' for events
just outside the user event range.
"""
unexpected_name = "UserEvent"
for event in (pygame.USEREVENT - 1, pygame.NUMEVENTS):
self.assertNotEqual(
pygame.event.event_name(event), unexpected_name, "0x{:X}".format(event)
)
def test_wait(self):
"""Ensure wait() waits for an event on the queue."""
# Test case without timeout.
event = pygame.event.Event(EVENT_TYPES[0], **EVENT_TEST_PARAMS[EVENT_TYPES[0]])
pygame.event.post(event)
wait_event = pygame.event.wait()
self.assertEqual(wait_event.type, event.type)
# Test case with timeout and no event in the queue.
wait_event = pygame.event.wait(250)
self.assertEqual(wait_event.type, pygame.NOEVENT)
# Test case with timeout and an event in the queue.
event = pygame.event.Event(EVENT_TYPES[0], **EVENT_TEST_PARAMS[EVENT_TYPES[0]])
pygame.event.post(event)
wait_event = pygame.event.wait(250)
self.assertEqual(wait_event.type, event.type)
def test_peek(self):
"""Ensure queued events can be peeked at."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
for event_type in event_types:
pygame.event.post(pygame.event.Event(event_type, **EVENT_TEST_PARAMS[event_type]))
# Ensure events can be checked individually.
for event_type in event_types:
self.assertTrue(pygame.event.peek(event_type))
# Ensure events can be checked as a sequence.
self.assertTrue(pygame.event.peek(event_types))
def test_peek__event_sequence(self):
"""Ensure peek() can handle a sequence of event types."""
event_types = [pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION]
other_event_type = pygame.MOUSEBUTTONUP
# Test when no events in the queue.
pygame.event.clear()
peeked = pygame.event.peek(event_types)
self.assertFalse(peeked)
# Test when an event type not in the list is in the queue.
pygame.event.clear()
pygame.event.post(pygame.event.Event(other_event_type, **EVENT_TEST_PARAMS[other_event_type]))
peeked = pygame.event.peek(event_types)
self.assertFalse(peeked)
# Test when 1 event type in the list is in the queue.
pygame.event.clear()
pygame.event.post(pygame.event.Event(event_types[0], **EVENT_TEST_PARAMS[event_types[0]]))
peeked = pygame.event.peek(event_types)
self.assertTrue(peeked)
# Test all events in the list are in the queue.
pygame.event.clear()
for etype in event_types:
pygame.event.post(pygame.event.Event(etype, **EVENT_TEST_PARAMS[etype]))
peeked = pygame.event.peek(event_types)
self.assertTrue(peeked)
def test_peek__empty_queue(self):
"""Ensure peek() works correctly on an empty queue."""
pygame.event.clear()
# Ensure all events can be checked.
peeked = pygame.event.peek()
self.assertFalse(peeked)
# Ensure events can be checked individually.
for event_type in EVENT_TYPES:
peeked = pygame.event.peek(event_type)
self.assertFalse(peeked)
# Ensure events can be checked as a sequence.
peeked = pygame.event.peek(EVENT_TYPES)
self.assertFalse(peeked)
def test_set_allowed(self):
"""Ensure a blocked event type can be unblocked/allowed."""
event = EVENT_TYPES[0]
pygame.event.set_blocked(event)
self.assertTrue(pygame.event.get_blocked(event))
pygame.event.set_allowed(event)
self.assertFalse(pygame.event.get_blocked(event))
def test_set_allowed__event_sequence(self):
"""Ensure a sequence of blocked event types can be unblocked/allowed.
"""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
pygame.event.set_blocked(event_types)
pygame.event.set_allowed(event_types)
for etype in event_types:
self.assertFalse(pygame.event.get_blocked(etype))
def test_set_allowed_all(self):
"""Ensure all events can be unblocked/allowed at once."""
pygame.event.set_blocked(None)
for e in EVENT_TYPES:
self.assertTrue(pygame.event.get_blocked(e))
pygame.event.set_allowed(None)
for e in EVENT_TYPES:
self.assertFalse(pygame.event.get_blocked(e))
def test_pump(self):
"""Ensure pump() functions properly."""
pygame.event.pump()
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'requires the SDL_VIDEODRIVER to be a non "dummy" value',
)
def test_set_grab__and_get_symmetric(self):
"""Ensure event grabbing can be enabled and disabled.
WARNING: Moving the mouse off the display during this test can cause it
to fail.
"""
surf = pygame.display.set_mode((10, 10))
pygame.event.set_grab(True)
self.assertTrue(pygame.event.get_grab())
pygame.event.set_grab(False)
self.assertFalse(pygame.event.get_grab())
def test_event_equality(self):
"""Ensure an events can be compared correctly."""
a = pygame.event.Event(EVENT_TYPES[0], a=1)
b = pygame.event.Event(EVENT_TYPES[0], a=1)
c = pygame.event.Event(EVENT_TYPES[1], a=1)
d = pygame.event.Event(EVENT_TYPES[0], a=2)
self.assertTrue(a == a)
self.assertFalse(a != a)
self.assertTrue(a == b)
self.assertFalse(a != b)
self.assertTrue(a != c)
self.assertFalse(a == c)
self.assertTrue(a != d)
self.assertFalse(a == d)
def test_get_blocked(self):
"""Ensure an event's blocked state can be retrieved."""
# Test each event is not blocked.
pygame.event.set_allowed(None)
for etype in EVENT_TYPES:
blocked = pygame.event.get_blocked(etype)
self.assertFalse(blocked)
# Test each event type is blocked.
pygame.event.set_blocked(None)
for etype in EVENT_TYPES:
blocked = pygame.event.get_blocked(etype)
self.assertTrue(blocked)
def test_get_blocked__event_sequence(self):
"""Ensure get_blocked() can handle a sequence of event types."""
event_types = [
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEMOTION,
pygame.MOUSEBUTTONDOWN,
pygame.MOUSEBUTTONUP,
]
# Test no event types in the list are blocked.
blocked = pygame.event.get_blocked(event_types)
self.assertFalse(blocked)
# Test when 1 event type in the list is blocked.
pygame.event.set_blocked(event_types[2])
blocked = pygame.event.get_blocked(event_types)
self.assertTrue(blocked)
# Test all event types in the list are blocked.
pygame.event.set_blocked(event_types)
blocked = pygame.event.get_blocked(event_types)
self.assertTrue(blocked)
@unittest.skipIf(
os.environ.get("SDL_VIDEODRIVER") == "dummy",
'requires the SDL_VIDEODRIVER to be a non "dummy" value',
)
def test_get_grab(self):
"""Ensure get_grab() works as expected"""
surf = pygame.display.set_mode((10, 10))
# Test 5 times
for i in range(5):
pygame.event.set_grab(i % 2)
self.assertEqual(pygame.event.get_grab(), i % 2)
def test_poll(self):
"""Ensure poll() works as expected"""
pygame.event.clear()
ev = pygame.event.poll()
# poll() on empty queue should return NOEVENT
self.assertEqual(ev.type, pygame.NOEVENT)
# test poll returns stuff in same order
e1 = pygame.event.Event(pygame.USEREVENT)
e2 = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_a)
e3 = pygame.event.Event(pygame.KEYUP, key=pygame.K_a)
pygame.event.post(e1)
pygame.event.post(e2)
pygame.event.post(e3)
self.assertEqual(pygame.event.poll().type, e1.type)
self.assertEqual(pygame.event.poll().type, e2.type)
self.assertEqual(pygame.event.poll().type, e3.type)
self.assertEqual(pygame.event.poll().type, pygame.NOEVENT)
################################################################################
if __name__ == "__main__":
unittest.main()
| [
"[email protected]"
]
| |
053856ce397586ba9db58c2ae9a1b73ace95139a | 82a42645c35b43542c63afb28d3dd0f891d71982 | /Stack_and_Queue/RedundantBraces.py | ec0bbb178edbfe11e9042351476d23c7e96b773f | []
| no_license | nehatomar12/Data-structures-and-Algorithms | 54e48ecd3cd360ff4ea0196243e4a8b4cdf6181f | b9566764de4faa0e95a4dfe90fe46f843ade4a8c | refs/heads/master | 2023-03-01T01:28:55.581679 | 2021-02-09T08:07:47 | 2021-02-09T08:07:47 | 292,843,092 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,094 | py | """
Given a string A denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.
Chech whether A has redundant braces or not.
Return 1 if A has redundant braces, else return 0.
Note: A will be always a valid expression.
Input 1:
A = "((a + b))"
Output 1:
1
Explanation 1:
((a + b)) has redundant braces so answer will be 1.
Input 2:
A = "(a + (a + b))"
Output 2:
0
"""
A = "((a + b))"
A = "(a + (a + b))"
#A = "(a)"
#A = " ((a+b-c)*c)"
def braces():
res = True
s = []
top = -1
temp = ""
for i in A:
if i != " ":
s.append(i)
top += 1
if top != -1 and s[top] == ')':
s.pop()
top -= 1
while top != -1 :
if s[top] == "(":
break
temp += s.pop()
top -= 1
s.pop()
top -= 1
if temp and len(temp) > 1:
temp =""
else:
res = False
if res:
return 0
return 1
print((braces()))
| [
"[email protected]"
]
| |
7e1cef525621e6e50f5dd544e860b0e514055996 | be1619e4ef51753443fbc82dedcd9bb5c32749ab | /migrations/tests/loader_files/app2/0001_initial.migration.py | 945e1b041c80a3593d661466e63eee2da73c15f9 | []
| no_license | PeterUSA123/migrations | 5264ea0deed4dc8670f54a6abdf5000439e10cb4 | 7e5dfb7c32970d9f2163d779a2e225feb123c740 | refs/heads/master | 2020-09-10T07:39:25.911462 | 2012-09-04T18:51:15 | 2012-09-04T18:51:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 383 | py | from migrations.api import *
class Migration(BaseMigration):
actions = [
CreateModel(
name = "Book",
fields = [
("title", Field("django.db.models.fields.CharField", [], {"max_length": "100"})),
("author", Field("django.db.models.fields.related.ForeignKey", ["app1.Author"], {})),
],
),
]
| [
"[email protected]"
]
| |
a93f34a8cdbdade867aa61abe760744aaaa75b92 | 6879a8596df6f302c63966a2d27f6b4d11cc9b29 | /abc/problems070/063/a.py | 02f33edc8d9d964b8d1658030eac30bb91092235 | []
| no_license | wkwkgg/atcoder | 41b1e02b88bf7a8291b709306e54cb56cb93e52a | 28a7d4084a4100236510c05a88e50aa0403ac7cd | refs/heads/master | 2020-07-26T03:47:19.460049 | 2020-03-01T18:29:57 | 2020-03-01T18:29:57 | 208,523,188 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 69 | py | A, B = map(int, input().split())
print("error" if A+B >= 10 else A+B) | [
"[email protected]"
]
| |
f0d8898bd3cd604ac6df4be28d7ffbec78e9e395 | 20d9130fdc21756c4f8fe255583922352f5c5762 | /src/DIRAC/Interfaces/scripts/dirac-framework-ping-service.py | 651aab2405ce29d834f1054882fa688175e87666 | []
| no_license | bopopescu/bes3-jinr | 095314e43f41f08bd48b248fe3ca627a5c009f58 | fdfd852c92a56192b8ee9970b66f0136e6e0afff | refs/heads/master | 2022-11-26T06:01:36.718508 | 2014-03-17T06:03:50 | 2014-03-17T06:03:50 | 282,113,617 | 0 | 0 | null | 2020-07-24T03:30:10 | 2020-07-24T03:30:09 | null | UTF-8 | Python | false | false | 1,430 | py | #!/usr/bin/env python
########################################################################
# $HeadURL$
# File : dirac-framework-ping-service
# Author : Stuart Paterson
########################################################################
"""
Ping the given DIRAC Service
"""
__RCSID__ = "55b8255 (2010-12-14 18:54:06 +0000) Ricardo Graciani <[email protected]>"
import DIRAC
from DIRAC.Core.Base import Script
Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1],
'Usage:',
' %s [option|cfgfile] ... System Service|System/Agent' % Script.scriptName,
'Arguments:',
' System: Name of the DIRAC system (ie: WorkloadManagement)',
' Service: Name of the DIRAC service (ie: Matcher)'] ) )
Script.parseCommandLine( ignoreErrors = True )
args = Script.getPositionalArgs()
if len( args ) == 1:
args = args[0].split( '/' )
if len( args ) < 2:
Script.showHelp()
from DIRAC.Interfaces.API.Dirac import Dirac
dirac = Dirac()
exitCode = 0
system = args[0]
service = args[1]
result = dirac.ping( system, service, printOutput = True )
if not result:
print 'ERROR: Null result from ping()'
exitCode = 2
elif not result['OK']:
print 'ERROR: ', result['Message']
exitCode = 2
DIRAC.exit( exitCode )
| [
"[email protected]"
]
| |
531256a3754c73218f5f4197dfd5e7e094ed1479 | d1032c2b568daf02de5cf2e7aaa33a608ffd20e1 | /Basic/1097_16694268(AC).py | 3e843332f77134831cb1f74c8ffc85ec0998a1ce | []
| no_license | Junhyeok1015/Codeup | 267edef68113951019d28d311d38aa91d6677bde | ee5207528fd22689311c2941b94d7ac2480fe0cc | refs/heads/master | 2023-02-12T17:10:06.481196 | 2021-01-17T02:34:23 | 2021-01-17T02:34:23 | 326,317,725 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 602 | py | list_ = []
for _ in range(19):
a = list(map(int, input().strip().split(" ")))
list_.append(a)
n = int(input())
for i in range(n):
a, b = list(map(int, input().strip().split(" ")))
for i in range(19):
if list_[a-1][i] == 0:
list_[a-1][i] = 1
else:
list_[a-1][i] = 0
for i in range(19):
if list_[i][b-1] == 0:
list_[i][b-1] = 1
else:
list_[i][b-1] = 0
for i in range(19):
line = ""
for j in range(19):
k = str(list_[i][j])
line += k + " "
print(line)
| [
"[email protected]"
]
| |
285ca8ee864c495bce6ae6df87254098f6f3ae2e | 4f875744ccae8fa9225318ce16fc483b7bf2735e | /facebook/phoneScreen/romanToInteger.py | b8b2400a7a9d68417e8d3c8bc1fe8508c27053a0 | []
| no_license | nguyenngochuy91/companyQuestions | 62c0821174bb3cb33c7af2c5a1e83a60e4a29977 | c937fe19be665ba7ac345e1729ff531f370f30e8 | refs/heads/master | 2020-07-27T05:58:36.794033 | 2020-04-10T20:57:15 | 2020-04-10T20:57:15 | 208,893,527 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 458 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 16:49:16 2019
@author: huyn
"""
def romanToInt(s: str) -> int:
d= {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
if not s:
return 0
current = d[s[0]]
accumulate = d[s[0]]
for i in range(len(s)-1):
v = d[s[i+1]]
if v>current:
accumulate= accumulate-current+v-current
else:
accumulate+=v
current=v
return accumulate | [
"[email protected]"
]
| |
19a398780eab3ca00a2386b563a810fa549b5d18 | eadd15064aa74811e7a3718b617636627ef4fd47 | /web/migrations/0013_image_name.py | 197a63613795ccaf8996f8c4be245d15c0425935 | []
| no_license | topsai/plasrefine_backstage | 262f7bb032daa4d018aac1519e1139cb060c3f91 | 1eb34dd0b13ebdc2a42dd6ed1aaa2d08c18ab5fb | refs/heads/master | 2023-04-12T13:24:22.710108 | 2021-05-08T14:16:41 | 2021-05-08T14:16:41 | 361,993,024 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 420 | py | # Generated by Django 3.2 on 2021-04-30 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0012_websetting_about'),
]
operations = [
migrations.AddField(
model_name='image',
name='name',
field=models.CharField(default=1, max_length=30),
preserve_default=False,
),
]
| [
"[email protected]"
]
| |
5ec77929fa075f87c5fd7bb35794fb7e2d867deb | d2c163f246d28b8519f8c89de23556e43be91684 | /www/captcha/tests/__init__.py | 70006e5cbc74a152160e2618d4b24e8629350210 | []
| no_license | boogiiieee/Iskcon | d7a2b8bdc3002ef3306fc5e7ddc577504d8533c9 | b672dbafee06af3ee6d646c75f442d97133f5ec9 | refs/heads/master | 2021-09-04T03:11:06.770094 | 2018-01-15T04:21:36 | 2018-01-15T04:21:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,292 | py | # -*- coding: utf-8 -*-
from captcha.conf import settings
from captcha.models import CaptchaStore, get_safe_now
from captcha.fields import CaptchaField, CaptchaTextInput
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
import datetime
class CaptchaCase(TestCase):
urls = 'captcha.tests.urls'
def setUp(self):
self.default_challenge = settings.get_challenge()()
self.math_challenge = settings._callable_from_string('captcha.helpers.math_challenge')()
self.chars_challenge = settings._callable_from_string('captcha.helpers.random_char_challenge')()
self.unicode_challenge = settings._callable_from_string('captcha.helpers.unicode_challenge')()
self.default_store, created = CaptchaStore.objects.get_or_create(challenge=self.default_challenge[0], response=self.default_challenge[1])
self.math_store, created = CaptchaStore.objects.get_or_create(challenge=self.math_challenge[0], response=self.math_challenge[1])
self.chars_store, created = CaptchaStore.objects.get_or_create(challenge=self.chars_challenge[0], response=self.chars_challenge[1])
self.unicode_store, created = CaptchaStore.objects.get_or_create(challenge=self.unicode_challenge[0], response=self.unicode_challenge[1])
def testImages(self):
for key in (self.math_store.hashkey, self.chars_store.hashkey, self.default_store.hashkey, self.unicode_store.hashkey):
response = self.client.get(reverse('captcha-image', kwargs=dict(key=key)))
self.failUnlessEqual(response.status_code, 200)
self.assertTrue(response.has_header('content-type'))
self.assertEquals(response._headers.get('content-type'), ('Content-Type', 'image/png'))
def testAudio(self):
if not settings.CAPTCHA_FLITE_PATH:
return
for key in (self.math_store.hashkey, self.chars_store.hashkey, self.default_store.hashkey):
response = self.client.get(reverse('captcha-audio', kwargs=dict(key=key)))
self.failUnlessEqual(response.status_code, 200)
self.assertTrue(len(response.content) > 1024)
self.assertTrue(response.has_header('content-type'))
self.assertEquals(response._headers.get('content-type'), ('Content-Type', 'audio/x-wav'))
def testFormSubmit(self):
r = self.client.get(reverse('captcha-test'))
self.failUnlessEqual(r.status_code, 200)
hash_ = r.content[r.content.find('value="') + 7:r.content.find('value="') + 47]
try:
response = CaptchaStore.objects.get(hashkey=hash_).response
except:
self.fail()
r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_, captcha_1=response, subject='xxx', sender='[email protected]'))
self.failUnlessEqual(r.status_code, 200)
self.assertTrue(r.content.find('Form validated') > 0)
r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_, captcha_1=response, subject='xxx', sender='[email protected]'))
self.failUnlessEqual(r.status_code, 200)
self.assertFalse(r.content.find('Form validated') > 0)
def testWrongSubmit(self):
r = self.client.get(reverse('captcha-test'))
self.failUnlessEqual(r.status_code, 200)
r = self.client.post(reverse('captcha-test'), dict(captcha_0='abc', captcha_1='wrong response', subject='xxx', sender='[email protected]'))
self.assertFormError(r, 'form', 'captcha', _('Invalid CAPTCHA'))
def testDeleteExpired(self):
self.default_store.expiration = get_safe_now() - datetime.timedelta(minutes=5)
self.default_store.save()
hash_ = self.default_store.hashkey
r = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_, captcha_1=self.default_store.response, subject='xxx', sender='[email protected]'))
self.failUnlessEqual(r.status_code, 200)
self.assertFalse(r.content.find('Form validated') > 0)
# expired -> deleted
try:
CaptchaStore.objects.get(hashkey=hash_)
self.fail()
except:
pass
def testCustomErrorMessage(self):
r = self.client.get(reverse('captcha-test-custom-error-message'))
self.failUnlessEqual(r.status_code, 200)
# Wrong answer
r = self.client.post(reverse('captcha-test-custom-error-message'), dict(captcha_0='abc', captcha_1='wrong response'))
self.assertFormError(r, 'form', 'captcha', 'TEST CUSTOM ERROR MESSAGE')
# empty answer
r = self.client.post(reverse('captcha-test-custom-error-message'), dict(captcha_0='abc', captcha_1=''))
self.assertFormError(r, 'form', 'captcha', _('This field is required.'))
def testRepeatedChallenge(self):
CaptchaStore.objects.create(challenge='xxx', response='xxx')
try:
CaptchaStore.objects.create(challenge='xxx', response='xxx')
except Exception:
self.fail()
def testRepeatedChallengeFormSubmit(self):
settings.CAPTCHA_CHALLENGE_FUNCT = 'captcha.tests.trivial_challenge'
r1 = self.client.get(reverse('captcha-test'))
r2 = self.client.get(reverse('captcha-test'))
self.failUnlessEqual(r1.status_code, 200)
self.failUnlessEqual(r2.status_code, 200)
hash_1 = r1.content[r1.content.find('value="') + 7:r1.content.find('value="') + 47]
hash_2 = r2.content[r2.content.find('value="') + 7:r2.content.find('value="') + 47]
try:
store_1 = CaptchaStore.objects.get(hashkey=hash_1)
store_2 = CaptchaStore.objects.get(hashkey=hash_2)
except:
self.fail()
self.assertTrue(store_1.pk != store_2.pk)
self.assertTrue(store_1.response == store_2.response)
self.assertTrue(hash_1 != hash_2)
r1 = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_1, captcha_1=store_1.response, subject='xxx', sender='[email protected]'))
self.failUnlessEqual(r1.status_code, 200)
self.assertTrue(r1.content.find('Form validated') > 0)
try:
store_2 = CaptchaStore.objects.get(hashkey=hash_2)
except:
self.fail()
r2 = self.client.post(reverse('captcha-test'), dict(captcha_0=hash_2, captcha_1=store_2.response, subject='xxx', sender='[email protected]'))
self.failUnlessEqual(r2.status_code, 200)
self.assertTrue(r2.content.find('Form validated') > 0)
def testOutputFormat(self):
settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s<p>Hello, captcha world</p>%(hidden_field)s%(text_field)s'
r = self.client.get(reverse('captcha-test'))
self.failUnlessEqual(r.status_code, 200)
self.assertTrue('<p>Hello, captcha world</p>' in r.content)
def testInvalidOutputFormat(self):
settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s'
try:
self.client.get(reverse('captcha-test'))
self.fail()
except ImproperlyConfigured, e:
self.failUnless('CAPTCHA_OUTPUT_FORMAT' in unicode(e))
def testPerFormFormat(self):
settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s testCustomFormatString %(hidden_field)s %(text_field)s'
r = self.client.get(reverse('captcha-test'))
self.failUnless('testCustomFormatString' in r.content)
r = self.client.get(reverse('test_per_form_format'))
self.failUnless('testPerFieldCustomFormatString' in r.content)
def testIssue31ProperLabel(self):
settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s %(hidden_field)s %(text_field)s'
r = self.client.get(reverse('captcha-test'))
self.failUnless('<label for="id_captcha_1"' in r.content)
def testIssue12ProperInstantiation(self):
"""
This test covers a default django field and widget behavior
It not assert anything. If something is wrong it will raise a error!
"""
settings.CAPTCHA_OUTPUT_FORMAT = u'%(image)s %(hidden_field)s %(text_field)s'
widget = CaptchaTextInput(attrs={'class': 'required'})
CaptchaField(widget=widget)
def trivial_challenge():
return 'trivial', 'trivial'
| [
"[email protected]"
]
| |
57b116ce2d853c1a87b2103a9ab456fb8fb82aa5 | 97d8d8f303545583e04356279b58c59e41bcb0e7 | /TransitAdScreen/settings/base.py | bf8535f899ce787bb222211c9c15aefdd5549c83 | [
"Apache-2.0"
]
| permissive | 8secz-johndpope/transit-advertising-screen-cms | 2493c270022ac03b17e4b4b1e9b426f568d01ed5 | 9c27d4d7ed9fe598c1c48ca96ee5d10f619c8683 | refs/heads/master | 2022-09-24T13:44:07.056409 | 2019-10-17T16:40:21 | 2019-10-17T16:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,983 | py | """
Django settings for TransitAdScreen project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'screens.apps.ScreensConfig',
'constance',
'constance.backends.database',
'import_export',
'mathfilters',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'TransitAdScreen.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'TransitAdScreen.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
# Constance
CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
CONSTANCE_CONFIG = {
'IMAGE_SERVER_URL': ('https://images.servername.com/', 'Image server URL', str),
}
| [
"[email protected]"
]
| |
3114d5b038163034c2754987fa9932c9df3025f7 | 07c4f43677af3c8384fd7dd2bd3498f80215625c | /async_worker/__init__.py | ee5e06e732c1aa9689d666bbde5e46a9066211be | [
"Apache-2.0"
]
| permissive | cxy19941228/DeepRL | 4d898deede02047b4df0d48f40cb0e313137474a | 41627588fb2e37869a314ae1af0d272f3f302285 | refs/heads/master | 2021-08-08T07:56:04.830382 | 2017-11-09T23:38:42 | 2017-11-09T23:38:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 165 | py | from .actor_critic import *
from .continuous_actor_critic import *
from .n_step_q import *
from .one_step_sarsa import *
from .one_step_q import *
from .ppo import * | [
"[email protected]"
]
| |
ffc166071e09834e5de7d3b6d8d2e3cdb3f976c3 | d8edd97f8f8dea3f9f02da6c40d331682bb43113 | /networks599.py | 4909057f21e18b14ca08a7f5d62ff4a0a2c7b16f | []
| no_license | mdubouch/noise-gan | bdd5b2fff3aff70d5f464150443d51c2192eeafd | 639859ec4a2aa809d17eb6998a5a7d217559888a | refs/heads/master | 2023-07-15T09:37:57.631656 | 2021-08-27T11:02:45 | 2021-08-27T11:02:45 | 284,072,311 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,922 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
__version__ = 205
# Number of wires in the CDC
n_wires = 3606
# Number of continuous features (E, t, dca)
n_features = 3
geom_dim = 2
class Gen(nn.Module):
def __init__(self, ngf, latent_dims, seq_len, encoded_dim):
super().__init__()
self.ngf = ngf
self.seq_len = seq_len
self.version = __version__
# Input: (B, latent_dims, 1)
self.act = nn.ReLU()
n512 = 128
self.lin0 = nn.Linear(latent_dims, seq_len//64*n512, bias=True)
self.bn0 = nn.BatchNorm1d(n512)
self.n512 = n512
self.convu1 = nn.ConvTranspose1d(n512, n512, 4, 4, 0)
self.bnu1 = nn.BatchNorm1d(n512)
n256 = 64
self.convu2 = nn.ConvTranspose1d(n512, n256, 4, 4, 0)
self.bnu2 = nn.BatchNorm1d(n256)
n128 = 32
self.convu3 = nn.ConvTranspose1d(n256, n128, 4, 4, 0)
self.bnu3 = nn.BatchNorm1d(n128)
n64 = 16
self.conv1 = nn.Conv1d(n128, n64, 3, 1, 1)
self.bn1 = nn.BatchNorm1d(n64)
self.convw1 = nn.Conv1d(n64, n64, 3, 1, 1)
self.bnw1 = nn.BatchNorm1d(n64)
self.convw2 = nn.Conv1d(n64, n64, 3, 1, 1)
self.bnw2 = nn.BatchNorm1d(n64)
self.convw3 = nn.Conv1d(n64, n_wires, 1, 1, 0, bias=False)
self.convp1 = nn.Conv1d(n64, n64, 3, 1, 1)
self.bnp1 = nn.BatchNorm1d(n64)
self.convp2 = nn.Conv1d(n64, n64, 3, 1, 1)
self.bnp2 = nn.BatchNorm1d(n64)
self.convp3 = nn.Conv1d(n64, n_features, 1, 1, 0)
self.out = nn.Tanh()
def forward(self, z, wire_to_xy):
# z: random point in latent space
x = self.act(self.bn0(self.lin0(z).view(-1, self.n512, self.seq_len // 64)))
x = self.act(self.bnu1(self.convu1(x)))
x = self.act(self.bnu2(self.convu2(x)))
x = self.act(self.bnu3(self.convu3(x)))
x = self.act(self.bn1(self.conv1(x)))
w = self.act(self.bnw1(self.convw1(x)))
w = self.act(self.bnw2(self.convw2(w)))
w = self.convw3(w)
wg = F.gumbel_softmax(w, dim=1, hard=True, tau=1.0)
#xy = torch.tensordot(wg, wire_to_xy, dims=[[1],[1]]).permute(0,2,1)
p = self.act(self.bnp1(self.convp1(x)))
p = self.act(self.bnp2(self.convp2(p)))
p = self.convp3(p)
#return torch.cat([self.out(p), xy], dim=1), wg
return self.out(p), wg
class Disc(nn.Module):
def __init__(self, ndf, seq_len, encoded_dim):
super().__init__()
self.version = __version__
# (B, n_features, 256)
self.act = nn.LeakyReLU(0.2)
class DBlock(nn.Module):
def __init__(self, channels):
super().__init__()
self.conv1 = nn.utils.spectral_norm(nn.Conv1d(channels, channels, 3, 1, 1))
self.conv2 = nn.utils.spectral_norm(nn.Conv1d(channels, channels, 3, 1, 1))
self.act = nn.LeakyReLU(0.2)
def forward(self, x):
y = self.conv1(self.act(x))
y = x + self.conv2(self.act(y))
y = nn.AvgPool1d(2)(y)
return y
n64 = 8
emb_dim=4
n192 = n64 * 2
#self.convpxy = nn.utils.spectral_norm(nn.Conv1d(n_features+geom_dim, n64, 1, 1, 0))
self.wemb = nn.utils.spectral_norm(nn.Conv1d(geom_dim + n_wires,
emb_dim, 1, 1, 0, bias=False))
#self.convw1 = nn.utils.spectral_norm(nn.Conv1d(emb_dim, n64, 3, 1, 1))
#self.convw2 = nn.utils.spectral_norm(nn.Conv1d(n64, n64, 3, 1, 1))
#self.convw3 = nn.utils.spectral_norm(nn.Conv1d(n64, n64, 3, 1, 1))
#self.convp1 = nn.utils.spectral_norm(nn.Conv1d(n_features, n64, 3, 1, 1))
#self.convp2 = nn.utils.spectral_norm(nn.Conv1d(n64, n64, 3, 1, 1))
#self.convp3 = nn.utils.spectral_norm(nn.Conv1d(n64, n64, 3, 1, 1))
self.pemb = nn.utils.spectral_norm(nn.Conv1d(n_features, emb_dim, 1, 1, 0, bias=False))
self.memb = nn.utils.spectral_norm(nn.Conv1d(emb_dim*2, emb_dim*4, 1, 1, 0, bias=False))
self.conv0 = nn.utils.spectral_norm(nn.Conv1d(emb_dim*4, n192, 3, 1, 1))
n256 = n64 * 4
self.conv1 = nn.utils.spectral_norm(nn.Conv1d(n192, n256, 3, 2, 1))
n512 = n256 * 2
self.conv2 = nn.utils.spectral_norm(nn.Conv1d(n256, n512, 3, 2, 1))
self.conv3 = nn.utils.spectral_norm(nn.Conv1d(n512, n512, 3, 2, 1))
self.conv4 = nn.utils.spectral_norm(nn.Conv1d(n512, n512, 3, 2, 1))
self.conv5 = nn.utils.spectral_norm(nn.Conv1d(n512, n512, 3, 2, 1))
#self.db1 = DBlock(n256)
#self.db2 = DBlock(n256)
#self.db3 = DBlock(n256)
#self.conv2 = nn.Conv1d(256, 512, 3, 2, 1)
#self.conv3 = nn.Conv1d(512, 1024, 3, 2, 1)
#self.conv4 = nn.Conv1d(1024, 2048, 3, 2, 1)
#self.lin0 = nn.Linear(256 * seq_len // 1, 1, bias=True)
#self.lin0 = nn.Linear(seq_len//4*512, 1)
#self.convf = nn.utils.spectral_norm(nn.Conv1d(n192, 1, 3, 1, 1, padding_mode='circular'))
self.lin0 = nn.utils.spectral_norm(nn.Linear(n512, 1))
self.out = nn.Identity()
def forward(self, x_):
# x_ is concatenated tensor of p_ and w_, shape (batch, features+n_wires, seq_len)
# p_ shape is (batch, features, seq_len),
# w_ is AE-encoded wire (batch, encoded_dim, seq_len)
seq_len = x_.shape[2]
x = x_
#dist = ((xy - nn.ConstantPad1d((1, 0), 0.0)(xy[:,:,:-1]))**2).sum(dim=1).unsqueeze(1)
p = x[:,:n_features]
xy = x[:,n_features:n_features+geom_dim]
wg = x[:,n_features+geom_dim:]
pxy = x[:,:n_features+geom_dim]
p = p
xy = xy
wg = wg
#print('mean %.2e %.2e' % (p.mean().item(), xy.mean().item()))
#print('std %.2e %.2e' % (p.std().item(), xy.std().item()))
w = self.wemb(torch.cat([wg, xy], dim=1))
p = self.pemb(p)
x = self.memb(torch.tanh(torch.cat([p, w], dim=1)))
#x = torch.cat([p, w], dim=1)
x = self.act(self.conv0(x))
#wg = (wg - wg.mean().detach()) / wg.std(1).mean().detach() * p.std(1).mean().detach()
#print('P VAR %.2e' % p.var(1).mean().item())
#print('XY VAR %.2e' % xy.var(1).mean().item())
#print('WG VAR %.2e' % wg.var(1).mean().item())
#wg.register_hook(hook)
#print(wg.argmax(dim=1)[0,0])
#xy = self.wireproj(wg, wire_to_xy)
#print(xy.shape)
#print(xy[0,:,0])
#x = self.act(self.conv0(pxy))
#pxy = self.convpxy(pxy)
#w = self.convw(wg)
#pxy = self.act(self.convpxy(pxy))
#xy = self.act(self.convxy2(xy))
#xy = self.act(self.convxy3(xy))
#xy = self.act(self.convxy4(xy))
#p = self.act(self.convp2(p))
#w = self.act(self.convw1(wg))
#w = self.act(self.convw2(w))
#w = self.act(self.convw3(w))
#w = self.act(self.convw4(w))
#p = self.convp(x)
#xy = self.convxy(xy
#x = torch.cat([pxy, w], dim=1)
x = self.act(self.conv1(x))
x = self.act(self.conv2(x))
x = self.act(self.conv3(x))
x = self.act(self.conv4(x))
x = self.act(self.conv5(x))
#self.db2.convd.weight.register_hook(printhook)
#x = self.db1(x)
#x = self.db2(x)
#x = self.act(self.db3(x))
x = self.lin0(x.mean(2))
#x = self.convf(x).mean(2)
return self.out(x)#.squeeze(1)
class VAE(nn.Module):
def __init__(self, encoded_dim):
super().__init__()
class Enc(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.act = nn.LeakyReLU(0.2)
self.lin1 = nn.Linear(n_wires, hidden_size)
self.lin2 = nn.Linear(hidden_size, encoded_dim)
self.out = nn.Tanh()
def forward(self, x):
x = self.act(self.lin1(x))
return self.out(self.lin2(x))
class Dec(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.act = nn.ReLU()
self.lin1 = nn.Linear(encoded_dim, hidden_size)
self.lin2 = nn.Linear(hidden_size, n_wires)
def forward(self, x):
x = self.act(self.lin1(x))
return self.lin2(x)
self.enc_net = Enc(512)
self.dec_net = Dec(512)
def enc(self, x):
return self.enc_net(x.permute(0, 2, 1)).permute(0,2,1)
def dec(self, x):
return self.dec_net(x.permute(0, 2, 1)).permute(0,2,1)
def forward(self, x):
y = self.dec_net(self.enc_net(x))
return y
def get_n_params(model):
return sum(p.reshape(-1).shape[0] for p in model.parameters())
| [
"[email protected]"
]
| |
93de096df8ef3defb9087ea670888bea064f46de | fa82dad9e83206d4630a55141bf44f50cbf0c3a8 | /day1_python/01_python200_src/093.py | d62211e665cf90be84d1cdc4d581519076449edf | []
| no_license | jsh2333/pyml | 8f8c53a43af23b8490b25f35f28d85f1087df28d | 157dfa7cc2f1458f12e451691a994ac6ef138cab | refs/heads/master | 2021-03-27T22:26:38.254206 | 2020-04-26T06:35:11 | 2020-04-26T06:35:11 | 249,114,580 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | url = 'http://www.naver.com/news/today=20160831'
log = 'name:홍길동 age:17 sex:남자 nation:조선'
ret1 = url.split('/')
print(ret1)
ret2 = log.split()
for data in ret2:
d1, d2 = data.split(':')
print('%s -> %s' %(d1, d2))
| [
"[email protected]"
]
| |
dbd174bfddafd6ac8f11846488ad2bd44d95b29e | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p04044/s849053305.py | 0b1342b80952e0cfcb0dc7796192d0f3752b6f68 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 374 | py | # row = [int(x) for x in input().rstrip().split(" ")]
# n = int(input().rstrip())
# s = input().rstrip()
def resolve():
import sys
input = sys.stdin.readline
n, l = [int(x) for x in input().rstrip().split(" ")]
s_list = [input().rstrip() for _ in range(n)]
s_list = sorted(s_list)
print("".join(s_list))
if __name__ == "__main__":
resolve()
| [
"[email protected]"
]
| |
6ccf0ca23a683d99e9f431477837de49ec028d4f | 9222114c0b39007eb1af715cf18fc95ff282b38c | /problems/415. Add Strings/1 - Backtracking.py | a96022d06c9d0b76ef3f2cbc3458d4236d83b04c | []
| no_license | Vasilic-Maxim/LeetCode-Problems | 1a2a09edca6489a349e5d69d087279630cff157d | 359f3b78da90c41c7e42e5c9e13d49b4fc67fe41 | refs/heads/master | 2021-07-10T22:03:29.327658 | 2021-06-07T12:42:52 | 2021-06-07T12:42:52 | 246,826,450 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 472 | py | from itertools import zip_longest
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
zero = ord("0")
carry = 0
result = []
for n1, n2 in zip_longest(reversed(num1), reversed(num2)):
n1 = 0 if n1 is None else ord(n1) - zero
n2 = 0 if n2 is None else ord(n2) - zero
carry, mod = divmod(n1 + n2 + carry, 10)
result.append(str(mod))
return "".join(result).reverse()
| [
"[email protected]"
]
| |
ee91dee71252520a9168a9f851ead2970876ff66 | 45bbb2d050c5e6acf85a2180f5c27d415a994185 | /KerasCode/mlp.py | a0e6547bf19f7e6756d192aad9932e15d4cf696d | []
| no_license | afcarl/dl_code | e25f07e9e7eba59d83ea0ddb90637bce605b35c9 | 2b0423673faba67f6ad653c04b6cd045a66f5e80 | refs/heads/master | 2020-03-22T09:59:01.003729 | 2017-05-17T02:34:20 | 2017-05-17T02:34:20 | 139,873,303 | 1 | 0 | null | 2018-07-05T16:11:15 | 2018-07-05T16:11:14 | null | UTF-8 | Python | false | false | 764 | py | from keras.models import Sequential
from keras.layers import Dense
import numpy
import os
import TheanoCode
# theano.config.device = 'gpu'
seed = 7
numpy.random.seed(seed)
data_path = "/".join([os.getcwd(), "../Data/pima-indians-diabetes.data.txt"])
dataset = numpy.loadtxt(data_path, delimiter=",")
X = dataset[:,0:8]
Y = dataset[:,8]
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, Y, nb_epoch=150, batch_size=10)
scores = model.evaluate(X, Y)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) | [
"[email protected]"
]
| |
91cebbe901bc6befd8740948246c41c36841c760 | d7016f69993570a1c55974582cda899ff70907ec | /sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2022_10_01_preview/operations/_application_group_operations.py | d525932cebd7a394c442f8b7de0dd59bdceb6620 | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
]
| permissive | kurtzeborn/azure-sdk-for-python | 51ca636ad26ca51bc0c9e6865332781787e6f882 | b23e71b289c71f179b9cf9b8c75b1922833a542a | refs/heads/main | 2023-03-21T14:19:50.299852 | 2023-02-15T13:30:47 | 2023-02-15T13:30:47 | 157,927,277 | 0 | 0 | MIT | 2022-07-19T08:05:23 | 2018-11-16T22:15:30 | Python | UTF-8 | Python | false | false | 26,182 | py | # pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import sys
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
from ..._serialization import Serializer
from .._vendor import _convert_request, _format_url_section
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
def build_list_by_namespace_request(
resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1
),
"namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
def build_create_or_update_application_group_request(
resource_group_name: str, namespace_name: str, application_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1
),
"namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6),
"applicationGroupName": _SERIALIZER.url(
"application_group_name", application_group_name, "str", max_length=256, min_length=1
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)
def build_delete_request(
resource_group_name: str, namespace_name: str, application_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1
),
"namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6),
"applicationGroupName": _SERIALIZER.url(
"application_group_name", application_group_name, "str", max_length=256, min_length=1
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_get_request(
resource_group_name: str, namespace_name: str, application_group_name: str, subscription_id: str, **kwargs: Any
) -> HttpRequest:
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
accept = _headers.pop("Accept", "application/json")
# Construct URL
_url = kwargs.pop(
"template_url",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}",
) # pylint: disable=line-too-long
path_format_arguments = {
"resourceGroupName": _SERIALIZER.url(
"resource_group_name", resource_group_name, "str", max_length=90, min_length=1
),
"namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6),
"applicationGroupName": _SERIALIZER.url(
"application_group_name", application_group_name, "str", max_length=256, min_length=1
),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
}
_url: str = _format_url_section(_url, **path_format_arguments) # type: ignore
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)
class ApplicationGroupOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.eventhub.v2022_10_01_preview.EventHubManagementClient`'s
:attr:`application_group` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_by_namespace(
self, resource_group_name: str, namespace_name: str, **kwargs: Any
) -> Iterable["_models.ApplicationGroup"]:
"""Gets a list of application groups for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ApplicationGroup or the result of cls(response)
:rtype:
~azure.core.paging.ItemPaged[~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
cls: ClsType[_models.ApplicationGroupListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_namespace_request(
resource_group_name=resource_group_name,
namespace_name=namespace_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_namespace.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
def extract_data(pipeline_response):
deserialized = self._deserialize("ApplicationGroupListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(get_next, extract_data)
list_by_namespace.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups"
}
@overload
def create_or_update_application_group(
self,
resource_group_name: str,
namespace_name: str,
application_group_name: str,
parameters: _models.ApplicationGroup,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ApplicationGroup:
"""Creates or updates an ApplicationGroup for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:param application_group_name: The Application Group name. Required.
:type application_group_name: str
:param parameters: The ApplicationGroup. Required.
:type parameters: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ApplicationGroup or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
def create_or_update_application_group(
self,
resource_group_name: str,
namespace_name: str,
application_group_name: str,
parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ApplicationGroup:
"""Creates or updates an ApplicationGroup for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:param application_group_name: The Application Group name. Required.
:type application_group_name: str
:param parameters: The ApplicationGroup. Required.
:type parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ApplicationGroup or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace
def create_or_update_application_group(
self,
resource_group_name: str,
namespace_name: str,
application_group_name: str,
parameters: Union[_models.ApplicationGroup, IO],
**kwargs: Any
) -> _models.ApplicationGroup:
"""Creates or updates an ApplicationGroup for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:param application_group_name: The Application Group name. Required.
:type application_group_name: str
:param parameters: The ApplicationGroup. Is either a ApplicationGroup type or a IO type.
Required.
:type parameters: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ApplicationGroup or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ApplicationGroup] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(parameters, (IO, bytes)):
_content = parameters
else:
_json = self._serialize.body(parameters, "ApplicationGroup")
request = build_create_or_update_application_group_request(
resource_group_name=resource_group_name,
namespace_name=namespace_name,
application_group_name=application_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.create_or_update_application_group.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ApplicationGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_or_update_application_group.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}"
}
@distributed_trace
def delete( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, namespace_name: str, application_group_name: str, **kwargs: Any
) -> None:
"""Deletes an ApplicationGroup for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:param application_group_name: The Application Group name. Required.
:type application_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_request(
resource_group_name=resource_group_name,
namespace_name=namespace_name,
application_group_name=application_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}"
}
@distributed_trace
def get(
self, resource_group_name: str, namespace_name: str, application_group_name: str, **kwargs: Any
) -> _models.ApplicationGroup:
"""Gets an ApplicationGroup for a Namespace.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param namespace_name: The Namespace name. Required.
:type namespace_name: str
:param application_group_name: The Application Group name. Required.
:type application_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ApplicationGroup or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2022_10_01_preview.models.ApplicationGroup
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2022-10-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2022-10-01-preview")
)
cls: ClsType[_models.ApplicationGroup] = kwargs.pop("cls", None)
request = build_get_request(
resource_group_name=resource_group_name,
namespace_name=namespace_name,
application_group_name=application_group_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ApplicationGroup", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/applicationGroups/{applicationGroupName}"
}
| [
"[email protected]"
]
| |
80e000c9d12a4180c7aa61e175235c04a2c00eb6 | a1a43879a2da109d9fe8d9a75f4fda73f0d7166b | /api/tests_v2/zeros_like.py | 52f67cbec0a4d72971c03445e047433928e0e79a | []
| no_license | PaddlePaddle/benchmark | a3ed62841598d079529c7440367385fc883835aa | f0e0a303e9af29abb2e86e8918c102b152a37883 | refs/heads/master | 2023-09-01T13:11:09.892877 | 2023-08-21T09:32:49 | 2023-08-21T09:32:49 | 173,032,424 | 78 | 352 | null | 2023-09-14T05:13:08 | 2019-02-28T03:14:16 | Python | UTF-8 | Python | false | false | 1,332 | py | # Copyright (c) 2020 PaddlePaddle Authors. 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.
from common_import import *
class PDZerosLike(PaddleAPIBenchmarkBase):
def build_program(self, config):
data = self.variable(
name='data', shape=config.x_shape, dtype=config.x_dtype)
result = paddle.zeros_like(x=data)
self.feed_vars = [data]
self.fetch_vars = [result]
class TFZerosLike(TensorflowAPIBenchmarkBase):
def build_graph(self, config):
data = self.variable(
name='data', shape=config.x_shape, dtype=config.x_dtype)
result = tf.zeros_like(input=data)
self.feed_list = [data]
self.fetch_list = [result]
if __name__ == '__main__':
test_main(PDZerosLike(), TFZerosLike(), config=APIConfig("zeros_like"))
| [
"[email protected]"
]
| |
1b27e6f24cd077a7f67416dc90786e02d2bbef4a | 78337fc3cd0d3be2307f42c4c7ae51bedb1d468b | /opengever/base/subscribers.py | 9c4dbb486292e6ee55509845467899ce58b5da03 | []
| no_license | sensecs1/opengever.core | af19bafce4491f3c648682783fc1c918dc1f5944 | 0666e86fade7835c98a118fa6319071f859fcdb5 | refs/heads/master | 2021-01-18T07:44:56.965935 | 2015-03-13T15:26:30 | 2015-03-13T15:26:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 762 | py | from five import grok
from OFS.interfaces import IObjectClonedEvent
from opengever.base import _
from plone.dexterity.interfaces import IDexterityContent
from zope.component.hooks import getSite
@grok.subscribe(IDexterityContent, IObjectClonedEvent)
def create_initial_version(obj, event):
"""When a object was copied, create an initial version.
"""
portal = getSite()
pr = portal.portal_repository
history = pr.getHistory(obj)
if history is not None and not len(history) > 0:
comment = _(u'label_initial_version_copied',
default="Initial version (document copied)")
# Create an initial version
pr._recursiveSave(obj, {}, pr._prepareSysMetadata(comment),
autoapply=pr.autoapply)
| [
"[email protected]"
]
| |
99f3a49b00e82b89201fee4a187fdd21f2dc6a13 | 20b6cdf48fab05027fa65cceb7812c0f4cd784f8 | /epidemics/utils/nested.py | 7e9cb281cbbb21fb7f806c49d04994c46f443701 | []
| no_license | cselab/covid19 | f260db9633ae77cd6857616b9a19168d647166fd | a867fed2a3cf7681f38fa9701b85a90400b1ad62 | refs/heads/master | 2023-02-07T14:55:30.703399 | 2020-10-05T09:12:18 | 2020-10-05T09:12:18 | 251,288,782 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,925 | py | import numpy as np
from multiprocessing import Pool
import pickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class WorkerPool(object):
def __init__(self, cores):
self.pool = Pool(processes=cores)
self.size = cores
def map(self, function, tasks):
return self.pool.map(function, tasks)
def priorTransformFromJs(p,js):
pt = np.zeros(len(p))
for idx in range(len(p)):
lb = js['Distributions'][idx]['Minimum']
ub = js['Distributions'][idx]['Maximum']
pt[idx] = lb+p[idx]*(ub-lb)
return pt
def resample_equal_with_idx(samples, weights, rstate=None):
if rstate is None:
rstate = np.random
if abs(np.sum(weights) - 1.) > 1e-9: # same tol as in np.random.choice.
# Guarantee that the weights will sum to 1.
warnings.warn("Weights do not sum to 1 and have been renormalized.")
weights = np.array(weights) / np.sum(weights)
# Make N subdivisions and choose positions with a consistent random offset.
nsamples = len(weights)
positions = (rstate.random() + np.arange(nsamples)) / nsamples
# Resample the data.
idx = np.zeros(nsamples, dtype=np.int)
cumulative_sum = np.cumsum(weights)
i, j = 0, 0
while i < nsamples:
if positions[i] < cumulative_sum[j]:
idx[i] = j
i += 1
else:
j += 1
return samples[idx], idx
def getPosteriorFromResult(result):
weights = np.exp(result.logwt - result.logz[-1]) # normalized weights
samples, idx = resample_equal_with_idx(result.samples, weights)
return samples, idx
# Plot histogram of sampes in diagonal
def plot_histogram(ax, theta):
dim = theta.shape[1]
num_bins = 30
for i in range(dim):
if (dim == 1):
ax_loc = ax
else:
ax_loc = ax[i, i]
hist, bins, _ = ax_loc.hist(
theta[:, i], num_bins, density=True, color='lightgreen', ec='black')
if i == 0:
# Rescale hist to scale of theta -> get correct axis titles
widths = np.diff(bins)
if (dim > 1):
hist = hist / np.max(hist) * (
ax_loc.get_xlim()[1] - ax_loc.get_xlim()[0])
bottom = ax_loc.get_xlim()[0]
ax_loc.cla()
ax_loc.bar(
bins[:-1],
hist,
widths,
color='lightgreen',
ec='black',
bottom=bottom)
ax_loc.set_ylim(ax_loc.get_xlim())
ax_loc.set_xticklabels([])
else:
ax_loc.cla()
ax_loc.bar(bins[:-1], hist, widths, color='lightgreen', ec='black')
elif i == theta.shape[1] - 1:
ax_loc.set_yticklabels([])
else:
ax_loc.set_xticklabels([])
ax_loc.set_yticklabels([])
ax_loc.tick_params(axis='both', which='both', length=0)
#Plot scatter plot in upper triangle of figure
def plot_upper_triangle(ax, theta, lik):
dim = theta.shape[1]
if (dim == 1):
return
for i in range(dim):
for j in range(i + 1, dim):
if lik:
ax[i, j].scatter(
theta[:, j], theta[:, i], marker='o', s=3, alpha=0.5, c=lik)
else:
ax[i, j].plot(theta[:, j], theta[:, i], marker='.', s=1, alpha=0.5)
ax[i, j].set_xticklabels([])
ax[i, j].set_yticklabels([])
ax[i, j].grid(b=True, which='both')
#Plot 2d histogram in lower triangle of figure
def plot_lower_triangle(ax, theta):
dim = theta.shape[1]
if (dim == 1):
return
for i in range(dim):
for j in range(i):
# returns bin values, bin edges and bin edges
H, xe, ye = np.histogram2d(theta[:, j], theta[:, i], 10, density=True)
# plot and interpolate data
ax[i, j].imshow(
H.T,
aspect="auto",
interpolation='spline16',
origin='lower',
extent=np.hstack((ax[j, j].get_xlim(), ax[i, i].get_xlim())),
cmap=plt.get_cmap('jet'))
if i < theta.shape[1] - 1:
ax[i, j].set_xticklabels([])
if j > 0:
ax[i, j].set_yticklabels([])
def plotNetsedResult(result, savepath=None):
samples, idx = getPosteriorFromResult(result)
numdim = len(samples[0])
numentries = len(samples)
llk = (result.logl[idx]).tolist()
fig, ax = plt.subplots(numdim, numdim, figsize=(8, 8))
samplesTmp = np.reshape(samples, (numentries, numdim))
plt.suptitle(
'{0} Plotter - \nNumber of Samples {1}'.format(
str("Nested Sampling"), str(numentries)).strip(),
fontweight='bold',
fontsize=12)
plot_histogram(ax, samplesTmp)
plot_upper_triangle(ax, samplesTmp, llk)
plot_lower_triangle(ax, samplesTmp)
# for i in range(numdim):
# ax[i, 0].set_ylabel(genList[idx]['Variables'][i]['Name'])
# ax[-1, i].set_xlabel(genList[idx]['Variables'][i]['Name'])
if (savepath==None):
print("TEST")
plt.show()
else:
plt.savefig(savepath)
| [
"[email protected]"
]
| |
ee6666217155863ba3f1a1250154627c6bc7f1d6 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_088/ch119_2020_09_19_21_49_34_845287.py | a275184e3182156e1d1a024a8eccecd18f2097b8 | []
| no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 173 | py | import math
def calcula_euler(x,n):
contador=2
inicio=1+x
while(soma<n):
inicio+=x**contador/math.factorial(contador)
contador+=1
return soma | [
"[email protected]"
]
| |
df81a6c8727317f97f6d51e6bdccbaa900d8640b | d4d2e656c5eb5a92165b5040059c1dc49cf54241 | /deprecated.py | e23531bcdb68b8a7f2a6657ded7c4af1a8ba3c3f | []
| no_license | ctmakro/lineopt | 9ee525fa525c4b0eba8d5c76cbc5d03ee6c5e4fe | e3eb06c858fa020b7688f6027e61c53e9ec5006b | refs/heads/master | 2020-03-24T03:40:56.324513 | 2019-01-07T11:01:23 | 2019-01-07T11:01:23 | 142,428,487 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,568 | py | import cv2
from cv2tools import vis,filt
import numpy as np
from scipy.optimize import minimize
# class that estimates pyramid loss between 2 images.
class PyramidLoss:
@staticmethod
def build_pyramid(img):
a = [img]
for i in range(5):
a.append(cv2.pyrDown(a[-1]))
return a
@staticmethod
def prepare(target):
# assume target is of float32.
# returns dict as temp storage for future computations.
return PyramidLoss.build_pyramid(target)
@staticmethod
def compare(incoming, prepared):
# assume incoming is of 8bit.
incoming_pyramid = \
PyramidLoss.build_pyramid((incoming/255.).astype('float32'))
target_pyramid = prepared
return sum([np.square((c-t)).mean()
for c,t in zip(incoming_pyramid, target_pyramid)])
# environment that optimizes lines to match an image.
class LineEnv:
def __init__(self):
self.target_pyramid = None
self.loss_metric = PyramidLoss
# load image as target
def load_image(self, path, is_filename=True, scale=1.0, target_width=None):
if is_filename:
# read image from file
orig = cv2.imread(path)
assert orig is not None
else:
# use in memory image
orig = path
if target_width is not None:
scale = target_width / orig.shape[1]
self.orig = orig
self.scale = scale
# set expected output h and w
self.orig_h, self.orig_w = orig.shape[0:2]
self.target_h, self.target_w = int(self.orig_h*scale), int(self.orig_w*scale)
self.orig_hw = [self.orig_h, self.orig_w]
self.target_hw = [self.target_h, self.target_w]
# resize
target = vis.resize_perfect(self.orig, self.target_h, self.target_w, cubic=True, a=3)
# log
print('loading image {}, scale:{:2.2f}, orig[{}x{}], now[{}x{}]'.format(
path, scale,
self.orig_w, self.orig_h, self.target_w, self.target_h))
# floatify
target = (target/255.).astype('float32')
# b/w
target = (target[:,:,1:2] + target[:,:,2:3]) *.5
# clip to normal range
target = np.clip(target*1+0.1, 0, 1)
self.target = target
# loss metric precomputation
self.precomputated = self.loss_metric.prepare(self.target)
def compare_with_target(self, img):
return self.loss_metric.compare(img, self.precomputated)
def get_blank_canvas(self):
return np.ones((self.target_h, self.target_w, 1), dtype='uint8')*255
def init_segments(self):
num_segs=60
self.segments = []
self.indices = []
k = 0
for i in range(num_segs):
# self.add(Connected(stochastic_points_that_connects() * w))
sptc = stochastic_points_that_connects()
self.segments.append(sptc * max(self.target_h, self.target_w))
k += len(sptc)
self.indices.append(k)
self.indices = self.indices[:-1]
assert len(self.indices) == num_segs - 1
def draw_on(self, canvas):
cv2.polylines(
canvas,
[(points*64).astype(np.int32) for points in self.segments],
isClosed = False,
color=(0, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
shift = 6,
)
def calculate_loss(self):
blank = self.get_blank_canvas()
self.draw_on(blank)
return self.compare_with_target(blank)
# into vector that could be optimized
def to_vec(self):
a = np.vstack(self.segments)
return a.flatten()
def from_vec(self, v):
vc = v.copy()
vc.shape = len(vc)//2, 2
self.segments = np.split(vc, self.indices, axis=0)
def stochastic_points_that_connects():
# rule:
# 1. sample 2 endpoint
# 2. find their middlepoint
# 3. repeat using the 2 endpoints of each of the 2 new segments.
# minimum dist between two connected points
mindist = 0.05
# given two point, return their centerpoint.
def get_stochastic_centerpoint(p1, p2):
c = (p1+p2)*.5
# dist = np.linalg.norm(p1-p2)
dist = np.sqrt(np.sum(np.square(p1-p2)))
if dist < mindist:
return None
# if two point already very close to each other,
# don't insert a centerpoint between them
else:
c += np.random.normal(loc=0, scale=0.2*dist, size=c.shape)
return c
# insert a new point between every two previously connected points.
def insert_between(points):
newpoints = []
for i in range(len(points)-1):
p1 = points[i]
p2 = points[i+1]
newpoints.append(p1)
cp = get_stochastic_centerpoint(p1, p2)
if cp is not None:
newpoints.append(cp)
newpoints.append(p2)
return newpoints
while 1:
points = [np.random.uniform(0,1,size=(2,)) for i in range(2)]
for i in range(5):
points = insert_between(points)
# if the number of points included is larger than 4
# we can return this as a legit polyline object
if len(points)>4:
return np.array(points)
# otherwise we try again
else:
continue
# a group of points connected by lines
class Connected:
def __init__(self, points=None):
self.points = points
def draw_on(self, canvas):
cv2.polylines(
canvas,
[(self.points*16).astype(np.int32)],
isClosed = False,
color=(0, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
shift = 4,
)
# penalties of various forms.
def calc_penalty(self):
# segment direction penalty: if connecting segments are facing different direction, give penalty.
deltas = self.points[:len(self.points)-1] - self.points[1:]
sq_norms = np.square(deltas[:,0]) + np.square(deltas[:,1])
# # normalize the vectors.
# norms = np.linalg.norm(deltas,axis=1,keepdims=True)
# deltas = deltas / (norms + 1e-2)
#
# dot_products = np.sum(
# deltas[:len(deltas)-1] * deltas[1:],
# axis=1,
# )
#
# # print(deltas.shape)
# # print(dot_products.shape)
#
# limited = np.maximum(-dot_products, 0)
# angular_pen = limited.mean()
min_length = 2
max_length = w
clipped = np.clip(sq_norms, min_length*min_length, max_length*max_length)
pen = np.mean(np.abs(sq_norms - clipped))
return pen
length_pen = np.maximum(min_length - sq_norms, 0).mean()
length_pen += np.maximum(sq_norms - max_length, 0).mean()
return angular_pen + length_pen
class ManyConnected:
def __init__(self, w=None, num_segs=60, iscopy=False):
# w = width, indicate the range of coordinates of the lines
self.list = []
self.clist = []
self.indices = []
if not iscopy:
k = 0
for i in range(num_segs):
# self.add(Connected(stochastic_points_that_connects() * w))
sptc = stochastic_points_that_connects()
self.list.append(sptc * w)
k += len(sptc)
self.indices.append(k)
self.indices = self.indices[:-1]
assert len(self.indices) == num_segs - 1
def add(self, connected):
self.list.append(connected.points)
self.clist.append(connected)
def draw_on(self, canvas):
cv2.polylines(
canvas,
[(points*64).astype(np.int32) for points in self.list],
isClosed = False,
color=(0, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
shift = 6,
)
# into vector that could be optimized
def to_vec(self):
a = np.vstack(self.list)
return a.flatten()
def from_vec(self, v):
vc = v.copy()
vc.shape = len(vc)//2, 2
self.list = np.split(vc, self.indices, axis=0)
# penalties of various forms.
def calc_penalty(self):
return sum([c.calc_penalty() for c in self.clist]) / len(self.clist)
# canvas width
w = 256
def newcanvas():
return np.ones((w,w,1), dtype='uint8')*255
mc = ManyConnected(w=w)
v = mc.to_vec()
print(type(v), v.shape)
mc.from_vec(v)
target = cv2.imread('hjt.jpg')
target = vis.resize_perfect(target, w, w, cubic=True, a=3)
target = (target/255.).astype('float32')
target = (target[:,:,1:2] + target[:,:,2:3]) *.5
target = np.clip(target*1+0.1, 0, 1)
def pyramid(img):
a = [img]
for i in range(5):
a.append(cv2.pyrDown(a[-1]))
return a
target_pyr = pyramid(target)
def multiscale_loss(canvas):
canvas_pyr = pyramid((canvas/255.).astype('float32'))
return sum([np.square((c-t)).mean() for c,t in zip(canvas_pyr, target_pyr)])
def singlescale_loss(canvas):
return np.square(canvas.astype('float32')/255. - target).mean()
def to_optimize(v, indices = None):
if indices is not None:
mc.indices = indices
mc.from_vec(v)
nc = newcanvas()
mc.draw_on(nc)
ml = multiscale_loss(nc)
# sl = singlescale_loss(nc)
# pen = mc.calc_penalty()
pen = 0
return ml
# return sl + pen * 0.001
if __name__ == '__main__':
from llll import PoolSlave
PoolSlave(to_optimize)
| [
"[email protected]"
]
| |
073c1c64a092fcea66e7e1774e63ffd5b6ae4e58 | 388d81ea4354877326a772bcaa54d276cee81283 | /Data Structures/1-D/Help Jarvis!.py | bc928fe401aa39cd1cc37d252fc1636df73cb52a | []
| no_license | anshumanairy/Hacker-Earth | 61a67fb5e6ce3ef4068ad904480386bf7095f1f7 | 9c3ed575eb7007b055cb149ff644a91f287d4de7 | refs/heads/master | 2022-11-28T21:48:38.450999 | 2020-08-08T20:45:49 | 2020-08-08T20:45:49 | 285,909,494 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 334 | py | def func():
T=int(input())
for i in range(T):
list1=list(input())
list1.sort()
check=1
for j in range(len(list1)-1):
if(int(list1[j+1])!=int(list1[j])+1):
check=0
print('NO')
break
if(check==1):
print('YES')
func() | [
"[email protected]"
]
| |
9cdde1ad8c49b5c7e5c0f70037b8e64f9ba08427 | 228de37ad02ee9af51a208ad3287224af1f2c472 | /app/travel/models/city_information.py | 6d19042d174b2b9a6fca2575bc78d656d1a06ecf | []
| no_license | kahee/MySmallTrip | cb0b0a9afdee009f3b4055af92af0bc5ec50f0cd | 75e1bf32993f137e70360f6aa3b22904d61bd24c | refs/heads/master | 2022-12-11T18:57:12.494011 | 2018-09-02T09:12:59 | 2018-09-02T09:12:59 | 130,799,032 | 1 | 0 | null | 2022-12-08T01:01:50 | 2018-04-24T05:08:26 | Python | UTF-8 | Python | false | false | 2,034 | py | import magic
from .product_base import ProductBase
from django.core.files import File
from django.db import models
from io import BytesIO
from PIL import Image
class CityInformation(ProductBase):
name = models.CharField('도시명', max_length=20)
continent = models.CharField('대륙', max_length=20)
nationality = models.CharField('나라', max_length=20)
city_image = models.ImageField('도시이미지', upload_to='city')
city_image_thumbnail = models.ImageField(upload_to='city-thumbnail')
def save(self, *args, **kwargs):
self._save_thumbnail_process()
super().save(*args, **kwargs)
def _save_thumbnail_process(self):
"""
save() 메서드 실행 도중 img_profile필드의 썸네일 생성에 관한 로직
:return:
"""
if self.city_image:
# 이미지파일의 이름과 확장자를 가져옴
full_name = self.city_image.name.rsplit('/')[-1]
full_name_split = full_name.rsplit('.', maxsplit=1)
temp_file = BytesIO()
temp_file.write(self.city_image.read())
temp_file.seek(0)
mime_info = magic.from_buffer(temp_file.read(), mime=True)
temp_file.seek(0)
name = full_name_split[0]
ext = mime_info.split('/')[-1]
# Pillow를 사용해 이미지 파일 로드
im = Image.open(self.city_image)
# 썸네일 형태로 데이터 변경
im.thumbnail((375, 199))
# 썸네일 이미지 데이터를 가지고 있을 임시 메모리 파일 생성
temp_file = BytesIO()
# 임시 메모리 파일에 Pillow인스턴스의 내용을 기록
im.save(temp_file, ext)
# 임시 메모리파일을 Django의 File로 한번 감싸 썸네일 필드에 저장
self.city_image_thumbnail.save(f'{name}_thumbnail.{ext}', File(temp_file), save=False)
else:
self.city_image_thumbnail.delete(save=False) | [
"[email protected]"
]
| |
ccd5157c5b4c9a6d812fe92d0c2ef85a5cdc3286 | c78f01652444caa083ca75211bae6903d98363cb | /devel/.private/hector_mapping/lib/python2.7/dist-packages/hector_mapping/msg/_HectorDebugInfo.py | 7a372d58becc1ac75f20e0ad7199a48ec033dc09 | [
"Apache-2.0"
]
| permissive | arijitnoobstar/UAVProjectileCatcher | 9179980f8095652811b69b70930f65b17fbb4901 | 3c1bed80df167192cb4b971b58c891187628142e | refs/heads/master | 2023-05-01T11:03:09.595821 | 2021-05-16T15:10:03 | 2021-05-16T15:10:03 | 341,154,017 | 19 | 7 | null | null | null | null | UTF-8 | Python | false | false | 5,561 | py | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from hector_mapping/HectorDebugInfo.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import hector_mapping.msg
class HectorDebugInfo(genpy.Message):
_md5sum = "4d33c0696c0c536f5c1447c260756674"
_type = "hector_mapping/HectorDebugInfo"
_has_header = False # flag to mark the presence of a Header object
_full_text = """HectorIterData[] iterData
================================================================================
MSG: hector_mapping/HectorIterData
float64[9] hessian
float64 conditionNum
float64 determinant
float64 conditionNum2d
float64 determinant2d
"""
__slots__ = ['iterData']
_slot_types = ['hector_mapping/HectorIterData[]']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
iterData
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(HectorDebugInfo, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.iterData is None:
self.iterData = []
else:
self.iterData = []
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
length = len(self.iterData)
buff.write(_struct_I.pack(length))
for val1 in self.iterData:
buff.write(_get_struct_9d().pack(*val1.hessian))
_x = val1
buff.write(_get_struct_4d().pack(_x.conditionNum, _x.determinant, _x.conditionNum2d, _x.determinant2d))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
if self.iterData is None:
self.iterData = None
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.iterData = []
for i in range(0, length):
val1 = hector_mapping.msg.HectorIterData()
start = end
end += 72
val1.hessian = _get_struct_9d().unpack(str[start:end])
_x = val1
start = end
end += 32
(_x.conditionNum, _x.determinant, _x.conditionNum2d, _x.determinant2d,) = _get_struct_4d().unpack(str[start:end])
self.iterData.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
length = len(self.iterData)
buff.write(_struct_I.pack(length))
for val1 in self.iterData:
buff.write(val1.hessian.tostring())
_x = val1
buff.write(_get_struct_4d().pack(_x.conditionNum, _x.determinant, _x.conditionNum2d, _x.determinant2d))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
codecs.lookup_error("rosmsg").msg_type = self._type
try:
if self.iterData is None:
self.iterData = None
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
self.iterData = []
for i in range(0, length):
val1 = hector_mapping.msg.HectorIterData()
start = end
end += 72
val1.hessian = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=9)
_x = val1
start = end
end += 32
(_x.conditionNum, _x.determinant, _x.conditionNum2d, _x.determinant2d,) = _get_struct_4d().unpack(str[start:end])
self.iterData.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
global _struct_I
return _struct_I
_struct_4d = None
def _get_struct_4d():
global _struct_4d
if _struct_4d is None:
_struct_4d = struct.Struct("<4d")
return _struct_4d
_struct_9d = None
def _get_struct_9d():
global _struct_9d
if _struct_9d is None:
_struct_9d = struct.Struct("<9d")
return _struct_9d
| [
"[email protected]"
]
| |
e293bee7a84c70a651836bf80d330077ffc03c8c | 65f8211fc33eb5f9ac1ff0d68902226ca9a58692 | /graph_algorithms/prim_list.py | 626165c26ecc2a08d4d6f6a6ddc24a40752d16f2 | []
| no_license | szarbartosz/asd-python | 46869f5699a1ef661e2df02e523af0adcddbbbda | 0130cc3dcbba6ad62e1516c98b5cbab85848d619 | refs/heads/master | 2022-12-13T19:02:53.699381 | 2020-09-11T13:29:31 | 2020-09-11T13:29:31 | 242,975,318 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,680 | py | from queue import PriorityQueue
def prim_list(G, s):
V = len(G)
Q = PriorityQueue()
visited = [False] * V
parent = [None] * V
d = [float('inf')] * V
d[s] = 0
Q.put((d[s], s))
def relax(u, v, w):
if d[v] > w:
d[v] = w
parent[v] = u
Q.put((d[v], v))
while not Q.empty():
(_, u) = Q.get()
visited[u] = True
for v in G[u]:
if not visited[v[0]]:
relax(u, v[0], v[1])
result = ['MST:']
sum = 0
for i in range(V):
if parent[i] is not None:
for j in range(len(G[i])):
if G[i][j][0] == parent[i]:
sum += G[i][j][1]
result.append('edge: ({}, {}) weight: {}'.format(parent[i], i, G[i][j][1]))
result.append('sum of weights: {}'.format(sum))
return result
G = [[(1, 4), (7, 8)],
[(0, 4), (2, 8), (7, 11)],
[(1, 8), (5, 4), (8, 2), (3, 7)],
[(2, 7), (4, 9), (5, 14)],
[(3, 9), (5, 10)],
[(3, 14), (2, 4), (6, 2), (4, 10)],
[(5, 2), (7, 1), (8, 6)],
[(6, 1), (0, 8), (1, 11), (8, 7)],
[(6, 6), (7, 7), (2, 2)]]
arr = prim_list(G, 1)
for i in range(len(arr)):
print(arr[i])
H = [[(1, 28), (5, 10)],
[(0, 28), (2, 16), (6, 14)],
[(1, 16), (3, 12)],
[(2, 12), (6, 18), (4, 22)],
[(3, 22), (6, 24), (5, 25)],
[(0, 10), (4, 25)],
[(1, 14), (3, 18), (4, 24)]]
print('\n')
arr = prim_list(H, 5)
for i in range(len(arr)):
print(arr[i])
I = [[(1, 3), (2, 1)],
[(0, 3), (2, 1)],
[(0, 1), (1, 1)]]
print('\n')
arr = prim_list(I, 0)
for i in range(len(arr)):
print(arr[i])
| [
"[email protected]"
]
| |
cb6e622957ed4c3fb52b382cdca781a32cd17fb3 | a6991b575847377f28b82cd725c67b324bc53d6c | /coderunner-quala/game.py | 0d4956df8ae63487d32b0d091991cfcd6bb994cf | []
| no_license | zakuro9715/atcoder | 7732712405b284487da87dfb56782d855a6f6af6 | 6c50e66e2de1964bb23d200c2c8d35af84f17b69 | refs/heads/master | 2021-05-16T03:17:57.743717 | 2019-12-06T07:57:59 | 2019-12-06T07:57:59 | 32,463,524 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 634 | py | import urllib.request
import settings
endpoint = 'https://game.coderunner.jp'
token = settings.token
def submit(text):
return _request('{0}/q?str={1}&token={2}'.format(endpoint, text, token))
def update_profile(text):
return _request('{0}/profile?text={1}&token={2}'.format(endpoint, text, token))
def _request(url):
try:
res = url, urllib.request.urlopen(url).read(), None
except urllib.error.HTTPError as e:
res = url, None, e
finally:
f = open(settings.logs, 'a')
f.writelines(map(lambda x: '{0}\n'.format(x), res))
f.write('\n')
f.close()
return res
| [
"[email protected]"
]
| |
4b7eae302416a02232a6fb6ec48defa11278f409 | c16ea32a4cddb6b63ad3bacce3c6db0259d2bacd | /google/devtools/cloudtrace/v2/devtools-cloudtrace-v2-py/tests/unit/gapic/trace_v2/test_trace_service.py | b9a4db869886afcb5775784ed8a4698949b38153 | [
"Apache-2.0"
]
| permissive | dizcology/googleapis-gen | 74a72b655fba2565233e5a289cfaea6dc7b91e1a | 478f36572d7bcf1dc66038d0e76b9b3fa2abae63 | refs/heads/master | 2023-06-04T15:51:18.380826 | 2021-06-16T20:42:38 | 2021-06-16T20:42:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 55,561 | py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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.
#
import os
import mock
import packaging.version
import grpc
from grpc.experimental import aio
import math
import pytest
from proto.marshal.rules.dates import DurationRule, TimestampRule
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.trace_v2.services.trace_service import TraceServiceAsyncClient
from google.cloud.trace_v2.services.trace_service import TraceServiceClient
from google.cloud.trace_v2.services.trace_service import transports
from google.cloud.trace_v2.services.trace_service.transports.base import _API_CORE_VERSION
from google.cloud.trace_v2.services.trace_service.transports.base import _GOOGLE_AUTH_VERSION
from google.cloud.trace_v2.types import trace
from google.cloud.trace_v2.types import tracing
from google.oauth2 import service_account
from google.protobuf import any_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.protobuf import wrappers_pb2 # type: ignore
from google.rpc import status_pb2 # type: ignore
import google.auth
# TODO(busunkim): Once google-api-core >= 1.26.0 is required:
# - Delete all the api-core and auth "less than" test cases
# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
reason="This test requires google-auth < 1.25.0",
)
requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
reason="This test requires google-auth >= 1.25.0",
)
requires_api_core_lt_1_26_0 = pytest.mark.skipif(
packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"),
reason="This test requires google-api-core < 1.26.0",
)
requires_api_core_gte_1_26_0 = pytest.mark.skipif(
packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"),
reason="This test requires google-api-core >= 1.26.0",
)
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
# If default endpoint is localhost, then default mtls endpoint will be the same.
# This method modifies the default endpoint so the client can produce a different
# mtls endpoint for endpoint testing purposes.
def modify_default_endpoint(client):
return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
sandbox_endpoint = "example.sandbox.googleapis.com"
sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
non_googleapi = "api.example.com"
assert TraceServiceClient._get_default_mtls_endpoint(None) is None
assert TraceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
assert TraceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint
assert TraceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint
assert TraceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint
assert TraceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
@pytest.mark.parametrize("client_class", [
TraceServiceClient,
TraceServiceAsyncClient,
])
def test_trace_service_client_from_service_account_info(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory:
factory.return_value = creds
info = {"valid": True}
client = client_class.from_service_account_info(info)
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == 'cloudtrace.googleapis.com:443'
@pytest.mark.parametrize("client_class", [
TraceServiceClient,
TraceServiceAsyncClient,
])
def test_trace_service_client_from_service_account_file(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == 'cloudtrace.googleapis.com:443'
def test_trace_service_client_get_transport_class():
transport = TraceServiceClient.get_transport_class()
available_transports = [
transports.TraceServiceGrpcTransport,
]
assert transport in available_transports
transport = TraceServiceClient.get_transport_class("grpc")
assert transport == transports.TraceServiceGrpcTransport
@pytest.mark.parametrize("client_class,transport_class,transport_name", [
(TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"),
(TraceServiceAsyncClient, transports.TraceServiceGrpcAsyncIOTransport, "grpc_asyncio"),
])
@mock.patch.object(TraceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceClient))
@mock.patch.object(TraceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceAsyncClient))
def test_trace_service_client_client_options(client_class, transport_class, transport_name):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(TraceServiceClient, 'get_transport_class') as gtc:
transport = transport_class(
credentials=ga_credentials.AnonymousCredentials()
)
client = client_class(transport=transport)
gtc.assert_not_called()
# Check that if channel is provided via str we will create a new one.
with mock.patch.object(TraceServiceClient, 'get_transport_class') as gtc:
client = client_class(transport=transport_name)
gtc.assert_called()
# Check the case api_endpoint is provided.
options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "never".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "always".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
# unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
with pytest.raises(MutualTLSChannelError):
client = client_class()
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}):
with pytest.raises(ValueError):
client = client_class()
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [
(TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc", "true"),
(TraceServiceAsyncClient, transports.TraceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"),
(TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc", "false"),
(TraceServiceAsyncClient, transports.TraceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"),
])
@mock.patch.object(TraceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceClient))
@mock.patch.object(TraceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TraceServiceAsyncClient))
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_trace_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env):
# This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
# mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
# Check the case client_cert_source is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
options = client_options.ClientOptions(client_cert_source=client_cert_source_callback)
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class(client_options=options)
if use_client_cert_env == "false":
expected_client_cert_source = None
expected_host = client.DEFAULT_ENDPOINT
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
with mock.patch.object(transport_class, '__init__') as patched:
with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True):
with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback):
if use_client_cert_env == "false":
expected_host = client.DEFAULT_ENDPOINT
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
expected_client_cert_source = client_cert_source_callback
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case client_cert_source and ADC client cert are not provided.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
with mock.patch.object(transport_class, '__init__') as patched:
with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False):
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize("client_class,transport_class,transport_name", [
(TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"),
(TraceServiceAsyncClient, transports.TraceServiceGrpcAsyncIOTransport, "grpc_asyncio"),
])
def test_trace_service_client_client_options_scopes(client_class, transport_class, transport_name):
# Check the case scopes are provided.
options = client_options.ClientOptions(
scopes=["1", "2"],
)
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize("client_class,transport_class,transport_name", [
(TraceServiceClient, transports.TraceServiceGrpcTransport, "grpc"),
(TraceServiceAsyncClient, transports.TraceServiceGrpcAsyncIOTransport, "grpc_asyncio"),
])
def test_trace_service_client_client_options_credentials_file(client_class, transport_class, transport_name):
# Check the case credentials file is provided.
options = client_options.ClientOptions(
credentials_file="credentials.json"
)
with mock.patch.object(transport_class, '__init__') as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
def test_trace_service_client_client_options_from_dict():
with mock.patch('google.cloud.trace_v2.services.trace_service.transports.TraceServiceGrpcTransport.__init__') as grpc_transport:
grpc_transport.return_value = None
client = TraceServiceClient(
client_options={'api_endpoint': 'squid.clam.whelk'}
)
grpc_transport.assert_called_once_with(
credentials=None,
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
def test_batch_write_spans(transport: str = 'grpc', request_type=tracing.BatchWriteSpansRequest):
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = None
response = client.batch_write_spans(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == tracing.BatchWriteSpansRequest()
# Establish that the response is the type that we expect.
assert response is None
def test_batch_write_spans_from_dict():
test_batch_write_spans(request_type=dict)
def test_batch_write_spans_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
client.batch_write_spans()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == tracing.BatchWriteSpansRequest()
@pytest.mark.asyncio
async def test_batch_write_spans_async(transport: str = 'grpc_asyncio', request_type=tracing.BatchWriteSpansRequest):
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
response = await client.batch_write_spans(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == tracing.BatchWriteSpansRequest()
# Establish that the response is the type that we expect.
assert response is None
@pytest.mark.asyncio
async def test_batch_write_spans_async_from_dict():
await test_batch_write_spans_async(request_type=dict)
def test_batch_write_spans_field_headers():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tracing.BatchWriteSpansRequest()
request.name = 'name/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
call.return_value = None
client.batch_write_spans(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
@pytest.mark.asyncio
async def test_batch_write_spans_field_headers_async():
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tracing.BatchWriteSpansRequest()
request.name = 'name/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
await client.batch_write_spans(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
def test_batch_write_spans_flattened():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = None
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_write_spans(
name='name_value',
spans=[trace.Span(name='name_value')],
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].name == 'name_value'
assert args[0].spans == [trace.Span(name='name_value')]
def test_batch_write_spans_flattened_error():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.batch_write_spans(
tracing.BatchWriteSpansRequest(),
name='name_value',
spans=[trace.Span(name='name_value')],
)
@pytest.mark.asyncio
async def test_batch_write_spans_flattened_async():
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.batch_write_spans),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = None
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
response = await client.batch_write_spans(
name='name_value',
spans=[trace.Span(name='name_value')],
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0].name == 'name_value'
assert args[0].spans == [trace.Span(name='name_value')]
@pytest.mark.asyncio
async def test_batch_write_spans_flattened_error_async():
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
await client.batch_write_spans(
tracing.BatchWriteSpansRequest(),
name='name_value',
spans=[trace.Span(name='name_value')],
)
def test_create_span(transport: str = 'grpc', request_type=trace.Span):
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_span),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = trace.Span(
name='name_value',
span_id='span_id_value',
parent_span_id='parent_span_id_value',
span_kind=trace.Span.SpanKind.INTERNAL,
)
response = client.create_span(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == trace.Span()
# Establish that the response is the type that we expect.
assert isinstance(response, trace.Span)
assert response.name == 'name_value'
assert response.span_id == 'span_id_value'
assert response.parent_span_id == 'parent_span_id_value'
assert response.span_kind == trace.Span.SpanKind.INTERNAL
def test_create_span_from_dict():
test_create_span(request_type=dict)
def test_create_span_empty_call():
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport='grpc',
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_span),
'__call__') as call:
client.create_span()
call.assert_called()
_, args, _ = call.mock_calls[0]
assert args[0] == trace.Span()
@pytest.mark.asyncio
async def test_create_span_async(transport: str = 'grpc_asyncio', request_type=trace.Span):
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_span),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trace.Span(
name='name_value',
span_id='span_id_value',
parent_span_id='parent_span_id_value',
span_kind=trace.Span.SpanKind.INTERNAL,
))
response = await client.create_span(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == trace.Span()
# Establish that the response is the type that we expect.
assert isinstance(response, trace.Span)
assert response.name == 'name_value'
assert response.span_id == 'span_id_value'
assert response.parent_span_id == 'parent_span_id_value'
assert response.span_kind == trace.Span.SpanKind.INTERNAL
@pytest.mark.asyncio
async def test_create_span_async_from_dict():
await test_create_span_async(request_type=dict)
def test_create_span_field_headers():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = trace.Span()
request.name = 'name/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_span),
'__call__') as call:
call.return_value = trace.Span()
client.create_span(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
@pytest.mark.asyncio
async def test_create_span_field_headers_async():
client = TraceServiceAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = trace.Span()
request.name = 'name/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.create_span),
'__call__') as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trace.Span())
await client.create_span(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'name=name/value',
) in kw['metadata']
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.TraceServiceGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.TraceServiceGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TraceServiceClient(
client_options={"credentials_file": "credentials.json"},
transport=transport,
)
# It is an error to provide scopes and a transport instance.
transport = transports.TraceServiceGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TraceServiceClient(
client_options={"scopes": ["1", "2"]},
transport=transport,
)
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.TraceServiceGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
client = TraceServiceClient(transport=transport)
assert client.transport is transport
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.TraceServiceGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.TraceServiceGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@pytest.mark.parametrize("transport_class", [
transports.TraceServiceGrpcTransport,
transports.TraceServiceGrpcAsyncIOTransport,
])
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
with mock.patch.object(google.auth, 'default') as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
assert isinstance(
client.transport,
transports.TraceServiceGrpcTransport,
)
def test_trace_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.TraceServiceTransport(
credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json"
)
def test_trace_service_base_transport():
# Instantiate the base transport.
with mock.patch('google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport.__init__') as Transport:
Transport.return_value = None
transport = transports.TraceServiceTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
'batch_write_spans',
'create_span',
)
for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
@requires_google_auth_gte_1_25_0
def test_trace_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport._prep_wrapped_messages') as Transport:
Transport.return_value = None
load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TraceServiceTransport(
credentials_file="credentials.json",
quota_project_id="octopus",
)
load_creds.assert_called_once_with("credentials.json",
scopes=None,
default_scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
quota_project_id="octopus",
)
@requires_google_auth_lt_1_25_0
def test_trace_service_base_transport_with_credentials_file_old_google_auth():
# Instantiate the base transport with a credentials file
with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport._prep_wrapped_messages') as Transport:
Transport.return_value = None
load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TraceServiceTransport(
credentials_file="credentials.json",
quota_project_id="octopus",
)
load_creds.assert_called_once_with("credentials.json", scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
quota_project_id="octopus",
)
def test_trace_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.trace_v2.services.trace_service.transports.TraceServiceTransport._prep_wrapped_messages') as Transport:
Transport.return_value = None
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TraceServiceTransport()
adc.assert_called_once()
@requires_google_auth_gte_1_25_0
def test_trace_service_auth_adc():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(google.auth, 'default', autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
TraceServiceClient()
adc.assert_called_once_with(
scopes=None,
default_scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
quota_project_id=None,
)
@requires_google_auth_lt_1_25_0
def test_trace_service_auth_adc_old_google_auth():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(google.auth, 'default', autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
TraceServiceClient()
adc.assert_called_once_with(
scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/trace.append',),
quota_project_id=None,
)
@pytest.mark.parametrize(
"transport_class",
[
transports.TraceServiceGrpcTransport,
transports.TraceServiceGrpcAsyncIOTransport,
],
)
@requires_google_auth_gte_1_25_0
def test_trace_service_transport_auth_adc(transport_class):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, 'default', autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/trace.append',),
quota_project_id="octopus",
)
@pytest.mark.parametrize(
"transport_class",
[
transports.TraceServiceGrpcTransport,
transports.TraceServiceGrpcAsyncIOTransport,
],
)
@requires_google_auth_lt_1_25_0
def test_trace_service_transport_auth_adc_old_google_auth(transport_class):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class(quota_project_id="octopus")
adc.assert_called_once_with(scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
quota_project_id="octopus",
)
@pytest.mark.parametrize(
"transport_class,grpc_helpers",
[
(transports.TraceServiceGrpcTransport, grpc_helpers),
(transports.TraceServiceGrpcAsyncIOTransport, grpc_helpers_async)
],
)
@requires_api_core_gte_1_26_0
def test_trace_service_transport_create_channel(transport_class, grpc_helpers):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object(
grpc_helpers, "create_channel", autospec=True
) as create_channel:
creds = ga_credentials.AnonymousCredentials()
adc.return_value = (creds, None)
transport_class(
quota_project_id="octopus",
scopes=["1", "2"]
)
create_channel.assert_called_with(
"cloudtrace.googleapis.com:443",
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
default_scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
scopes=["1", "2"],
default_host="cloudtrace.googleapis.com",
ssl_credentials=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
@pytest.mark.parametrize(
"transport_class,grpc_helpers",
[
(transports.TraceServiceGrpcTransport, grpc_helpers),
(transports.TraceServiceGrpcAsyncIOTransport, grpc_helpers_async)
],
)
@requires_api_core_lt_1_26_0
def test_trace_service_transport_create_channel_old_api_core(transport_class, grpc_helpers):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object(
grpc_helpers, "create_channel", autospec=True
) as create_channel:
creds = ga_credentials.AnonymousCredentials()
adc.return_value = (creds, None)
transport_class(quota_project_id="octopus")
create_channel.assert_called_with(
"cloudtrace.googleapis.com:443",
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
ssl_credentials=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
@pytest.mark.parametrize(
"transport_class,grpc_helpers",
[
(transports.TraceServiceGrpcTransport, grpc_helpers),
(transports.TraceServiceGrpcAsyncIOTransport, grpc_helpers_async)
],
)
@requires_api_core_lt_1_26_0
def test_trace_service_transport_create_channel_user_scopes(transport_class, grpc_helpers):
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object(
grpc_helpers, "create_channel", autospec=True
) as create_channel:
creds = ga_credentials.AnonymousCredentials()
adc.return_value = (creds, None)
transport_class(quota_project_id="octopus", scopes=["1", "2"])
create_channel.assert_called_with(
"cloudtrace.googleapis.com:443",
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
scopes=["1", "2"],
ssl_credentials=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
@pytest.mark.parametrize("transport_class", [transports.TraceServiceGrpcTransport, transports.TraceServiceGrpcAsyncIOTransport])
def test_trace_service_grpc_transport_client_cert_source_for_mtls(
transport_class
):
cred = ga_credentials.AnonymousCredentials()
# Check ssl_channel_credentials is used if provided.
with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
mock_ssl_channel_creds = mock.Mock()
transport_class(
host="squid.clam.whelk",
credentials=cred,
ssl_channel_credentials=mock_ssl_channel_creds
)
mock_create_channel.assert_called_once_with(
"squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
ssl_credentials=mock_ssl_channel_creds,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
# is used.
with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
transport_class(
credentials=cred,
client_cert_source_for_mtls=client_cert_source_callback
)
expected_cert, expected_key = client_cert_source_callback()
mock_ssl_cred.assert_called_once_with(
certificate_chain=expected_cert,
private_key=expected_key
)
def test_trace_service_host_no_port():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint='cloudtrace.googleapis.com'),
)
assert client.transport._host == 'cloudtrace.googleapis.com:443'
def test_trace_service_host_with_port():
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint='cloudtrace.googleapis.com:8000'),
)
assert client.transport._host == 'cloudtrace.googleapis.com:8000'
def test_trace_service_grpc_transport_channel():
channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TraceServiceGrpcTransport(
host="squid.clam.whelk",
channel=channel,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert transport._ssl_channel_credentials == None
def test_trace_service_grpc_asyncio_transport_channel():
channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TraceServiceGrpcAsyncIOTransport(
host="squid.clam.whelk",
channel=channel,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert transport._ssl_channel_credentials == None
# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize("transport_class", [transports.TraceServiceGrpcTransport, transports.TraceServiceGrpcAsyncIOTransport])
def test_trace_service_transport_channel_mtls_with_client_cert_source(
transport_class
):
with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred:
with mock.patch.object(transport_class, "create_channel") as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
with mock.patch.object(google.auth, 'default') as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=client_cert_source_callback,
)
adc.assert_called_once()
grpc_ssl_channel_cred.assert_called_once_with(
certificate_chain=b"cert bytes", private_key=b"key bytes"
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
assert transport._ssl_channel_credentials == mock_ssl_cred
# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize("transport_class", [transports.TraceServiceGrpcTransport, transports.TraceServiceGrpcAsyncIOTransport])
def test_trace_service_transport_channel_mtls_with_adc(
transport_class
):
mock_ssl_cred = mock.Mock()
with mock.patch.multiple(
"google.auth.transport.grpc.SslCredentials",
__init__=mock.Mock(return_value=None),
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(transport_class, "create_channel") as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
mock_cred = mock.Mock()
with pytest.warns(DeprecationWarning):
transport = transport_class(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=None,
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
scopes=(
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/trace.append',
),
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
def test_span_path():
project = "squid"
trace = "clam"
span = "whelk"
expected = "projects/{project}/traces/{trace}/spans/{span}".format(project=project, trace=trace, span=span, )
actual = TraceServiceClient.span_path(project, trace, span)
assert expected == actual
def test_parse_span_path():
expected = {
"project": "octopus",
"trace": "oyster",
"span": "nudibranch",
}
path = TraceServiceClient.span_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_span_path(path)
assert expected == actual
def test_common_billing_account_path():
billing_account = "cuttlefish"
expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, )
actual = TraceServiceClient.common_billing_account_path(billing_account)
assert expected == actual
def test_parse_common_billing_account_path():
expected = {
"billing_account": "mussel",
}
path = TraceServiceClient.common_billing_account_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_common_billing_account_path(path)
assert expected == actual
def test_common_folder_path():
folder = "winkle"
expected = "folders/{folder}".format(folder=folder, )
actual = TraceServiceClient.common_folder_path(folder)
assert expected == actual
def test_parse_common_folder_path():
expected = {
"folder": "nautilus",
}
path = TraceServiceClient.common_folder_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_common_folder_path(path)
assert expected == actual
def test_common_organization_path():
organization = "scallop"
expected = "organizations/{organization}".format(organization=organization, )
actual = TraceServiceClient.common_organization_path(organization)
assert expected == actual
def test_parse_common_organization_path():
expected = {
"organization": "abalone",
}
path = TraceServiceClient.common_organization_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_common_organization_path(path)
assert expected == actual
def test_common_project_path():
project = "squid"
expected = "projects/{project}".format(project=project, )
actual = TraceServiceClient.common_project_path(project)
assert expected == actual
def test_parse_common_project_path():
expected = {
"project": "clam",
}
path = TraceServiceClient.common_project_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_common_project_path(path)
assert expected == actual
def test_common_location_path():
project = "whelk"
location = "octopus"
expected = "projects/{project}/locations/{location}".format(project=project, location=location, )
actual = TraceServiceClient.common_location_path(project, location)
assert expected == actual
def test_parse_common_location_path():
expected = {
"project": "oyster",
"location": "nudibranch",
}
path = TraceServiceClient.common_location_path(**expected)
# Check that the path construction is reversible.
actual = TraceServiceClient.parse_common_location_path(path)
assert expected == actual
def test_client_withDEFAULT_CLIENT_INFO():
client_info = gapic_v1.client_info.ClientInfo()
with mock.patch.object(transports.TraceServiceTransport, '_prep_wrapped_messages') as prep:
client = TraceServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
client_info=client_info,
)
prep.assert_called_once_with(client_info)
with mock.patch.object(transports.TraceServiceTransport, '_prep_wrapped_messages') as prep:
transport_class = TraceServiceClient.get_transport_class()
transport = transport_class(
credentials=ga_credentials.AnonymousCredentials(),
client_info=client_info,
)
prep.assert_called_once_with(client_info)
| [
"bazel-bot-development[bot]@users.noreply.github.com"
]
| bazel-bot-development[bot]@users.noreply.github.com |
0f8cc58656b66668df127c7d77176ab02c8389e5 | 88d555a009f9075e59177fac70036892f397b439 | /basenji/archive/augmentation.py | 50b223c90c872923f1db563e272389153f3313a9 | [
"Apache-2.0"
]
| permissive | calico/basenji | f9f406971d355dda81821dcf274696a7d27e332d | 615b9eec8a591783b16d959029ddad08edae853d | refs/heads/master | 2023-09-04T11:14:15.620786 | 2023-07-27T00:05:13 | 2023-07-27T00:05:13 | 96,346,574 | 326 | 143 | Apache-2.0 | 2023-08-16T00:36:32 | 2017-07-05T17:54:18 | Python | UTF-8 | Python | false | false | 5,944 | py | # 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
# https://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.
# =========================================================================
import pdb
import tensorflow as tf
from basenji import ops
def stochastic_rc(seq_1hot):
"""Stochastically reverse complement a one hot encoded DNA sequence."""
rcseq_1hot = tf.gather(seq_1hot, [3, 2, 1, 0], axis=-1)
rcseq_1hot = tf.reverse(rcseq_1hot, axis=[1])
reverse_bool = tf.random_uniform(shape=[]) > 0.5
seq_1hot_aug = tf.cond(reverse_bool, lambda: rcseq_1hot, lambda: seq_1hot)
return seq_1hot_aug, reverse_bool
def reverse_preds(rp_tuple):
(preds, reverse_bool) = rp_tuple
preds_rev = tf.reverse(preds, axis=[1])
preds_match = tf.cond(reverse_bool, lambda: preds, lambda: preds_rev)
return preds_match
################################################################################
def shift_sequence(seq, shift_amount, pad_value=0.25):
"""Shift a sequence left or right by shift_amount.
Args:
seq: a [batch_size, sequence_length, sequence_depth] sequence to shift
shift_amount: the signed amount to shift (tf.int32 or int)
pad_value: value to fill the padding (primitive or scalar tf.Tensor)
"""
if seq.shape.ndims != 3:
raise ValueError('input sequence should be rank 3')
input_shape = seq.shape
pad = pad_value * tf.ones_like(seq[:, 0:tf.abs(shift_amount), :])
def _shift_right(_seq):
sliced_seq = _seq[:, :-shift_amount:, :]
return tf.concat([pad, sliced_seq], axis=1)
def _shift_left(_seq):
sliced_seq = _seq[:, -shift_amount:, :]
return tf.concat([sliced_seq, pad], axis=1)
output = tf.cond(
tf.greater(shift_amount, 0), lambda: _shift_right(seq),
lambda: _shift_left(seq))
output.set_shape(input_shape)
return output
def augment_deterministic_set(data_ops, augment_rc=False, augment_shifts=[0]):
"""
Args:
data_ops: dict with keys 'sequence,' 'label,' and 'na.'
augment_rc: Boolean
augment_shifts: List of ints.
Returns
data_ops_list:
"""
augment_pairs = []
for ashift in augment_shifts:
augment_pairs.append((False, ashift))
if augment_rc:
augment_pairs.append((True, ashift))
data_ops_list = []
for arc, ashift in augment_pairs:
data_ops_aug = augment_deterministic(data_ops, arc, ashift)
data_ops_list.append(data_ops_aug)
return data_ops_list
def augment_deterministic(data_ops, augment_rc=False, augment_shift=0):
"""Apply a deterministic augmentation, specified by the parameters.
Args:
data_ops: dict with keys 'sequence,' 'label,' and 'na.'
augment_rc: Boolean
augment_shift: Int
Returns
data_ops: augmented data, with all existing keys transformed
and 'reverse_preds' bool added.
"""
data_ops_aug = {}
for key in data_ops:
if key not in ['sequence']:
data_ops_aug[key] = data_ops[key]
if augment_shift == 0:
data_ops_aug['sequence'] = data_ops['sequence']
else:
shift_amount = tf.constant(augment_shift, shape=(), dtype=tf.int64)
data_ops_aug['sequence'] = shift_sequence(data_ops['sequence'], shift_amount)
if augment_rc:
data_ops_aug = augment_deterministic_rc(data_ops_aug)
else:
data_ops_aug['reverse_preds'] = tf.zeros((), dtype=tf.bool)
return data_ops_aug
def augment_deterministic_rc(data_ops):
"""Apply a deterministic reverse complement augmentation.
Args:
data_ops: dict with keys 'sequence,' 'label,' and 'na.'
Returns
data_ops_aug: augmented data ops
"""
data_ops_aug = ops.reverse_complement_transform(data_ops)
data_ops_aug['reverse_preds'] = tf.ones((), dtype=tf.bool)
return data_ops_aug
def augment_stochastic_rc(data_ops):
"""Apply a stochastic reverse complement augmentation.
Args:
data_ops: dict with keys 'sequence,' 'label,' and 'na.'
Returns
data_ops_aug: augmented data
"""
reverse_preds = tf.random_uniform(shape=[]) > 0.5
data_ops_aug = tf.cond(reverse_preds, lambda: ops.reverse_complement_transform(data_ops),
lambda: data_ops.copy())
data_ops_aug['reverse_preds'] = reverse_preds
return data_ops_aug
def augment_stochastic_shifts(seq, augment_shifts):
"""Apply a stochastic shift augmentation.
Args:
seq: input sequence of size [batch_size, length, depth]
augment_shifts: list of int offsets to sample from
Returns:
shifted and padded sequence of size [batch_size, length, depth]
"""
shift_index = tf.random_uniform(shape=[], minval=0,
maxval=len(augment_shifts), dtype=tf.int64)
shift_value = tf.gather(tf.constant(augment_shifts), shift_index)
seq = tf.cond(tf.not_equal(shift_value, 0),
lambda: shift_sequence(seq, shift_value),
lambda: seq)
return seq
def augment_stochastic(data_ops, augment_rc=False, augment_shifts=[]):
"""Apply stochastic augmentations,
Args:
data_ops: dict with keys 'sequence,' 'label,' and 'na.'
augment_rc: Boolean for whether to apply reverse complement augmentation.
augment_shifts: list of int offsets to sample shift augmentations.
Returns:
data_ops_aug: augmented data
"""
if augment_shifts:
data_ops['sequence'] = augment_stochastic_shifts(data_ops['sequence'],
augment_shifts)
if augment_rc:
data_ops = augment_stochastic_rc(data_ops)
else:
data_ops['reverse_preds'] = tf.zeros((), dtype=tf.bool)
return data_ops
| [
"[email protected]"
]
| |
6863d4fb2fa2c83913a6cfce35a272bbbd68db57 | 255e19ddc1bcde0d3d4fe70e01cec9bb724979c9 | /dockerized-gists/f828b38421dfbee59daf/snippet.py | b7817810ac5fdc2fc629f33ee3356f6c29cd2707 | [
"MIT"
]
| permissive | gistable/gistable | 26c1e909928ec463026811f69b61619b62f14721 | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | refs/heads/master | 2023-02-17T21:33:55.558398 | 2023-02-11T18:20:10 | 2023-02-11T18:20:10 | 119,861,038 | 76 | 19 | null | 2020-07-26T03:14:55 | 2018-02-01T16:19:24 | Python | UTF-8 | Python | false | false | 2,937 | py | """
Physics simulation with PyODE followed by a (basic) rendering with Vapory
See the result here: http://i.imgur.com/TdhxwGz.gifv
Zulko 2014
This script is placed in the Public Domain (Licence Creative Commons 0)
"""
# =============== FIRST PART : SIMULATION WITH PyODE
import ode
lx, ly, lz, density = 1.0, 1.0, 1.0, 1.0
world = ode.World()
world.setGravity( (0,-9.81,0) )
world.setCFM(1E-6)
space = ode.Space()
contactgroup = ode.JointGroup()
geoms = []
def near_callback(args, geom1, geom2):
"""Callback function for the collide() method below.
This function checks if the given geoms do collide and
creates contact joints if they do.
"""
contacts = ode.collide(geom1, geom2)
world,contactgroup = args
for c in contacts:
c.setBounce(0.01)
c.setMu(60000)
j = ode.ContactJoint(world, contactgroup, c)
j.attach(geom1.getBody(), geom2.getBody())
def new_cube(xyz):
""" Creates a new PyODE cude at position (x,y,z) """
body = ode.Body(world)
M = ode.Mass()
M.setBox(density, lx, ly, lz)
body.setMass(M)
body.shape = "box"
body.boxsize = (lx, ly, lz)
body.setPosition(xyz)
geom = ode.GeomBox(space, lengths=body.boxsize)
geom.setBody(body)
geoms.append(geom) # avoids that geom gets trashed
return body
# The objects of the scene:
floor = ode.GeomPlane(space, (0,1,0), 0)
cubes = [new_cube(xyz) for xyz in
[(0.5,3,0.5),(0.5,4,0),(0,5,0),(-0.5,6,0),
(-0.5,7,-0.5),(0,8,0.5)]]
# Start the simulation !
t = 0.0
dt = 0.005
duration = 4.0
trajectories = []
while t<duration:
trajectories.append([(c.getPosition(), c.getRotation())
for c in cubes])
space.collide((world,contactgroup), near_callback)
world.step(dt)
contactgroup.empty()
t+=dt
# =============== SECOND PART : RENDERING WITH VAPORY
from moviepy.editor import VideoClip, ipython_display
from vapory import *
light = LightSource( [10,10,10], 'color', [3,3,3],
'parallel', 'point_at', [0, 0, 0])
ground = Plane([0,1,0],0, Texture('Rosewood'))
def vapory_box(xyz, R):
""" Draws a box with at the given position and rotation"""
return Box([-lx/2, -ly/2, -lz/2], [lx/2, ly/2, lz/2],
Texture('T_Ruby_Glass'), Interior('ior',4),
'matrix', R+xyz)
def make_frame(t):
""" Returns the image of the scene rendered at time t """
boxes = [vapory_box(position, rotation)
for (position, rotation) in trajectories[int(t/dt)]]
scene = Scene( Camera("location", [0,3,-4], "look_at", [0,0,0]),
[light, ground, Background("White")] + boxes,
included=["colors.inc", "textures.inc", "glass.inc"])
return scene.render(height=300, width=400, antialiasing=0.0001)
clip = VideoClip(make_frame, duration=duration)
clip.write_videofile("pyODE.avi", codec='png', fps=20) # lossless format | [
"[email protected]"
]
| |
7fae4a50aac90c167dfa619bd30118ca39f52bff | d30ebe0bc57289f2f566cecab68b1c338f34c4ad | /bigml/tests/test_02_dev_prediction.py | 1e85df76644faa9bbd13f104ae6f50345e37bc5d | [
"Apache-2.0"
]
| permissive | alanponce/python | cdfaee04a36dd19ab13cce7e9d8fed557e0d9cc8 | 9423b4c4968b81ee14cef1ab6cd62d23dfa8bd26 | refs/heads/next | 2020-12-28T23:45:26.384281 | 2016-04-29T01:38:58 | 2016-04-29T01:38:58 | 57,441,721 | 1 | 0 | null | 2016-04-30T12:52:05 | 2016-04-30T12:52:03 | Python | UTF-8 | Python | false | false | 3,325 | py | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2015-2016 BigML
#
# 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.
""" Testing prediction creation in DEV mode
"""
from world import world, setup_module, teardown_module
import create_source_steps as source_create
import read_source_steps as source_read
import create_dataset_steps as dataset_create
import create_model_steps as model_create
import create_prediction_steps as prediction_create
class TestDevPrediction(object):
def setup(self):
"""
Switches to DEV mode for this class methods only
"""
print "\n-------------------\nTests in: %s\n" % __name__
world.api.delete_project(world.project_id)
world.api = world.api_dev_mode
world.project_id = world.api.create_project( \
{"name": world.test_project_name})['resource']
def teardown(self):
"""
Debug information
"""
print "\nEnd of tests in: %s\n-------------------\n" % __name__
def test_scenario1(self):
"""
Scenario: Successfully creating a prediction in DEV mode:
Given I want to use api in DEV mode
When I create a data source uploading a "<data>" file
And I wait until the source is ready less than <time_1> secs
And the source has DEV True
And I create a dataset
And I wait until the dataset is ready less than <time_2> secs
And I create a model
And I wait until the model is ready less than <time_3> secs
When I create a prediction for "<data_input>"
Then the prediction for "<objective>" is "<prediction>"
Examples:
| data | time_1 | time_2 | time_3 | data_input | objective | prediction |
| ../data/iris.csv | 10 | 10 | 10 | {"petal width": 0.5} | 000004 | Iris-setosa |
"""
print self.test_scenario1.__doc__
examples = [
['data/iris.csv', '10', '10', '10', '{"petal width": 0.5}', '000004', 'Iris-setosa']]
for example in examples:
print "\nTesting with:\n", example
source_create.i_upload_a_file(self, example[0])
source_create.the_source_is_finished(self, example[1])
source_read.source_has_dev(self, True)
dataset_create.i_create_a_dataset(self)
dataset_create.the_dataset_is_finished_in_less_than(self, example[2])
model_create.i_create_a_model(self)
model_create.the_model_is_finished_in_less_than(self, example[3])
prediction_create.i_create_a_prediction(self, example[4])
prediction_create.the_prediction_is(self, example[5], example[6])
| [
"[email protected]"
]
| |
077c541ab06e9bf347eb23beeab6465e7d5db980 | d83fde3c891f44014f5339572dc72ebf62c38663 | /_bin/google-cloud-sdk/.install/.backup/lib/surface/organizations/set_iam_policy.py | 929a22f897c4a754e6a303c96cd35346964f7d5e | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gyaresu/dotfiles | 047cc3ca70f4b405ba272856c69ee491a79d2ebe | e5e533b3a081b42e9492b228f308f6833b670cfe | refs/heads/master | 2022-11-24T01:12:49.435037 | 2022-11-01T16:58:13 | 2022-11-01T16:58:13 | 17,139,657 | 1 | 1 | null | 2020-07-25T14:11:43 | 2014-02-24T14:59:59 | Python | UTF-8 | Python | false | false | 2,780 | py | # Copyright 2015 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.
"""Command to set IAM policy for a resource."""
from __future__ import absolute_import
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.command_lib.organizations import flags
from googlecloudsdk.command_lib.organizations import orgs_base
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class SetIamPolicy(orgs_base.OrganizationCommand):
"""Set IAM policy for an organization.
Given an organization ID and a file encoded in JSON or YAML that contains the
IAM policy, this command will set the IAM policy for that organization.
"""
detailed_help = {
'EXAMPLES': (
'\n'.join([
'The following command reads an IAM policy defined in a JSON',
'file `policy.json` and sets it for an organization with the ID',
'`123456789`:',
'',
' $ {command} 123456789 policy.json',
]))
}
@staticmethod
def Args(parser):
flags.IdArg('whose IAM policy you want to set.').AddToParser(parser)
parser.add_argument(
'policy_file', help='JSON or YAML file containing the IAM policy.')
def Run(self, args):
messages = self.OrganizationsMessages()
policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
update_mask = iam_util.ConstructUpdateMaskFromPolicy(args.policy_file)
# To preserve the existing set-iam-policy behavior of always overwriting
# bindings and etag, add bindings and etag to update_mask.
if 'bindings' not in update_mask:
update_mask += ',bindings'
if 'etag' not in update_mask:
update_mask += ',etag'
set_iam_policy_request = messages.SetIamPolicyRequest(
policy=policy,
updateMask=update_mask)
policy_request = (
messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest(
organizationsId=args.id,
setIamPolicyRequest=set_iam_policy_request))
result = self.OrganizationsClient().SetIamPolicy(policy_request)
iam_util.LogSetIamPolicy(args.id, 'organization')
return result
| [
"[email protected]"
]
| |
7bd188b9a79352c9745f901ed5b9ffc3d20ca7ee | a6fc9cec97fbbd6ecc08715c43e4dd53606e2110 | /_apscheduler/example/config.py | 30569ac472e19331db956c59d43ebbe6fa580d60 | []
| no_license | BennyJane/python-demo | 2848acaaa81d5011d9dfc1585b3d6b685178f88e | 75098ec4f9c8288d637ee1f9585f824fcb5267ee | refs/heads/master | 2023-04-11T12:24:30.245205 | 2021-04-24T23:47:56 | 2021-04-24T23:47:56 | 264,815,200 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 984 | py | # !/usr/bin/env python
# -*-coding:utf-8 -*-
# PROJECT : Python-Exercise
# Time :2020/12/8 23:02
# Warning :The Hard Way Is Easier
from apscheduler.jobstores.redis import RedisJobStore
# from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
job_stores = {
"redis": RedisJobStore(), # 设置一个名为redis的job存储,后端使用 redis
# 一个名为 default 的 job 存储,后端使用数据库(使用 Sqlite)
# "default": SQLAlchemyJobStore(url="sqlite:///jobs.sqlite")
}
executors = {
"default": ThreadPoolExecutor(20), # 设置一个名为 default的线程池执行器, 最大线程设置为20个
"processpool": ProcessPoolExecutor(5), # 设置一个名为 processpool的进程池执行器,最大进程数设为5个
}
# 开启job合并,设置job最大实例上限为3
job_default = {
'coalesce': False,
'max_instances': 3
}
| [
"[email protected]"
]
| |
e95d133fd1c2811df04b70f079d3dca33c08a7e3 | c913c952cf4019d67f02bf1971917116da375c81 | /Data/OMIMresults/omimResults1000to1020.py | 6fb25ec53d1ed4b1888151c50da205c21fa676e7 | []
| no_license | jiangchb/OMIMscraping | 57afa5b2f8b7ca975e7459814e0410a872f71990 | 27d4ac8faea526b1c70937317caec064bed00a0a | refs/heads/master | 2022-03-14T21:35:56.102665 | 2019-11-22T15:48:48 | 2019-11-22T15:48:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 87,366 | py | omim = {'omim': {
'version': '1.0',
'searchResponse': {
'search': '*',
'expandedSearch': '*:*',
'parsedSearch': '+*:* ()',
'searchSuggestion': None,
'searchSpelling': None,
'filter': '',
'expandedFilter': None,
'fields': '',
'searchReport': None,
'totalResults': 7368,
'startIndex': 1000,
'endIndex': 1019,
'sort': '',
'operator': '',
'searchTime': 1.0,
'clinicalSynopsisList': [
{'clinicalSynopsis': {
'mimNumber': 114580,
'prefix': '%',
'preferredTitle': 'CANDIDIASIS, FAMILIAL, 1; CANDF1',
'oldFormat': {
'Immunology': 'Chronic mucocutaneous candidiasis {SNOMEDCT:234568006} {UMLS C0006845 HP:0002728} {HPO HP:0002728 C0006845}; Recurrent viral infections {SNOMEDCT:452021000124103} {UMLS C1837066 HP:0004429} {HPO HP:0004429 C1837066}; Cutaneous anergy {UMLS C1855781 HP:0002965} {HPO HP:0002965 C1855781};',
'Skin': 'Dermatophytosis {SNOMEDCT:47382004} {ICD10CM:B35,B35.9} {ICD9CM:110.9,110} {UMLS C0011636,C0040247};',
'Hair': 'Alopecia {SNOMEDCT:56317004,278040002} {ICD10CM:L65.9} {ICD9CM:704.0,704.00} {UMLS C1559115,C0002170 HP:0001596,HP:0002293} {HPO HP:0001596 C0002170};',
'Teeth': 'Teeth loss {SNOMEDCT:37320007,25540007} {ICD9CM:525.10} {UMLS C0080233};',
'Endocrine': 'No associated endocrinopathy;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': True,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': True,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': True,
'hematologyExists': False,
'immunologyExists': True,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114600,
'prefix': '%',
'preferredTitle': 'CANINE TEETH, ABSENCE OF UPPER PERMANENT',
'oldFormat': {
'Teeth': 'Absent permanent canines; Persistent deciduous canines;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': True,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114620,
'preferredTitle': 'CRANIOFACIOFRONTODIGITAL SYNDROME',
'inheritance': '?Autosomal dominant',
'growthHeight': 'Short stature (below 3rd centile) {UMLS C4227449} {HPO HP:0004322 C0349588}',
'headAndNeckHead': '''Macrocephaly {SNOMEDCT:19410003,12138000} {ICD10CM:Q75.3} {UMLS C2243051,C0221355 HP:0001355,HP:0000256} {HPO HP:0000256 C4083076,C4255213,C4280663,C4280664} {EOM ID:1d53660e657259f0 IMG:Macrocephaly-small.jpg};\nDolicocephaly {SNOMEDCT:72239002} {ICD10CM:Q67.2} {UMLS C0221358 HP:0000268}''',
'headAndNeckFace': '''Prominent forehead {UMLS C1837260 HP:0011220} {HPO HP:0011220 C1837260,C1867446} {EOM ID:510a51e4083c1d6f IMG:Forehead,Prominent-small.jpg};\nCoarse face {UMLS C1845847 HP:0000280} {HPO HP:0000280 C1845847,C4072825} {EOM ID:39ff7c97ca920a5d IMG:Face,Coarse-small.jpg}''',
'headAndNeckEars': 'Low-set ears {SNOMEDCT:95515009} {ICD10CM:Q17.4} {UMLS C0239234 HP:0000369} {HPO HP:0000369 C0239234}',
'headAndNeckEyes': '''Hypertelorism {SNOMEDCT:22006008} {ICD10CM:Q75.2} {ICD9CM:376.41} {UMLS C0020534 HP:0000316} {HPO HP:0000316 C0020534} {EOM ID:71d9f1be67c7f8b6 IMG:Eyes,Widely_Spaced-small.jpg};\nExophthalmos {SNOMEDCT:18265008} {ICD10CM:H05.20} {ICD9CM:376.30} {UMLS C0015300 HP:0000520} {HPO HP:0000520 C0015300,C1837760,C1848490,C1862425};\nHypermetropia {SNOMEDCT:38101003} {ICD10CM:H52.0} {ICD9CM:367.0} {UMLS C0020490 HP:0000540} {HPO HP:0000540 C0020490};\nHorizontal nystagmus {SNOMEDCT:81756001} {UMLS C0271385 HP:0000666} {HPO HP:0000666 C0271385};\nExophoria and/or exotropia {UMLS C4231617}''',
'headAndNeckNose': '''Flat nasal bridge {UMLS C1836542 HP:0005280} {HPO HP:0005280 C1836542,C3550546,C4280495} {EOM ID:000fb29123c16757 IMG:Nasal_Bridge,Depressed-small.jpg};\nShort nose {UMLS C1854114 HP:0003196} {HPO HP:0003196 C0426414,C1854114} {EOM ID:daeb9fb85b0b970f IMG:Nose,Short-small.jpg};\nAnteverted nostrils {SNOMEDCT:708670007} {UMLS C1840077 HP:0000463} {HPO HP:0000463 C1840077}''',
'headAndNeckMouth': 'Long philtrum {UMLS C1865014 HP:0000343} {HPO HP:0000343 C1865014} {EOM ID:e1d74175c310388d IMG:Philtrum,Long-small.jpg}',
'headAndNeckTeeth': '''Malocclusion {SNOMEDCT:707598004,47944004} {ICD10CM:M26.4} {ICD9CM:524.4} {UMLS C0024636 HP:0000689} {HPO HP:0000689 C0024636,C4280613,C4280614};\nDental anomalies {UMLS C0262444 HP:0000164} {HPO HP:0000164 C0040427,C0262444}''',
'headAndNeckNeck': 'Short neck {SNOMEDCT:95427009} {UMLS C0521525 HP:0000470} {HPO HP:0000470 C0521525} {EOM ID:c75e63fd749ec7a8 IMG:Neck,Short-small.jpg}',
'cardiovascularHeart': '''Cardiomegaly {SNOMEDCT:8186001} {ICD10CM:I51.7} {ICD9CM:429.3} {UMLS C0018800 HP:0001640} {HPO HP:0001640 C0018800};\nSystolic murmur {SNOMEDCT:31574009} {ICD10CM:R01.1} {UMLS C0232257 HP:0031664}''',
'chestExternalFeatures': 'Short and wide thorax {UMLS C4231623}',
'chestRibsSternumClaviclesAndScapulae': 'Pectus excavatum {SNOMEDCT:391987005,391982004} {ICD10CM:Q67.6} {ICD9CM:754.81} {UMLS C2051831,C0016842 HP:0000767} {HPO HP:0000767 C2051831}',
'abdomenExternalFeatures': 'Prominent abdomen {UMLS C1850290}',
'skeletal': '''Joint hypermobility {SNOMEDCT:298203008,298181000} {UMLS C0086437,C1844820 HP:0001388,HP:0001382} {HPO HP:0001382 C1844820};\nDelayed bone age {SNOMEDCT:123983008} {UMLS C0541764 HP:0002750} {HPO HP:0002750 C0541764}''',
'skeletalSkull': '''Malar bone hypoplasia {UMLS C3275634};\nJ-shaped sella turcica {UMLS C1854718 HP:0002680} {HPO HP:0002680 C1854718,C4072841,C4072842}''',
'skeletalSpine': 'Small vertebral bodies {UMLS C1863353 HP:0008479} {HPO HP:0008479 C1863353}',
'skeletalPelvis': 'Hypoplastic pelvis {UMLS C3536734 HP:0008839} {HPO HP:0008839 C3536734}',
'skeletalLimbs': '''Cubitus valgus {SNOMEDCT:54583007} {ICD10CM:M21.02} {ICD9CM:736.01} {UMLS C0158465 HP:0002967} {HPO HP:0002967 C0158465};\nSlender bones with thin corticals {UMLS C4231624}''',
'skinNailsHairSkin': '''Wrinkled palms {UMLS C4231622};\nWrinkled soles {UMLS C4231621};\nCutis laxa {SNOMEDCT:58588007} {ICD10CM:Q82.8} {UMLS C0010495 HP:0000973} {HPO HP:0000973 C0010495,C2930812,C4280606};\nEcchymosis {SNOMEDCT:77643000,302227002} {UMLS C0013491 HP:0031364} {HPO HP:0031364}''',
'skinNailsHairHair': '''Scanty, thin hair {UMLS C4231620};\nHypopigmented hair {UMLS C4231619}''',
'neurologicCentralNervousSystem': 'Mental retardation (IQ 60-68) {UMLS C4231625} {HPO HP:0001249 C0025362,C0423903,C0917816,C1843367,C3714756,C4020876}',
'miscellaneous': 'Based on one report of 4 unrelated sporadic patients {UMLS C4231618}',
'inheritanceExists': True,
'growthExists': True,
'growthHeightExists': True,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': True,
'headAndNeckFaceExists': True,
'headAndNeckEarsExists': True,
'headAndNeckEyesExists': True,
'headAndNeckNoseExists': True,
'headAndNeckMouthExists': True,
'headAndNeckTeethExists': True,
'headAndNeckNeckExists': True,
'cardiovascularExists': True,
'cardiovascularHeartExists': True,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': True,
'chestExternalFeaturesExists': True,
'chestRibsSternumClaviclesAndScapulaeExists': True,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': True,
'abdomenExternalFeaturesExists': True,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': True,
'skeletalSkullExists': True,
'skeletalSpineExists': True,
'skeletalPelvisExists': True,
'skeletalLimbsExists': True,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': True,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': True,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': True,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114650,
'preferredTitle': 'CAR FACTOR DEFICIENCY',
'oldFormat': {
'Heme': 'Bleeding disorder {SNOMEDCT:362970003,64779008,248250000} {ICD10CM:D68.9} {ICD9CM:286} {UMLS C0005779,C1458140 HP:0001928,HP:0001892,HP:0003256};',
'Lab': 'Defect in thromboplastin generation; Car factor deficiency {UMLS C1861898};',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': True,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114700,
'preferredTitle': 'CARABELLI ANOMALY OF MAXILLARY MOLAR TEETH',
'oldFormat': {
'Teeth': 'Grooves, pits, tubercles or bulges of maxillary molars;',
'Inheritance': 'Autosomal dominant vs. multifactorial;'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': True,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114835,
'prefix': '*',
'preferredTitle': 'CARBOXYLESTERASE 1; CES1',
'oldFormat': {
'Oncology': 'Increased frequency of CES1 deficiency in non-Hodgkin lymphoma (NHL) and B-cell chronic lymphocytic leukemia (CLL);',
'Immunology': 'CES1 deficiency reported in rheumatoid arthritis;',
'Lab': 'Negative monocyte alpha-naphthylacetate and alpha-naphthylbutyrate esterase staining reactions;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': True,
'neoplasiaExists': True,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 114900,
'prefix': '%',
'preferredTitle': 'CARCINOID TUMORS, INTESTINAL',
'oldFormat': {
'Oncology': 'Intestinal carcinoid {UMLS C4024988 HP:0006723} {HPO HP:0006723 C4024988}; Appendiceal carcinoid; Malignant carcinoid of ileum;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': True,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115000,
'preferredTitle': 'CARDIAC ARRHYTHMIA',
'oldFormat': {
'Cardiac': 'Arrhythmia {SNOMEDCT:698247007} {ICD10CM:I49.9} {ICD9CM:427,427.9} {UMLS C0003811 HP:0011675} {HPO HP:0011675 C0003811,C0264886,C0522055,C0855329,C1832603,C1842820}; Polymorphic and polytopic ventricular extrasystoles {UMLS C4024998 HP:0006696} {HPO HP:0006696 C4024998};',
'Neuro': 'Syncopal attacks;',
'Misc': 'Sudden death {SNOMEDCT:26636000} {UMLS C1964022,C0011071 HP:0001699} {HPO HP:0001699 C0011071};',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': True,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115080,
'prefix': '#',
'preferredTitle': 'CARDIAC CONDUCTION DEFECT',
'oldFormat': {
'Cardiac': 'Progressive atrial conduction defect; Arrhythmia {SNOMEDCT:698247007} {ICD10CM:I49.9} {ICD9CM:427,427.9} {UMLS C0003811 HP:0011675} {HPO HP:0011675 C0003811,C0264886,C0522055,C0855329,C1832603,C1842820};',
'Neuro': 'Syncope {SNOMEDCT:271594007,309585006,272030005} {ICD10CM:R55} {ICD9CM:780.2} {UMLS C0039070,C4554644,C3541349 HP:0001279} {HPO HP:0001279 C0039070};',
'Misc': 'Sudden death {SNOMEDCT:26636000} {UMLS C1964022,C0011071 HP:0001699} {HPO HP:0001699 C0011071};',
'Lab': 'Fatty and mononuclear cell infiltration in the atrioventricular conduction system and the main left bundle branch;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': True,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115150,
'prefix': '#',
'preferredTitle': 'CARDIOFACIOCUTANEOUS SYNDROME 1; CFC1',
'inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147}',
'growthHeight': 'Short stature, postnatal {UMLS C1835465}',
'growthOther': 'Failure to thrive {SNOMEDCT:54840006,433476000,432788009} {ICD10CM:R62.51} {ICD9CM:783.41} {UMLS C2315100,C0015544,C3887638 HP:0001508} {HPO HP:0001508 C0231246,C2315100}',
'headAndNeckHead': '''Macrocephaly, relative {SNOMEDCT:3961000119101} {UMLS C1849075 HP:0004482} {HPO HP:0004482 C1849075};\nDolichocephaly {SNOMEDCT:72239002} {ICD10CM:Q67.2} {UMLS C0221358 HP:0000268} {HPO HP:0000268 C0221358,C4280653,C4280654,C4280655,C4280656} {EOM ID:e09c1185a1ef3e38 IMG:Dolichocephaly-small.jpg}''',
'headAndNeckFace': '''Prominent forehead {UMLS C1837260 HP:0011220} {HPO HP:0011220 C1837260,C1867446} {EOM ID:510a51e4083c1d6f IMG:Forehead,Prominent-small.jpg};\nBitemporal narrowing {UMLS C1839758 HP:0000341} {HPO HP:0000341 C1839758} {EOM ID:03f02219fe5521b4 IMG:Forehead,Narrow-small.jpg};\nShallow orbital ridges {UMLS C1861869 HP:0009891} {HPO HP:0009891 C1861869,C4020777};\nProminent philtrum {UMLS C1839797 HP:0002002} {HPO HP:0002002 C1839797,C4020861} {EOM ID:3c771454d4293f5e IMG:Philtrum,Deep-small.jpg};\nCoarse facial features {UMLS C1845847 HP:0000280} {HPO HP:0000280 C1845847,C4072825};\nMicrognathia {SNOMEDCT:32958008} {UMLS C0025990 HP:0000347} {HPO HP:0000347 C0025990,C0240295,C1857130} {EOM ID:8bbf61b4ad7ca2ef IMG:Micrognathia-small.jpg};\nConvex facial profile {SNOMEDCT:248171000} {UMLS C0424479}''',
'headAndNeckEars': '''Posteriorly rotated ears {SNOMEDCT:253251006} {UMLS C0431478 HP:0000358} {HPO HP:0000358 C0431478};\nLow-set ears {SNOMEDCT:95515009} {ICD10CM:Q17.4} {UMLS C0239234 HP:0000369} {HPO HP:0000369 C0239234};\nEarlobe creases {UMLS C1851897 HP:0009908};\nHearing loss {SNOMEDCT:15188001,343087000,103276001} {ICD10CM:H91.9} {ICD9CM:389,389.9} {UMLS C3887873,C2029884,C1384666,C0018772,C0011053 HP:0000365} {HPO HP:0000365 C0011053,C0018772,C0339789,C1384666}''',
'headAndNeckEyes': '''Ptosis {SNOMEDCT:11934000,29696001} {ICD10CM:H02.4,H02.40,H02.409} {ICD9CM:374.3,374.30} {UMLS C0005745,C0033377 HP:0000508} {HPO HP:0000508 C0005745} {EOM ID:1bd157b764ec7aea IMG:Ptosis-small.jpg};\nNystagmus {SNOMEDCT:563001} {ICD10CM:H55.0,H55.00} {ICD9CM:379.50} {UMLS C1963184,C4554036,C0028738 HP:0000639} {HPO HP:0000639 C0028738};\nStrabismus {SNOMEDCT:22066006,128602000} {ICD10CM:H50.40,H50.9} {ICD9CM:378.30} {UMLS C2020541,C1423541,C0038379 HP:0032012,HP:0000486} {HPO HP:0000486 C0038379};\nDownslanting palpebral fissures {SNOMEDCT:246800008} {UMLS C0423110 HP:0000494} {HPO HP:0000494 C0423110};\nHypertelorism {SNOMEDCT:22006008} {ICD10CM:Q75.2} {ICD9CM:376.41} {UMLS C0020534 HP:0000316} {HPO HP:0000316 C0020534} {EOM ID:71d9f1be67c7f8b6 IMG:Eyes,Widely_Spaced-small.jpg};\nExophthalmos {SNOMEDCT:18265008} {ICD10CM:H05.20} {ICD9CM:376.30} {UMLS C0015300 HP:0000520} {HPO HP:0000520 C0015300,C1837760,C1848490,C1862425};\nEpicanthal folds {SNOMEDCT:74824007} {UMLS C0229249,C0678230 HP:0000286} {HPO HP:0000286 C0678230};\nMyopia {SNOMEDCT:57190000} {ICD10CM:H52.1} {ICD9CM:367.1} {UMLS C0027092 HP:0000545} {HPO HP:0000545 C0027092};\nOptic nerve dysplasia {UMLS C2676026 HP:0001093} {HPO HP:0001093 C2676026};\nOculomotor apraxia {SNOMEDCT:193662007,405810005,405809000} {ICD10CM:H16.32} {UMLS C0271270,C3489733,C0543874 HP:0000657} {HPO HP:0000657 C3489733,C4020886};\nLoss of visual acuity {SNOMEDCT:13164000} {UMLS C1839364,C0234632 HP:0000529,HP:0007663} {HPO HP:0000529 C1839364,C3277697};\nAbsence of eyebrows {UMLS C2266639 HP:0100840};\nAbsence of eyelashes {UMLS C0239447}''',
'headAndNeckNose': '''Short upturned nose {UMLS C0240583};\nBulbous nasal tip {UMLS C1855751 HP:0000414} {HPO HP:0000414 C0240543,C1834118,C1855751} {EOM ID:042e23a2026636c8 IMG:Nose,Bulbous-small.jpg};\nDepressed nasal bridge {UMLS C1836542 HP:0005280} {HPO HP:0005280 C1836542,C3550546,C4280495} {EOM ID:000fb29123c16757 IMG:Nasal_Bridge,Depressed-small.jpg}''',
'headAndNeckMouth': '''Submucous cleft palate {SNOMEDCT:763108005} {UMLS C4551487} {EOM ID:30b9e9da9758d9d7 IMG:Palate,Submucous_Cleft-small.jpg};\nHigh-arched palate {SNOMEDCT:27272007} {ICD10CM:Q38.5} {UMLS C0240635 HP:0000218} {HPO HP:0000218 C0240635};\nOpen mouth {SNOMEDCT:262016004} {UMLS C0240379,C4285242 HP:0000194} {HPO HP:0000194 C0240379};\nTongue thrusting {SNOMEDCT:424583005,110343009} {UMLS C1829460 HP:0100703} {HPO HP:0100703 C1829460}''',
'headAndNeckTeeth': '''Malocclusion {SNOMEDCT:707598004,47944004} {ICD10CM:M26.4} {ICD9CM:524.4} {UMLS C0024636 HP:0000689} {HPO HP:0000689 C0024636,C4280613,C4280614};\nOpen bite {SNOMEDCT:35580009} {UMLS C0266061 HP:0010807} {HPO HP:0010807 C0266061} {EOM ID:10b2b6e5a7551847 IMG:Open_Bite-small.jpg};\nPosterior crossbite {SNOMEDCT:111326002} {UMLS C0266059}''',
'cardiovascularHeart': '''Atrial septal defects {SNOMEDCT:70142008,253366007,405752007} {ICD10CM:Q21.1} {UMLS C0018817 HP:0001631};\nPulmonic stenosis {SNOMEDCT:56786000} {UMLS C1956257,C0034089 HP:0001642} {HPO HP:0001642 C1956257};\nHypertrophic cardiomyopathy {SNOMEDCT:195020003,233873004,45227007} {ICD10CM:I42.1,I42.2} {ICD9CM:425.1,425.11} {UMLS C0340425,C4551472,C0007194 HP:0001639} {HPO HP:0001639 C0007194}''',
'chestExternalFeatures': '''Pectus excavatum {SNOMEDCT:391987005,391982004} {ICD10CM:Q67.6} {ICD9CM:754.81} {UMLS C2051831,C0016842 HP:0000767} {HPO HP:0000767 C2051831};\nPectus carinatum {SNOMEDCT:205101001,38774000} {ICD10CM:Q67.7} {ICD9CM:754.82} {UMLS C2939416,C0158731 HP:0000768} {HPO HP:0000768 C0158731}''',
'abdomenSpleen': 'Splenomegaly {SNOMEDCT:16294009} {ICD10CM:R16.1} {ICD9CM:789.2} {UMLS C0038002 HP:0001744} {HPO HP:0001744 C0038002}',
'abdomenGastrointestinal': '''Poor feeding {SNOMEDCT:78164000,299698007} {ICD10CM:R63.3} {UMLS C0576456,C0232466 HP:0011968} {HPO HP:0011968 C0232466};\nDysmotility {UMLS C0679316};\nVomiting {SNOMEDCT:249497008,422400008,300359004} {ICD10CM:R11.1,R11.10} {UMLS C3898969,C4084768,C4084769,C1963281,C4084766,C4084767,C0042963 HP:0002013} {HPO HP:0002013 C0042963};\nConstipation {SNOMEDCT:14760008} {ICD10CM:K59.0,K59.00} {ICD9CM:564.0,564.00} {UMLS C1963087,C0009806,C3641755,C4084722,C4084723,C4084724 HP:0002019} {HPO HP:0002019 C0009806,C0237326};\nGastroesophageal reflux {SNOMEDCT:722884003,698065002,235595009} {ICD10CM:K21,K21.9} {ICD9CM:530.81} {UMLS C4317146,C0017168,C3813607 HP:0002020} {HPO HP:0002020 C0017168,C0018834}''',
'genitourinaryKidneys': 'Hydronephrosis {SNOMEDCT:43064006} {ICD10CM:N13.30} {ICD9CM:591} {UMLS C0020295 HP:0000126} {HPO HP:0000126 C0020295}',
'skeletal': '''Joint hyperextensibility {SNOMEDCT:298181000} {UMLS C1844820 HP:0001382} {HPO HP:0001382 C1844820};\nDelayed bone age {SNOMEDCT:123983008} {UMLS C0541764 HP:0002750} {HPO HP:0002750 C0541764};\nOsteopenia {SNOMEDCT:312894000,78441005} {UMLS C0029453 HP:0000938} {HPO HP:0000938 C0029453,C0747078}''',
'skeletalHands': '''Hyperextensible fingers {UMLS C1844577 HP:0001187} {HPO HP:0001187 C1844577};\nClinodactyly {SNOMEDCT:17268007} {UMLS C4551485,C0265610 HP:0030084,HP:0040019} {HPO HP:0030084 C0265610,C4280304} {EOM ID:483af428f909c76c IMG:Clinodactyly-small.jpg};\nMultiple palmar creases {UMLS C1861872 HP:0006114} {HPO HP:0006114 C1861872}''',
'skeletalFeet': 'Multiple plantar creases {UMLS C1861873 HP:0008113} {HPO HP:0008113 C1861873}',
'skinNailsHairSkin': '''Severe atopic dermatitis {UMLS C1861874};\nIchthyosis {SNOMEDCT:13059002} {ICD10CM:Q80,Q80.9} {ICD9CM:757.1} {UMLS C0020758,C0020757 HP:0008064} {HPO HP:0008064 C0020757};\nHyperkeratosis (especially extensor surfaces) {UMLS C1861875} {HPO HP:0000962 C0870082};\nCavernous hemangioma {SNOMEDCT:33377007,416824008,56975005} {ICD10CM:D18.0} {UMLS C0018920 HP:0001048} {HPO HP:0001048 C0018920};\nKeratosis pilaris {SNOMEDCT:5132005} {UMLS C0263383} {HPO HP:0032152};\nMultiple palmar creases {UMLS C1861872 HP:0006114} {HPO HP:0006114 C1861872};\nMultiple lentigines {UMLS C1328931 HP:0001003} {HPO HP:0001003 C0036651,C1328931}''',
'skinNailsHairHair': '''Sparse, curly hair {UMLS C1861876};\nSlow-growing hair {UMLS C1832348 HP:0002217} {HPO HP:0002217 C1832348};\nAbsence of eyebrows {UMLS C2266639 HP:0100840};\nAbsence of eyelashes {UMLS C0239447}''',
'neurologicCentralNervousSystem': '''Mild to moderate mental retardation {UMLS C1861865};\nSeizures {SNOMEDCT:91175000} {UMLS C0036572 HP:0001250} {HPO HP:0001250 C0014544,C0036572};\nHypotonia {SNOMEDCT:398152000,398151007} {UMLS C0026827,C1858120 HP:0001290,HP:0001252} {HPO HP:0001290 C1858120};\nHypertonia {SNOMEDCT:41581000,56731001} {UMLS C0026826 HP:0001276} {HPO HP:0001276 C0026826};\nHydrocephalus {SNOMEDCT:230745008} {ICD10CM:G91,G91.9} {UMLS C1963137,C0020255 HP:0000238} {HPO HP:0000238 C0020255};\nCortical atrophy {SNOMEDCT:278849000} {UMLS C0235946,C4551583 HP:0002120,HP:0002059} {HPO HP:0002120 C0235946};\nFrontal lobe hypoplasia {UMLS C1849172,C2237042 HP:0007333} {HPO HP:0007333 C1849172};\nHypoplasia or absence of the corpus callosum {UMLS C1861866 HP:0007370} {HPO HP:0007370 C1861866};\nBrain stem atrophy {UMLS C1861867}''',
'neurologicPeripheralNervousSystem': 'Peripheral axonal neuropathy (uncommon) {UMLS C3549545} {HPO HP:0003477 C0270921,C1263857}',
'prenatalManifestationsAmnioticFluid': 'Polyhydramnios {SNOMEDCT:86203003} {ICD10CM:O40} {ICD9CM:657,657.0} {UMLS C0020224 HP:0001561} {HPO HP:0001561 C0020224}',
'prenatalManifestationsDelivery': 'Premature delivery {SNOMEDCT:161765003,282020008,49550006} {ICD9CM:644.2} {UMLS C4552742,C0151526,C0438076 HP:0001622} {HPO HP:0001622 C0151526,C0233315}',
'miscellaneous': '''Most cases are sporadic {UMLS C1865403};\nAssociated with advanced paternal age {UMLS C1857548};\nAutosomal dominant transmission has been rarely reported {UMLS C3276489};\nPhenotypic similarities to Noonan syndrome ({163950});\nPhenotypic similarities to Costello syndrome ({218040})''',
'molecularBasis': '''Caused by mutation in the V-Ki-Ras2 Kirsten rat sarcoma 2 viral oncogene homolog gene (KRAS, {190070.0009});\nCaused by mutation in the V-Raf murine sarcoma viral oncogene homolog B1 gene (BRAF, {164757.0012});\nCaused by mutation in the mitogen-activated protein kinase kinase 1 gene (MAP2K1, {176872.0001});\nCaused by mutation in the mitogen-activated protein kinase kinase 1 gene (MAP2K2, {601263.0001})''',
'inheritanceExists': True,
'growthExists': True,
'growthHeightExists': True,
'growthWeightExists': False,
'growthOtherExists': True,
'headAndNeckExists': True,
'headAndNeckHeadExists': True,
'headAndNeckFaceExists': True,
'headAndNeckEarsExists': True,
'headAndNeckEyesExists': True,
'headAndNeckNoseExists': True,
'headAndNeckMouthExists': True,
'headAndNeckTeethExists': True,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': True,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': True,
'chestExternalFeaturesExists': True,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': True,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': True,
'abdomenGastrointestinalExists': True,
'genitourinaryExists': True,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': True,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': True,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': True,
'skeletalFeetExists': True,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': True,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': True,
'neurologicPeripheralNervousSystemExists': True,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': True,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': True,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': True,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': True,
'molecularBasisExists': True,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115195,
'prefix': '#',
'preferredTitle': 'CARDIOMYOPATHY, FAMILIAL HYPERTROPHIC, 2; CMH2',
'oldFormat': {
'Cardiac': 'Hypertrophic cardiomyopathy {SNOMEDCT:195020003,233873004,45227007} {ICD10CM:I42.1,I42.2} {ICD9CM:425.1,425.11} {UMLS C0340425,C4551472,C0007194 HP:0001639} {HPO HP:0001639 C0007194};',
'Inheritance': 'Autosomal dominant (1q3) {HPO HP:0000006 C0443147}; other forms at loci on chromosomes 11, 14, 15 and at least one other locus;'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115196,
'prefix': '#',
'preferredTitle': 'CARDIOMYOPATHY, FAMILIAL HYPERTROPHIC, 3; CMH3',
'oldFormat': {
'Cardiac': 'Hypertrophic cardiomyopathy {SNOMEDCT:195020003,233873004,45227007} {ICD10CM:I42.1,I42.2} {ICD9CM:425.1,425.11} {UMLS C0340425,C4551472,C0007194 HP:0001639} {HPO HP:0001639 C0007194};',
'Inheritance': 'Autosomal dominant (15) {HPO HP:0000006 C0443147}; other forms at loci on chromosomes 1, 11, 14, and at least one other locus;'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115197,
'prefix': '#',
'preferredTitle': 'CARDIOMYOPATHY, FAMILIAL HYPERTROPHIC, 4; CMH4',
'inheritance': '''Autosomal dominant (incomplete penetrance) {HPO HP:0000006 C0443147};\nAutosomal recessive {SNOMEDCT:258211005} {UMLS C0441748 HP:0000007} {HPO HP:0000007 C0441748,C4020899}''',
'cardiovascularHeart': '''Hypertrophic cardiomyopathy {SNOMEDCT:195020003,233873004,45227007} {ICD10CM:I42.1,I42.2} {ICD9CM:425.1,425.11} {UMLS C0340425,C4551472,C0007194 HP:0001639} {HPO HP:0001639 C0007194};\nChest pain {SNOMEDCT:29857009} {ICD10CM:R07.9} {ICD9CM:786.50,786.5} {UMLS C0008031,C2926613 HP:0100749} {HPO HP:0100749 C0008031};\nCardiomegaly {SNOMEDCT:8186001} {ICD10CM:I51.7} {ICD9CM:429.3} {UMLS C0018800 HP:0001640} {HPO HP:0001640 C0018800};\nBilateral ventricular hypertrophy;\nEnlarged right atrium {SNOMEDCT:67751000119106} {UMLS C0748427 HP:0030718};\nProgressive heart failure {UMLS C4692816};\nPericardial effusion {SNOMEDCT:373945007} {UMLS C4554646,C0031039,C1253937 HP:0001698} {HPO HP:0001698 C0031039};\nFirst-degree atrioventricular block;\nReduced left ventricular systolic function;\nReduced shortening fraction of left ventricle;\nReduced right ventricular systolic function;\nEnlarged left ventricular end systolic diameter;\nThickened interventricular septum {HPO HP:0005144 C1845019};\nComplete and incomplete left bundle branch block;\nRight bundle branch block {SNOMEDCT:59118001,164907000} {ICD10CM:I45.10,I45.0} {ICD9CM:426.4} {UMLS C0085615,C0344421 HP:0011712} {HPO HP:0011712 C0085615};\nVentricular fibrillation {SNOMEDCT:164896001,71908006} {ICD10CM:I49.01} {ICD9CM:427.41} {UMLS C0344435,C1962976,C2108112,C0042510,C4554001 HP:0001663} {HPO HP:0001663 C0042510};\nCardiac arrest {SNOMEDCT:397829000,410429000} {ICD10CM:I46} {ICD9CM:427.5} {UMLS C4553105,C0018790 HP:0001695} {HPO HP:0001695 C0018790}''',
'cardiovascularVascular': '''Syncope {SNOMEDCT:271594007,309585006,272030005} {ICD10CM:R55} {ICD9CM:780.2} {UMLS C0039070,C4554644,C3541349 HP:0001279} {HPO HP:0001279 C0039070};\nTransient ischemic attack {SNOMEDCT:266257000} {ICD10CM:G45.9} {ICD9CM:435,435.9} {UMLS C0917805,C0007787 HP:0002326} {HPO HP:0002326 C0917805};\nStroke {SNOMEDCT:230690007} {ICD10CM:I63.9} {UMLS C0038454,C4554100 HP:0001297} {HPO HP:0001297 C0038454}''',
'respiratoryLung': '''Dyspnea {SNOMEDCT:267036007,230145002} {ICD10CM:R06.0,R06.00,R06.02} {ICD9CM:786.05} {UMLS C2024878,C0013404,C1963100 HP:0002098,HP:0002094} {HPO HP:0002094 C0013404};\nPulmonary edema {SNOMEDCT:19242006} {ICD10CM:J81,J81.1} {UMLS C4553407,C0034063 HP:0100598} {HPO HP:0100598 C0034063}''',
'abdomen': 'Ascites {SNOMEDCT:389026000} {ICD10CM:R18,R18.8} {ICD9CM:789.5} {UMLS C0003962,C4553641 HP:0001541} {HPO HP:0001541 C0003962}',
'abdomenLiver': 'Hepatomegaly {SNOMEDCT:80515008} {ICD10CM:R16.0} {ICD9CM:789.1} {UMLS C0019209 HP:0002240} {HPO HP:0002240 C0019209}',
'muscleSoftTissue': '''Myopathic changes (seen in homozygous patient) {HPO HP:0003198 C0026848};\nNumerous small fibers (seen in homozygous patient);\nDisorganization of sarcomeres on electron microscopy (seen in homozygous patient);\nPartial depletion of thick filaments (seen in homozygous patient)''',
'miscellaneous': '''Incomplete penetrance with heterozygous mutations;\nSudden death may occur, particularly during vigorous exercise;\nHomozygotes are more severely affected, with death in the neonatal period;\nPatients carrying the F305Pfs*27 mutation ({600958.0030}) are at higher risk of sudden death''',
'molecularBasis': 'Caused by mutation in the myosin-binding protein C gene (MYBPC3, {600958.0001})',
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': True,
'cardiovascularVascularExists': True,
'respiratoryExists': True,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': True,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': True,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': True,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': True,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': True,
'molecularBasisExists': True,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115200,
'prefix': '#',
'preferredTitle': 'CARDIOMYOPATHY, DILATED, 1A; CMD1A',
'oldFormat': {
'Cardiac': 'Congestive cardiomyopathy {SNOMEDCT:53043001,399020009,195021004} {ICD10CM:I42.0} {UMLS C0007193,C1449563 HP:0001644} {HPO HP:0001644 C0007193}; Conduction defects {SNOMEDCT:44808001} {ICD10CM:I45.9} {ICD9CM:426.9,426} {UMLS C0264886}; Atrial fibrillation or flutter; Ventricular arrhythmia {SNOMEDCT:44103008,164893009} {UMLS C1883529,C0085612,C0344424,C4553764 HP:0004308} {HPO HP:0004308 C0085612}; Congestive heart failure {SNOMEDCT:42343007} {ICD10CM:I50.9} {ICD9CM:428.0} {UMLS C0018802 HP:0001635} {HPO HP:0001635 C0018801,C0018802}; Pericardial effusion {SNOMEDCT:373945007} {UMLS C4554646,C0031039,C1253937 HP:0001698} {HPO HP:0001698 C0031039};',
'Neuro': 'Normal neurologic examination; Adams-Stokes attacks;',
'Lab': 'Myocardial deposits of a nonmetachromatic, diastase-resistant, PAS-positive polysaccharide; Defect in suppressor lymphocyte function;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147}; ? a recessive form also;'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115210,
'prefix': '#',
'preferredTitle': 'CARDIOMYOPATHY, FAMILIAL RESTRICTIVE, 1; RCM1',
'oldFormat': {
'Cardiac': 'Restrictive cardiomyopathy {SNOMEDCT:90828009,415295002} {ICD10CM:I42.5} {UMLS C1963079,C0007196 HP:0001723} {HPO HP:0001723 C0007196};',
'Lab': 'Diastolic dysfunction and atrial enlargement without ventricular dilatation by echocardiography;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115250,
'preferredTitle': 'COLLAGENOMA, FAMILIAL CUTANEOUS',
'oldFormat': {
'Cardiac': 'Tricuspid regurgitation {SNOMEDCT:111287006} {UMLS C0040961 HP:0005180} {HPO HP:0005180 C0040961}; Cardiomyopathy, esp. right ventricular {UMLS C2063326 HP:0011663}; Atrial fibrillation {SNOMEDCT:164889003,49436004} {ICD9CM:427.31} {UMLS C0344434,C0004238,C2926591,C1963067 HP:0005110} {HPO HP:0005110 C0004238}; Chronic congestive heart failure {SNOMEDCT:88805009} {UMLS C0264722};',
'GU': 'Primary testicular failure {SNOMEDCT:48723006,370997001} {UMLS C1384582 HP:0008720} {HPO HP:0008720 C1384582};',
'Skin': 'Cutaneous collagenomas; Congenital posterior occipital alopecia {UMLS C4024850 HP:0007534} {HPO HP:0007534 C4024850};',
'Eyes': 'Iris atrophy {SNOMEDCT:95709007} {UMLS C0423319 HP:0001089} {HPO HP:0001089 C0423319};',
'Ears': 'Sensorineural hearing loss {SNOMEDCT:60700002} {ICD10CM:H90.5} {ICD9CM:389.1,389.10} {UMLS C0018784 HP:0000407} {HPO HP:0000407 C0018784};',
'Vascular': 'Recurrent vasculitis;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': True,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': True,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': True,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115300,
'prefix': '#',
'preferredTitle': 'HYPERCAROTENEMIA AND VITAMIN A DEFICIENCY, AUTOSOMAL DOMINANT; HCVAD',
'inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147}',
'skinNailsHairSkin': 'Yellow-orange colored skin {UMLS C2751425}',
'laboratoryAbnormalities': '''Increased serum beta-carotene {UMLS C2751422};\nDecreased serum vitamin A {UMLS C2751423};\nDecreased conversion of beta-carotene to vitamin A (retinol) {UMLS C2751424}''',
'molecularBasis': 'Caused by mutation in the beta-carotene 15,15-prime-monooxygenase 1 gene (BCMO1, {605748.0001}).',
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': False,
'molecularBasisExists': True,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115310,
'prefix': '#',
'preferredTitle': 'PARAGANGLIOMAS 4; PGL4',
'inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147}',
'headAndNeckEars': 'Pulsatile tinnitus (tympanic paraganglioma) {UMLS C1854340} {HPO HP:0008629 C0751559}',
'cardiovascularHeart': '''Palpitations (with pheochromocytoma) {UMLS C1854346} {HPO HP:0001962 C0030252};\nTachycardia (with pheochromocytoma) {UMLS C1854347} {HPO HP:0001649 C0039231,C4020868}''',
'cardiovascularVascular': 'Hypertension (with pheochromocytoma) {UMLS C1397267} {HPO HP:0000822 C0020538,C0497247}',
'skinNailsHairSkin': 'Diaphoresis (with pheochromocytoma) {UMLS C1854341} {HPO HP:0000975 C0020458,C0038990,C0700590}',
'neurologicCentralNervousSystem': '''Headache (with pheochromocytoma) {UMLS C1854337} {HPO HP:0002315 C0018681};\nCranial nerve palsies can arise with head and neck paragangliomas {UMLS C1854338}''',
'neurologicBehavioralPsychiatricManifestations': 'Anxiety (with pheochromocytoma) {UMLS C1854339} {HPO HP:0000739 C0003467,C4020884}',
'neoplasia': '''Paragangliomas {SNOMEDCT:72787006,253029009,302833002,803009,127027008} {UMLS C0030421 HP:0002668} {HPO HP:0002668 C0030421};\nMultiple tumors in 28% of patients {UMLS C1861849};\nParagangliomas, head and neck (31%) {UMLS C1861850} {HPO HP:0002864 C1333944};\nChemodectomas {SNOMEDCT:72787006,51747000,302833002,127027008,803009,127028003,253029009,30699005,302834008} {UMLS C0030421,C0030422,C0007279 HP:0030074,HP:0002668} {HPO HP:0030074 C0007279};\nCarotid body tumors {SNOMEDCT:72787006,302833002,127027008,803009,127028003,253029009,30699005} {UMLS C0030421,C0007279 HP:0030074,HP:0002668} {HPO HP:0002668 C0030421};\nGlomus jugular tumors {SNOMEDCT:32037004,127030001} {UMLS C0017671 HP:0003001};\nPheochromocytomas, adrenal (28%) {UMLS C1861851} {HPO HP:0006748 C0031511};\nPheochromocytomas, extraadrenal (48%) {UMLS C1861852};\nMalignancy (34%) {UMLS C1861853};\nGastrointestinal stromal tumors (less common) {UMLS C3149028} {HPO HP:0100723 C0238198};\nRenal cell carcinoma (less common) {UMLS C1861854} {HPO HP:0005584 C0007134};\nNeuroblastoma (less common) {UMLS C2751421} {HPO HP:0003006 C0027819}''',
'laboratoryAbnormalities': 'Increased urinary catecholamines (with pheochromocytoma) {UMLS C1861855}',
'miscellaneous': '''Adult onset (mean 30 years, range 10-65 years) {UMLS C1861857} {HPO HP:0003581 C1853562};\nIncomplete penetrance (range 13% to 77% by 50 years of age) {UMLS C3549546} {HPO HP:0003829 C1836598};\nSigns and symptoms depend on tumor location and activity {UMLS C1854351};\nPatients may have head and neck paragangliomas only, adrenal or extraadrenal pheochromocytomas only, or both {UMLS C1868644};\nSee also PGL1 ({168000})''',
'molecularBasis': 'Caused by mutation in the succinate dehydrogenase complex subunit B gene (SDHB, {185470.0001})',
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': True,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': True,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': True,
'cardiovascularHeartExists': True,
'cardiovascularVascularExists': True,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': False,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': False,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': True,
'skinNailsHairSkinExists': True,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': True,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': True,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': True,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': True,
'molecularBasisExists': True,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115400,
'preferredTitle': 'CARPAL DISPLACEMENT',
'oldFormat': {
'Limbs': 'Carpal bossing;',
'Radiology': 'Misshapen distal carpal epiphyses;',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': True,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': True,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': False,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': False,
'miscellaneousExists': False,
'molecularBasisExists': False,
'matches': ''
} },
{'clinicalSynopsis': {
'mimNumber': 115430,
'prefix': '#',
'preferredTitle': 'CARPAL TUNNEL SYNDROME; CTS1',
'oldFormat': {
'Neuro': 'Constrictive median neuropathy {UMLS C4023009 HP:0012185} {HPO HP:0012185 C4023009}; Tunnel sign;',
'Limbs': 'Thickened transverse carpal ligament; Digital flexor tenosynovitis {SNOMEDCT:448251000124102} {ICD10CM:M65.3} {UMLS C0158328 HP:0012276} {HPO HP:0012276 C4022974};',
'Misc': 'Responsive to pyridoxine administration; Early onset age;',
'Lab': 'Vitamin B6 deficiency {SNOMEDCT:386080007} {ICD10CM:E53.1} {ICD9CM:266.1} {UMLS C0936215 HP:0008326} {HPO HP:0008326 C0936215};',
'Inheritance': 'Autosomal dominant {SNOMEDCT:263681008} {UMLS C0443147 HP:0000006} {HPO HP:0000006 C0443147};'
} ,
'oldFormatExists': True,
'inheritanceExists': True,
'growthExists': False,
'growthHeightExists': False,
'growthWeightExists': False,
'growthOtherExists': False,
'headAndNeckExists': False,
'headAndNeckHeadExists': False,
'headAndNeckFaceExists': False,
'headAndNeckEarsExists': False,
'headAndNeckEyesExists': False,
'headAndNeckNoseExists': False,
'headAndNeckMouthExists': False,
'headAndNeckTeethExists': False,
'headAndNeckNeckExists': False,
'cardiovascularExists': False,
'cardiovascularHeartExists': False,
'cardiovascularVascularExists': False,
'respiratoryExists': False,
'respiratoryNasopharynxExists': False,
'respiratoryLarynxExists': False,
'respiratoryAirwaysExists': False,
'respiratoryLungExists': False,
'chestExists': False,
'chestExternalFeaturesExists': False,
'chestRibsSternumClaviclesAndScapulaeExists': False,
'chestBreastsExists': False,
'chestDiaphragmExists': False,
'abdomenExists': False,
'abdomenExternalFeaturesExists': False,
'abdomenLiverExists': False,
'abdomenPancreasExists': False,
'abdomenBiliaryTractExists': False,
'abdomenSpleenExists': False,
'abdomenGastrointestinalExists': False,
'genitourinaryExists': False,
'genitourinaryExternalGenitaliaMaleExists': False,
'genitourinaryExternalGenitaliaFemaleExists': False,
'genitourinaryInternalGenitaliaMaleExists': False,
'genitourinaryInternalGenitaliaFemaleExists': False,
'genitourinaryKidneysExists': False,
'genitourinaryUretersExists': False,
'genitourinaryBladderExists': False,
'skeletalExists': True,
'skeletalSkullExists': False,
'skeletalSpineExists': False,
'skeletalPelvisExists': False,
'skeletalLimbsExists': True,
'skeletalHandsExists': False,
'skeletalFeetExists': False,
'skinNailsHairExists': False,
'skinNailsHairSkinExists': False,
'skinNailsHairSkinHistologyExists': False,
'skinNailsHairSkinElectronMicroscopyExists': False,
'skinNailsHairNailsExists': False,
'skinNailsHairHairExists': False,
'muscleSoftTissueExists': False,
'neurologicExists': True,
'neurologicCentralNervousSystemExists': False,
'neurologicPeripheralNervousSystemExists': False,
'neurologicBehavioralPsychiatricManifestationsExists': False,
'voiceExists': False,
'metabolicFeaturesExists': False,
'endocrineFeaturesExists': False,
'hematologyExists': False,
'immunologyExists': False,
'neoplasiaExists': False,
'prenatalManifestationsExists': False,
'prenatalManifestationsMovementExists': False,
'prenatalManifestationsAmnioticFluidExists': False,
'prenatalManifestationsPlacentaAndUmbilicalCordExists': False,
'prenatalManifestationsMaternalExists': False,
'prenatalManifestationsDeliveryExists': False,
'laboratoryAbnormalitiesExists': True,
'miscellaneousExists': True,
'molecularBasisExists': False,
'matches': ''
}
} ]
}
} } | [
"[email protected]"
]
| |
593d13c224a279fdd6e7316dac0be8555af09385 | 491f9c9b618242953329a8e633fd9bf0bb1cb3fe | /learn_pytest/python_examination/sync_lock.py | 5519da2e10fea248403d3b16ef3f4f2f0ac1fac3 | []
| no_license | xshen1122/Scripts | 656d599e47a70a3b3e89e4f95cf97ee391ff9a7e | c1ed60abc7885d4a86ba077efc8bcf0fbdbafd75 | refs/heads/master | 2021-06-28T04:46:31.370809 | 2020-10-21T07:52:15 | 2020-10-21T07:52:15 | 172,480,092 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,204 | py | # sync_lock.py
#coding=utf-8
import threading
import time
'''
charactors:
1. only 1 global
2. only 1 lock
3. before add, acquire lock,after add, release lock
'''
g_num = 0
# 创建一个互斥锁
# 默认是未上锁的状态
mutex = threading.Lock()
def work1(num):
global g_num
for i in range(num):
mutex.acquire() # 上锁
g_num += 1
mutex.release() # 解锁
print("----in work1, g_num is %d---"%g_num)
def work2(num):
global g_num
for i in range(num):
mutex.acquire() # 上锁
g_num += 1
mutex.release() # 解锁
print("----in work2, g_num is %d---"%g_num)
def main():
print("---线程创建之前g_num is %d---"%g_num)
# 创建两个线程,各自对g_num进行相加
t1 = threading.Thread(target=work1, args=(10000000,))
t1.start()
t2 = threading.Thread(target=work2, args=(10000000,))
t2.start()
while len(threading.enumerate()) != 1:
time.sleep(1)
print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)
if __name__ == "__main__":
main()
'''
first time:
---线程创建之前g_num is 0---
----in work2, g_num is 19820884---
----in work1, g_num is 20000000---
2个线程对同一个全局变量操作之后的最终结果是:20000000
second time:
---线程创建之前g_num is 0---
----in work2, g_num is 19739028---
----in work1, g_num is 20000000---
2个线程对同一个全局变量操作之后的最终结果是:20000000
锁的好处:
确保了某段关键代码只能由一个线程从头到尾完整地执行
锁的坏处:
阻止了多线程并发执行,包含锁的某段代码实际上只能以单线程模式执行,效率就大大地下降了
由于可以存在多个锁,不同的线程持有不同的锁,并试图获取对方持有的锁时,可能会造成死锁
Avoid dead lock
综上所述,银行家算法是从当前状态出发,逐个按安全序列检查各客户谁能完成其工作,
然后假定其完成工作且归还全部贷款,再进而检查下一个能完成工作的客户,......。
如果所有客户都能完成工作,则找到一个安全序列,银行家才是安全的
''' | [
"[email protected]"
]
| |
ed59d8a4c0d35e75c635155b41d8cc44e1c46c8b | 336b63131998e41e9968bbb036d4244ab259d479 | /lesson4_full_responsiveness/full_responsive_blog/blog/__init__.py | a1ac2bb4d1582f9183f80af99300c66def808063 | []
| no_license | jreiher2003/responsiveImages | 1c93e32143784d63e149354f216b513e275c93b2 | ed8acbc2695bd55b30c9d60d39a83caf2819e431 | refs/heads/master | 2020-06-05T14:48:47.482907 | 2015-08-24T14:30:02 | 2015-08-24T14:30:02 | 40,184,731 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 70 | py | from flask import Flask
app = Flask(__name__)
from blog import views | [
"[email protected]"
]
| |
3ebef0181194e685a308c0d0dc844268473d9e40 | b3330bd3365767b89afb9c432f4deb722b39ac1c | /python/interviews/airbnb_interview.py | 0606e6cdb6d380deac6a5ec412d64fba6ca83161 | []
| no_license | hguochen/algorithms | 944df332d5b39220bd59cbd62dc74b12e335fb9e | 703e71a5cd9e002d800340df879ed475a404d092 | refs/heads/master | 2022-02-27T12:11:10.607042 | 2022-02-18T21:04:00 | 2022-02-18T21:04:00 | 13,767,503 | 5 | 7 | null | null | null | null | UTF-8 | Python | false | false | 3,109 | py | '''
A host gets a set of back to back reservation requests (inquiries) for stays
of various lengths. The information about these requests is stored in an array,
where each value is an integer representing the length of a stay in nights. All
of these inquiries are back to back, which means that stay number i+1 starts
right after stay number i ends. The host wants to have time to prepare the
listing for the next guest, so they don't want to accept inquiries that are
adjacent to each other. In other words, if they accept inquiry i, they can't
also accept either i-1 or i+1.
Under these conditions, what is the maximum number of nights the host can
accept?
Some examples:
[5, 1, 2, 6] = 11 [5,2] [5,6] [1,6]
[4, 9, 6] = 10 [4, 6] [9]
[4, 11, 6] = 11
[4, 10, 3, 1, 5] = 15
[1] -> [1]
[1,2] -> [1] [2]
[1,2,3] -> [1,3], [2], [3]
[1,2,3,4] -> [1,3] [1,4] [2,4]
every index will generate n-2
'''
import copy
def max_nights(array):
"""
Dynamic programming solution.
O(n)
"""
if len(array) < 1:
return 0
elif len(array) <= 2:
return max(array)
else:
compare = [[array[0]], array[0]]
if array[1] > array[0]:
gap = [[array[1]], array[1]]
else:
gap = copy.deepcopy(compare)
for i in xrange(2, len(array)):
if compare[1] + array[i] > gap[1]:
compare[0].append(array[i])
compare[1] = compare[1] + array[i]
compare, gap = gap, compare
else:
compare = copy.deepcopy(gap)
return gap
# assumptions
# min 0 size
# max infinite
# all integeres in array are positive and no 0s
# get subsets of from the original array based on rules to omit immediate next
# request
# compute the sum of subsets and return the largest value
# O(n * n-2) -> O(n^2)
def maximum_nights(array):
if len(array) < 1:
return 0
largest = 0
for i in xrange(len(array)): # O(n)
temp = 0
if i == len(array)-2:
if array[i] > largest:
largest = array[i]
break
for item in array[i+2:]: # O(n-2)
temp = array[i] + item
if temp > largest:
largest = temp
return largest
# O(n)
# possible to update the largest with only 1 run
def maximum_nights3(array):
if len(array) < 1:
return 0
largest = 0
for i in xrange(len(array)):
if i == len(array)-2:
if array[i] > largest:
largest = array[i]
break
sliced = array[i+2:]
if len(sliced) < 1:
continue
temp = array[i] + max(sliced)
if temp > largest:
largest = temp
return largest
if __name__ == "__main__":
test1 = [5, 1, 2, 6, 20, 2]
test2 = [4, 9, 6]
test3 = [4, 11, 6]
test4 = [4, 10, 3, 1, 5]
print maximum_nights3(test1), max_nights(test1) # 11
print maximum_nights3(test2), max_nights(test2) # 10
print maximum_nights3(test3), max_nights(test3) # 11
print maximum_nights3(test4), max_nights(test4) # 15
| [
"[email protected]"
]
| |
dee6ff4b161070ca78004c953b96b987c2b5e47f | 786027545626c24486753351d6e19093b261cd7d | /ghidra9.2.1_pyi/ghidra/graph/job/MoveVertexToCenterAnimatorFunctionGraphJob.pyi | 1a8355245b98205e284af676d6f82d0cd3aae7d4 | [
"MIT"
]
| permissive | kohnakagawa/ghidra_scripts | 51cede1874ef2b1fed901b802316449b4bf25661 | 5afed1234a7266c0624ec445133280993077c376 | refs/heads/main | 2023-03-25T08:25:16.842142 | 2021-03-18T13:31:40 | 2021-03-18T13:31:40 | 338,577,905 | 14 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,133 | pyi | import ghidra.graph.job
import ghidra.util.task
import java.awt.geom
import java.lang
class MoveVertexToCenterAnimatorFunctionGraphJob(ghidra.graph.job.MoveViewAnimatorFunctionGraphJob):
def __init__(self, __a0: edu.uci.ics.jung.visualization.VisualizationServer, __a1: object, __a2: bool): ...
def canShortcut(self) -> bool: ...
def dispose(self) -> None: ...
def equals(self, __a0: object) -> bool: ...
def execute(self, listener: ghidra.graph.job.GraphJobListener) -> None: ...
def getClass(self) -> java.lang.Class: ...
def hashCode(self) -> int: ...
def isFinished(self) -> bool: ...
def notify(self) -> None: ...
def notifyAll(self) -> None: ...
def setBusyListener(self, listener: ghidra.util.task.BusyListener) -> None: ...
def setOffset(self, offsetFromOriginalPoint: java.awt.geom.Point2D) -> None: ...
def shortcut(self) -> None: ...
def toString(self) -> unicode: ...
@overload
def wait(self) -> None: ...
@overload
def wait(self, __a0: long) -> None: ...
@overload
def wait(self, __a0: long, __a1: int) -> None: ...
| [
"[email protected]"
]
| |
6a12630e2c604bd3d4846c1c689b8ef29ce522f5 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/semantic_segmentation/MMseg-swin/configs/segformer/segformer_mit-b3_8x1_1024x1024_160k_cityscapes.py | 8eda8e4380774b352568fcd4f9bafd8ea178d8d0 | [
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
]
| permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 3,795 | py | # -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017
# All rights reserved.
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==========================================================================
# -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017
# All rights reserved.
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==========================================================================
_base_ = ['./segformer_mit-b0_8x1_1024x1024_160k_cityscapes.py']
checkpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/segformer/mit_b3_20220624-13b1141c.pth' # noqa
model = dict(
backbone=dict(
init_cfg=dict(type='Pretrained', checkpoint=checkpoint),
embed_dims=64,
num_layers=[3, 4, 18, 3]),
decode_head=dict(in_channels=[64, 128, 320, 512]))
| [
"[email protected]"
]
| |
0ae6ded01b3c8dfb6041f106bfef7ba3f04ad22b | 23561a4d2a9c169b8c2fdeb330f6ff4e2d2e4581 | /dayu_widgets/examples/MMessageTest.py | fc96b0a5b93cfdc7e6ff28861c8d997c2e72e752 | [
"MIT"
]
| permissive | DangoWang/dayu_widgets | 3e04516d15bd73e8544c17deb2ce91f80981bce1 | 980a3d40388e2022cc581dd1b9c6e9ed19788f35 | refs/heads/master | 2020-06-06T05:37:24.986564 | 2019-06-04T12:06:15 | 2019-06-04T12:06:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,892 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2019.2
# Email : [email protected]
###################################################################
import functools
from dayu_widgets.MButtonGroup import MPushButtonGroup
from dayu_widgets.MDivider import MDivider
from dayu_widgets.MFieldMixin import MFieldMixin
from dayu_widgets.MLabel import MLabel
from dayu_widgets.MMessage import MMessage
from dayu_widgets.MPushButton import MPushButton
from dayu_widgets.qt import *
class MMessageTest(QWidget, MFieldMixin):
def __init__(self, parent=None):
super(MMessageTest, self).__init__(parent)
self._init_ui()
def _init_ui(self):
button3 = MPushButton(text='Normal Message', type=MPushButton.PrimaryType)
button4 = MPushButton(text='Success Message', type=MPushButton.SuccessType)
button5 = MPushButton(text='Warning Message', type=MPushButton.WarningType)
button6 = MPushButton(text='Error Message', type=MPushButton.ErrorType)
button3.clicked.connect(functools.partial(self.slot_show_message, MMessage.info, {'text': u'这是一条普通提示'}))
button4.clicked.connect(functools.partial(self.slot_show_message, MMessage.success, {'text': u'恭喜你,成功啦!'}))
button5.clicked.connect(functools.partial(self.slot_show_message, MMessage.warning, {'text': u'我警告你哦!'}))
button6.clicked.connect(functools.partial(self.slot_show_message, MMessage.error, {'text': u'失败了!'}))
sub_lay1 = QHBoxLayout()
sub_lay1.addWidget(button3)
sub_lay1.addWidget(button4)
sub_lay1.addWidget(button5)
sub_lay1.addWidget(button6)
button_duration = MPushButton(text='show 5s Message')
button_duration.clicked.connect(functools.partial(self.slot_show_message, MMessage.info,
{'text': u'该条消息将显示5秒后关闭',
'duration': 5
}))
button_closable = MPushButton(text='closable Message')
button_closable.clicked.connect(functools.partial(self.slot_show_message, MMessage.info,
{'text': u'可手动关闭提示',
'closable': True
}))
main_lay = QVBoxLayout()
main_lay.addWidget(MDivider('different type'))
main_lay.addLayout(sub_lay1)
main_lay.addWidget(MLabel(u'不同的提示状态:普通、成功、警告、错误。默认2秒后消失'))
main_lay.addWidget(MDivider('set duration'))
main_lay.addWidget(button_duration)
main_lay.addWidget(MLabel(u'自定义时长,config中设置duration值,单位为秒'))
main_lay.addWidget(MDivider('set closable'))
main_lay.addWidget(button_closable)
main_lay.addWidget(MLabel(u'设置是否可关闭,config中设置closable 为 True'))
button_grp = MPushButtonGroup()
button_grp.set_button_list([
{'text': 'set duration to 1s',
'clicked': functools.partial(self.slot_set_config, MMessage.config, {'duration': 1})},
{'text': 'set duration to 10s',
'clicked': functools.partial(self.slot_set_config, MMessage.config, {'duration': 10})},
{'text': 'set top to 5',
'clicked': functools.partial(self.slot_set_config, MMessage.config, {'top': 5})},
{'text': 'set top to 50',
'clicked': functools.partial(self.slot_set_config, MMessage.config, {'top': 50})},
])
loading_button = MPushButton.primary('Display a loading indicator')
loading_button.clicked.connect(self.slot_show_loading)
main_lay.addWidget(MDivider('set global setting'))
main_lay.addWidget(button_grp)
main_lay.addWidget(MLabel(u'全局设置默认duration(默认2秒);top(离parent顶端的距离,默认24px)'))
main_lay.addWidget(loading_button)
main_lay.addStretch()
self.setLayout(main_lay)
def slot_show_message(self, func, config):
func(parent=self, **config)
def slot_set_config(self, func, config):
func(**config)
def slot_show_loading(self):
msg = MMessage.loading(u'正在加载中', parent=self)
msg.sig_closed.connect(functools.partial(MMessage.success, u'加载成功啦!!哈哈哈哈', self))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
test = MMessageTest()
from dayu_widgets import dayu_theme
dayu_theme.apply(test)
test.show()
sys.exit(app.exec_())
| [
"[email protected]"
]
| |
f1259a4f81b2d648cd09e4d43b32528aacea3340 | 491235d50ab27bb871d58a5dfff74d6a4aa9bbe6 | /pong-client/pong.py | 0df4af0d73a6bda898022ba8e51b66bc7b2083b6 | []
| no_license | elgrandt/Pong-Network | 768bb861757d1fb98be3b761a66ad14e632f7932 | 204e1c5d9fbd53eece906d56df394602bdc269b6 | refs/heads/master | 2022-12-06T16:12:01.506699 | 2020-08-18T03:27:47 | 2020-08-18T03:27:47 | 288,315,589 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,305 | py | import pygame
import network
from gui import server_list,events,server_connect_menu,status_cur,loading
import gui
import global_knowns
from twisted.internet import reactor,threads
import sys
import thread
import global_knowns as gk
import elements
class game:
def __init__(self,IOSYS):
self.IOSYS = IOSYS
self.elements = []
menu_connect = server_connect_menu.server_connect()
menu_connect.set_position((300-menu_connect.W/2,200-menu_connect.H/2))
self.mc = menu_connect
self.elements.append(menu_connect)
self.STATUS = "TOCONNECT"
def handleData(self,data):
if (data["packet"] == global_knowns.welcome):
self.handleStart()
elif (data["packet"] == gk.rooms_information):
self.update_rooms(data["rooms"])
elif (data["packet"] == gk.extra_rooms_info):
self.update_room_extra(data["data"])
elif (data["packet"] == gk.element_list):
self.updateElements(data["data"])
elif (data["packet"] == gk.start_game):
self.startSendMove()
elif (data["packet"] == gk.stop_game):
self.endSendMove()
def logic_update(self,EVENTS):
for x in range(len(self.elements)):
self.elements[x].logic_update(EVENTS)
if (self.STATUS == "TOCONNECT"):
self.update_menu_connect()
elif (self.STATUS == "CONNECTING"):
self.update_connecting()
elif (self.STATUS == "ROOMLIST"):
self.update_room_list()
elif (self.STATUS == "ERROR"):
self.update_error_connect()
elif (self.STATUS == "GAME"):
self.updateGame()
def graphic_update(self,SCREEN):
for x in range(len(self.elements)):
self.elements[x].graphic_update(SCREEN)
def update_menu_connect(self):
if (self.mc.button_connect.button.pressed):
self.start_connect(self.mc.get_host(),self.mc.get_port())
def start_connect(self,host,port):
self.mc.set_loading()
self.STATUS = "CONNECTING"
self.reactorStart( host,port,self.IOSYS.NETWORK)
def update_connecting(self):
pass
def reactorStart(self,GAME_IP,GAME_PORT,connection):
if (GAME_IP == "Host"):
GAME_IP = "localhost"
GAME_PORT = "9999"
reactor.connectTCP(GAME_IP, int(GAME_PORT), connection) # @UndefinedVariable
def handleStart(self):
self.elements = []
sl = server_list(self.IOSYS.NETWORK)
sl.set_position((0,0))
self.elements.append(sl)
self.sl = sl
if (self.STATUS == "CONNECTING"):
self.STATUS = "ROOMLIST"
self.get_info()
def handleFail(self):
if (self.STATUS == "CONNECTING"):
self.STATUS = "ERROR"
self.mc.set_error()
def update_room_list(self):
if (self.sl.end == True):
self.STATUS = "GAME"
self.elements = []
self.elementManager = elements.manager(self.IOSYS.NETWORK)
self.elements.append(self.elementManager)
def update_error_connect(self):
if (self.mc.ta.button.pressed):
x,y = self.mc.X,self.mc.Y
self.mc.__init__()
self.mc.set_position((x,y))
self.STATUS = "TOCONNECT"
def get_info(self):
self.IOSYS.NETWORK.protocol.sendData({"packet":gk.get_rooms_information})
def update_rooms(self,data):
self.sl.update(data)
def update_room_extra(self,data):
if (self.STATUS == "ROOMLIST"):
self.sl.update_extra(data)
def updateGame(self):
pass
def updateElements(self,data):
if (self.STATUS == "GAME"):
self.elementManager.updateElements(data)
def startSendMove(self):
self.elementManager.startSend()
def stopSendMove(self):
self.elementManager.stopSend()
class iosys:
def __init__(self):
#OUTPUT
self.SCREEN = pygame.display.set_mode((600,400))
#INPUT
self.EVENTS = events.events()
#LOGIC
self.GAME = game(self)
#NETWORK
self.NETWORK = network.gameClientFactory(self.GAME)
#CLOCK
self.CLOCK = pygame.time.Clock()
#ON
self.ON = True
def updating(self):
if (True):
self.SCREEN.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quitGame()
self.EVENTS.update_keyboard(pygame.key.get_pressed())
self.EVENTS.update_mouse(pygame.mouse.get_pos(),pygame.mouse.get_pressed())
self.GAME.logic_update(self.EVENTS)
self.GAME.graphic_update(self.SCREEN)
status_cur.update()
pygame.display.update()
reactor.callLater(1./40,self.updating)# @UndefinedVariable
def quitGame(self):
reactor.stop()# @UndefinedVariable
pygame.quit()
def main():
pygame.init()
io = iosys()
io.updating()
reactor.run()# @UndefinedVariable
main()
| [
"[email protected]"
]
| |
a2c5d72364cb3e960aa0ad31b96f0ece5611e5db | ce76b3ef70b885d7c354b6ddb8447d111548e0f1 | /case/world/different_point/work_or_day.py | ec81da39db35106ef6fe892116e21fe8b9443a91 | []
| no_license | JingkaiTang/github-play | 9bdca4115eee94a7b5e4ae9d3d6052514729ff21 | 51b550425a91a97480714fe9bc63cb5112f6f729 | refs/heads/master | 2021-01-20T20:18:21.249162 | 2016-08-19T07:20:12 | 2016-08-19T07:20:12 | 60,834,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py |
#! /usr/bin/env python
def little_time(str_arg):
thing(str_arg)
print('be_woman_with_new_company')
def thing(str_arg):
print(str_arg)
if __name__ == '__main__':
little_time('leave_different_person')
| [
"[email protected]"
]
| |
3262ec6b92ac1240518c3b7f9d92a29fc31d4712 | 74434b547122c5f13f748c981851bfbdfdfc3a32 | /orders/migrations/0003_auto_20200509_1214.py | f98f90ce8ca8900504147176259d769937090bb0 | []
| no_license | anthonylauly/My-Shop---Django-2-By-Example | a4a597a6f1d243aebc74e30005034da4b3a0cf4a | 2e47abe19e1fc1f35ad73049f1f077ee805ad945 | refs/heads/main | 2023-01-30T00:20:44.343128 | 2020-12-08T06:05:43 | 2020-12-08T06:05:43 | 313,935,913 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 374 | py | # Generated by Django 2.2.12 on 2020-05-09 12:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_order_braintree_id'),
]
operations = [
migrations.AlterModelOptions(
name='order',
options={'ordering': ('-created',), 'verbose_name': 'order'},
),
]
| [
"[email protected]"
]
| |
a4dd4b1312533cde33af7a3832573538a1280377 | ad8bb38dc80e5898d59f140b93e044cca86a8c02 | /greedy-algorithms/assignment_2/tests/test_clustering.py | 8d7d0f0bb07293e8eac1cc5ff3b05fb7986c23ad | []
| no_license | ybim/stanford-algs | 5c4358fd7fa4e23ae6c1660b97d7596c4e6d4400 | 6c4749f2a4c2fc36630f74833acd352ce08b2a43 | refs/heads/master | 2021-03-04T03:45:13.444826 | 2018-03-25T21:07:28 | 2018-03-25T21:07:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 874 | py | import os
import os.path
import logging
from ..clustering import read_file, maximum_spacing
import pytest
test_dir = os.path.join(os.path.dirname(__file__),
'cluster_cases')
def lookup_spacing(f):
f = f.replace('input', 'output')
with open(f, 'r') as handle:
return int(handle.readlines()[0])
def pytest_generate_tests(metafunc):
idlist = []
argvalues = []
for case in metafunc.cls.cases:
idlist.append(case)
argvalues.append(os.path.join(test_dir, case))
metafunc.parametrize('_in', argvalues, ids=idlist, scope='class')
class TestCluster:
cases = [f for f in os.listdir(test_dir)
if f.startswith('input') and f.endswith('.txt')]
def test_clustering(self, _in):
nodes, edges = read_file(_in)
assert maximum_spacing(nodes, edges) == lookup_spacing(_in)
| [
"[email protected]"
]
| |
c87160c690087c80faa23886e3d2eb5ad52a67c4 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_53/143.py | d02c162e499137e8369e07af73f72116b53679db | []
| no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 258 | py | #!/usr/bin/env python
f = open('A-large.in', 'r')
n = int(f.readline())
count = 0
for line in f:
res = 'OFF'
count+=1
(n,k) = line.split()
n = int(n)
k = int(k)
if k>0:
if k%(2**n) == (2**n-1):
res = 'ON'
print 'Case #' + str(count) + ': '+ res
| [
"[email protected]"
]
| |
839b24b461961df7d7a77ebcc140ceeea25f949d | 265c94e9b4fdfd1aefbcef85242db4e1beef45df | /src/ch4/predictData_2015_0.25.py | 8d62a5850ed480818401d16854286573eee494f2 | []
| no_license | Relph1119/machine-learning-blueprints | 283cc1a6ee843ae4c806466af8f9a0df2325ecb6 | c46c5bd93bd781f96d41a80a03a797ca3e673627 | refs/heads/master | 2022-12-09T11:34:34.883337 | 2020-08-26T08:48:24 | 2020-08-26T08:48:24 | 136,500,353 | 2 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,171 | py | import getFeature as gft
from sklearn.ensemble import RandomForestClassifier
from sklearn import linear_model
import pandas as pd
import matplotlib.pyplot as plt
X = gft.X
ipos = gft.ipos
X_train, X_test = X[173:], X[:173]
y_train = ipos['$ Chg Open to Close'][173:].map(lambda x: 1 if x>=.25 else 0)
y_test = ipos['$ Chg Open to Close'][:173].map(lambda x: 1 if x>=.25 else 0)
clf = linear_model.LogisticRegression()
clf.fit(X_train, y_train)
clf.score(X_test, y_test)
#print(ipos[(ipos['Date']>='2015-01-01')]['$ Chg Open to Close'].describe())
pred_label=clf.predict(X_test)
results=[]
for pl, tl, idx, chg in zip(pred_label, y_test, y_test.index, ipos.iloc[y_test.index]['$ Chg Open to Close']):
if pl == tl:
results.append([idx, chg, pl, tl, 1])
else:
results.append([idx, chg, pl, tl, 0])
rf = pd.DataFrame(results, columns=['index', '$ chg', 'predicted', 'actual', 'correct'])
print(rf[rf['predicted']==1]['$ chg'].describe())
fig, ax = plt.subplots(figsize=(15, 10))
rf[rf['predicted']==1]['$ chg'].plot(kind='bar')
ax.set_title('Model Predicted Buys', y=1.01)
ax.set_ylabel('$ Change Open to Close')
ax.set_xlabel('Index')
plt.show() | [
"[email protected]"
]
| |
0e9b6c56ee63c623900c65faf8d6ad30c2b7eb88 | 7fc3d33c2ba5426ee6d68e80dd6c279320051ac2 | /nvis/base.py | d53390d0995cc0c38c002e377283d6d654f0ce95 | []
| no_license | sinhrks/nvis | e2f4b8382a3fe99f0c69051cfe64ee3d6ae29e51 | 7efb98f812a39572a9d2207ce5689ac0a56ba44f | refs/heads/master | 2021-01-12T13:26:41.363157 | 2016-09-25T22:14:19 | 2016-09-25T22:14:19 | 69,165,187 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,704 | py | #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import collections
import six
import traitlets
from enum import Enum
import nvis.common as com
class _JSObject(traitlets.HasTraits):
"""
Base class for JS instances, which can be converted to
JavaScript instance
"""
def __eq__(self, other):
# conmpare with script
if isinstance(other, _JSObject):
return self.script == other.script
return False
@property
def _klass(self):
return "Cesium.{0}".format(self.__class__.__name__)
@property
def _props(self):
raise NotImplementedError('must be overriden in child classes')
@property
def _property_dict(self):
props = collections.OrderedDict()
for p in self._props:
props[p] = getattr(self, p)
return props
@property
def script(self):
props = self._property_dict
results = com.to_jsobject(props)
return ''.join(results)
class _Enum(Enum):
@property
def script(self):
return self.value
class RistrictedList(_JSObject):
widget = traitlets.Instance(klass=_JSObject)
def __init__(self, widget, allowed, propertyname):
self.widget = widget
self._items = []
self._allowed = allowed
self._propertyname = propertyname
def add(self, item, **kwargs):
if com.is_listlike(item):
for i in item:
self.add(i, **kwargs)
elif isinstance(item, self._allowed):
for key, value in six.iteritems(kwargs):
setattr(item, key, value)
self._items.append(item)
else:
msg = 'item must be {allowed} instance: {item}'
if isinstance(self._allowed, tuple):
allowed = ', '.join([a.__name__ for a in self._allowed])
else:
allowed = self._allowed
raise ValueError(msg.format(allowed=allowed, item=item))
def clear(self):
self._items = []
def __len__(self):
return len(self._items)
def __getitem__(self, item):
return self._items[item]
@property
def script(self):
"""
return list of scripts built from entities
each script may be a list of comamnds also
"""
results = []
for item in self._items:
script = """{varname}.{propertyname}.add({item});"""
script = script.format(varname=self.widget._varname,
propertyname=self._propertyname,
item=item.script)
results.append(script)
return results
| [
"[email protected]"
]
| |
90f1ed30332f1619a1573ce61dab44dbb952e827 | 117f066c80f3863ebef74463292bca6444f9758a | /ray/do.py | a0649d1bcc56f44ebc03bdcbe163b03e6ef80cbd | []
| no_license | cottrell/notebooks | c6de3842cbaeb71457d270cbe6fabc8695a6ee1b | 9eaf3d0500067fccb294d064ab78d7aaa03e8b4d | refs/heads/master | 2023-08-09T22:41:01.996938 | 2023-08-04T22:41:51 | 2023-08-04T22:41:51 | 26,830,272 | 3 | 1 | null | 2023-03-04T03:58:03 | 2014-11-18T21:14:23 | Python | UTF-8 | Python | false | false | 322 | py | import numpy as np
import ray
def init():
return ray.init()
def bounce():
ray.disconnect()
# might be incorrect
return ray.init()
def f(x):
return x ** 2
f_remote = ray.remote(f)
def g(x, seed=1):
np.random.seed(seed)
x = np.random.randn(10, 5) + x
return x
g_remote = ray.remote(g)
| [
"[email protected]"
]
| |
f8e52d6fa581c4d3b98559e464663fb186f6b5f8 | c2e50f81a127b83fd181442f4d7a5b4751d767e6 | /tools/coverage/gcda_clean.py | c222c448a3d91facd453d8ebf9d68be989166fed | [
"Apache-2.0"
]
| permissive | Thunderbrook/Paddle | 72eda072fae8fd7d555198aadec7ec8899ccb387 | 4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5 | refs/heads/develop | 2022-11-05T09:53:16.633465 | 2020-04-09T09:17:40 | 2020-04-09T09:17:40 | 196,961,339 | 0 | 0 | Apache-2.0 | 2020-12-17T08:57:33 | 2019-07-15T08:51:53 | C++ | UTF-8 | Python | false | false | 1,825 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" usage: gcda_clean.py pull_id. """
import os
import sys
from github import Github
def get_pull(pull_id):
"""Get pull.
Args:
pull_id (int): Pull id.
Returns:
github.PullRequest.PullRequest
"""
token = os.getenv('GITHUB_API_TOKEN',
'e1f9c3cf211d5c20e65bd9ab7ec07983da284bca')
github = Github(token, timeout=60)
repo = github.get_repo('PaddlePaddle/Paddle')
pull = repo.get_pull(pull_id)
return pull
def get_files(pull_id):
"""Get files.
Args:
pull_id (int): Pull id.
Returns:
iterable: The generator will yield every filename.
"""
pull = get_pull(pull_id)
for file in pull.get_files():
yield file.filename
def clean(pull_id):
"""Clean.
Args:
pull_id (int): Pull id.
Returns:
None.
"""
changed = []
for file in get_files(pull_id):
changed.append('/paddle/build/{}.gcda'.format(file))
for parent, dirs, files in os.walk('/paddle/build/'):
for gcda in files:
if gcda.endswith('.gcda'):
trimmed = parent
# convert paddle/fluid/imperative/CMakeFiles/layer.dir/layer.cc.gcda
# to paddle/fluid/imperative/layer.cc.gcda
if trimmed.endswith('.dir'):
trimmed = os.path.dirname(trimmed)
if trimmed.endswith('CMakeFiles'):
trimmed = os.path.dirname(trimmed)
# remove no changed gcda
if os.path.join(trimmed, gcda) not in changed:
gcda = os.path.join(parent, gcda)
os.remove(gcda)
if __name__ == '__main__':
pull_id = sys.argv[1]
pull_id = int(pull_id)
clean(pull_id)
| [
"[email protected]"
]
| |
c0a77d989d2367e946c726db66d379941cb95e58 | 191a7f83d964f74a2b3c7faeb4fc47d9c63d521f | /.history/main_20210529115051.py | 1db23d5522089aab30d37049645fc3bb97d85fce | []
| no_license | AndreLiu1225/Kinder-Values-Survey | 2a317feee8d5b17c27da2b2116742656e35d8ab9 | 090c27da0c822abb7dfc0ec6e13ae1b3dcb7bbf3 | refs/heads/master | 2023-05-03T00:26:00.481423 | 2021-06-04T03:24:19 | 2021-06-04T03:24:19 | 371,989,154 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,895 | py | from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, IntegerField, SelectField, RadioField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
import datetime
import matplotlib.pyplot as plt
app = Flask(__name__)
app.config['SECRET_KEY'] = "0c8973c8a5e001bb0c816a7b56c84f3a"
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///site.db"
db = SQLAlchemy(app)
class Survey(db.Model):
age = db.Column(db.Integer, nullable=False, primary_key=True)
email = db.Column(db.String(50), unique=False, nullable=False)
profession = db.Column(db.String(50), nullable=False)
power = db.Column(db.Integer, nullable=False)
tradition = db.Column(db.Integer, nullable=False)
achievement = db.Column(db.Integer, nullable=False)
stimulation = db.Column(db.Integer, nullable=False)
hedonism = db.Column(db.Integer, nullable=False)
conformity = db.Column(db.Integer, nullable=False)
security = db.Column(db.Integer, nullable=False)
self_direction = db.Column(db.Integer, nullable=False)
benevolence = db.Column(db.Integer, nullable=False)
universalism = db.Column(db.Integer, nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
def __repr__(self):
return f"Survey('{self.age}', '{self.name}', '{self.date_posted}')"
class MCQ(FlaskForm):
email = StringField("What is your email?", validators=[DataRequired(), Email(message=('Not a valid email address')), Length(max=50)])
age = IntegerField("Please enter your age", validators=[DataRequired()])
profession = StringField("What is your profession?", validators=[DataRequired(), Length(max=30)])
# Self-Enhancement
power = IntegerField("Do you desire a higher social status and dominance over others? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
hedonism = IntegerField("Is personal gratification the most important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
achievement = IntegerField("Is achievement according to social standards important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
# Conservation
tradition = IntegerField("Do you care about preserving traditions? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
conformity = IntegerField("Do you think restraint of actions against social norms is important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
security = IntegerField("Do you value safety, harmony and stability of society, of relationships, and of self? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
# Openness to change
stimulation = IntegerField("Do you prefer novel and exciting challenges in life? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
self_direction = IntegerField("Do you think independent thought and action are important (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
# Self-transcendence
benevolence = IntegerField("Are preserving and enhancing the welfare of your friends and family the most important? (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
universalism = IntegerField("I find it important to understand, tolerate, appreciate and protect all ethnicities and people. (4- It is my utmost priority, 3-It is important, 2-Doesn't bother me, 1-Not even a thought)", validators=[DataRequired()])
submit = SubmitField("Submit")
@app.route('/', methods=['POST','GET'])
def values_quiz():
form = MCQ()
if form.validate_on_submit():
post = Survey(age=form.age.data, email=form.email.data, profession=form.profession.data, power=form.power.data,
tradition=form.tradition.data, achievement=form.achievement.data, stimulation=form.stimulation.data,
hedonism=form.hedonism.data, conformity=form.conformity.data, self_direction=form.self_direction.data,
benevolence=form.benevolence.data, universalism=form.universalism.data, security=form.security.data)
# if Survey.is_email_in_database(form.email.data):
# flash(f"The user with {form.email.data} has already filled the survey", "danger")
db.session.add(post)
db.session.commit()
flash(f'Survey is completed by {form.email.data}', 'success')
return redirect(url_for('data_dashboard'))
else:
flash('Ensure all questions are answered correctly', 'warning')
return render_template('MCQ.html', form=form)
@app.route('/results', methods=['GET'])
def data_dashboard():
power = request.form['power']
tradition = request.form['tradition']
achievement = request.form['achievement']
stimulation = request.form['stimulation']
hedonism = request.form['hedonism']
conformity = request.form['conformity']
security = request.form['security']
self_direction = request['self_direction']
benevolence = request['benevolence']
universalism = request['universalism']
values = [power, tradition, achievement, stimulation, hedonism, conformity, security, self_direction, benevolence, universalism]
values_labels = ['Openness to Change', 'Self-Transcendence',
'Conservation', 'Self-Enchancement']
openness = [hedonism, stimulation, self_direction]
self_enhancement = [hedonism, achievement, power]
conservation = [tradition, conformity, security]
self_trans = [universalism, benevolence]
total_sum = sum(values)
open_sum = round(sum(openness)/total_sum*100)
enhance_sum = round(sum(self_enhancement)/total_sum*100)
trans_sum = round(sum(self_trans)/total_sum*100)
cons_sum = round(sum(conservation)/total_sum*100)
sum_v = [open_sum, enhance_sum, trans_sum, cons_sum]
# initiating the range of y ticks
ran = [20,40,60,80,100]
plt.xticks(ran, values_labels)
# Calling bar plot function
plt.bar(ran, sum_v)
plt.title('Percentage obtained on each dynamic values')
plt.ylabel('Percentage')
plt.xlabel('Dynamic value types')
return render_template('data_dashboard.html', image=plt.show())
if __name__ == "__main__":
app.run(debug=True)
| [
"[email protected]"
]
| |
fb7165c445a5220131bc572f6c89d995c80cc8bb | e27eebd9cacba56eb0e161cf9584b856db4543b5 | /code/version-demo/venv/bin/django-admin | f3b2a60f6246b15c8ef89d632a053b19ff026f34 | []
| no_license | Dosimz/django-rest-framework-notes | fd374f9793057f9fbfe85c072912a019ef26b73a | 1d0cf0e9cd9042e432f883cd9c3fa2504e5b9a22 | refs/heads/master | 2020-06-25T15:36:33.700321 | 2019-08-03T04:26:40 | 2019-08-03T04:26:40 | 199,354,041 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 345 | #!/run/media/yuyi/068AE93F8AE92BBD/python/django-rest-framework/code/version-demo/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"[email protected]"
]
| ||
6f2dabcbae6f1bfd32f6f0a5a6ad9d3664682f52 | 05bf7de1337bc938578accba64416863cec1ed63 | /bin/Python27/Lib/site-packages/babel/messages/extract.py | efddbf5e691c23c9a2e7cf1af5308e72897a7e90 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
]
| permissive | metamorph-inc/openmeta-mms | d0dccae88e7532594f02c5eff8daa74c6c0e4010 | 2644cb7273916e36c3725785fc9a44948d64c343 | refs/heads/master | 2023-04-06T11:09:36.316306 | 2023-03-28T18:17:55 | 2023-03-28T18:17:55 | 70,078,378 | 21 | 8 | NOASSERTION | 2023-01-14T09:31:14 | 2016-10-05T16:29:54 | Python | UTF-8 | Python | false | false | 26,281 | py | # -*- coding: utf-8 -*-
"""
babel.messages.extract
~~~~~~~~~~~~~~~~~~~~~~
Basic infrastructure for extracting localizable messages from source files.
This module defines an extensible system for collecting localizable message
strings from a variety of sources. A native extractor for Python source
files is builtin, extractors for other sources can be added using very
simple plugins.
The main entry points into the extraction functionality are the functions
`extract_from_dir` and `extract_from_file`.
:copyright: (c) 2013 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
import os
from os.path import relpath
import sys
from tokenize import generate_tokens, COMMENT, NAME, OP, STRING
from babel.util import parse_encoding, parse_future_flags, pathmatch
from babel._compat import PY2, text_type
from textwrap import dedent
GROUP_NAME = 'babel.extractors'
DEFAULT_KEYWORDS = {
'_': None,
'gettext': None,
'ngettext': (1, 2),
'ugettext': None,
'ungettext': (1, 2),
'dgettext': (2,),
'dngettext': (2, 3),
'N_': None,
'pgettext': ((1, 'c'), 2),
'npgettext': ((1, 'c'), 2, 3)
}
DEFAULT_MAPPING = [('**.py', 'python')]
empty_msgid_warning = (
'%s: warning: Empty msgid. It is reserved by GNU gettext: gettext("") '
'returns the header entry with meta information, not the empty string.')
def _strip_comment_tags(comments, tags):
"""Helper function for `extract` that strips comment tags from strings
in a list of comment lines. This functions operates in-place.
"""
def _strip(line):
for tag in tags:
if line.startswith(tag):
return line[len(tag):].strip()
return line
comments[:] = map(_strip, comments)
def extract_from_dir(dirname=None, method_map=DEFAULT_MAPPING,
options_map=None, keywords=DEFAULT_KEYWORDS,
comment_tags=(), callback=None, strip_comment_tags=False):
"""Extract messages from any source files found in the given directory.
This function generates tuples of the form ``(filename, lineno, message,
comments, context)``.
Which extraction method is used per file is determined by the `method_map`
parameter, which maps extended glob patterns to extraction method names.
For example, the following is the default mapping:
>>> method_map = [
... ('**.py', 'python')
... ]
This basically says that files with the filename extension ".py" at any
level inside the directory should be processed by the "python" extraction
method. Files that don't match any of the mapping patterns are ignored. See
the documentation of the `pathmatch` function for details on the pattern
syntax.
The following extended mapping would also use the "genshi" extraction
method on any file in "templates" subdirectory:
>>> method_map = [
... ('**/templates/**.*', 'genshi'),
... ('**.py', 'python')
... ]
The dictionary provided by the optional `options_map` parameter augments
these mappings. It uses extended glob patterns as keys, and the values are
dictionaries mapping options names to option values (both strings).
The glob patterns of the `options_map` do not necessarily need to be the
same as those used in the method mapping. For example, while all files in
the ``templates`` folders in an application may be Genshi applications, the
options for those files may differ based on extension:
>>> options_map = {
... '**/templates/**.txt': {
... 'template_class': 'genshi.template:TextTemplate',
... 'encoding': 'latin-1'
... },
... '**/templates/**.html': {
... 'include_attrs': ''
... }
... }
:param dirname: the path to the directory to extract messages from. If
not given the current working directory is used.
:param method_map: a list of ``(pattern, method)`` tuples that maps of
extraction method names to extended glob patterns
:param options_map: a dictionary of additional options (optional)
:param keywords: a dictionary mapping keywords (i.e. names of functions
that should be recognized as translation functions) to
tuples that specify which of their arguments contain
localizable strings
:param comment_tags: a list of tags of translator comments to search for
and include in the results
:param callback: a function that is called for every file that message are
extracted from, just before the extraction itself is
performed; the function is passed the filename, the name
of the extraction method and and the options dictionary as
positional arguments, in that order
:param strip_comment_tags: a flag that if set to `True` causes all comment
tags to be removed from the collected comments.
:see: `pathmatch`
"""
if dirname is None:
dirname = os.getcwd()
if options_map is None:
options_map = {}
absname = os.path.abspath(dirname)
for root, dirnames, filenames in os.walk(absname):
for subdir in dirnames:
if subdir.startswith('.') or subdir.startswith('_'):
dirnames.remove(subdir)
dirnames.sort()
filenames.sort()
for filename in filenames:
filepath = os.path.join(root, filename).replace(os.sep, '/')
for message_tuple in check_and_call_extract_file(
filepath,
method_map,
options_map,
callback,
keywords,
comment_tags,
strip_comment_tags,
dirpath=absname,
):
yield message_tuple
def check_and_call_extract_file(filepath, method_map, options_map,
callback, keywords, comment_tags,
strip_comment_tags, dirpath=None):
"""Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file.
Note that the extraction method mappings are based relative to dirpath.
So, given an absolute path to a file `filepath`, we want to check using
just the relative path from `dirpath` to `filepath`.
Yields 5-tuples (filename, lineno, messages, comments, context).
:param filepath: An absolute path to a file that exists.
:param method_map: a list of ``(pattern, method)`` tuples that maps of
extraction method names to extended glob patterns
:param options_map: a dictionary of additional options (optional)
:param callback: a function that is called for every file that message are
extracted from, just before the extraction itself is
performed; the function is passed the filename, the name
of the extraction method and and the options dictionary as
positional arguments, in that order
:param keywords: a dictionary mapping keywords (i.e. names of functions
that should be recognized as translation functions) to
tuples that specify which of their arguments contain
localizable strings
:param comment_tags: a list of tags of translator comments to search for
and include in the results
:param strip_comment_tags: a flag that if set to `True` causes all comment
tags to be removed from the collected comments.
:param dirpath: the path to the directory to extract messages from.
:return: iterable of 5-tuples (filename, lineno, messages, comments, context)
:rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None]
"""
# filename is the relative path from dirpath to the actual file
filename = relpath(filepath, dirpath)
for pattern, method in method_map:
if not pathmatch(pattern, filename):
continue
options = {}
for opattern, odict in options_map.items():
if pathmatch(opattern, filename):
options = odict
if callback:
callback(filename, method, options)
for message_tuple in extract_from_file(
method, filepath,
keywords=keywords,
comment_tags=comment_tags,
options=options,
strip_comment_tags=strip_comment_tags
):
yield (filename, ) + message_tuple
break
def extract_from_file(method, filename, keywords=DEFAULT_KEYWORDS,
comment_tags=(), options=None, strip_comment_tags=False):
"""Extract messages from a specific file.
This function returns a list of tuples of the form ``(lineno, message, comments, context)``.
:param filename: the path to the file to extract messages from
:param method: a string specifying the extraction method (.e.g. "python")
:param keywords: a dictionary mapping keywords (i.e. names of functions
that should be recognized as translation functions) to
tuples that specify which of their arguments contain
localizable strings
:param comment_tags: a list of translator tags to search for and include
in the results
:param strip_comment_tags: a flag that if set to `True` causes all comment
tags to be removed from the collected comments.
:param options: a dictionary of additional options (optional)
:returns: list of tuples of the form ``(lineno, message, comments, context)``
:rtype: list[tuple[int, str|tuple[str], list[str], str|None]
"""
with open(filename, 'rb') as fileobj:
return list(extract(method, fileobj, keywords, comment_tags, options,
strip_comment_tags))
def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(),
options=None, strip_comment_tags=False):
"""Extract messages from the given file-like object using the specified
extraction method.
This function returns tuples of the form ``(lineno, message, comments, context)``.
The implementation dispatches the actual extraction to plugins, based on the
value of the ``method`` parameter.
>>> source = b'''# foo module
... def run(argv):
... print(_('Hello, world!'))
... '''
>>> from babel._compat import BytesIO
>>> for message in extract('python', BytesIO(source)):
... print(message)
(3, u'Hello, world!', [], None)
:param method: an extraction method (a callable), or
a string specifying the extraction method (.e.g. "python");
if this is a simple name, the extraction function will be
looked up by entry point; if it is an explicit reference
to a function (of the form ``package.module:funcname`` or
``package.module.funcname``), the corresponding function
will be imported and used
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a dictionary mapping keywords (i.e. names of functions
that should be recognized as translation functions) to
tuples that specify which of their arguments contain
localizable strings
:param comment_tags: a list of translator tags to search for and include
in the results
:param options: a dictionary of additional options (optional)
:param strip_comment_tags: a flag that if set to `True` causes all comment
tags to be removed from the collected comments.
:raise ValueError: if the extraction method is not registered
:returns: iterable of tuples of the form ``(lineno, message, comments, context)``
:rtype: Iterable[tuple[int, str|tuple[str], list[str], str|None]
"""
func = None
if callable(method):
func = method
elif ':' in method or '.' in method:
if ':' not in method:
lastdot = method.rfind('.')
module, attrname = method[:lastdot], method[lastdot + 1:]
else:
module, attrname = method.split(':', 1)
func = getattr(__import__(module, {}, {}, [attrname]), attrname)
else:
try:
from pkg_resources import working_set
except ImportError:
pass
else:
for entry_point in working_set.iter_entry_points(GROUP_NAME,
method):
func = entry_point.load(require=True)
break
if func is None:
# if pkg_resources is not available or no usable egg-info was found
# (see #230), we resort to looking up the builtin extractors
# directly
builtin = {
'ignore': extract_nothing,
'python': extract_python,
'javascript': extract_javascript
}
func = builtin.get(method)
if func is None:
raise ValueError('Unknown extraction method %r' % method)
results = func(fileobj, keywords.keys(), comment_tags,
options=options or {})
for lineno, funcname, messages, comments in results:
if funcname:
spec = keywords[funcname] or (1,)
else:
spec = (1,)
if not isinstance(messages, (list, tuple)):
messages = [messages]
if not messages:
continue
# Validate the messages against the keyword's specification
context = None
msgs = []
invalid = False
# last_index is 1 based like the keyword spec
last_index = len(messages)
for index in spec:
if isinstance(index, tuple):
context = messages[index[0] - 1]
continue
if last_index < index:
# Not enough arguments
invalid = True
break
message = messages[index - 1]
if message is None:
invalid = True
break
msgs.append(message)
if invalid:
continue
# keyword spec indexes are 1 based, therefore '-1'
if isinstance(spec[0], tuple):
# context-aware *gettext method
first_msg_index = spec[1] - 1
else:
first_msg_index = spec[0] - 1
if not messages[first_msg_index]:
# An empty string msgid isn't valid, emit a warning
where = '%s:%i' % (hasattr(fileobj, 'name') and
fileobj.name or '(unknown)', lineno)
sys.stderr.write((empty_msgid_warning % where) + '\n')
continue
messages = tuple(msgs)
if len(messages) == 1:
messages = messages[0]
if strip_comment_tags:
_strip_comment_tags(comments, comment_tags)
yield lineno, messages, comments, context
def extract_nothing(fileobj, keywords, comment_tags, options):
"""Pseudo extractor that does not actually extract anything, but simply
returns an empty list.
"""
return []
def extract_python(fileobj, keywords, comment_tags, options):
"""Extract messages from Python source code.
It returns an iterator yielding tuples in the following form ``(lineno,
funcname, message, comments)``.
:param fileobj: the seekable, file-like object the messages should be
extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results
:param options: a dictionary of additional options (optional)
:rtype: ``iterator``
"""
funcname = lineno = message_lineno = None
call_stack = -1
buf = []
messages = []
translator_comments = []
in_def = in_translator_comments = False
comment_tag = None
encoding = parse_encoding(fileobj) or options.get('encoding', 'UTF-8')
future_flags = parse_future_flags(fileobj, encoding)
if PY2:
next_line = fileobj.readline
else:
next_line = lambda: fileobj.readline().decode(encoding)
tokens = generate_tokens(next_line)
for tok, value, (lineno, _), _, _ in tokens:
if call_stack == -1 and tok == NAME and value in ('def', 'class'):
in_def = True
elif tok == OP and value == '(':
if in_def:
# Avoid false positives for declarations such as:
# def gettext(arg='message'):
in_def = False
continue
if funcname:
message_lineno = lineno
call_stack += 1
elif in_def and tok == OP and value == ':':
# End of a class definition without parens
in_def = False
continue
elif call_stack == -1 and tok == COMMENT:
# Strip the comment token from the line
if PY2:
value = value.decode(encoding)
value = value[1:].strip()
if in_translator_comments and \
translator_comments[-1][0] == lineno - 1:
# We're already inside a translator comment, continue appending
translator_comments.append((lineno, value))
continue
# If execution reaches this point, let's see if comment line
# starts with one of the comment tags
for comment_tag in comment_tags:
if value.startswith(comment_tag):
in_translator_comments = True
translator_comments.append((lineno, value))
break
elif funcname and call_stack == 0:
if tok == OP and value == ')':
if buf:
messages.append(''.join(buf))
del buf[:]
else:
messages.append(None)
if len(messages) > 1:
messages = tuple(messages)
else:
messages = messages[0]
# Comments don't apply unless they immediately preceed the
# message
if translator_comments and \
translator_comments[-1][0] < message_lineno - 1:
translator_comments = []
yield (message_lineno, funcname, messages,
[comment[1] for comment in translator_comments])
funcname = lineno = message_lineno = None
call_stack = -1
messages = []
translator_comments = []
in_translator_comments = False
elif tok == STRING:
# Unwrap quotes in a safe manner, maintaining the string's
# encoding
# https://sourceforge.net/tracker/?func=detail&atid=355470&
# aid=617979&group_id=5470
code = compile('# coding=%s\n%s' % (str(encoding), value),
'<string>', 'eval', future_flags)
value = eval(code, {'__builtins__': {}}, {})
if PY2 and not isinstance(value, text_type):
value = value.decode(encoding)
buf.append(value)
elif tok == OP and value == ',':
if buf:
messages.append(''.join(buf))
del buf[:]
else:
messages.append(None)
if translator_comments:
# We have translator comments, and since we're on a
# comma(,) user is allowed to break into a new line
# Let's increase the last comment's lineno in order
# for the comment to still be a valid one
old_lineno, old_comment = translator_comments.pop()
translator_comments.append((old_lineno + 1, old_comment))
elif call_stack > 0 and tok == OP and value == ')':
call_stack -= 1
elif funcname and call_stack == -1:
funcname = None
elif tok == NAME and value in keywords:
funcname = value
def extract_javascript(fileobj, keywords, comment_tags, options):
"""Extract messages from JavaScript source code.
:param fileobj: the seekable, file-like object the messages should be
extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results
:param options: a dictionary of additional options (optional)
Supported options are:
* `jsx` -- set to false to disable JSX/E4X support.
* `template_string` -- set to false to disable ES6
template string support.
"""
from babel.messages.jslexer import Token, tokenize, unquote_string
funcname = message_lineno = None
messages = []
last_argument = None
translator_comments = []
concatenate_next = False
encoding = options.get('encoding', 'utf-8')
last_token = None
call_stack = -1
dotted = any('.' in kw for kw in keywords)
for token in tokenize(
fileobj.read().decode(encoding),
jsx=options.get("jsx", True),
template_string=options.get("template_string", True),
dotted=dotted
):
if ( # Turn keyword`foo` expressions into keyword("foo") calls:
funcname and # have a keyword...
(last_token and last_token.type == 'name') and # we've seen nothing after the keyword...
token.type == 'template_string' # this is a template string
):
message_lineno = token.lineno
messages = [unquote_string(token.value)]
call_stack = 0
token = Token('operator', ')', token.lineno)
if token.type == 'operator' and token.value == '(':
if funcname:
message_lineno = token.lineno
call_stack += 1
elif call_stack == -1 and token.type == 'linecomment':
value = token.value[2:].strip()
if translator_comments and \
translator_comments[-1][0] == token.lineno - 1:
translator_comments.append((token.lineno, value))
continue
for comment_tag in comment_tags:
if value.startswith(comment_tag):
translator_comments.append((token.lineno, value.strip()))
break
elif token.type == 'multilinecomment':
# only one multi-line comment may preceed a translation
translator_comments = []
value = token.value[2:-2].strip()
for comment_tag in comment_tags:
if value.startswith(comment_tag):
lines = value.splitlines()
if lines:
lines[0] = lines[0].strip()
lines[1:] = dedent('\n'.join(lines[1:])).splitlines()
for offset, line in enumerate(lines):
translator_comments.append((token.lineno + offset,
line))
break
elif funcname and call_stack == 0:
if token.type == 'operator' and token.value == ')':
if last_argument is not None:
messages.append(last_argument)
if len(messages) > 1:
messages = tuple(messages)
elif messages:
messages = messages[0]
else:
messages = None
# Comments don't apply unless they immediately precede the
# message
if translator_comments and \
translator_comments[-1][0] < message_lineno - 1:
translator_comments = []
if messages is not None:
yield (message_lineno, funcname, messages,
[comment[1] for comment in translator_comments])
funcname = message_lineno = last_argument = None
concatenate_next = False
translator_comments = []
messages = []
call_stack = -1
elif token.type in ('string', 'template_string'):
new_value = unquote_string(token.value)
if concatenate_next:
last_argument = (last_argument or '') + new_value
concatenate_next = False
else:
last_argument = new_value
elif token.type == 'operator':
if token.value == ',':
if last_argument is not None:
messages.append(last_argument)
last_argument = None
else:
messages.append(None)
concatenate_next = False
elif token.value == '+':
concatenate_next = True
elif call_stack > 0 and token.type == 'operator' \
and token.value == ')':
call_stack -= 1
elif funcname and call_stack == -1:
funcname = None
elif call_stack == -1 and token.type == 'name' and \
token.value in keywords and \
(last_token is None or last_token.type != 'name' or
last_token.value != 'function'):
funcname = token.value
last_token = token
| [
"[email protected]"
]
| |
2678e12e0ef37185b07dd5045587321dab24ceab | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_116/1538.py | f953c8478ab10037f18a92cc014c6473535f8868 | []
| no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,103 | py | #!/usr/bin/env python
row = 4
col = 4
def getState(matrix):
hasEmpty = False
# Check row
for i in range(4):
flag = matrix[i][0]
if (matrix[i][1] == flag or matrix[i][1] == 'T') \
and (matrix[i][2] == flag or matrix[i][2] == 'T') \
and (matrix[i][3] == flag or matrix[i][3] == 'T'):
if flag == "X":
return "X won"
if flag == "O":
return "O won"
for j in range(1,4):
if matrix[i][j] == '.':
hasEmpty = True
# Check col
for i in range(4):
flag = matrix[0][i]
if (matrix[1][i] == flag or matrix[1][i] == 'T') \
and (matrix[2][i] == flag or matrix[2][i] == 'T') \
and (matrix[3][i] == flag or matrix[3][i] == 'T'):
if flag == "X":
return "X won"
if flag == "O":
return "O won"
for j in range(1,4):
if matrix[j][i] == '.':
hasEmpty = True
# Check diagonal
flag = matrix[0][0]
if (matrix[1][1] == flag or matrix[1][1] == 'T') \
and (matrix[2][2] == flag or matrix[2][2] == 'T') \
and (matrix[3][3] == flag or matrix[3][3] == 'T'):
if flag == "X":
return "X won"
if flag == "O":
return "O won"
flag = matrix[0][3]
if (matrix[1][2] == flag or matrix[1][2] == 'T') \
and (matrix[2][1] == flag or matrix[2][1] == 'T') \
and (matrix[3][0] == flag or matrix[3][0] == 'T'):
if flag == "X":
return "X won"
if flag == "O":
return "O won"
if hasEmpty:
return "Game has not completed"
else:
return "Draw"
#f = open("small")
f = open("A-small-attempt0.in")
lines = f.readlines()
num = int(lines[0])
wfile = open("lk", "w")
index = 1
for i in range(num):
matrix = []
for j in range(index, index+4):
ns = list(lines[j].strip())
matrix.append(ns)
wfile.write("Case #%d: %s\n" % (i+1, getState(matrix)))
index += 5
| [
"[email protected]"
]
| |
55ac6c0ae11f11916c7b39010ebf387a1da71342 | a515ea9f5e34116789111551e510998c41d5de13 | /projet/utilisateur/apps.py | ce28368522a4d6f3d831f1efd42aa7b743bb6d2e | []
| no_license | ometeore/nutella | ad2073d533fdbb93bee8a330fbc74fd58c096f1f | 3086b09972ddb1e08c8cc58fb2fc1abef93d2147 | refs/heads/master | 2022-12-11T03:01:07.387249 | 2020-05-15T11:16:19 | 2020-05-15T11:16:19 | 232,634,085 | 0 | 0 | null | 2022-04-22T23:01:07 | 2020-01-08T18:44:53 | CSS | UTF-8 | Python | false | false | 97 | py | from django.apps import AppConfig
class UtilisateurConfig(AppConfig):
name = "utilisateur"
| [
"[email protected]"
]
| |
41187fee24fba11e59e9c8b13bd1af25a462c4bd | 3854700ad938a19efbb934fb0706793d70848ff1 | /docs/python/algorytmy/heron.py | 378735c8ff661796f1d4195070da01ca9670741d | []
| no_license | xinulsw/linetc | 0e0c94f3bd814a9ef8da9f2613785f605c04ed6e | 7311063d640ca1889dca1cd9d6f8b40541c8809a | refs/heads/master | 2022-06-21T05:40:32.139937 | 2022-05-27T15:33:05 | 2022-05-27T15:33:05 | 28,744,486 | 1 | 5 | null | 2016-12-30T14:13:33 | 2015-01-03T13:30:50 | Python | UTF-8 | Python | false | false | 724 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Obliczanie wartości pierwiastka kwadratowego z podanej liczby
# przy użyciu metody Herona: a(n) = (a(n-1) + x / a(n-1)) / 2
# <eCG>
def pierwiastek(x, d):
a = x # inicjalizacja szkuanej wartości
while abs(a - (x / a)) > d:
a = (a + (x / a)) / 2
return a
def main(args):
# liczba dla której szukamy pierwiastka
x = float(raw_input("Podaj liczbę: "))
# dokładność obliczeń
d = float(raw_input("Podaj dokładność: "))
# drukujemy wynik z dokładnością do 6 miejsc
print "Pierwiastek kwadratowy: {:.6f}".format(pierwiastek(x, d))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
| [
"[email protected]"
]
| |
1abcc7f2b6d5b4a36c17904f6e1a96671de2fdab | 0a94e12fc91815bdf510d748f37fdfccabe8c9d4 | /apps/channel/apps.py | 4a944471e4680481f436845da0a7ee13fb599faf | []
| no_license | zhuoxiaojian/SemSupport | 0cb47e2612373b90e4a6b95165bc39d49a9bd0ac | 4dd4582c03daf43b589298c6061846d40aa3666f | refs/heads/master | 2022-12-23T15:18:35.411711 | 2019-09-26T12:16:08 | 2019-09-26T12:16:08 | 129,690,135 | 1 | 0 | null | 2022-12-07T23:51:23 | 2018-04-16T05:38:27 | JavaScript | UTF-8 | Python | false | false | 123 | py | from django.apps import AppConfig
class ChannelConfig(AppConfig):
name = 'channel'
verbose_name = "渠道管理"
| [
"[email protected]"
]
| |
671a4259b297caaf1b440af131b996017d579c02 | 4c3467d15408362150528c98022016e3af48a481 | /day05/day05.py | 97d0ddbbe0a70fad197e58908870483548377405 | []
| no_license | Ha-Young/nomad_python_challenge | 7659fc1f5d08b9925156f48e5150bd6981593452 | d4b476ad27fcc039851f7c7acbc4d925d678d6b2 | refs/heads/master | 2022-12-12T10:59:38.154297 | 2020-09-06T14:16:52 | 2020-09-06T14:16:52 | 257,329,572 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,100 | py | import os
import requests
from bs4 import BeautifulSoup
os.system("clear")
url = "https://www.iban.com/currency-codes"
req = requests.get(url)
soup = BeautifulSoup(req.text, "html.parser")
table = soup.find('table', {'class': 'table'})
tbody = table.find('tbody')
trs = tbody.find_all('tr')
dict_country_code = {}
for i, tr in enumerate(trs):
tds = tr.find_all('td')
country = tds[0].text.strip()
currency = tds[1].text.strip()
code = tds[2].text.strip()
number = tds[3].text.strip()
dict_country_code[i] = {
'country':country,
'currency': currency,
'code': code,
'number':number
}
print("Hello Please Choose select a country")
for key, value in dict_country_code.items():
print(key,value['country'])
while(True):
try:
inputNum = int(input('#: '))
if inputNum not in dict_country_code.keys():
print("Choose a number from the list.")
else :
print('You Chose',dict_country_code[inputNum]['country'])
print('The currency code is',dict_country_code[inputNum]['code'])
break
except:
print("That wasn't a number")
| [
"[email protected]"
]
| |
fb05f1a8484b67ea8c719f094c1624f8289d9513 | d7db8cd9cf18d21a57c6bdb1a3ead018d81801a9 | /字节跳动/数组与排序/数组中第k个最大元素.py | d961475a12f37bea9f668fbae3335b8f3f7edfb3 | []
| no_license | Eleanoryuyuyu/LeetCode | a1e8c230162a3a850e6714ed7c2d4d946bc5f33b | 44b65f3ab6cc6ca3ef2a2fd7ef39d4df0cd7f7eb | refs/heads/master | 2021-06-01T15:25:44.812448 | 2020-08-06T07:32:44 | 2020-08-06T07:32:44 | 144,653,156 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,027 | py | from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def partition(left, right):
paviot = nums[left]
while left < right:
while left < right and nums[right] >= paviot:
right -= 1
nums[left] = nums[right]
while left < right and nums[left] <= paviot:
left += 1
nums[right] = nums[left]
nums[left] = paviot
return left
n = len(nums)
p = n - k
left, right = 0, n - 1
index = partition(left, right)
while index != p:
if index < p:
left = index + 1
index = partition(left, right)
elif index > p:
right = index - 1
index = partition(left, right)
else:
return nums[index]
return nums[index]
nums = [3,2,3,1,2,4,5,5,6]
print(Solution().findKthLargest(nums, 4))
| [
"[email protected]"
]
| |
749a83635590f91958b0fa30ea5f38c31e32c731 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03501/s922794977.py | 5523fded6aaa20bcb5866877f8ac12b3802b27f7 | []
| no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 86 | py | n,a,b =map(int,input().split())
p1=a*n
p2=b
if p1>=p2:
print(p2)
else:
print(p1) | [
"[email protected]"
]
| |
bad84b93239fac0a1e4e0d53a6650b8a3c99b62a | bdec175f02173938f99e546e772ce8b3730a3f48 | /lists/ex48.py | 83c5d0115be5792c374e8c614d5037b552d518fe | []
| no_license | hmunduri/MyPython | 99f637f6665a733903968047aa46b763d9557858 | af26f3a4ffb9b786d682114635b432480010ffc8 | refs/heads/master | 2020-03-09T13:13:59.873228 | 2018-04-20T22:33:30 | 2018-04-20T22:33:30 | 128,805,444 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 164 | py | #Python program print a nested lists using the print() function.
import sys
colors = [['Red'], ['Green'], ['Black']]
print(' '.join([str(lst) for lst in colors]))
| [
"[email protected]"
]
| |
f2c38ad89b093cb62129bdcd1e825b1f8d27054b | fc0a6e0f9ffa90a2473fec77bc52ea02e9b21f55 | /venv/lib/python3.7/site-packages/akshare/news/news_east_money.py | b585d6d945b5f41bbe2d071cbf638da2a4c7259b | []
| no_license | YixuanSeanZhou/COVID19_Scraping | 3903e697caf406c7d357afd8cc43811d62896244 | b84890c4a5ddef589cd76d1ed8fd4a1976f4e3c4 | refs/heads/master | 2022-09-08T16:14:33.292096 | 2020-05-23T04:26:02 | 2020-05-23T04:26:02 | 266,261,823 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 464 | py | # -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Author: Albert King
date: 2019/12/12 15:08
contact: [email protected]
desc:
"""
import newspaper
sina_paper = newspaper.build('http://futures.hexun.com/domestic/', language='zh')
for article in sina_paper.articles:
print(article)
sina_paper.size()
first_article = sina_paper.articles[5]
first_article.download()
first_article.parse()
print(first_article.title)
print(first_article.text)
| [
"[email protected]"
]
| |
55da86fb8f84ec5ba233473cb4b4e33d46b04933 | acb8e84e3b9c987fcab341f799f41d5a5ec4d587 | /langs/7/r2o.py | b1e584959f21efb11d426d8dcff4e551e69c13b7 | []
| no_license | G4te-Keep3r/HowdyHackers | 46bfad63eafe5ac515da363e1c75fa6f4b9bca32 | fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2 | refs/heads/master | 2020-08-01T12:08:10.782018 | 2016-11-13T20:45:50 | 2016-11-13T20:45:50 | 73,624,224 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import sys
def printFunction(lineRemaining):
if lineRemaining[0] == '"' and lineRemaining[-1] == '"':
if len(lineRemaining) > 2:
#data to print
lineRemaining = lineRemaining[1:-1]
print ' '.join(lineRemaining)
else:
print
def main(fileName):
with open(fileName) as f:
for line in f:
data = line.split()
if data[0] == 'r2O':
printFunction(data[1:])
else:
print 'ERROR'
return
if __name__ == '__main__':
main(sys.argv[1]) | [
"[email protected]"
]
| |
d75c687734fdd3778c4f88537fea21cdca140a57 | 1ee910d6602123eb1328f56419b04e31b3761b6b | /lib/python3.5/site-packages/twilio/rest/sync/v1/__init__.py | c1aab31243a7200a57ff60b634bef12ef3b66f88 | [
"MIT"
]
| permissive | mraza007/Pizza-or-Not-a-Pizza | 7fc89e0905c86fbd3c77a9cc834a4b6098912aeb | 6ad59d046adbd6be812c7403d9cb8ffbdbd6b0b8 | refs/heads/master | 2022-12-15T15:47:34.779838 | 2018-07-04T02:28:56 | 2018-07-04T02:28:56 | 127,992,302 | 30 | 4 | MIT | 2022-11-22T00:43:51 | 2018-04-04T01:56:26 | Python | UTF-8 | Python | false | false | 938 | py | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.sync.v1.service import ServiceList
class V1(Version):
def __init__(self, domain):
"""
Initialize the V1 version of Sync
:returns: V1 version of Sync
:rtype: twilio.rest.sync.v1.V1.V1
"""
super(V1, self).__init__(domain)
self.version = 'v1'
self._services = None
@property
def services(self):
"""
:rtype: twilio.rest.sync.v1.service.ServiceList
"""
if self._services is None:
self._services = ServiceList(self)
return self._services
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Sync.V1>'
| [
"[email protected]"
]
| |
846f8c744283c2744979fd2dd8191c67d3644b56 | 9cd25c62e501741bbf4f982058ac60b8cdf815dc | /src/lightmlrestapi/testing/dummy_applications.py | efb57cdfea1de298b00d1f4654558e4e00d82658 | [
"MIT"
]
| permissive | sdpython/lightmlrestapi | c60c2960b271e59750ebfe8fafc9c70304f92cbc | def172965eb197d8ab7f812c3f5f5ce129593cef | refs/heads/master | 2022-07-09T06:56:31.458790 | 2022-05-19T23:46:52 | 2022-05-19T23:46:52 | 110,975,162 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,528 | py | """
@file
@brief Machine Learning Post request
"""
import os
import falcon
import numpy
from .data import get_wiki_img
from ..mlapp import MachineLearningPost, AuthMiddleware, MLStoragePost
from ..args import base642image, image2array, encrypt_password
def dummy_application(app=None, **params):
"""
Defines a dummy application using this API.
It returns a score produced by a model trained
on `Iris datasets <http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html>`_
and two features.
@param app application, if None, creates one
@param params parameters sent to @see cl MachineLearningPost
@return app
.. exref::
:title: Query a REST API with features
This example shows how to query a :epkg:`REST API`
by sending a vector of features.
You can start it by running:
::
start_mlrestapi --name=dummy
And then query it with:
::
import requests
import ujson
features = ujson.dumps({'X': [0.1, 0.2]})
r = requests.post('http://127.0.0.1:8081', data=features)
print(r)
print(r.json())
It should return:
::
{'Y': [[0.4994216179, 0.4514893599, 0.0490890222]]}
"""
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
y = iris.target
clf = LogisticRegression()
clf.fit(X, y)
if app is None:
app = falcon.API()
route = MachineLearningPost(
lambda clf=clf: clf, LogisticRegression.predict_proba, ccall='multi', **params)
# Let's check it works.
one = clf.predict_proba(X[:1])
two = route.check_single(X[0])
if type(one) != type(two): # pylint: disable=C0123
raise RuntimeError("Type mismath")
app.add_route('/', route)
return app
def _distance_img(img1, img2, arr1=None):
"""
Computes the distance between two images.
The function uses :epkg:`Pillow`.
@param img1 reference :epkg:`PIL:Image.Image`
@param img2 new image :epkg:`PIL:Image.Image`
@param arr1 img1 as an array if available (to avoid converting
the same image multiple times)
@return distance (in [0, 1]) or list of distances
"""
arr1 = image2array(img1) if arr1 is None else arr1
if isinstance(img2, list):
return [_distance_img(img1, im2, arr1) for im2 in img2]
else:
im2 = img2
if img1.size != im2.size:
im2 = im2.resize(img1.size)
if im2.mode != 'RGB':
im2 = im2.convert('RGB')
arr2 = image2array(im2)
# raise Exception("THIS {0}-{1}-{2}".format(im2.size, img1.size, arr1 is None))
diff = arr1.ravel() - arr2.ravel()
total = numpy.abs(diff)
return total.sum() / float(len(total)) / 255
def _distance_img_b64(img1, img2, arr1=None):
"""
Calls @see fn _distance_img on an image encoded with :epkg:`*pyf:base64`.
@param img1 reference :epkg:`PIL:Image.Image`
@param img2 new image or list of images encoded with :epkg:`*pyf:base64`
@param arr1 img1 as an array if available (to avoid converting
the same image multiple times)
@return distance (in [0, 1]) or list of distances
"""
if isinstance(img2, list):
img2 = [base642image(img) for img in img2]
else:
img2 = base642image(img2)
return _distance_img(img1, img2, arr1)
def dummy_application_image(app=None, options=None, **params):
"""
Defines a dummy application using this API
and processing one image. The API ingests
an image, resizes it to 224x224 and returns
a distance to an original image from
subfolder *data*.
@param app application, if None, creates one
@param options if not empty, path to an image
@param params parameters sent to @see cl MachineLearningPost
@return app
.. exref::
:title: Query a REST API with an image
This example shows how to query a REST API
by sending an image.
You can start it by running:
::
start_mlrestapi --name=dummyimg
And then query it with:
::
import requests
import ujson
from lightmlrestapi.args import image2base64
img = "path_to_image"
b64 = image2base64(img)[1]
features = ujson.dumps({'X': b64}, reject_bytes=False)
r = requests.post('http://127.0.0.1:8081', data=features)
print(r)
print(r.json())
It should return something like:
::
{'distance': [0.21]}
"""
if options is None or not isinstance(options, str) or len(options) == 0:
options = get_wiki_img()
if not os.path.exists(options):
raise FileNotFoundError("Unable to find image '{0}'.".format(options))
from PIL import Image
img_base = Image.open(get_wiki_img())
if img_base.size != (224, 224):
img_base = img_base.resize((224, 224))
if img_base.mode != 'RGB':
img_base = img_base.convert('RGB')
if app is None:
app = falcon.API()
app.add_route(
'/', MachineLearningPost(lambda: None, lambda model, X: _distance_img_b64(img_base, X), **params))
return app
def dummy_application_fct(restapi_load, restapi_predict, users=None, algo='sha224', app=None, **params):
"""
Defines an application as defined in the tutorial
:ref:`l-dummy-function-application`.
@param restapi_load function to load a model
@param restapi_predict predict function
@param params parameters sent to @see cl MachineLearningPost
@param users restrict to authenticated users,
@see fn load_passwords
@param algo algorithm used to encrypt password
@param app application, if None, creates one
"""
if app is None:
if users:
middleware = [AuthMiddleware(users, algo=algo)]
app = falcon.API(middleware=middleware)
else:
app = falcon.API()
app.add_route(
'/', MachineLearningPost(restapi_load, restapi_predict, **params))
return app
def dummy_application_neighbors(app=None, **params):
"""
Defines a dummy application using this API.
It returns a list of neighbors with a score
on `Iris datasets <http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html>`_.
@param app application, if None, creates one
@param params parameters sent to @see cl MachineLearningPost
@return app
.. exref::
:title: Query a REST API with an image and get neighbors
A previous example shows how to send an image,
this one illustrates a result which is a classifier result
neither a regressor one but neighbors.
You can start it by running:
::
start_mlrestapi --name=dummyknn
And then query it with:
::
import requests
import ujson
features = ujson.dumps({'X': [0.1, 0.2]})
r = requests.post('http://127.0.0.1:8081', data=features)
print(r)
print(r.json())
It should return:
::
{'Y': [[[41, 4.8754486973], [13, 5.0477717856], [8, 5.0774009099], [38, 5.1312766443], [60, 5.2201532545]]]}
"""
from sklearn import datasets
from sklearn.neighbors import NearestNeighbors
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
knn = NearestNeighbors(n_neighbors=5)
knn.fit(X)
def to_serie(knn, x):
"converts into series"
dist, ind = knn.kneighbors(x)
res = []
for i in range(0, len(x)):
res.append([(int(j), float(s))
for j, s in zip(ind[i, :], dist[i, :])])
return res
if app is None:
app = falcon.API()
app.add_route(
'/', MachineLearningPost(lambda: knn, lambda knn, x: to_serie(knn, x),
ccall='multi', **params))
return app
def dummy_application_neighbors_image(app=None, options=None, **params):
"""
Defines a dummy application using this API.
It returns a list of one neighbor for an image
and metadata (random).
@param app application, if None, creates one
@param options if not empty, path to an image
@param params parameters sent to @see cl MachineLearningPost
@return app
You can start it by running:
::
start_mlrestapi --name=dummyknnimg
And then query it with:
::
import requests
import ujson
from lightmlrestapi.args import image2base64
img = "path_to_image"
b64 = image2base64(img)[1]
features = ujson.dumps({'X': b64}, reject_bytes=False)
r = requests.post('http://127.0.0.1:8081', data=features)
print(r)
print(r.json())
It should return:
::
{'Y': [[[41, 4.8754486973, {'name': 'wiki.png', description='something'}]]]}
"""
if options is None or not isinstance(options, str) or len(options) == 0:
options = get_wiki_img()
if not os.path.exists(options):
raise FileNotFoundError("Unable to find image '{0}'.".format(options))
from PIL import Image
img_base = Image.open(get_wiki_img())
if img_base.size != (224, 224):
img_base = img_base.resize((224, 224))
if img_base.mode != 'RGB':
img_base = img_base.convert('RGB')
def mypredict(img_base, X):
"overwrites predict"
res = _distance_img_b64(img_base, X)
final = []
for r, x in zip(res, X):
final.append([(0, r, dict(name=os.path.split(options)[1],
description="image from wikipedia: {0}".format(len(x))))])
return final
if app is None:
app = falcon.API()
app.add_route(
'/', MachineLearningPost(lambda: img_base, mypredict, ccall='multi', **params))
return app
def dummy_application_auth(app=None, algo="sha224", **params):
"""
Defines a dummy application using this API
including authentification.
It returns a score produced by a model trained
on `Iris datasets <http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html>`_
and two features.
@param app application, if None, creates one
@param algo algorithm used to encrypt the passwords
@param params parameters sent to @see cl MachineLearningPost
@return app
It adds one users with the login 'me' and the password 'dummy'.
"""
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
y = iris.target
clf = LogisticRegression()
clf.fit(X, y)
if app is None:
zoo = encrypt_password("dummy", algo=algo)
data = "login,pwd\nme,{0}".format(zoo)
app = falcon.API(middleware=[AuthMiddleware(data, algo=algo)])
route = MachineLearningPost(
lambda clf=clf: clf, LogisticRegression.predict_proba, ccall='multi', **params)
# Let's check it works.
one = clf.predict_proba(X[:1])
two = route.check_single(X[0])
if type(one) != type(two): # pylint: disable=C0123
raise RuntimeError("Type mismath")
app.add_route('/', route)
return app
def dummy_mlstorage(app=None, **params):
"""
Defines a dummy application using this API.
It stores a model and it returns a score produced by a model trained
on `Iris datasets <http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html>`_
and two features.
@param app application, if None, creates one
@param params parameters sent to @see cl MLStoragePost
@return app
"""
if app is None:
app = falcon.API()
route = MLStoragePost(**params)
app.add_route('/', route)
return app
| [
"[email protected]"
]
| |
b02dbf261aa073b6ee44836616403995bc7d2945 | 590a3dab75527bb8742165e84d7108d056826351 | /py_tutorials/py_tutorials/1_supervised/train_svm.py | 0d87c8c10e65447b4213b9ff822672393d37ac32 | []
| no_license | onkarganjewar/ipam-tutorials | 2cfa5055484531f2cc2fdd051ddf0ea771a08a37 | a8451dd121d0a4029bc26c27ee28b45dfc6e51c0 | refs/heads/master | 2021-01-13T12:48:50.944781 | 2016-10-30T02:57:09 | 2016-10-30T02:57:09 | 72,319,739 | 0 | 0 | null | 2016-10-30T02:05:48 | 2016-10-30T02:05:47 | null | UTF-8 | Python | false | false | 1,996 | py | import logging
import sys
import time
import numpy as np
from numpy import arange, dot, maximum, ones, tanh, zeros
from numpy.random import randn
from skdata import mnist
from autodiff import fmin_sgd, fmin_l_bfgs_b
from utils import show_filters
def main():
# -- top-level parameters of this script
dtype = 'float32' # XXX
n_examples = 50000
online_batch_size = 1
online_epochs = 2
batch_epochs = 30
lbfgs_m = 20
# -- load and prepare the data set
data_view = mnist.views.OfficialVectorClassification(x_dtype=dtype)
n_classes = 10
x = data_view.train.x[:n_examples]
y = data_view.train.y[:n_examples]
y1 = -1 * ones((len(y), n_classes)).astype(dtype)
y1[arange(len(y)), y] = 1
# --initialize the SVM model
w = zeros((x.shape[1], n_classes), dtype=dtype)
b = zeros(n_classes, dtype=dtype)
def svm(ww, bb, xx=x, yy=y1):
# -- one vs. all linear SVM loss
margin = yy * (dot(xx, ww) + bb)
hinge = maximum(0, 1 - margin)
cost = hinge.mean(axis=0).sum()
return cost
# -- stage-1 optimization by stochastic gradient descent
print 'Starting SGD'
n_batches = n_examples / online_batch_size
w, b = fmin_sgd(svm, (w, b),
streams={
'xx': x.reshape((n_batches, online_batch_size, x.shape[1])),
'yy': y1.reshape((n_batches, online_batch_size, y1.shape[1]))},
loops=online_epochs,
stepsize=0.001,
print_interval=10000,
)
print 'SGD complete, about to start L-BFGS'
show_filters(w.T, (28, 28), (2, 5,))
# -- stage-2 optimization by L-BFGS
print 'Starting L-BFGS'
w, b = fmin_l_bfgs_b(svm, (w, b),
maxfun=batch_epochs,
iprint=1,
m=lbfgs_m)
print 'L-BFGS complete'
show_filters(w.T, (28, 28), (2, 5,))
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
sys.exit(main())
| [
"[email protected]"
]
| |
9039e65c812006506a37289b4b5417f47fc945cf | ecf62aae48e02420cd99008f58c4725c6da56d22 | /models/review.py | 094c86885b823cd171680a2c1fc29a9485940188 | []
| no_license | ThibautBernard/AirBnB_clone | e3110415acd98b56134928eee0d2befb6bd68a25 | d495dd85add4332880eacf00b338704c2799d3e5 | refs/heads/main | 2023-03-08T15:51:46.968249 | 2021-03-03T15:58:29 | 2021-03-03T15:58:29 | 337,568,140 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 261 | py | #!/usr/bin/python3
from models.base_model import BaseModel
"""
Class that represent a Review
"""
class Review(BaseModel):
place_id = ""
user_id = ""
text = ""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
| [
"[email protected]"
]
| |
c7180dd05c2a2ac7ef806bd02421eb8c3dd4eea2 | e780e90151f26fd94f04c8a6a8ec6f642d7bcfc3 | /ivi/agilent/agilentMSO7014B.py | dd385343f403b961d04616abe01b838ea82ebcf1 | [
"MIT"
]
| permissive | dboonz/python-ivi | a235d811363ef55e415d0a2edd29c95c170e8883 | 1e1b5e765876f09610b6041423f6732a273d4c3e | refs/heads/master | 2020-12-25T01:44:58.430340 | 2013-02-20T20:28:21 | 2013-02-20T20:28:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,599 | py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .agilent7000B import *
class agilentMSO7014B(agilent7000B):
"Agilent InfiniiVision MSO7014B IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._instrument_id = 'AGILENT TECHNOLOGIES,MSO7014B'
self._analog_channel_count = 4
self._digital_channel_count = 16
self._channel_count = 20
self._bandwidth = 100e6
self._init_channels()
| [
"[email protected]"
]
| |
cf724605d7c7e871ac40fdaf6028dd3062921960 | de9b8b7192a0a81e9249823bb2b86f0b7e452863 | /.history/classes/Menu_20171107204738.py | 85e1903a1741c67e3c654ecf7d94421796037429 | [
"MIT"
]
| permissive | reecebenson/uwe-dadsa-tennis-a | f5eaeb1b96d4e61f29279514e68eeea8ad6533db | d0763f819b300fcd0ce27041f5bc4ef0519c00bf | refs/heads/master | 2023-07-08T16:13:23.963348 | 2017-11-30T12:07:01 | 2017-11-30T12:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,156 | py | # DADSA - Assignment 1
# Reece Benson
from functools import partial
from os import system as call
from collections import OrderedDict
class Menu():
# Define the variables we will be using
_app = None
_menu = None
_current = [ "main" ]
_current_menu = "main"
just_called_back = False
def __init__(self, app):
# Set our Application
self._app = app
def load(self):
# Define our Menu
self._menu = { }
# Create our Menu
self._menu['main'] = { "new_season": "New Season", "load_season": "Load Season" }
self._menu['back'] = lambda: self.go_back()
self._menu['new_season'] = { "ns_players": "Players", "ns_tournaments": "Tournaments", "ns_prizemoney": "Prize Money", "ns_difficulty": "Difficulty", "back": "Back" }
self._menu['ns_players'] = { "ns_viewplayers": "View Players", "ns_viewplayer": "View Player", "back": "Back" }
self._menu['ns_tournaments'] = { "ns_viewtournaments": "Example Tournament 1", "back": "Back" }
self._menu['ns_prizemoney'] = { "ns_setprizemoney": "Set Prize Money", "ns_viewprizemoney": "View Prize Money", "back": "Back" }
self._menu['ns_difficulty'] = { "ns_setdifficulty": "Set Difficulty", "ns_viewdifficulty": "View Difficulty", "back": "Back" }
self._menu['load_season'] = { }
# Append our Seasons to the "Load Season" Menu
for seasonId in self._app.handler.get_seasons():
season = self._app.handler.get_season(seasonId)
seasonVar = 'ls_'+str(seasonId)
self._menu['load_season'].update({ seasonVar: season.name() })
# Create our menu option for loading a season
self._menu[seasonVar] = { seasonVar+"_select": "Select Tournament", seasonVar+"_players": "View Players", seasonVar+"_details": "View Details", "back": "Back" }
# Create our menu options
self._menu[seasonVar+"_select"] = { }
self._menu[seasonVar+"_players"] = { }
self._menu[seasonVar+"_details"] = lambda: print(season.display("details"))
# Fill our menu options with extra options
# > "Select Tournament"
for tournament_name in season.tournaments():
tournamentVar = seasonVar+"_select_"+tournament_name
self._menu[seasonVar+"_select"].update({ seasonVar+"_select_"+tournament_name: "Select {0}".format(tournament_name) })
# Set our gender specifiers within the tournament
self._menu[seasonVar+"_select_"+tournament_name] = { }
for gdr in season.rounds():
self._menu[seasonVar+"_select_"+tournament_name].update({ seasonVar+"_select_"+tournament_name+"_"+gdr: "View {0} Rounds".format(gdr) })
self._menu[seasonVar+"_select_"+tournament_name+"_"+gdr] = { }
for rnd in season.rounds()[gdr]:
self._menu[seasonVar+"_select_"+tournament_name+"_"+gdr].update({ seasonVar+"_select_"+tournament_name+"-"+gdr+"-"+rnd: "Round {0}".format(rnd) })
self._menu[seasonVar+"_select_"+tournament_name+"-"+gdr+"-"+rnd] = partial(print, season.name(), tournament_name, gdr, rnd)
self._menu[seasonVar+"_select_"+tournament_name+"_"+gdr].update({ "back": "Back" })
# Add tournament specific options
self._menu[seasonVar+"_select_"+tournament_name].update({ seasonVar+"_select_"+tournament_name+"_difficulty": "View Difficulty", seasonVar+"_select_"+tournament_name+"_prizemoney": "View Prize Money" })
self._menu[seasonVar+"_select_"+tournament_name+"_difficulty"] = partial(print, season.tournament(tournament_name).display("difficulty"))
self._menu[seasonVar+"_select_"+tournament_name+"_prizemoney"] = partial(print, season.tournament(tournament_name).display("prize_money"))
# Add our back option
self._menu[seasonVar+"_select_"+tournament_name].update({ "back": "Back" })
# > "View Players"
for gdr in season.players():
self._menu[seasonVar+"_players"].update({ seasonVar+"_players_"+gdr: "List {0}s".format(gdr) })
self._menu[seasonVar+"_players_"+gdr] = lambda: print(season.display("players", gdr))
# > Add the back options to each submenu
self._menu[seasonVar+"_select"].update({ "back": "Back" })
self._menu[seasonVar+"_players"].update({ "back": "Back" })
self._menu["load_season"].update({ "back": "Back" })
# Display our Menu
self.display("main")
def go_back(self):
# Set our flag to true
self.just_called_back = True
# Pop off the last item of the list
self._current.pop()
# Set our current menu to the last element of the list
self._current_menu = self._current[-1]
def strike(self, text):
result = ''
for c in text:
result = result + c + '\u0336'
return result
def display(self, index = None, error = None):
# Clear our terminal window
call("cls")
# Define our variables
cur_count = 0
menu_item = self.get_menu(index or "main")
# Error Handling
if(error != None):
print("\n", "Error!", error, "\n")
# Menu Title, set tree
print("Please select an option: ({})".format("/".join(self._current)))
menu_counter = 0
for m in menu_item:
# Get our menu name
menu_name = menu_item[m]
# Increase our Counter
menu_counter += 1
# Check that the menu option is available
if(m in self._menu):
# Is the Menu Item a Function?
m_type = None
if(callable(self._menu[m])):
m_type = ""
else:
m_type = "->"
# Print our Menu Item
print("{0}. {1} {2}".format(menu_counter, menu_name, m_type))
else:
print(self.strike("{0}. {1} [?]".format(menu_counter, menu_name)))
# Get User Input
self.get_input()
def validate_menu(self, index):
try:
menu_name = [ (v) for k,v in enumerate(self._menu) if(k == index) ][0]
return menu_name
except IndexError:
return None
def get_menu(self, menu_name):
# Check our Menu exists
if(not menu_name in self._menu):
return None
else:
return self._menu[menu_name]
def menu_exists(self, index):
# Find our indexed menu
menu_item = self.get_menu(self._current_menu)
menu_found = None
menu_counter = 0
for m in menu_item:
# Get our menu name
menu_name = menu_item[m]
# Increase our Counter
menu_counter += 1
# Check that the menu option is available
if(m in self._menu):
# Has our menu been found?
if(menu_counter == index):
# Check if it's a function or a submenu
if(callable(self._menu[m])):
# Call our function
menu_found = self._menu[m]
else:
menu_found = m
else:
menu_found = None
return menu_found
def get_input(self):
# Wrap this in a try/except to validate any errors with input
try:
# Get users input
resp = int(input('>>> '))
# Validate some set input calls
if(resp == "exit"):
raise KeyboardInterrupt
elif(resp == ""):
return self.display(self._current_menu, "Please select a valid option!")
# Validate input from current menu
menu_selected = self.menu_exists(resp)
if(menu_selected != None and callable(menu_selected) != True):
print(menu_selected)
self._current.append(menu_selected)
self._current_menu = menu_selected
self.display(menu_selected)
elif(callable(menu_selected)):
# Clear our screen
call("cls")
# Call our function
menu_selected()
# Hold the user so they can see the result (if back hasn't just been called)
if(self.just_called_back == False):
input("\n>>> Press <Return> to continue...")
else:
self.just_called_back = False
# Display our menu again to stop from program termination
self.display(self._current_menu)
else:
self.display(self._current_menu, "Please select a valid option!")
except KeyboardInterrupt:
self._app.exit()
except ValueError:
self.display(self._current_menu, "Please select a valid option!")
| [
"[email protected]"
]
| |
db81a9b45a6e7f46cba1807fbdb51d5e43c86df0 | 65b4522c04c2be071c2d42095956fe950fe1cebe | /lib/viscojapan/plots/plot_L_curve.py | b89df84bae00664d50f081bdee6e2e51759c6520 | []
| no_license | geodesy/viscojapan | ac0cd93f7a2134cd2651623b94879dcc21c0c46a | 03e70265b56eb5994e73bcb6066f0be338e42f27 | refs/heads/master | 2021-03-03T18:19:07.779601 | 2015-07-16T03:50:49 | 2015-07-16T03:50:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,286 | py | import glob
import h5py
from pylab import loglog, xlabel, ylabel, grid, text
__all__=['plot_L_from_res_h5','plot_L']
def plot_L_from_res_h5(pathname, x_key, y_key, **kwargs):
flist = glob.glob(pathname)
flist = sorted(flist)
xs = []
ys = []
for f in flist:
with h5py.File(f,'r') as fid:
x = fid[x_key][...]
y = fid[y_key][...]
xs.append(x)
ys.append(y)
handle = loglog(xs,ys, **kwargs)
xlabel(x_key)
ylabel(y_key)
grid('on')
return handle
def plot_L(nres,nsol,alphas=None,lanos=None,
label=None,color='blue'):
'''
alphas - regularization parameters array
lanos - array that indicates which alphas pairs are labeled.
None means label every two.
label - L-curve label
'''
assert len(nres)==len(nsol)
if alphas is not None:
assert len(nres)==len(alphas)
# plot L-curve
loglog(nres,nsol,'o',label=label,color=color)
if alphas is not None:
if lanos is None:
lanos = range(0,len(alphas),2)
for ano in lanos:
text(nres[ano],nsol[ano],'%d/%.2G'%(ano,alphas[ano]),color='red')
xlabel('Residual Norm ($\log_{10}{||Gm-d||_2}$)')
ylabel('Solution Roughness ($\log_{10}{||Lm||_2}$)')
grid('on')
| [
"[email protected]"
]
| |
fe818fd05b441670f8e8b077bf332b1d6bd364eb | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/sieve-big-5382.py | 39b19e40d61fac9a071c6abfa5fda3f69668e122 | []
| no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 31,755 | py | # A resizable list of integers
class Vector(object):
items: [int] = None
size: int = 0
def __init__(self:"Vector"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector", idx: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector") -> int:
return self.size
# A resizable list of integers
class Vector2(object):
items: [int] = None
items2: [int] = None
size: int = 0
size2: int = 0
def __init__(self:"Vector2"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector2") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector2") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector2") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector2") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector2", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector2", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector2", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector2", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector2", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector2", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector2", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector2", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector2") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector2") -> int:
return self.size
# A resizable list of integers
class Vector3(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
def __init__(self:"Vector3"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector3") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector3") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector3") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector3") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector3", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector3", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector3", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector3", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector3", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector3", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector3", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector3", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector3", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector3", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector3", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector3", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector3") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector3") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector3") -> int:
return self.size
# A resizable list of integers
class Vector4(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
items4: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
size4: int = 0
def __init__(self:"Vector4"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector4") -> int:
return len(self.items)
# Returns current capacity
def capacity4(self:"Vector4") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity4(self:"Vector4") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector4", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector4", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector4", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append4(self:"Vector4", item: int, item2: int, item3: int, item4: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector4", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector4", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all4(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector4", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector4", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector4", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector4", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector4", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector4", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector4") -> int:
return self.size
# Retrieves the current size of the vector
def length4(self:"Vector4") -> int:
return self.size
# A resizable list of integers
class Vector5(object):
items: [int] = None
items2: [int] = None
items3: [int] = None
items4: [int] = None
items5: [int] = None
size: int = 0
size2: int = 0
size3: int = 0
size4: int = 0
size5: int = 0
def __init__(self:"Vector5"):
self.items = [0]
# Returns current capacity
def capacity(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity2(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity3(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity4(self:"Vector5") -> int:
return len(self.items)
# Returns current capacity
def capacity5(self:"Vector5") -> int:
return len(self.items)
# Increases capacity of vector by one element
def increase_capacity(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity2(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity3(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity4(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Increases capacity of vector by one element
def increase_capacity5(self:"Vector5") -> int:
self.items = self.items + [0]
return self.capacity()
# Appends one item to end of vector
def append(self:"Vector5", item: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append2(self:"Vector5", item: int, item2: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append3(self:"Vector5", item: int, item2: int, item3: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append4(self:"Vector5", item: int, item2: int, item3: int, item4: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends one item to end of vector
def append5(self:"Vector5", item: int, item2: int, item3: int, item4: int, item5: int) -> object:
if self.size == self.capacity():
self.increase_capacity()
self.items[self.size] = item
self.size = self.size + 1
# Appends many items to end of vector
def append_all(self:"Vector5", new_items: [int]) -> object:
item:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all2(self:"Vector5", new_items: [int], new_items2: [int]) -> object:
item:int = 0
item2:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all3(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
for item in new_items:
self.append($Exp)
# Appends many items to end of vector
def append_all4(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
for item in new_items:
self.append(item)
# Appends many items to end of vector
def append_all5(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int], new_items5: [int]) -> object:
item:int = 0
item2:int = 0
item3:int = 0
item4:int = 0
item5:int = 0
for item in new_items:
self.append(item)
# Removes an item from the middle of vector
def remove_at(self:"Vector5", idx: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at2(self:"Vector5", idx: int, idx2: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at3(self:"Vector5", idx: int, idx2: int, idx3: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Removes an item from the middle of vector
def remove_at5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> object:
if idx < 0:
return
while idx < self.size - 1:
self.items[idx] = self.items[idx + 1]
idx = idx + 1
self.size = self.size - 1
# Retrieves an item at a given index
def get(self:"Vector5", idx: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get2(self:"Vector5", idx: int, idx2: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get3(self:"Vector5", idx: int, idx2: int, idx3: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> int:
return self.items[idx]
# Retrieves an item at a given index
def get5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> int:
return self.items[idx]
# Retrieves the current size of the vector
def length(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length2(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length3(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length4(self:"Vector5") -> int:
return self.size
# Retrieves the current size of the vector
def length5(self:"Vector5") -> int:
return self.size
# A faster (but more memory-consuming) implementation of vector
class DoublingVector(Vector):
doubling_limit:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector2(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector2") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector2") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector3(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector3") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector4(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
doubling_limit4:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity4(self:"DoublingVector4") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# A faster (but more memory-consuming) implementation of vector
class DoublingVector5(Vector):
doubling_limit:int = 1000
doubling_limit2:int = 1000
doubling_limit3:int = 1000
doubling_limit4:int = 1000
doubling_limit5:int = 1000
# Overriding to do fewer resizes
def increase_capacity(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity2(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity3(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity4(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Overriding to do fewer resizes
def increase_capacity5(self:"DoublingVector5") -> int:
if (self.capacity() <= self.doubling_limit // 2):
self.items = self.items + self.items
else:
# If doubling limit has been reached, fall back to
# standard capacity increases
self.items = self.items + [0]
return self.capacity()
# Makes a vector in the range [i, j)
def vrange(i:int, j:int) -> Vector:
v:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange2(i:int, j:int, i2:int, j2:int) -> Vector:
v:Vector = None
v2:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange3(i:int, j:int, i2:int, j2:int, i3:int, j3:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange4(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
def vrange5(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int, i5:int, j5:int) -> Vector:
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v5:Vector = None
v = DoublingVector()
while i < j:
v.append(i)
i = i + 1
return v
# Sieve of Eratosthenes (not really)
def sieve(v:Vector) -> object:
i:int = 0
j:int = 0
k:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve2(v:Vector, v2:Vector) -> object:
i:int = 0
i2:int = 0
j:int = 0
j2:int = 0
k:int = 0
k2:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve3(v:Vector, v2:Vector, v3:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
j:int = 0
j2:int = 0
j3:int = 0
k:int = 0
k2:int = 0
k3:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve4(v:Vector, v2:Vector, v3:Vector, v4:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
j:int = 0
j2:int = 0
j3:int = 0
j4:int = 0
k:int = 0
k2:int = 0
k3:int = 0
k4:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
def sieve5(v:Vector, v2:Vector, v3:Vector, v4:Vector, v5:Vector) -> object:
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
j:int = 0
j2:int = 0
j3:int = 0
j4:int = 0
j5:int = 0
k:int = 0
k2:int = 0
k3:int = 0
k4:int = 0
k5:int = 0
while i < v.length():
k = v.get(i)
j = i + 1
while j < v.length():
if v.get(j) % k == 0:
v.remove_at(j)
else:
j = j + 1
i = i + 1
# Input parameter
n:int = 50
n2:int = 50
n3:int = 50
n4:int = 50
n5:int = 50
# Data
v:Vector = None
v2:Vector = None
v3:Vector = None
v4:Vector = None
v5:Vector = None
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
# Crunch
v = vrange(2, n)
v2 = vrange(2, n)
v3 = vrange(2, n)
v4 = vrange(2, n)
v5 = vrange(2, n)
sieve(v)
# Print
while i < v.length():
print(v.get(i))
i = i + 1
| [
"[email protected]"
]
| |
e263b3bbee16c780f42e47780248423245375d51 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_frolicking.py | ef11ef8bcd650fd92541f71619da24e6b40dcd57 | [
"MIT"
]
| permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py |
from xai.brain.wordbase.nouns._frolic import _FROLIC
#calss header
class _FROLICKING(_FROLIC, ):
def __init__(self,):
_FROLIC.__init__(self)
self.name = "FROLICKING"
self.specie = 'nouns'
self.basic = "frolic"
self.jsondata = {}
| [
"[email protected]"
]
| |
838d7b35de18b5ea779615da2b03c44eab3be0f5 | 1cbcf8660d3ea833b0a9aa3d36fe07839bc5cfc5 | /apps/sources/reqparsers/enum.py | c1cbff7b7ef84aa38e0efda18fd5cdbe51f2f9ab | []
| no_license | zhanghe06/migration_project | f77776969907740494281ac6d7485f35d4765115 | 0264b292873b211bfeca0d645cc41abc9efe883f | refs/heads/master | 2022-12-12T10:55:43.475939 | 2019-09-29T09:19:13 | 2019-09-29T09:19:13 | 185,584,884 | 0 | 1 | null | 2022-12-08T05:04:58 | 2019-05-08T10:31:57 | Python | UTF-8 | Python | false | false | 306 | py | #!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: enum.py
@time: 2019-04-26 15:55
"""
from __future__ import unicode_literals
structure_key_item = 'enum'
structure_key_items = 'enums'
structure_key_item_cn = '枚举类型'
structure_key_items_cn = '枚举类型'
| [
"[email protected]"
]
| |
20429d1f27e52eeb5e975b6e89b687a9a43d7777 | 6fcfb638fa725b6d21083ec54e3609fc1b287d9e | /python/wookayin_tensorflow-talk-debugging/tensorflow-talk-debugging-master/codes/40-mnist-name.py | 76816d57890463ede3dc3542f2f265757740f1bb | []
| no_license | LiuFang816/SALSTM_py_data | 6db258e51858aeff14af38898fef715b46980ac1 | d494b3041069d377d6a7a9c296a14334f2fa5acc | refs/heads/master | 2022-12-25T06:39:52.222097 | 2019-12-12T08:49:07 | 2019-12-12T08:49:07 | 227,546,525 | 10 | 7 | null | 2022-12-19T02:53:01 | 2019-12-12T07:29:39 | Python | UTF-8 | Python | false | false | 1,989 | py | import tensorflow as tf
import tensorflow.contrib.layers as layers
from datetime import datetime
# MNIST input data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
def multilayer_perceptron(x):
W_fc1 = tf.Variable(tf.random_normal([784, 256], mean=0, stddev=1))
b_fc1 = tf.Variable([0] * 256) # ???????
fc1 = tf.nn.xw_plus_b(x, W_fc1, b_fc1)
fc2 = layers.fully_connected(fc1, 256, activation_fn=tf.nn.relu, scope='fc2')
out = layers.fully_connected(fc2, 10, activation_fn=None, scope='out')
return out
# build model, loss, and train op
x = tf.placeholder(tf.float32, [None, 784], name='placeholder_x')
y = tf.placeholder(tf.float32, [None, 10], name='placeholder_y')
pred = multilayer_perceptron(x)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
def train(session):
batch_size = 200
session.run(tf.global_variables_initializer())
# Training cycle
for epoch in range(10):
epoch_loss = 0.0
batch_steps = mnist.train.num_examples / batch_size
for i in range(batch_steps):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, c = session.run([train_op, loss],
feed_dict={x: batch_x, y: batch_y})
epoch_loss += c / batch_steps
print "[%s] Epoch %02d, Loss = %.6f" % (datetime.now(), epoch, epoch_loss)
# Test model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
def main():
with tf.Session(config=tf.ConfigProto(
gpu_options=tf.GPUOptions(allow_growth=True),
device_count={'GPU': 1})) as session:
train(session)
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
5bb7686bae0152f74da147be60815db92ab4eecf | aa0d55b2aa22da0af6545ce0da46d04dbdc3bffc | /cpgames/core/games/gobang/__init__.py | 6b648191eb7f92c3653f36b0ac7b8a5c76dea903 | [
"Apache-2.0"
]
| permissive | cyanghsieh/Games | 19fdad463cf12cbd503a399ed2700c0dae615714 | 07767df6d181b9eae89ce0a8b883d19afb450cc1 | refs/heads/master | 2023-05-11T11:11:09.777569 | 2023-02-22T14:28:18 | 2023-02-22T14:28:18 | 283,113,319 | 0 | 0 | MIT | 2020-07-28T05:49:13 | 2020-07-28T05:49:12 | null | UTF-8 | Python | false | false | 47 | py | '''initialize'''
from .gobang import GobangGame | [
"[email protected]"
]
| |
e00f6197eedaeabfbe42d2c14ed4cc0528ae47e6 | 67e817ca139ca039bd9eee5b1b789e5510119e83 | /Tree/[508]Most Frequent Subtree Sum.py | d1d33c1d3ec9ef186d0feb9017ac84a00713155f | []
| no_license | dstch/my_leetcode | 0dc41e7a2526c2d85b6b9b6602ac53f7a6ba9273 | 48a8c77e81cd49a75278551048028c492ec62994 | refs/heads/master | 2021-07-25T21:30:41.705258 | 2021-06-06T08:58:29 | 2021-06-06T08:58:29 | 164,360,878 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,920 | py | #
# Given the root of a tree, you are asked to find the most frequent subtree sum.
# The subtree sum of a node is defined as the sum of all the node values formed b
# y the subtree rooted at that node (including the node itself). So what is the mo
# st frequent subtree sum value? If there is a tie, return all the values with the
# highest frequency in any order.
#
#
# Examples 1
# Input:
#
# 5
# / \
# 2 -3
#
# return [2, -3, 4], since all the values happen only once, return all of them i
# n any order.
#
#
# Examples 2
# Input:
#
# 5
# / \
# 2 -5
#
# return [2], since 2 happens twice, however -5 only occur once.
#
#
# Note:
# You may assume the sum of values in any subtree is in the range of 32-bit sign
# ed integer.
# Related Topics Hash Table Tree
# 👍 840 👎 143
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
dic = {}
m = 0
def func(node, m):
if node is not None:
m = func(node.left, m)
m = func(node.right, m)
s = node.val
if node.left:
s += node.left.val
if node.right:
s += node.right.val
node.val = s
if node.val in dic:
dic[node.val] += 1
else:
dic[node.val] = 1
if dic[node.val] > m:
m = dic[node.val]
return m
m = func(root, m)
print(dic)
return [x for x in dic if dic[x] == m]
# leetcode submit region end(Prohibit modification and deletion)
| [
"[email protected]"
]
| |
7d7cf6f0f0807e1d13c773d7fd9c579e4981bccd | 3bfaf1de118ecb3863b89737a935c32d7bcf9d28 | /Leetcode/range-sum-query-immutable/source.py | d0628d3d2202ca61a51883566eace81843919629 | []
| no_license | ndjman7/Algorithm | 13db942c6228c2d55e5c0cdf997db834cf617988 | a4bd428e51a2dcebc81214564ac3fd967175f7ae | refs/heads/master | 2021-06-21T12:41:42.006005 | 2020-12-25T07:47:52 | 2020-12-26T12:43:15 | 163,792,061 | 2 | 0 | null | 2019-09-03T04:35:15 | 2019-01-02T03:57:05 | C++ | UTF-8 | Python | false | false | 537 | py | class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.cache = [0 for i in range(len(nums)+1)]
for i in range(len(nums)):
self.cache[i + 1] = self.cache[i] + nums[i]
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.cache[j + 1] - self.cache[i]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
| [
"[email protected]"
]
| |
6e7b2f202fd14008d5f076ad4fbac305307205ba | 2d358ffb51f03cc64cc2da0f684b0928aebe139c | /test7/myapp/models.py | 833b515eca90cae41e62460be8e577d84dc608ad | []
| no_license | 853695319/learningdjango | 195ffabdbd3a5b6bc4386cbb678504c0d2cd0095 | d2aac1117bb2ca31e4f247a9d206adcf3a9f39a2 | refs/heads/master | 2020-05-03T04:59:16.094900 | 2019-04-23T06:25:02 | 2019-04-23T06:25:02 | 178,437,059 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 304 | py | from django.db import models
from django.contrib.auth.models import User
class Note(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField()
title = models.CharField(max_length=200)
body = models.TextField()
def __unicode__(self):
return self.title
| [
"[email protected]"
]
| |
a3f65da104bc7e4c2972ff9282afb01091ef9cc2 | 5bd624a1c1d4834b49fe5e2d2bf9446d08a36161 | /pytype/infer.py | fe1b722b8992f0bc0c1200ea92c4651ce74e6714 | [
"Apache-2.0",
"MIT"
]
| permissive | tharvik/pytype | ce3c7eca73082b047508df715ce7d179f28e15ba | df526720c96b08d328b2214d08eaa67ca342b01a | refs/heads/master | 2020-12-01T09:32:24.823351 | 2016-07-12T00:29:39 | 2016-07-12T14:18:14 | 63,402,024 | 0 | 0 | null | 2016-07-15T07:41:27 | 2016-07-15T07:41:27 | null | UTF-8 | Python | false | false | 24,398 | py | """Code for generating and storing inferred types."""
import collections
import logging
import os
import StringIO
import subprocess
from pytype import abstract
from pytype import convert_structural
from pytype import output
from pytype import state as frame_state
from pytype import utils
from pytype import vm
from pytype.pytd import optimize
from pytype.pytd import pytd
from pytype.pytd import utils as pytd_utils
from pytype.pytd.parse import visitors
log = logging.getLogger(__name__)
CallRecord = collections.namedtuple("CallRecord",
["function", "positional_arguments",
"keyword_arguments", "return_value"])
class AnalysisFrame(object):
"""Frame representing the "analysis function" that calls everything."""
def __init__(self):
self.f_code = None # for recursion detection
self.f_builtins = None
self.current_opcode = None # for memoizations of unknowns
class CallTracer(vm.VirtualMachine):
"""Virtual machine that records all function calls.
Attributes:
exitpoint: A CFG node representing the program exit. Needs to be set before
analyze_types.
"""
# TODO(pludemann): def isinstance(self, obj, classes) - see
# TypegraphVirtualMachine.isinstance
def __init__(self, *args, **kwargs):
super(CallTracer, self).__init__(*args, **kwargs)
self._unknowns = {}
self._calls = set()
self._method_calls = set()
self.exitpoint = None
def create_argument(self, node, signature, method_name, i):
name = signature.param_names[i]
t = signature.annotations.get(name)
if t:
return self.instantiate(t.to_variable(node, t.name), node)
else:
return self.create_new_unknown(node, name)
def create_varargs(self, node):
value = abstract.Instance(self.tuple_type, self)
value.overwrite_type_parameter(
node, "T", self.create_new_unknown(node, "varargs_value"))
return value.to_variable(node, "*args")
def create_kwargs(self, node):
key_type = self.primitive_class_instances[str].to_variable(node, "str")
value_type = self.create_new_unknown(node, "kwargs_value")
kwargs = abstract.Instance(self.dict_type, self)
kwargs.overwrite_type_parameter(
node, abstract.Dict.KEY_TYPE_PARAM, key_type)
kwargs.overwrite_type_parameter(
node, abstract.Dict.VALUE_TYPE_PARAM, value_type)
return kwargs.to_variable(node, "**kwargs")
def call_function_in_frame(self, node, var, args, kwargs,
starargs, starstarargs):
frame = AnalysisFrame()
self.push_frame(frame)
log.info("Analyzing %r", [v.name for v in var.data])
state = frame_state.FrameState.init(node)
state, ret = self.call_function_with_state(
state, var, args, kwargs, starargs, starstarargs)
self.pop_frame(frame)
return state.node, ret
def analyze_method(self, val, node):
method = val.data
if isinstance(method, (abstract.InterpreterFunction,
abstract.BoundInterpreterFunction)):
args = [self.create_argument(node, method.signature, val.data.name, i)
for i in range(method.argcount())]
varargs = self.create_varargs(node) if method.has_varargs() else None
kwargs = self.create_kwargs(node) if method.has_kwargs() else None
fvar = val.AssignToNewVariable("f", node)
new_node, _ = self.call_function_in_frame(
node, fvar, args, {}, varargs, kwargs)
new_node.ConnectTo(node)
node = new_node
return node
def analyze_method_var(self, name, var, node):
log.info("Analyzing %s", name)
for val in var.Bindings(node):
node2 = self.analyze_method(val, node)
node2.ConnectTo(node)
return node
def bind_method(self, name, methodvar, instance, clsvar, node):
bound = self.program.NewVariable(name)
for m in methodvar.Data(node):
bound.AddBinding(m.property_get(instance, clsvar), [], node)
return bound
def instantiate(self, clsv, node):
"""Build an (dummy) instance from a class, for analyzing it."""
n = self.program.NewVariable(clsv.name)
for cls in clsv.Data(node):
instance = cls.instantiate(node)
n.PasteVariable(instance, node)
return n
def init_class(self, node, val):
instance = self.instantiate(val.AssignToNewVariable(val.data.name, node),
node)
cls = val.data
node, init = cls.get_attribute(node, "__init__", instance.bindings[0], val)
clsvar = val.AssignToNewVariable("cls", node)
if init:
bound_init = self.bind_method("__init__", init, instance, clsvar, node)
node = self.analyze_method_var("__init__", bound_init, node)
return node, clsvar, instance
def analyze_class(self, val, node):
node, clsvar, instance = self.init_class(node, val)
for name, methodvar in sorted(val.data.members.items()):
b = self.bind_method(name, methodvar, instance, clsvar, node)
node2 = self.analyze_method_var(name, b, node)
node2.ConnectTo(node)
return node
def analyze_function(self, val, node):
if val.data.is_attribute_of_class:
# We'll analyze this function as part of a class.
log.info("Analyze functions: Skipping class method %s", val.data.name)
elif val.data.is_closure():
# We analyze closures as part of the function they're defined in.
log.info("Analyze functions: Skipping closure %s", val.data.name)
else:
node2 = self.analyze_method(val, node)
node2.ConnectTo(node)
return node
def analyze_toplevel(self, node, defs, ignore):
for name, var in sorted(defs.items()): # sort, for determinicity
if name not in ignore:
for value in var.bindings:
if isinstance(value.data, abstract.InterpreterClass):
node2 = self.analyze_class(value, node)
node2.ConnectTo(node)
elif isinstance(value.data, (abstract.InterpreterFunction,
abstract.BoundInterpreterFunction)):
node2 = self.analyze_function(value, node)
node2.ConnectTo(node)
def analyze(self, node, defs, ignore):
assert not self.frame
self.analyze_toplevel(node, defs, ignore)
return node
def trace_unknown(self, name, unknown):
self._unknowns[name] = unknown
def trace_call(self, func, posargs, namedargs, result):
"""Add an entry into the call trace.
Args:
func: A typegraph Value of functions that was called.
posargs: The positional arguments, an iterable over cfg.Value.
namedargs: The keyword arguments, a dict mapping str to cfg.Value.
result: A Variable of the possible result values.
"""
log.debug("Logging call to %r with %d args, return %r",
func, len(posargs), result)
args = tuple(posargs)
kwargs = tuple((namedargs or {}).items())
if isinstance(func.data, abstract.BoundPyTDFunction):
self._method_calls.add(CallRecord(func, args, kwargs, result))
elif isinstance(func.data, abstract.PyTDFunction):
self._calls.add(CallRecord(func, args, kwargs, result))
def pytd_classes_for_unknowns(self):
classes = []
for name, var in self._unknowns.items():
for value in var.FilteredData(self.exitpoint):
classes.append(value.to_structural_def(name))
return classes
def pytd_for_types(self, defs, ignore):
for name, var in defs.items():
abstract.variable_set_official_name(var, name)
data = []
for name, var in defs.items():
if name in output.TOP_LEVEL_IGNORE or name in ignore:
continue
options = var.FilteredData(self.exitpoint)
if (len(options) > 1 and not
all(isinstance(o, (abstract.InterpreterFunction,
abstract.BoundInterpreterFunction))
for o in options)):
# It's ambiguous whether this is a type, a function or something
# else, so encode it as a constant.
combined_types = pytd_utils.JoinTypes(t.to_type() for t in options)
data.append(pytd.Constant(name, combined_types))
else:
for option in options:
if hasattr(option, "to_pytd_def"):
d = option.to_pytd_def(name) # Deep definition
else:
d = option.to_type() # Type only
if isinstance(d, pytd.TYPE):
data.append(pytd.Constant(name, d))
else:
data.append(d)
return pytd_utils.WrapTypeDeclUnit("inferred", data)
@staticmethod
def _call_traces_to_function(call_traces, name_transform=lambda x: x):
funcs = collections.defaultdict(pytd_utils.OrderedSet)
for funcvar, args, kws, retvar in call_traces:
if isinstance(funcvar.data, abstract.BoundFunction):
func = funcvar.data.underlying.signatures[0]
else:
func = funcvar.data.signatures[0]
arg_names = func.get_parameter_names()
arg_types = (a.data.to_type()
for a in func.get_bound_arguments() + list(args))
ret = pytd_utils.JoinTypes(t.to_type() for t in retvar.data)
funcs[funcvar.data.name].add(pytd.Signature(
tuple(pytd.Parameter(n, t)
for n, t in zip(arg_names, arg_types)) +
tuple(pytd.Parameter(name, a.data.to_type())
for name, a in kws),
ret, has_optional=False, exceptions=(), template=()))
functions = []
for name, signatures in funcs.items():
functions.append(pytd.Function(name_transform(name), tuple(signatures),
pytd.METHOD))
return functions
def _pack_name(self, name):
"""Pack a name, for unpacking with type_match.unpack_name_of_partial()."""
return "~" + name.replace(".", "~")
def pytd_functions_for_call_traces(self):
return self._call_traces_to_function(self._calls, self._pack_name)
def pytd_classes_for_call_traces(self):
class_to_records = collections.defaultdict(list)
for call_record in self._method_calls:
args = call_record.positional_arguments
if not any(isinstance(a.data, abstract.Unknown) for a in args):
# We don't need to record call signatures that don't involve
# unknowns - there's nothing to solve for.
continue
clsvar = args[0].data.get_class()
for cls in clsvar.data:
if isinstance(cls, abstract.PyTDClass):
class_to_records[cls].append(call_record)
classes = []
for cls, call_records in class_to_records.items():
full_name = cls.module + "." + cls.name if cls.module else cls.name
classes.append(pytd.Class(
name=self._pack_name(full_name),
parents=(), # not used in solver
methods=self._call_traces_to_function(call_records),
constants=(),
template=(),
))
return classes
def pytd_aliases(self):
return () # TODO(kramm): Compute these.
def compute_types(self, defs, ignore):
self.program.Freeze()
ty = pytd_utils.Concat(
self.pytd_for_types(defs, ignore),
pytd.TypeDeclUnit(
"unknowns",
tuple(), # constants
tuple(self.pytd_classes_for_unknowns()) +
tuple(self.pytd_classes_for_call_traces()),
tuple(self.pytd_functions_for_call_traces()),
tuple(self.pytd_aliases())))
ty = ty.Visit(optimize.PullInMethodClasses())
ty = ty.Visit(visitors.DefaceUnresolved(
[ty, self.loader.concat_all()], "~unknown"))
return ty
def _create_call_arg(self, name, t, node):
if t == pytd.ClassType("__builtin__.object"):
# As an arg, "object" means: we can use anything for this argument,
# because everything inherits from object.
# TODO(kramm): Maybe we should use AnythingType for params without type.
return self.create_new_unsolvable(node, name)
else:
return self.create_pytd_instance(name, t, {}, node)
def _check_function(self, pytd_function, f, node, skip_self=False):
"""Check that a function or method is compatible with its PYTD."""
for sig in pytd_function.signatures:
args = [self._create_call_arg(name, t, node)
for name, t in sig.params[(1 if skip_self else 0):]]
nominal_return = self.convert_constant_to_value("ret", sig.return_type)
for val in f.bindings:
fvar = val.AssignToNewVariable("f", node)
_, retvar = self.call_function_in_frame(
node, fvar, args, {}, None, None)
if retvar.bindings:
for combination in utils.deep_variable_product([retvar]):
view = {value.variable: value for value in combination}
match = abstract.match_var_against_type(retvar, nominal_return,
{}, node, view)
if match is None:
if isinstance(val.data, (abstract.InterpreterFunction,
abstract.BoundInterpreterFunction)):
self.errorlog.bad_return_type(
val.data.get_first_opcode(),
pytd_function, view[retvar].data, sig.return_type)
else:
log.error("%s is not a function?", val.data.name)
else:
log.error("Couldn't call %s", pytd_function.name)
def check_types(self, node, defs, ast, py_filename, pytd_filename):
"""Verify that the types declared in PyTD work with the Python code.
E.g. if there's a PyTD signature
def abs(x: int) -> int
then we'll call the abs() function with an integer and verify that we get
an integer back.
Any error we encounter will be logged.
Args:
node: The CFG node at the end of the program.
defs: All top-level identifiers declared by the program.
ast: The PyTD AST.
py_filename: Filename of the Python file.
pytd_filename: Filename of the PyTD file.
"""
# TODO(kramm): Do much more checking here.
for item in ast.functions + ast.classes + ast.constants:
if item.name not in defs:
self.errorlog.missing_definition(item, pytd_filename, py_filename)
if self.errorlog.has_error():
return
for pytd_function in ast.functions:
self._check_function(pytd_function, defs[pytd_function.name], node)
for pytd_cls in ast.classes:
cls = defs[pytd_cls.name]
for val in cls.bindings:
# TODO(kramm): The call to the constructor of this should use the pytd.
node2, _, instance = self.init_class(node, val)
for pytd_method in pytd_cls.methods:
_, method = self._retrieve_attr(node, instance, pytd_method.name)
if method is None:
raise NotImplementedError("getattr(%s) failed!" % pytd_method.name)
# TODO(kramm): Should this be the node returned from _retrieve_attr?
self._check_function(pytd_method, method, node2, skip_self=True)
def _pretty_variable(var):
"""Return a pretty printed string for a Variable."""
lines = []
single_value = len(var.bindings) == 1
if not single_value:
# Write a description of the variable (for single value variables this
# will be written along with the value later on).
lines.append("$%d %s" % (var.id, var.name))
for value in var.bindings:
data = utils.maybe_truncate(value.data)
if single_value:
binding = "%s, %s = %s" % (value, var.name, data)
else:
binding = " #%d %s" % (value.data.id, data)
if len(value.origins) == 1:
# Single origin. Use the binding as a prefix when writing the orign.
prefix = binding + ", "
else:
# Multiple origins, write the binding on its own line, then indent all
# of the origins.
lines.append(binding)
prefix = " "
for origin in value.origins:
src = utils.pretty_dnf([[str(v) for v in source_set]
for source_set in origin.source_sets])
lines.append("%s%s @%d" %(prefix, src, origin.where.id))
return "\n".join(lines)
def program_to_text(program):
"""Generate a text (CFG nodes + assignments) version of a program.
For debugging only.
Args:
program: An instance of cfg.Program
Returns:
A string representing all of the data for this program.
"""
s = StringIO.StringIO()
seen = set()
for node in utils.order_nodes(program.cfg_nodes):
seen.add(node)
s.write("%s\n" % node.Label())
s.write(" From: %s\n" % ", ".join(n.Label() for n in node.incoming))
s.write(" To: %s\n" % ", ".join(n.Label() for n in node.outgoing))
s.write("\n")
variables = set(value.variable for value in node.bindings)
for var in sorted(variables, key=lambda v: v.id):
# If a variable is bound in more than one node then it will be listed
# redundantly multiple times. One alternative would be to only list the
# values that occur in the given node, and then also list the other nodes
# that assign the same variable.
# Write the variable, indenting by two spaces.
s.write(" %s\n" % _pretty_variable(var).replace("\n", "\n "))
s.write("\n")
return s.getvalue()
def program_to_dot(program, ignored, only_cfg=False):
"""Convert a typegraph.Program into a dot file.
Args:
program: The program to convert.
ignored: A set of names that should be ignored. This affects most kinds of
nodes.
only_cfg: If set, only output the control flow graph.
Returns:
A str of the dot code.
"""
def objname(n):
return n.__class__.__name__ + str(id(n))
def escape(s):
return repr(s)[1:-1].replace('"', '\\"')
print("cfg nodes=%d, vals=%d, variables=%d" % (
len(program.cfg_nodes),
sum(len(v.bindings) for v in program.variables),
len(program.variables)))
sb = StringIO.StringIO()
sb.write("digraph {\n")
for node in program.cfg_nodes:
if node in ignored:
continue
sb.write("%s[shape=polygon,sides=4,label=\"<%d>%s\"];\n"
% (objname(node), node.id, node.name))
for other in node.outgoing:
sb.write("%s -> %s [penwidth=2.0];\n" % (objname(node), objname(other)))
if only_cfg:
sb.write("}\n")
return sb.getvalue()
for variable in program.variables:
if variable.name in ignored:
continue
if all(origin.where == program.entrypoint
for value in variable.bindings
for origin in value.origins):
# Ignore "boring" values (a.k.a. constants)
continue
sb.write('%s[label="%s",shape=polygon,sides=4,distortion=.1];\n'
% (objname(variable), escape(variable.name)))
for val in variable.bindings:
sb.write("%s -> %s [arrowhead=none];\n" %
(objname(variable), objname(val)))
sb.write("%s[label=\"%s@0x%x\",fillcolor=%s];\n" %
(objname(val), repr(val.data)[:10], id(val.data),
"white" if val.origins else "red"))
for loc, srcsets in val.origins:
if loc == program.entrypoint:
continue
for srcs in srcsets:
sb.write("%s[label=\"\"];\n" % (objname(srcs)))
sb.write("%s -> %s [color=pink,arrowhead=none,weight=40];\n"
% (objname(val), objname(srcs)))
if loc not in ignored:
sb.write("%s -> %s [style=dotted,arrowhead=none,weight=5]\n"
% (objname(loc), objname(srcs)))
for src in srcs:
sb.write("%s -> %s [color=lightblue,weight=2];\n"
% (objname(src), objname(srcs)))
sb.write("}\n")
return sb.getvalue()
def _get_module_name(filename, options):
"""Return, or try to reverse-engineer, the name of the module we're analyzing.
If a module was passed using --module-name, that name will be returned.
Otherwise, this method tries to deduce the module name from the PYTHONPATH
and the filename. This will not always be possible. (It depends on the
filename starting with an entry in the pythonpath.)
The module name is used for relative imports.
Args:
filename: The filename of a Python file. E.g. "src/foo/bar/my_module.py".
options: An instance of config.Options.
Returns:
A module name, e.g. "foo.bar.my_module", or None if we can't determine the
module name.
"""
if options.module_name is not None:
return options.module_name
elif filename:
filename, _ = os.path.splitext(filename)
for path in options.pythonpath:
# TODO(kramm): What if filename starts with "../"? (os.pardir)
if filename.startswith(path):
subdir = filename[len(path):].lstrip(os.sep)
return subdir.replace(os.sep, ".")
def check_types(py_src, pytd_src, py_filename, pytd_filename, errorlog,
options,
run_builtins=True,
reverse_operators=False,
cache_unknowns=False,
maximum_depth=None):
"""Verify a PyTD against the Python code."""
tracer = CallTracer(errorlog=errorlog, options=options,
module_name=_get_module_name(py_filename, options),
reverse_operators=reverse_operators,
cache_unknowns=cache_unknowns,
maximum_depth=maximum_depth)
loc, defs, _ = tracer.run_program(py_src, py_filename, run_builtins)
ast = pytd_utils.ParsePyTD(pytd_src, pytd_filename, options.python_version,
lookup_classes=True)
ast = tracer.loader.resolve_ast(ast)
tracer.check_types(loc, defs, ast,
os.path.basename(py_filename),
os.path.basename(pytd_filename))
def infer_types(src,
errorlog, options,
filename=None, run_builtins=True,
deep=True, solve_unknowns=True,
reverse_operators=False, cache_unknowns=False,
maximum_depth=None):
"""Given Python source return its types.
Args:
src: A string containing Python source code.
errorlog: Where error messages go. Instance of errors.ErrorLog.
options: config.Options object
filename: Filename of the program we're parsing.
run_builtins: Whether to preload the native Python builtins when running
the program.
deep: If True, analyze all functions, even the ones not called by the main
execution flow.
solve_unknowns: If yes, try to replace structural types ("~unknowns") with
nominal types.
reverse_operators: Experimental. Allow overloading __radd__ etc.
For user-defined types only - our builtins don't need reverse operators.
cache_unknowns: If True, do a faster approximation of unknown types.
maximum_depth: Depth of the analysis. Default: unlimited.
Returns:
A TypeDeclUnit
Raises:
AssertionError: In case of a bad parameter combination.
"""
tracer = CallTracer(errorlog=errorlog, options=options,
module_name=_get_module_name(filename, options),
reverse_operators=reverse_operators,
cache_unknowns=cache_unknowns,
maximum_depth=maximum_depth)
loc, defs, builtin_names = tracer.run_program(src, filename, run_builtins)
log.info("===Done run_program===")
# TODO(pludemann): make test_inference.InferDedent and this code the same:
if deep:
tracer.exitpoint = tracer.analyze(loc, defs, builtin_names)
else:
tracer.exitpoint = loc
ast = tracer.compute_types(defs, builtin_names)
ast = tracer.loader.resolve_ast(ast)
if solve_unknowns:
log.info("=========== PyTD to solve =============\n%s", pytd.Print(ast))
ast = convert_structural.convert_pytd(ast, tracer.loader.concat_all())
if options.output_cfg or options.output_typegraph:
if options.output_cfg and options.output_typegraph:
raise AssertionError("Can output CFG or typegraph, but not both")
dot = program_to_dot(tracer.program, set([]), bool(options.output_cfg))
proc = subprocess.Popen(["/usr/bin/dot", "-T", "svg", "-o",
options.output_cfg or options.output_typegraph],
stdin=subprocess.PIPE)
proc.stdin.write(dot)
proc.stdin.close()
if options.output_debug:
text = program_to_text(tracer.program)
if options.output_debug == "-":
log.info("=========== Program Dump =============\n%s", text)
else:
with open(options.output_debug, "w") as fi:
fi.write(text)
return ast
| [
"[email protected]"
]
| |
50e2de4f73782ca8217362cece9dcdc7a601d9ce | e1891d21594e17431abfcbbc36f3b479cc3eb5d3 | /blog/models.py | 6bd8baaea251d83aa5a832c354cda7a972d1e99d | []
| no_license | Ankrate/venezoproject | 01978d72332cf642637333715f695f6c6d04d7a7 | a26ccd270573420d29ba39fd37f2b9f572d010c3 | refs/heads/master | 2020-07-07T11:15:36.953266 | 2019-08-26T12:40:05 | 2019-08-26T12:40:05 | 202,558,469 | 0 | 0 | null | 2019-08-15T14:42:57 | 2019-08-15T14:42:57 | null | UTF-8 | Python | false | false | 1,780 | py | from django.db import models
import os, random
from django.db.models.signals import pre_save
from .utils import unique_slug_generator
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
print (instance)
print (filename)
name, ext = get_filename_ext(filename)
new_filename = random.randint(1, 234982304)
final_filename = '{}{}'.format(new_filename, ext)
return f'blog/{new_filename}/{final_filename}'
class BlogCategories(models.Model):
title = models.CharField(max_length=2555)
slug = models.SlugField(blank=True, unique=True, max_length=255)
class Meta:
verbose_name_plural = 'Категории блога'
def __str__(self):
return self.title
class BlogModel(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True, max_length=255)
description = models.TextField()
short_desc = models.TextField(blank=True)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
category = models.ForeignKey(BlogCategories,related_name='category', on_delete=models.CASCADE, default=1)
publish = models.DateField(auto_now=True)
class Meta:
verbose_name_plural = 'Статьи'
def __str__(self):
return self.title
def blog_pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(blog_pre_save_receiver, sender=BlogModel)
pre_save.connect(blog_pre_save_receiver, sender=BlogCategories)
| [
"[email protected]"
]
| |
4fa9358de28f9b8aa414f45aa1e563eb13718b7a | 8e24e8bba2dd476f9fe612226d24891ef81429b7 | /geeksforgeeks/python/python_all/124_1.py | 1860506797a3534ef6306aab0ebc6ad7919b518a | []
| no_license | qmnguyenw/python_py4e | fb56c6dc91c49149031a11ca52c9037dc80d5dcf | 84f37412bd43a3b357a17df9ff8811eba16bba6e | refs/heads/master | 2023-06-01T07:58:13.996965 | 2021-06-15T08:39:26 | 2021-06-15T08:39:26 | 349,059,725 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,000 | py | Python | Intersection in Tuple Records Data
Sometimes, while working with data, we may have a problem in which we require
to find the matching records between two lists that we receive. This is a very
common problem and records usually occur as a tuple. Let’s discuss certain
ways in which this problem can be solved.
**Method #1 : Using list comprehension**
List comprehension can opt as method to perform this task in one line rather
than running a loop to find the common element. In this, we just iterate for
single list and check if any element occurs in other one.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Intersection in Tuple Records Data
# Using list comprehension
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best',
3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Intersection in Tuple Records Data
# Using list comprehension
res = [ele1 for ele1 in test_list1
for ele2 in test_list2 if ele1 == ele2]
# printing result
print("The Intersection of data records is : " + str(res))
---
__
__
**Output :**
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
**Method #2 : Usingset.intersection()**
This task can also be performed in smaller way using the generic set
intersection. In this, we first convert the list of records to a set and then
perform its intersection using intersection().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Intersection in Tuple Records Data
# Using set.intersection()
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best',
3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Intersection in Tuple Records Data
# set.intersection()
res = list(set(test_list1).intersection(set(test_list2)))
# printing result
print("The Intersection of data records is : " + str(res))
---
__
__
**Output :**
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
| [
"[email protected]"
]
| |
a767ea85226a3a33df945842b2bedd5921f415aa | a537ac145d19a1a6cfb1ee3556144292df4ebe29 | /django_libs/tests/test_app/models.py | 0859a44e00cd78b6ad4899f9cf438e081b81b6e3 | [
"MIT"
]
| permissive | papasax/django-libs | 80e0d122ec2c41ebbafddb11ffc69bd2794efeec | 734c7b3506d8aab78f91dae10eda4c150be18240 | refs/heads/master | 2021-01-09T09:01:01.400301 | 2014-12-04T21:12:09 | 2014-12-04T21:12:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,008 | py | """Models for the ``test_app`` app."""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from simple_translation.translation_pool import translation_pool
from ...models_mixins import (
SimpleTranslationMixin,
SimpleTranslationPublishedManager,
)
class DummyProfile(SimpleTranslationMixin, models.Model):
"""Just a dummy profile model for testing purposes."""
user = models.ForeignKey('auth.User')
dummy_field = models.CharField(
verbose_name=_('Dummy Field'),
max_length=128,
)
objects = SimpleTranslationPublishedManager()
class DummyProfileTranslation(models.Model):
"""Just a translation of the dummy profile."""
dummy_translation = models.CharField(max_length=128)
is_published = models.BooleanField(default=True)
language = models.CharField(max_length=8, default='en')
dummyprofile = models.ForeignKey(DummyProfile)
translation_pool.register_translation(DummyProfile, DummyProfileTranslation)
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.