hexsha
string | size
int64 | ext
string | lang
string | max_stars_repo_path
string | max_stars_repo_name
string | max_stars_repo_head_hexsha
string | max_stars_repo_licenses
list | max_stars_count
int64 | max_stars_repo_stars_event_min_datetime
string | max_stars_repo_stars_event_max_datetime
string | max_issues_repo_path
string | max_issues_repo_name
string | max_issues_repo_head_hexsha
string | max_issues_repo_licenses
list | max_issues_count
int64 | max_issues_repo_issues_event_min_datetime
string | max_issues_repo_issues_event_max_datetime
string | max_forks_repo_path
string | max_forks_repo_name
string | max_forks_repo_head_hexsha
string | max_forks_repo_licenses
list | max_forks_count
int64 | max_forks_repo_forks_event_min_datetime
string | max_forks_repo_forks_event_max_datetime
string | content
string | avg_line_length
float64 | max_line_length
int64 | alphanum_fraction
float64 | qsc_code_num_words_quality_signal
int64 | qsc_code_num_chars_quality_signal
float64 | qsc_code_mean_word_length_quality_signal
float64 | qsc_code_frac_words_unique_quality_signal
float64 | qsc_code_frac_chars_top_2grams_quality_signal
float64 | qsc_code_frac_chars_top_3grams_quality_signal
float64 | qsc_code_frac_chars_top_4grams_quality_signal
float64 | qsc_code_frac_chars_dupe_5grams_quality_signal
float64 | qsc_code_frac_chars_dupe_6grams_quality_signal
float64 | qsc_code_frac_chars_dupe_7grams_quality_signal
float64 | qsc_code_frac_chars_dupe_8grams_quality_signal
float64 | qsc_code_frac_chars_dupe_9grams_quality_signal
float64 | qsc_code_frac_chars_dupe_10grams_quality_signal
float64 | qsc_code_frac_chars_replacement_symbols_quality_signal
float64 | qsc_code_frac_chars_digital_quality_signal
float64 | qsc_code_frac_chars_whitespace_quality_signal
float64 | qsc_code_size_file_byte_quality_signal
float64 | qsc_code_num_lines_quality_signal
float64 | qsc_code_num_chars_line_max_quality_signal
float64 | qsc_code_num_chars_line_mean_quality_signal
float64 | qsc_code_frac_chars_alphabet_quality_signal
float64 | qsc_code_frac_chars_comments_quality_signal
float64 | qsc_code_cate_xml_start_quality_signal
float64 | qsc_code_frac_lines_dupe_lines_quality_signal
float64 | qsc_code_cate_autogen_quality_signal
float64 | qsc_code_frac_lines_long_string_quality_signal
float64 | qsc_code_frac_chars_string_length_quality_signal
float64 | qsc_code_frac_chars_long_word_length_quality_signal
float64 | qsc_code_frac_lines_string_concat_quality_signal
float64 | qsc_code_cate_encoded_data_quality_signal
float64 | qsc_code_frac_chars_hex_words_quality_signal
float64 | qsc_code_frac_lines_prompt_comments_quality_signal
float64 | qsc_code_frac_lines_assert_quality_signal
float64 | qsc_codepython_cate_ast_quality_signal
float64 | qsc_codepython_frac_lines_func_ratio_quality_signal
float64 | qsc_codepython_cate_var_zero_quality_signal
bool | qsc_codepython_frac_lines_pass_quality_signal
float64 | qsc_codepython_frac_lines_import_quality_signal
float64 | qsc_codepython_frac_lines_simplefunc_quality_signal
float64 | qsc_codepython_score_lines_no_logic_quality_signal
float64 | qsc_codepython_frac_lines_print_quality_signal
float64 | qsc_code_num_words
int64 | qsc_code_num_chars
int64 | qsc_code_mean_word_length
int64 | qsc_code_frac_words_unique
null | qsc_code_frac_chars_top_2grams
int64 | qsc_code_frac_chars_top_3grams
int64 | qsc_code_frac_chars_top_4grams
int64 | qsc_code_frac_chars_dupe_5grams
int64 | qsc_code_frac_chars_dupe_6grams
int64 | qsc_code_frac_chars_dupe_7grams
int64 | qsc_code_frac_chars_dupe_8grams
int64 | qsc_code_frac_chars_dupe_9grams
int64 | qsc_code_frac_chars_dupe_10grams
int64 | qsc_code_frac_chars_replacement_symbols
int64 | qsc_code_frac_chars_digital
int64 | qsc_code_frac_chars_whitespace
int64 | qsc_code_size_file_byte
int64 | qsc_code_num_lines
int64 | qsc_code_num_chars_line_max
int64 | qsc_code_num_chars_line_mean
int64 | qsc_code_frac_chars_alphabet
int64 | qsc_code_frac_chars_comments
int64 | qsc_code_cate_xml_start
int64 | qsc_code_frac_lines_dupe_lines
int64 | qsc_code_cate_autogen
int64 | qsc_code_frac_lines_long_string
int64 | qsc_code_frac_chars_string_length
int64 | qsc_code_frac_chars_long_word_length
int64 | qsc_code_frac_lines_string_concat
null | qsc_code_cate_encoded_data
int64 | qsc_code_frac_chars_hex_words
int64 | qsc_code_frac_lines_prompt_comments
int64 | qsc_code_frac_lines_assert
int64 | qsc_codepython_cate_ast
int64 | qsc_codepython_frac_lines_func_ratio
int64 | qsc_codepython_cate_var_zero
int64 | qsc_codepython_frac_lines_pass
int64 | qsc_codepython_frac_lines_import
int64 | qsc_codepython_frac_lines_simplefunc
int64 | qsc_codepython_score_lines_no_logic
int64 | qsc_codepython_frac_lines_print
int64 | effective
string | hits
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eed75ce868931dabebd40ef5cd1f3bab8cc08cc7
| 10,094
|
py
|
Python
|
torchrec/distributed/test_utils/test_sharding.py
|
samiwilf/torchrec
|
50ff0973d5d01ec80fe36ba5f1d524c92c799836
|
[
"BSD-3-Clause"
] | 1
|
2022-03-07T09:06:11.000Z
|
2022-03-07T09:06:11.000Z
|
torchrec/distributed/test_utils/test_sharding.py
|
samiwilf/torchrec
|
50ff0973d5d01ec80fe36ba5f1d524c92c799836
|
[
"BSD-3-Clause"
] | null | null | null |
torchrec/distributed/test_utils/test_sharding.py
|
samiwilf/torchrec
|
50ff0973d5d01ec80fe36ba5f1d524c92c799836
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import cast, Dict, List, Optional, Tuple, Union
import torch
import torch.distributed as dist
import torch.nn as nn
from fbgemm_gpu.split_embedding_configs import EmbOptimType
from torchrec.distributed.embedding_types import EmbeddingTableConfig
from torchrec.distributed.model_parallel import DistributedModelParallel
from torchrec.distributed.planner import (
EmbeddingShardingPlanner,
ParameterConstraints,
Topology,
)
from torchrec.distributed.test_utils.multi_process import MultiProcessContext
from torchrec.distributed.test_utils.test_model import (
ModelInput,
TestEBCSharder,
TestEBSharder,
TestETCSharder,
TestETSharder,
TestSparseNNBase,
)
from torchrec.distributed.types import (
ModuleSharder,
ShardedTensor,
ShardingEnv,
ShardingPlan,
ShardingType,
)
from torchrec.modules.embedding_configs import BaseEmbeddingConfig
from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizerWrapper
class SharderType(Enum):
EMBEDDING_BAG = "embedding_bag"
EMBEDDING_BAG_COLLECTION = "embedding_bag_collection"
EMBEDDING_TOWER = "embedding_tower"
EMBEDDING_TOWER_COLLECTION = "embedding_tower_collection"
def create_test_sharder(
sharder_type: str, sharding_type: str, kernel_type: str
) -> Union[TestEBSharder, TestEBCSharder, TestETSharder, TestETCSharder]:
if sharder_type == SharderType.EMBEDDING_BAG.value:
return TestEBSharder(sharding_type, kernel_type, {"learning_rate": 0.1})
elif sharder_type == SharderType.EMBEDDING_BAG_COLLECTION.value:
return TestEBCSharder(sharding_type, kernel_type, {"learning_rate": 0.1})
elif sharder_type == SharderType.EMBEDDING_TOWER.value:
return TestETSharder(sharding_type, kernel_type, {"learning_rate": 0.1})
elif sharder_type == SharderType.EMBEDDING_TOWER_COLLECTION.value:
return TestETCSharder(sharding_type, kernel_type, {"learning_rate": 0.1})
else:
raise ValueError(f"Sharder not supported {sharder_type}")
def generate_inputs(
world_size: int,
tables: List[EmbeddingTableConfig],
weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
batch_size: int = 4,
num_float_features: int = 16,
) -> Tuple[ModelInput, List[ModelInput]]:
return ModelInput.generate(
batch_size=batch_size,
world_size=world_size,
num_float_features=num_float_features,
tables=tables,
weighted_tables=weighted_tables or [],
)
def gen_model_and_input(
model_class: TestSparseNNBase,
tables: List[EmbeddingTableConfig],
embedding_groups: Dict[str, List[str]],
world_size: int,
weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
num_float_features: int = 16,
dense_device: Optional[torch.device] = None,
sparse_device: Optional[torch.device] = None,
) -> Tuple[nn.Module, List[Tuple[ModelInput, List[ModelInput]]]]:
torch.manual_seed(0)
model = model_class(
tables=cast(List[BaseEmbeddingConfig], tables),
num_float_features=num_float_features,
weighted_tables=cast(List[BaseEmbeddingConfig], weighted_tables),
embedding_groups=embedding_groups,
dense_device=dense_device,
sparse_device=sparse_device,
)
inputs = [
generate_inputs(
world_size=world_size,
tables=tables,
weighted_tables=weighted_tables,
num_float_features=num_float_features,
)
]
return (model, inputs)
def copy_state_dict(
loc: Dict[str, Union[torch.Tensor, ShardedTensor]],
glob: Dict[str, torch.Tensor],
) -> None:
for name, tensor in loc.items():
assert name in glob
global_tensor = glob[name]
if isinstance(global_tensor, ShardedTensor):
global_tensor = global_tensor.local_shards()[0].tensor
if isinstance(tensor, ShardedTensor):
for local_shard in tensor.local_shards():
assert global_tensor.ndim == local_shard.tensor.ndim
shard_meta = local_shard.metadata
t = global_tensor.detach()
if t.ndim == 1:
t = t[
shard_meta.shard_offsets[0] : shard_meta.shard_offsets[0]
+ local_shard.tensor.shape[0]
]
elif t.ndim == 2:
t = t[
shard_meta.shard_offsets[0] : shard_meta.shard_offsets[0]
+ local_shard.tensor.shape[0],
shard_meta.shard_offsets[1] : shard_meta.shard_offsets[1]
+ local_shard.tensor.shape[1],
]
else:
raise ValueError("Tensors with ndim > 2 are not supported")
local_shard.tensor.copy_(t)
else:
tensor.copy_(global_tensor)
def sharding_single_rank_test(
rank: int,
world_size: int,
model_class: TestSparseNNBase,
embedding_groups: Dict[str, List[str]],
tables: List[EmbeddingTableConfig],
sharders: List[ModuleSharder[nn.Module]],
backend: str,
optim: EmbOptimType,
weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
constraints: Optional[Dict[str, ParameterConstraints]] = None,
local_size: Optional[int] = None,
) -> None:
with MultiProcessContext(rank, world_size, backend, local_size) as ctx:
# Generate model & inputs.
(global_model, inputs) = gen_model_and_input(
model_class=model_class,
tables=tables,
weighted_tables=weighted_tables,
embedding_groups=embedding_groups,
world_size=world_size,
num_float_features=16,
)
global_model = global_model.to(ctx.device)
global_input = inputs[0][0].to(ctx.device)
local_input = inputs[0][1][rank].to(ctx.device)
# Shard model.
local_model = model_class(
tables=cast(List[BaseEmbeddingConfig], tables),
weighted_tables=cast(List[BaseEmbeddingConfig], weighted_tables),
embedding_groups=embedding_groups,
dense_device=ctx.device,
sparse_device=torch.device("meta"),
num_float_features=16,
)
planner = EmbeddingShardingPlanner(
topology=Topology(
world_size, ctx.device.type, local_world_size=ctx.local_size
),
constraints=constraints,
)
plan: ShardingPlan = planner.collective_plan(local_model, sharders, ctx.pg)
"""
Simulating multiple nodes on a single node. However, metadata information and
tensor placement must still be consistent. Here we overwrite this to do so.
NOTE:
inter/intra process groups should still behave as expected.
TODO: may need to add some checks that only does this if we're running on a
single GPU (which should be most cases).
"""
for group in plan.plan:
for _, parameter_sharding in plan.plan[group].items():
if (
parameter_sharding.sharding_type
in {
ShardingType.TABLE_ROW_WISE.value,
ShardingType.TABLE_COLUMN_WISE.value,
}
and ctx.device.type != "cpu"
):
sharding_spec = parameter_sharding.sharding_spec
if sharding_spec is not None:
# pyre-ignore
for shard in sharding_spec.shards:
placement = shard.placement
rank: Optional[int] = placement.rank()
assert rank is not None
shard.placement = torch.distributed._remote_device(
f"rank:{rank}/cuda:{rank}"
)
local_model = DistributedModelParallel(
local_model,
env=ShardingEnv.from_process_group(ctx.pg),
plan=plan,
sharders=sharders,
device=ctx.device,
)
dense_optim = KeyedOptimizerWrapper(
dict(local_model.named_parameters()),
lambda params: torch.optim.SGD(params, lr=0.1),
)
local_opt = CombinedOptimizer([local_model.fused_optimizer, dense_optim])
# Load model state from the global model.
copy_state_dict(local_model.state_dict(), global_model.state_dict())
# Run a single training step of the sharded model.
local_pred = gen_full_pred_after_one_step(local_model, local_opt, local_input)
all_local_pred = []
for _ in range(world_size):
all_local_pred.append(torch.empty_like(local_pred))
dist.all_gather(all_local_pred, local_pred, group=ctx.pg)
# Run second training step of the unsharded model.
assert optim == EmbOptimType.EXACT_SGD
global_opt = torch.optim.SGD(global_model.parameters(), lr=0.1)
global_pred = gen_full_pred_after_one_step(
global_model, global_opt, global_input
)
# Compare predictions of sharded vs unsharded models.
torch.testing.assert_allclose(global_pred, torch.cat(all_local_pred))
def gen_full_pred_after_one_step(
model: nn.Module,
opt: torch.optim.Optimizer,
input: ModelInput,
) -> torch.Tensor:
# Run a single training step of the global model.
opt.zero_grad()
model.train(True)
loss, _ = model(input)
loss.backward()
# pyre-fixme[20]: Argument `closure` expected.
opt.step()
# Run a forward pass of the global model.
with torch.no_grad():
model.train(False)
full_pred = model(input)
return full_pred
| 36.705455
| 86
| 0.645928
| 1,121
| 10,094
| 5.587868
| 0.236396
| 0.018678
| 0.025543
| 0.020115
| 0.260057
| 0.220945
| 0.150224
| 0.110951
| 0.087963
| 0.087963
| 0
| 0.005716
| 0.272043
| 10,094
| 274
| 87
| 36.839416
| 0.846761
| 0.058649
| 0
| 0.200913
| 0
| 0
| 0.025881
| 0.00804
| 0
| 0
| 0
| 0.007299
| 0.022831
| 1
| 0.027397
| false
| 0
| 0.063927
| 0.004566
| 0.146119
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eed9c6dd573fe2bb3afc30e2202d6ac77f9cb554
| 330
|
py
|
Python
|
examples/optimizers/science/create_hgso.py
|
anukaal/opytimizer
|
5f1ccc0da80e6a4cabd99578fa24cf4f6466f9b9
|
[
"Apache-2.0"
] | 528
|
2018-10-01T20:00:09.000Z
|
2022-03-27T11:15:31.000Z
|
examples/optimizers/science/create_hgso.py
|
anukaal/opytimizer
|
5f1ccc0da80e6a4cabd99578fa24cf4f6466f9b9
|
[
"Apache-2.0"
] | 17
|
2019-10-30T00:47:03.000Z
|
2022-03-21T11:39:28.000Z
|
examples/optimizers/science/create_hgso.py
|
anukaal/opytimizer
|
5f1ccc0da80e6a4cabd99578fa24cf4f6466f9b9
|
[
"Apache-2.0"
] | 35
|
2018-10-01T20:03:23.000Z
|
2022-03-20T03:54:15.000Z
|
from opytimizer.optimizers.science import HGSO
# One should declare a hyperparameters object based
# on the desired algorithm that will be used
params = {
'n_clusters': 2,
'l1': 0.0005,
'l2': 100,
'l3': 0.001,
'alpha': 1.0,
'beta': 1.0,
'K': 1.0
}
# Creates an HGSO optimizer
o = HGSO(params=params)
| 19.411765
| 51
| 0.633333
| 50
| 330
| 4.16
| 0.8
| 0.028846
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.086957
| 0.233333
| 330
| 16
| 52
| 20.625
| 0.735178
| 0.357576
| 0
| 0
| 0
| 0
| 0.125
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.090909
| 0
| 0.090909
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eeddefbcddacdcd31162977b74fe0703603b2f9f
| 2,668
|
py
|
Python
|
adverse/urls.py
|
michael-xander/communique-webapp
|
85b450d7f6d0313c5e5ef53a262a850b7e93c3d6
|
[
"MIT"
] | null | null | null |
adverse/urls.py
|
michael-xander/communique-webapp
|
85b450d7f6d0313c5e5ef53a262a850b7e93c3d6
|
[
"MIT"
] | null | null | null |
adverse/urls.py
|
michael-xander/communique-webapp
|
85b450d7f6d0313c5e5ef53a262a850b7e93c3d6
|
[
"MIT"
] | null | null | null |
from django.conf.urls import url
from .views import (EmergencyContactCreateView, EmergencyContactUpdateView, EmergencyContactDeleteView,
EmergencyContactDetailView, EmergencyContactListView, AdverseEventTypeUpdateView,
AdverseEventTypeCreateView, AdverseEventTypeDeleteView, AdverseEventTypeDetailView,
AdverseEventTypeListView, AdverseEventCreateView, AdverseEventDeleteView, AdverseEventDetailView,
AdverseEventListView, AdverseEventUpdateView, AdverseEventExportFormView, AdverseEventExportListView)
urlpatterns = [
url(r'^emergency-contacts/$', EmergencyContactListView.as_view(), name='adverse_emergency_contact_list'),
url(r'^emergency-contacts/create/$', EmergencyContactCreateView.as_view(), name='adverse_emergency_contact_create'),
url(r'^emergency-contacts/(?P<pk>[0-9]+)/$', EmergencyContactDetailView.as_view(),
name='adverse_emergency_contact_detail'),
url(r'^emergency-contacts/(?P<pk>[0-9]+)/update/$', EmergencyContactUpdateView.as_view(),
name='adverse_emergency_contact_update'),
url(r'^emergency-contacts/(?P<pk>[0-9]+)/delete/$', EmergencyContactDeleteView.as_view(),
name='adverse_emergency_contact_delete'),
url(r'^event-types/$', AdverseEventTypeListView.as_view(), name='adverse_event_type_list'),
url(r'^event-types/create/$', AdverseEventTypeCreateView.as_view(), name='adverse_event_type_create'),
url(r'^event-types/(?P<pk>[0-9]+)/$', AdverseEventTypeDetailView.as_view(), name='adverse_event_type_detail'),
url(r'^event-types/(?P<pk>[0-9]+)/update/$', AdverseEventTypeUpdateView.as_view(), name='adverse_event_type_update'),
url(r'^event-types/(?P<pk>[0-9]+)/delete/$', AdverseEventTypeDeleteView.as_view(), name='adverse_event_type_delete'),
url(r'^events/$', AdverseEventListView.as_view(), name='adverse_event_list'),
url(r'^events/create/$', AdverseEventCreateView.as_view(), name='adverse_event_create'),
url(r'^events/(?P<pk>[0-9]+)/$', AdverseEventDetailView.as_view(), name='adverse_event_detail'),
url(r'^events/(?P<pk>[0-9]+)/update/$', AdverseEventUpdateView.as_view(), name='adverse_event_update'),
url(r'^events/(?P<pk>[0-9]+)/delete/$', AdverseEventDeleteView.as_view(), name='adverse_event_delete'),
url(r'^events/export/$', AdverseEventExportFormView.as_view(), name='adverse_event_export_form'),
url(r'^events/export/(?P<start_year>[0-9]{4})-(?P<start_month>[0-9]{2})-(?P<start_day>[0-9]{2})/(?P<end_year>[0-9]{4})-(?P<end_month>[0-9]{2})-(?P<end_day>[0-9]{2})/$',
AdverseEventExportListView.as_view(), name='adverse_event_export_list'),
]
| 86.064516
| 172
| 0.725262
| 302
| 2,668
| 6.178808
| 0.182119
| 0.036442
| 0.091104
| 0.154877
| 0.386388
| 0.284566
| 0.096463
| 0.072347
| 0
| 0
| 0
| 0.01495
| 0.097451
| 2,668
| 31
| 173
| 86.064516
| 0.759967
| 0
| 0
| 0
| 0
| 0.034483
| 0.38329
| 0.325965
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.068966
| 0
| 0.068966
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eee0e160c355877e9ab99acba82ef48b402d10db
| 2,795
|
py
|
Python
|
termlog/interpret.py
|
brianbruggeman/termlog
|
361883f790ab6fae158095585370672e3ca8e354
|
[
"MIT"
] | 1
|
2019-11-22T09:32:25.000Z
|
2019-11-22T09:32:25.000Z
|
termlog/interpret.py
|
brianbruggeman/termlog
|
361883f790ab6fae158095585370672e3ca8e354
|
[
"MIT"
] | null | null | null |
termlog/interpret.py
|
brianbruggeman/termlog
|
361883f790ab6fae158095585370672e3ca8e354
|
[
"MIT"
] | null | null | null |
"""Interprets each AST node"""
import ast
import textwrap
from typing import Any, Dict, List
def extract_fields(code: str) -> Dict[str, Any]:
"""Extracts data from code block searching for variables
Args:
code: the code block to parse
"""
# Parsing expects that the code have no indentation
code = textwrap.dedent(code)
parsed = ast.parse(code)
queue: List[Any] = parsed.body
data = []
fields: Dict[str, Any] = {}
# Grab field names to get data needed for message
count = -1
while queue:
count += 1
node = queue.pop(0)
ignored = tuple([ast.ImportFrom, ast.Import, ast.Assert, ast.Raise])
unhandled = tuple(
[
ast.Constant,
ast.Dict,
ast.DictComp,
ast.Expr,
ast.GeneratorExp,
ast.For,
ast.List,
ast.ListComp,
ast.Return,
ast.Subscript,
ast.Try,
ast.With,
]
)
if isinstance(node, (list, tuple)):
queue.extend(node)
elif isinstance(node, (ast.Expr, ast.FormattedValue, ast.Assign, ast.Starred, ast.Attribute, ast.Subscript, ast.AnnAssign)):
queue.append(node.value)
elif isinstance(node, (ast.Call,)):
queue.extend(node.args)
elif isinstance(node, (ast.JoinedStr, ast.BoolOp)):
queue.extend(node.values)
elif isinstance(node, (ast.Str,)):
data.append(node.s)
elif isinstance(node, (ast.Name,)):
fields.update({node.id: None})
elif isinstance(node, (ast.BinOp,)):
queue.append(node.left)
queue.append(node.right)
elif isinstance(node, (ast.FunctionDef,)):
queue.extend(node.body)
elif isinstance(node, (ast.If, ast.IfExp)):
queue.append(node.body)
queue.append(node.orelse)
# elif isinstance(node, (ast.DictComp,)):
# queue.extend(node.generators)
# queue.append(node.key)
# queue.append(node.value)
# elif isinstance(node, (ast.Try,)):
# queue.extend(node.body)
# queue.extend(node.orelse)
# queue.extend(node.finalbody)
elif isinstance(node, ignored):
pass
elif isinstance(node, unhandled):
# print("Termlog Warning [Debug ast.Node]:", node, ", ".join([d for d in dir(node) if not d.startswith("_")]))
pass
else:
print("Termlog Warning [Unhandled ast.Node]:", node, ", ".join([d for d in dir(node) if not d.startswith("_")]))
if count > 4096: # to prevent a runaway queue
break
return fields
| 34.9375
| 132
| 0.544544
| 315
| 2,795
| 4.822222
| 0.342857
| 0.119816
| 0.142199
| 0.138249
| 0.113232
| 0.113232
| 0.113232
| 0.113232
| 0.05925
| 0.05925
| 0
| 0.003757
| 0.333453
| 2,795
| 79
| 133
| 35.379747
| 0.811594
| 0.218247
| 0
| 0.033898
| 0
| 0
| 0.018605
| 0
| 0
| 0
| 0
| 0
| 0.016949
| 1
| 0.016949
| false
| 0.033898
| 0.067797
| 0
| 0.101695
| 0.016949
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eee600143ae9d2506a33cc7fd8cd95666e09cf2a
| 453
|
py
|
Python
|
2/2.py
|
pyl/AdventOfCode
|
575a8ba2eb6bd597201986444a799a4384ac3983
|
[
"MIT"
] | null | null | null |
2/2.py
|
pyl/AdventOfCode
|
575a8ba2eb6bd597201986444a799a4384ac3983
|
[
"MIT"
] | null | null | null |
2/2.py
|
pyl/AdventOfCode
|
575a8ba2eb6bd597201986444a799a4384ac3983
|
[
"MIT"
] | null | null | null |
import os
import re
# from .m.red import readInput
data = open("2\\input.txt").read().split('\n')
parsedData = []
for x in data:
parsedData.append(list(filter(None, re.split("[- :]", x))))
parsedData.pop()
count = 0
for x in parsedData:
print(x)
if(x[3][int(x[0])-1] != x[3][int(x[1])-1]
and (x[3][int(x[1])-1] == x[2]
or x[3][int(x[0])-1] == x[2])):
print("found" + ' '.join(x))
count += 1
print(count)
| 15.62069
| 63
| 0.527594
| 79
| 453
| 3.025316
| 0.443038
| 0.033473
| 0.083682
| 0.100418
| 0.138075
| 0.138075
| 0.075314
| 0
| 0
| 0
| 0
| 0.048159
| 0.220751
| 453
| 28
| 64
| 16.178571
| 0.628895
| 0.06181
| 0
| 0
| 0
| 0
| 0.059102
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.125
| 0
| 0.125
| 0.1875
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eee72143266c2f7d061e2031c509c2b48483a480
| 1,183
|
py
|
Python
|
dd3/visitor/views.py
|
za/dd3
|
b70d795fb3bd3ff805696b632beabf6d1f342389
|
[
"Apache-2.0"
] | null | null | null |
dd3/visitor/views.py
|
za/dd3
|
b70d795fb3bd3ff805696b632beabf6d1f342389
|
[
"Apache-2.0"
] | null | null | null |
dd3/visitor/views.py
|
za/dd3
|
b70d795fb3bd3ff805696b632beabf6d1f342389
|
[
"Apache-2.0"
] | null | null | null |
from django.shortcuts import render
from django.http import JsonResponse
from django.db import connections
from django.db.models import Count
from django.contrib import admin
from visitor.models import Apache
import json
admin.site.register(Apache)
# Create your views here.
def text(request):
apachelogs_list = Apache.objects.all()
context_dict = {'apaches': apachelogs_list}
return render(request, 'index.html', context_dict)
def render_javascript(request):
lists = [
{ "date": "2015-11-28", "visit": 10 },
{ "date": "2015-10-09", "visit": 8 },
{ "date": "2015-11-01", "visit": 25 },
]
context_dict = {'lists_as_json': lists}
return render(request, 'lists.html', context_dict)
def render_javascript2(request):
apaches = Apache.objects.all()
alist = []
for apache in apaches:
dateformat = "%Y-%m-%d %H:%M:%S" #2015-11-21 18:36:00
date_dict1 = apache.date
date_dict2 = date_dict1.strftime(dateformat)
adict = {'date': date_dict2, 'visit': apache.visit}
alist.append(adict)
context_dict = {'data_as_json': alist}
return render(request, 'logs.html', context_dict)
def render_javascript3(request):
return render(request, 'scatterplot.html')
| 26.886364
| 55
| 0.718512
| 165
| 1,183
| 5.036364
| 0.430303
| 0.079422
| 0.091456
| 0.064982
| 0.086643
| 0
| 0
| 0
| 0
| 0
| 0
| 0.048181
| 0.140321
| 1,183
| 43
| 56
| 27.511628
| 0.768928
| 0.035503
| 0
| 0
| 0
| 0
| 0.140598
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.121212
| false
| 0
| 0.212121
| 0.030303
| 0.454545
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eee9f9f542f197693a4587a809d1d13007ab6153
| 8,391
|
py
|
Python
|
features/steps/zz_08_materials_steps.py
|
tewarfel/RayTracerChallenge_1
|
736cc5d159c267c9bcc14d42abb03eedc2f7e5f1
|
[
"MIT"
] | 2
|
2020-05-13T20:54:50.000Z
|
2021-06-06T03:37:41.000Z
|
features/steps/zz_08_materials_steps.py
|
tewarfel/RayTracerChallenge_1
|
736cc5d159c267c9bcc14d42abb03eedc2f7e5f1
|
[
"MIT"
] | null | null | null |
features/steps/zz_08_materials_steps.py
|
tewarfel/RayTracerChallenge_1
|
736cc5d159c267c9bcc14d42abb03eedc2f7e5f1
|
[
"MIT"
] | null | null | null |
from behave import *
from hamcrest import assert_that, equal_to
from vec3 import Vec3, vec3
from vec4 import Vec4, point, vector
from base import equal, normalize, transform, ray, lighting
import numpy as np
from shape import material, sphere, test_shape, normal_at, set_transform, intersect, glass_sphere, point_light
from base import render, translation, scaling, view_transform, world, camera, color, rotation_y, rotation_z, rotation_x, stripe_at, stripe_pattern
from parse_type import TypeBuilder
from step_helper import *
valid_test_objects = ["light","m", "in_shadow"]
parse_test_object = TypeBuilder.make_choice(valid_test_objects)
register_type(TestObject=parse_test_object)
valid_test_variables = ["intensity", "position", "eyev", "normalv", "result", "c1", "c2"]
parse_test_variable = TypeBuilder.make_choice(valid_test_variables)
register_type(TestVariable=parse_test_variable)
valid_light_elements = ["position", "intensity"]
parse_light_element = TypeBuilder.make_choice(valid_light_elements)
register_type(LightElement=parse_light_element)
valid_material_elements = ["color", "ambient", "diffuse", "specular", "shininess", "reflective", "transparency", "refractive_index", "pattern"]
parse_material_element = TypeBuilder.make_choice(valid_material_elements)
register_type(MaterialElement=parse_material_element)
valid_boolean_values = ["true", "false"]
parse_boolean_value = TypeBuilder.make_choice(valid_boolean_values)
register_type(BooleanValue=parse_boolean_value)
@given("{item:TestVariable} ← color({r:g}, {g:g}, {b:g})")
def step_impl_color_assign(context, item, r, g, b):
ensure_context_has_tuple(context)
context.tuple[item] = color(float(r), float(g), float(b))
@given("{item:TestVariable} ← point({x:g}, {y:g}, {z:g})")
def step_impl_point_assign_B(context, item, x, y, z):
ensure_context_has_tuple(context)
context.tuple[item] = point(float(x), float(y), float(z))
@given("{item:TestObject} ← true")
def step_impl_logic_assign_true(context, item):
ensure_context_has_dict(context)
context.dict[item] = True
@given("{item:TestVariable} ← vector({x:g}, √{ynum:g}/{ydenom:g}, -√{znum:g}/{zdenom:g})")
def step_impl_vector_assign_B(context, item, x, ynum, ydenom, znum, zdenom):
ensure_context_has_tuple(context)
context.tuple[item] = vector(float(x), np.sqrt(float(ynum)) / float(ydenom), -np.sqrt(float(znum)) / float(zdenom))
@given("{item:TestVariable} ← vector({x:g}, {y:g}, -{z:g})")
def step_impl_vector_assign_C(context, item, x, y, z):
ensure_context_has_tuple(context)
context.tuple[item] = vector(float(x), float(y), -float(z))
@given("{item:TestVariable} ← vector({x:g}, {y:g}, {z:g})")
def step_impl_vector_assign_D(context, item, x, y, z):
ensure_context_has_tuple(context)
context.tuple[item] = vector(float(x), float(y), float(z))
@given("{item:TestVariable} ← vector({x:g}, -√{ynum:g}/{ydenom:g}, -√{znum:g}/{zdenom:g})")
def step_impl_vector_assign_E(context, item, x, ynum, ydenom, znum, zdenom):
ensure_context_has_tuple(context)
context.tuple[item] = vector(float(x), -np.sqrt(float(ynum)) / float(ydenom),
-np.sqrt(float(znum)) / float(zdenom))
@given("{item:TestObject} ← material()")
def step_impl_generic_material_given(context, item):
ensure_context_has_dict(context)
context.dict[item] = material()
@given("{item:TestObject} ← point_light(point({px:g}, {py:g}, {pz:g}), color({red:g}, {green:g}, {blue:g}))")
def step_impl_point_light_for_materials(context, item, px, py, pz, red, green, blue):
ensure_context_has_dict(context)
real_position = point(float(px), float(py), float(pz))
real_intensity = color(float(red), float(green), float(blue))
context.dict[item] = point_light(real_position, real_intensity)
@given("{item:TestObject}.pattern ← stripe_pattern(color({r1:g}, {g1:g}, {b1:g}), color({r2:g}, {g2:g}, {b2:g}))")
def step_set_background_color(context, item, r1, g1, b1, r2, g2, b2):
assert (item in context.dict.keys())
context.dict[str(item)].pattern = stripe_pattern(color(float(r1), float(g1), float(b1)),
color(float(r2), float(g2), float(b2)))
@when("{item:TestVariable} ← lighting({material:TestObject}, {light:TestObject}, {point_position:TestVariable}, {eye_vector:TestVariable}, {normal_vector:TestVariable})")
def step_set_lighting_values(context, item, material, light, point_position, eye_vector, normal_vector):
assert(material in context.dict.keys())
assert(light in context.dict.keys())
assert(point_position in context.tuple.keys())
assert(eye_vector in context.tuple.keys())
assert(normal_vector in context.tuple.keys())
material_val = context.dict[str(material)]
light_val = context.dict[str(light)]
point_value = context.tuple[str(point_position)]
eye_vec_value = context.tuple[str(eye_vector)]
norm_vec_value = context.tuple[str(normal_vector)]
lighting_value = lighting(material_val, sphere(), light_val, point_value, eye_vec_value, norm_vec_value)
context.tuple[str(item)] = lighting_value
@when("{item:TestVariable} ← lighting({material:TestObject}, {light:TestObject}, point({px:g}, {py:g}, {pz:g}), {eye_vector:TestVariable}, {normal_vector:TestVariable}, {in_shadow:BooleanValue})")
def step_set_lighting_values_with_shadow_explicit_point(context, item, material, light, px, py, pz, eye_vector, normal_vector, in_shadow):
assert (material in context.dict.keys())
assert (light in context.dict.keys())
assert (eye_vector in context.tuple.keys())
assert (normal_vector in context.tuple.keys())
material_val = context.dict[str(material)]
light_val = context.dict[str(light)]
point_value = point(float(px), float(py), float(pz))
eye_vec_value = context.tuple[str(eye_vector)]
norm_vec_value = context.tuple[str(normal_vector)]
in_shadow_value = True if in_shadow=="true" else False
lighting_value = lighting(material_val, sphere(), light_val, point_value, eye_vec_value, norm_vec_value, in_shadow_value)
context.tuple[str(item)] = lighting_value
@when("{item:TestVariable} ← lighting({material:TestObject}, {light:TestObject}, {point_position:TestVariable}, {eye_vector:TestVariable}, {normal_vector:TestVariable}, {in_shadow:TestObject})")
def step_set_lighting_values_with_shadow_defined_point(context, item, material, light, point_position, eye_vector, normal_vector, in_shadow):
assert (material in context.dict.keys())
assert (light in context.dict.keys())
assert (point_position in context.tuple.keys())
assert (eye_vector in context.tuple.keys())
assert (normal_vector in context.tuple.keys())
assert (in_shadow in context.dict.keys())
material_val = context.dict[str(material)]
light_val = context.dict[str(light)]
point_value = context.tuple[str(point_position)]
eye_vec_value = context.tuple[str(eye_vector)]
norm_vec_value = context.tuple[str(normal_vector)]
in_shadow_value = context.dict[str(in_shadow)]
lighting_value = lighting(material_val, sphere(), light_val, point_value, eye_vec_value, norm_vec_value, in_shadow_value)
context.tuple[str(item)] = lighting_value
@then("{item:TestObject}.{element:MaterialElement} = color({red:g}, {green:g}, {blue:g})")
def step_impl_ray_intersect_list_count(context, item, element, red, green, blue):
assert(item in context.dict.keys())
local_object_str = "context.dict['"+str(item)+"']."+str(element)
local_object = eval(local_object_str)
value = color(float(red), float(green), float(blue))
assert(equal(local_object, value))
@then("{item:TestObject}.{element:MaterialElement} = {value:g}")
def step_impl_ray_intersect_list_count(context, item, element, value):
assert(item in context.dict.keys())
local_object_str = "context.dict['"+str(item)+"']."+str(element)
local_object = eval(local_object_str)
value = float(value)
assert(equal(local_object, value))
@then("{item:TestVariable} = color({red:g}, {green:g}, {blue:g})")
def step_lighting_color_test(context, item, red, green, blue):
assert(item in context.tuple.keys())
local_object_str = "context.tuple['"+str(item)+"']"
local_object = eval(local_object_str)
value = color(float(red), float(green), float(blue))
assert(equal(local_object, value))
| 45.603261
| 196
| 0.725539
| 1,195
| 8,391
| 4.87113
| 0.121339
| 0.055661
| 0.030923
| 0.037794
| 0.689572
| 0.645937
| 0.627899
| 0.583061
| 0.560385
| 0.552826
| 0
| 0.003402
| 0.124181
| 8,391
| 183
| 197
| 45.852459
| 0.786365
| 0
| 0
| 0.410448
| 0
| 0.097015
| 0.185198
| 0.073531
| 0
| 0
| 0
| 0
| 0.171642
| 1
| 0.119403
| false
| 0
| 0.074627
| 0
| 0.19403
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eeea7ce35f96919784a10c51746fa125d0fb04fb
| 741
|
py
|
Python
|
data/thread_generator.py
|
beesk135/ReID-Survey
|
d1467c0ce5d3ca78640196360a05df9ff9f9f42a
|
[
"MIT"
] | null | null | null |
data/thread_generator.py
|
beesk135/ReID-Survey
|
d1467c0ce5d3ca78640196360a05df9ff9f9f42a
|
[
"MIT"
] | null | null | null |
data/thread_generator.py
|
beesk135/ReID-Survey
|
d1467c0ce5d3ca78640196360a05df9ff9f9f42a
|
[
"MIT"
] | null | null | null |
import threading
import time
import numpy as np
from collections import deque
class ThreadGenerator(threading.Thread):
def __init__(self, generator, max_queue_size=10):
threading.Thread.__init__(self)
self.generator = ThreadGenerator
self.buffer = deque(maxlen=max_queue_size)
self.max_queue_size = max_queue_size
def push(self, X):
while(len(self.buffer) == self.max_queue_size):
time.sleep(1e-6)
self.buffer.append(X)
def grab(self):
while (len(self.buffer) <= 0):
time.sleep(1e-6)
data = self.buffer.popleft()
return data
def run(self):
while True:
data = next(self.generator)
self.push(data)
| 29.64
| 55
| 0.62753
| 95
| 741
| 4.705263
| 0.4
| 0.089485
| 0.134228
| 0.071588
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.012963
| 0.271255
| 741
| 24
| 56
| 30.875
| 0.814815
| 0
| 0
| 0.086957
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.173913
| false
| 0
| 0.173913
| 0
| 0.434783
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eeee2179bf362d1c71b12b2f474e4d3a6d80e573
| 1,544
|
py
|
Python
|
spug/data_pipeline/sources/stock.py
|
syeehyn/spug
|
216976e0171bbc14042377fbbb535180bd2efaf3
|
[
"Apache-2.0"
] | null | null | null |
spug/data_pipeline/sources/stock.py
|
syeehyn/spug
|
216976e0171bbc14042377fbbb535180bd2efaf3
|
[
"Apache-2.0"
] | null | null | null |
spug/data_pipeline/sources/stock.py
|
syeehyn/spug
|
216976e0171bbc14042377fbbb535180bd2efaf3
|
[
"Apache-2.0"
] | 1
|
2021-12-05T22:54:28.000Z
|
2021-12-05T22:54:28.000Z
|
"""
fetch historical stocks prices
"""
from tqdm import tqdm
import pandas as pd
import pandas_datareader as pdr
from .base import DataFetcher
def get_stock_price(symbol, start, end):
"""get stock price of a company over a time range
Args:
symbol (str): ticker symbol of a stock
start (datetime.datetime): start time
end (datetime.datetime): end time
Returns:
pd.DataFrame: stock price of a company over a time range
"""
df = (
pdr.yahoo.daily.YahooDailyReader(symbol, start=start, end=end)
.read()
.reset_index()[["Date", "High", "Low", "Open", "Close", "Volume", "Adj Close"]]
)
df["date"] = pd.to_datetime(df.Date)
return df.drop("Date", axis=1)
class StockFetcher(DataFetcher):
def __init__(self, **configs):
super().__init__(**configs)
def get_data(self):
"""get stock prices of companies over a time range
Args:
symbol (list): ticker symbols of stocks
start (datetime.datetime): start time
end (datetime.datetime): end time
Returns:
pd.DataFrame: stock prices of companies over a time range
"""
dfs = pd.DataFrame()
symbols = self.companies
symbols = list(map(lambda x: list(x.keys())[0], symbols))
for symbol in tqdm(symbols):
df = get_stock_price(symbol, self.start_date, self.end_date)
df["ticker_symbol"] = symbol
dfs = dfs.append(df)
return dfs.reset_index(drop=True)
| 31.510204
| 87
| 0.613342
| 199
| 1,544
| 4.658291
| 0.361809
| 0.03452
| 0.038835
| 0.06041
| 0.332255
| 0.332255
| 0.31068
| 0.31068
| 0.238403
| 0.170442
| 0
| 0.001784
| 0.273964
| 1,544
| 48
| 88
| 32.166667
| 0.825156
| 0.340026
| 0
| 0
| 0
| 0
| 0.061202
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.125
| false
| 0
| 0.166667
| 0
| 0.416667
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eeef030e3640987cf35e25ed5365b60fde947fe0
| 2,963
|
py
|
Python
|
src/gluonts/nursery/tsbench/src/tsbench/evaluations/metrics/performance.py
|
RingoIngo/gluon-ts
|
62fb20c36025fc969653accaffaa783671709564
|
[
"Apache-2.0"
] | 1
|
2022-03-28T01:17:00.000Z
|
2022-03-28T01:17:00.000Z
|
src/gluonts/nursery/tsbench/src/tsbench/evaluations/metrics/performance.py
|
RingoIngo/gluon-ts
|
62fb20c36025fc969653accaffaa783671709564
|
[
"Apache-2.0"
] | null | null | null |
src/gluonts/nursery/tsbench/src/tsbench/evaluations/metrics/performance.py
|
RingoIngo/gluon-ts
|
62fb20c36025fc969653accaffaa783671709564
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file 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 __future__ import annotations
from dataclasses import dataclass
from typing import cast, Dict, List, Union
import numpy as np
import pandas as pd
from .metric import Metric
@dataclass
class Performance:
"""
The performance class encapsulates the metrics that are recorded for configurations.
"""
training_time: Metric
latency: Metric
num_model_parameters: Metric
num_gradient_updates: Metric
ncrps: Metric
mase: Metric
smape: Metric
nrmse: Metric
nd: Metric
@classmethod
def from_dict(cls, metrics: Dict[str, Union[float, int]]) -> Performance:
"""
Initializes a new performance object from the given 1D dictionary. Metrics are expected to
be provided via `<metric>_mean` and `<metric>_std` keys.
"""
kwargs = {
m: Metric(metrics[f"{m}_mean"], metrics[f"{m}_std"])
for m in cls.metrics()
}
return Performance(**kwargs) # type: ignore
@classmethod
def metrics(cls) -> List[str]:
"""
Returns the list of metrics that are exposed by the performance class.
"""
# pylint: disable=no-member
return list(cls.__dataclass_fields__.keys()) # type: ignore
@classmethod
def to_dataframe(
cls, performances: List[Performance], std: bool = True
) -> pd.DataFrame:
"""
Returns a data frame representing the provided performances.
"""
fields = sorted(
Performance.__dataclass_fields__.keys()
) # pylint: disable=no-member
result = np.empty((len(performances), 18 if std else 9))
offset = 2 if std else 1
for i, performance in enumerate(performances):
for j, field in enumerate(fields):
result[i, j * offset] = cast(
Metric, getattr(performance, field)
).mean
if std:
result[i, j * offset + 1] = cast(
Metric, getattr(performance, field)
).std
return pd.DataFrame(
result,
columns=[
f
for field in fields
for f in (
[f"{field}_mean", f"{field}_std"]
if std
else [f"{field}_mean"]
)
],
)
| 31.521277
| 98
| 0.59433
| 348
| 2,963
| 4.979885
| 0.445402
| 0.034622
| 0.01558
| 0.027698
| 0.038084
| 0
| 0
| 0
| 0
| 0
| 0
| 0.007448
| 0.320284
| 2,963
| 93
| 99
| 31.860215
| 0.853029
| 0.335471
| 0
| 0.087719
| 0
| 0
| 0.026867
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.052632
| false
| 0
| 0.105263
| 0
| 0.385965
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eef6f9b0de74e501a4d4981b8350d4bf8e08d58a
| 4,403
|
py
|
Python
|
kerascv/layers/matchers/argmax_matcher.py
|
tanzhenyu/keras-cv
|
b7208ee25735c492ccc171874e34076111dcf637
|
[
"Apache-2.0"
] | null | null | null |
kerascv/layers/matchers/argmax_matcher.py
|
tanzhenyu/keras-cv
|
b7208ee25735c492ccc171874e34076111dcf637
|
[
"Apache-2.0"
] | null | null | null |
kerascv/layers/matchers/argmax_matcher.py
|
tanzhenyu/keras-cv
|
b7208ee25735c492ccc171874e34076111dcf637
|
[
"Apache-2.0"
] | null | null | null |
import tensorflow as tf
from kerascv.layers.iou_similarity import IOUSimilarity
iou_layer = IOUSimilarity()
class ArgMaxMatcher(tf.keras.layers.Layer):
"""ArgMax matcher"""
# [pos, neutral, neg]
def __init__(self, matched_threshold, unmatched_threshold):
self.matched_threshold = matched_threshold
self.unmatched_threshold = unmatched_threshold
super(ArgMaxMatcher, self).__init__()
# similarity: [#num_anchors, #num_gt_boxes]
# matched_values: [#num_gt_boxes, dim]
# unmatched_values: [dim]
# ignored_values: [dim]
def call(self, similarity, matched_values, unmatched_values, ignored_values):
# [#num_anchors]
matched_indices = tf.argmax(similarity, axis=1)
# [#num_anchors]
matched_max_vals = tf.reduce_max(similarity, axis=1)
above_unmatched_threshold_indices = tf.cast(
tf.greater(matched_max_vals, self.unmatched_threshold), tf.float32
)
# [#num_anchors]
below_unmatched_threshold_indices = tf.greater(
self.unmatched_threshold, matched_max_vals
)
below_unmatched_threshold_indices = tf.cast(
below_unmatched_threshold_indices, matched_values.dtype
)
# [#num_anchors]
between_threshold_indices = tf.logical_and(
tf.greater_equal(matched_max_vals, self.unmatched_threshold),
tf.greater(self.matched_threshold, matched_max_vals),
)
between_threshold_indices = tf.cast(
between_threshold_indices, matched_values.dtype
)
# [#num_anchors, dim]
matched_vals = tf.gather(matched_values, matched_indices)
if matched_vals.shape.rank > 1:
# [#num_anchors, 1]
below_unmatched_threshold_indices = below_unmatched_threshold_indices[
:, tf.newaxis
]
# [#num_anchors, 1]
between_threshold_indices = between_threshold_indices[:, tf.newaxis]
matched_vals = tf.add(
tf.multiply(
matched_vals,
tf.constant(1, dtype=matched_values.dtype)
- below_unmatched_threshold_indices,
),
tf.multiply(unmatched_values, below_unmatched_threshold_indices),
)
matched_vals = tf.add(
tf.multiply(
matched_vals,
tf.constant(1, dtype=matched_values.dtype) - between_threshold_indices,
),
tf.multiply(ignored_values, between_threshold_indices),
)
return matched_vals
def get_config(self):
config = {
"matched_threshold": self.matched_threshold,
"unmatched_threshold": self.unmatched_threshold,
}
base_config = super(ArgMaxMatcher, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@tf.function(
input_signature=[
tf.TensorSpec(shape=(None, 4), dtype=tf.float32),
tf.TensorSpec(shape=(None, 1), dtype=tf.int64),
tf.TensorSpec(shape=(None, 4), dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.float32),
]
)
def target_assign_argmax(
ground_truth_boxes,
ground_truth_labels,
anchors,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3):
if tf.equal(tf.size(ground_truth_boxes), 0):
num_anchors = tf.shape(anchors)[0]
matched_gt_boxes = tf.identity(anchors)
matched_gt_labels = tf.zeros((num_anchors, 1), dtype=tf.int64)
positive_mask = tf.zeros((num_anchors, 1), tf.bool)
negative_mask = tf.zeros((num_anchors, 1), tf.bool)
return matched_gt_boxes, matched_gt_labels, positive_mask, negative_mask
# [n_gt_boxes, n_anchors]
similarity = iou_layer(ground_truth_boxes, anchors)
# [n_anchors]
matched_gt_indices = tf.argmax(similarity, axis=0)
# [n_anchors]
matched_max_vals = tf.reduce_max(similarity, axis=0)
positive_mask = tf.greater(matched_max_vals, positive_iou_threshold)
negative_mask = tf.greater(negative_iou_threshold, matched_max_vals)
matched_gt_boxes = tf.gather(ground_truth_boxes, matched_gt_indices)
matched_gt_labels = tf.gather(ground_truth_labels, matched_gt_indices)
return matched_gt_boxes, matched_gt_labels, positive_mask, negative_mask
| 39.666667
| 87
| 0.661821
| 508
| 4,403
| 5.375984
| 0.173228
| 0.105456
| 0.059319
| 0.076895
| 0.410839
| 0.295496
| 0.264738
| 0.204687
| 0.184182
| 0.134017
| 0
| 0.010488
| 0.242108
| 4,403
| 111
| 88
| 39.666667
| 0.807911
| 0.071315
| 0
| 0.162791
| 0
| 0
| 0.008867
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.046512
| false
| 0
| 0.023256
| 0
| 0.127907
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eef840e020a73705ee971a6562f13c86679b8ac7
| 538
|
py
|
Python
|
Atv1-Distribuida/servidorBackup.py
|
rodolfotr/Computacao_Distribuida
|
1d9db06ef4ab7290a6ce9666b5cb83987cc74e9d
|
[
"MIT"
] | null | null | null |
Atv1-Distribuida/servidorBackup.py
|
rodolfotr/Computacao_Distribuida
|
1d9db06ef4ab7290a6ce9666b5cb83987cc74e9d
|
[
"MIT"
] | null | null | null |
Atv1-Distribuida/servidorBackup.py
|
rodolfotr/Computacao_Distribuida
|
1d9db06ef4ab7290a6ce9666b5cb83987cc74e9d
|
[
"MIT"
] | null | null | null |
import socket
import struct
IP_BACKUP = '127.0.0.1'
PORTA_BACKUP = 5000
ARQUIVO_BACKUP = "/home/aluno-uffs/Documentos/Trab_Final/Atv1-Distribuida/cliente_BACKUP.c"
#Recebe o arquivo.
sockReceber = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sockReceber.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sockReceber.bind((IP_BACKUP, PORTA_BACKUP))
while (True):
l = sockReceber.recv(1561651651)
if (l):
f = open(ARQUIVO_BACKUP,'wb')
f.write(l)
f.close()
sockReceber.close()
| 25.619048
| 91
| 0.734201
| 76
| 538
| 5.026316
| 0.605263
| 0.094241
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.047516
| 0.139405
| 538
| 21
| 92
| 25.619048
| 0.777538
| 0.031599
| 0
| 0
| 0
| 0
| 0.159309
| 0.138196
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.133333
| 0
| 0.133333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eef8835ed3e8db9f839217b35bfd1e4b67953a9b
| 634
|
py
|
Python
|
examples/example_regression.py
|
QuantLet/localpoly
|
7db50e3fb2caf39af8f9db1f2108fd1a81fc51bc
|
[
"MIT"
] | 1
|
2021-04-28T09:39:53.000Z
|
2021-04-28T09:39:53.000Z
|
examples/example_regression.py
|
QuantLet/localpoly
|
7db50e3fb2caf39af8f9db1f2108fd1a81fc51bc
|
[
"MIT"
] | null | null | null |
examples/example_regression.py
|
QuantLet/localpoly
|
7db50e3fb2caf39af8f9db1f2108fd1a81fc51bc
|
[
"MIT"
] | 1
|
2021-05-11T19:06:17.000Z
|
2021-05-11T19:06:17.000Z
|
import numpy as np
from matplotlib import pyplot as plt
from localpoly.base import LocalPolynomialRegression
# simulate data
np.random.seed(1)
X = np.linspace(-np.pi, np.pi, num=150)
y_real = np.sin(X)
y = np.random.normal(0, 0.3, len(X)) + y_real
# local polynomial regression
model = LocalPolynomialRegression(X=X, y=y, h=0.8469, kernel="gaussian", gridsize=100)
prediction_interval = (X.min(), X.max())
results = model.fit(prediction_interval)
# plot
plt.scatter(X, y)
plt.plot(X, y_real, "grey", ls="--", alpha=0.5, label="function")
plt.plot(results["X"], results["fit"], "r", alpha=0.9, label="fit")
plt.legend()
plt.show()
| 27.565217
| 86
| 0.706625
| 106
| 634
| 4.179245
| 0.528302
| 0.022573
| 0.027088
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.033808
| 0.113565
| 634
| 22
| 87
| 28.818182
| 0.754448
| 0.072555
| 0
| 0
| 0
| 0
| 0.05137
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.2
| 0
| 0.2
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eefc3d409d2d8b66094f301c43a67fdc4a9f6792
| 2,829
|
py
|
Python
|
utils/phase0/state_transition.py
|
hwwhww/eth2.0-specs
|
729757d4279db4535b176361d67d1567c0df314b
|
[
"CC0-1.0"
] | 3
|
2020-07-22T14:51:07.000Z
|
2022-01-02T12:02:45.000Z
|
utils/phase0/state_transition.py
|
hwwhww/eth2.0-specs
|
729757d4279db4535b176361d67d1567c0df314b
|
[
"CC0-1.0"
] | null | null | null |
utils/phase0/state_transition.py
|
hwwhww/eth2.0-specs
|
729757d4279db4535b176361d67d1567c0df314b
|
[
"CC0-1.0"
] | null | null | null |
from . import spec
from typing import ( # noqa: F401
Any,
Callable,
List,
NewType,
Tuple,
)
from .spec import (
BeaconState,
BeaconBlock,
)
def process_transaction_type(state: BeaconState,
transactions: List[Any],
max_transactions: int,
tx_fn: Callable[[BeaconState, Any], None]) -> None:
assert len(transactions) <= max_transactions
for transaction in transactions:
tx_fn(state, transaction)
def process_transactions(state: BeaconState, block: BeaconBlock) -> None:
process_transaction_type(
state,
block.body.proposer_slashings,
spec.MAX_PROPOSER_SLASHINGS,
spec.process_proposer_slashing,
)
process_transaction_type(
state,
block.body.attester_slashings,
spec.MAX_ATTESTER_SLASHINGS,
spec.process_attester_slashing,
)
process_transaction_type(
state,
block.body.attestations,
spec.MAX_ATTESTATIONS,
spec.process_attestation,
)
process_transaction_type(
state,
block.body.deposits,
spec.MAX_DEPOSITS,
spec.process_deposit,
)
process_transaction_type(
state,
block.body.voluntary_exits,
spec.MAX_VOLUNTARY_EXITS,
spec.process_voluntary_exit,
)
assert len(block.body.transfers) == len(set(block.body.transfers))
process_transaction_type(
state,
block.body.transfers,
spec.MAX_TRANSFERS,
spec.process_transfer,
)
def process_block(state: BeaconState,
block: BeaconBlock,
verify_state_root: bool=False) -> None:
spec.process_block_header(state, block)
spec.process_randao(state, block)
spec.process_eth1_data(state, block)
process_transactions(state, block)
if verify_state_root:
spec.verify_block_state_root(state, block)
def process_epoch_transition(state: BeaconState) -> None:
spec.update_justification_and_finalization(state)
spec.process_crosslinks(state)
spec.maybe_reset_eth1_period(state)
spec.apply_rewards(state)
spec.process_ejections(state)
spec.update_registry_and_shuffling_data(state)
spec.process_slashings(state)
spec.process_exit_queue(state)
spec.finish_epoch_update(state)
def state_transition(state: BeaconState,
block: BeaconBlock,
verify_state_root: bool=False) -> BeaconState:
while state.slot < block.slot:
spec.cache_state(state)
if (state.slot + 1) % spec.SLOTS_PER_EPOCH == 0:
process_epoch_transition(state)
spec.advance_slot(state)
if block.slot == state.slot:
process_block(state, block, verify_state_root)
| 28.009901
| 80
| 0.653588
| 303
| 2,829
| 5.818482
| 0.257426
| 0.081112
| 0.087351
| 0.107204
| 0.195122
| 0.195122
| 0.113443
| 0.063528
| 0.063528
| 0
| 0
| 0.00337
| 0.265818
| 2,829
| 100
| 81
| 28.29
| 0.84545
| 0.003535
| 0
| 0.162791
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.023256
| 1
| 0.05814
| false
| 0
| 0.034884
| 0
| 0.093023
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
eefe78a5c5393bb02f57187df46d42fbd870dd68
| 2,460
|
py
|
Python
|
openghg/client/_search.py
|
openghg/openghg
|
9a05dd6fe3cee6123898b8f390cfaded08dbb408
|
[
"Apache-2.0"
] | 5
|
2021-03-02T09:04:07.000Z
|
2022-01-25T09:58:16.000Z
|
openghg/client/_search.py
|
openghg/openghg
|
9a05dd6fe3cee6123898b8f390cfaded08dbb408
|
[
"Apache-2.0"
] | 229
|
2020-09-30T15:08:39.000Z
|
2022-03-31T14:23:55.000Z
|
openghg/client/_search.py
|
openghg/openghg
|
9a05dd6fe3cee6123898b8f390cfaded08dbb408
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from Acquire.Client import Wallet
if TYPE_CHECKING:
from openghg.dataobjects import SearchResults
__all__ = ["Search"]
class Search:
def __init__(self, service_url: Optional[str] = None):
if service_url is not None:
self._service_url = service_url
else:
self._service_url = "https://fn.openghg.org/t"
wallet = Wallet()
self._service = wallet.get_service(service_url=f"{self._service_url}/openghg")
def search(
self,
species: Union[str, List] = None,
site: Union[str, List] = None,
inlet: Union[str, List] = None,
instrument: Union[str, List] = None,
start_date: str = None,
end_date: str = None,
skip_ranking: bool = False,
data_type: str = "timeseries",
) -> Union[SearchResults, Dict]:
"""Search for surface observations data in the object store
Args:
species: Species
site: Three letter site code
inlet: Inlet height
instrument: Instrument name
start_date: Start date
end_date: End date
Returns:
SearchResults: SearchResults object
"""
from openghg.dataobjects import SearchResults
if self._service is None:
raise PermissionError("Cannot use a null service")
if not any((species, site, inlet, instrument)):
raise ValueError("We must have at least one of species, site, inlet or instrument")
args = {}
if species is not None:
args["species"] = species
if site is not None:
args["site"] = site
if inlet is not None:
args["inlet"] = inlet
if instrument is not None:
args["instrument"] = instrument
if start_date is not None:
args["start_date"] = start_date
if end_date is not None:
args["end_date"] = end_date
args["skip_ranking"] = str(skip_ranking)
args["data_type"] = str(data_type)
response: Dict = self._service.call_function(function="search.search", args=args)
try:
results_data = response["results"]
search_results = SearchResults.from_data(results_data)
return search_results
except KeyError:
return response
| 29.638554
| 96
| 0.597561
| 284
| 2,460
| 5
| 0.309859
| 0.054225
| 0.044366
| 0.05493
| 0.08169
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.31748
| 2,460
| 82
| 97
| 30
| 0.845742
| 0.110976
| 0
| 0.038462
| 0
| 0
| 0.114762
| 0.012857
| 0
| 0
| 0
| 0
| 0
| 1
| 0.038462
| false
| 0
| 0.096154
| 0
| 0.192308
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e101989a4d6808941cf59d0b6ca5c8dec9a09fac
| 4,467
|
py
|
Python
|
models/seeding/base.py
|
Sanzeed/balanced_influence_maximization
|
0797b8a8f536cac8023e128ab13eb532f902bcad
|
[
"MIT"
] | 4
|
2021-06-03T02:53:46.000Z
|
2022-01-25T07:07:08.000Z
|
models/seeding/base.py
|
Sanzeed/balanced_influence_maximization
|
0797b8a8f536cac8023e128ab13eb532f902bcad
|
[
"MIT"
] | null | null | null |
models/seeding/base.py
|
Sanzeed/balanced_influence_maximization
|
0797b8a8f536cac8023e128ab13eb532f902bcad
|
[
"MIT"
] | 1
|
2021-06-17T02:17:22.000Z
|
2021-06-17T02:17:22.000Z
|
import numpy as np
from scipy.stats import bernoulli
import heapq
class DiffusionModel:
def __init__(self, graph, majority, get_diffusion_probability, num_rels):
self.graph = graph
self.majority = majority
nodes = sorted(self.graph.nodes())
self.node_index_map = {nodes[i] : i for i in range(len(nodes))}
self.group_vector = np.array([int(graph.nodes[node]['label'] == majority) for node in nodes])
self.num_rels = num_rels
self.get_diffusion_probability = get_diffusion_probability
self.__generate_live_edges()
def __generate_live_edges(self):
edges = list(self.graph.edges())
self.live_edges = {}
edge_probabilities = [self.get_diffusion_probability(u, v,
self.graph.nodes[u]['label'],
self.graph.nodes[v]['label']) for (u, v) in edges]
for i in range(self.num_rels):
edge_life_indicators = bernoulli.rvs(edge_probabilities)
self.live_edges[i] = {edges[i] for i in range(len(edges)) if edge_life_indicators[i]}
assert len(self.live_edges) == self.num_rels
def __is_live_edge(self, rel_index, u, v):
if self.graph.is_directed():
return (u, v) in self.live_edges[rel_index]
else:
return (u, v) in self.live_edges[rel_index] or (v, u) in self.live_edges[rel_index]
def compute_influence_data(self, rel_index, u):
bfs_queue = {u}
visited_nodes = set()
influence_set, majority_in_influence_set = set(), set()
while bfs_queue:
node_to_visit = bfs_queue.pop()
visited_nodes.add(node_to_visit)
influence_set.add(node_to_visit)
if self.graph.nodes[node_to_visit]['label'] == self.majority:
majority_in_influence_set.add(node_to_visit)
for neighbor in self.graph.neighbors(node_to_visit):
if neighbor not in visited_nodes and self.__is_live_edge(rel_index, node_to_visit, neighbor):
bfs_queue.add(neighbor)
return influence_set, majority_in_influence_set
def generate_seeding_data(self):
pass
class GreedySeedingModel(DiffusionModel):
def __init__(self, graph, majority, get_diffusion_probability, num_rels, k):
super(GreedySeedingModel, self).__init__(graph, majority, get_diffusion_probability, num_rels)
self.queue = [(float('-inf'), -1, v) for v in self.graph.nodes()]
heapq.heapify(self.queue)
self.k = k
self.current_objective_value = 0
self.active_set_map = {i : set() for i in range(self.num_rels)}
self.majority_set_map = {i : set() for i in range(self.num_rels)}
self.seeding_data = {'active_set' : {i + 1 : set() for i in range(self.k)},
'majority' : {i + 1 : set() for i in range(self.k)},
'seeds' : []}
def compute_expected_marginal_gain(self, v):
pass
def do_next_iteration(self):
inc, iter_flag, u = heapq.heappop(self.queue)
if iter_flag == len(self.seeding_data['seeds']):
self.seeding_data['seeds'].append(u)
self.current_objective_value += -inc
for rel_index in range(self.num_rels):
influence, majority = self.compute_influence_data(rel_index, u)
self.active_set_map[rel_index].update(influence)
self.majority_set_map[rel_index].update(majority)
self.seeding_data['active_set'][iter_flag + 1] = sum(map(len, self.active_set_map.values())) / self.num_rels
self.seeding_data['majority'][iter_flag + 1] = sum(map(len, self.majority_set_map.values())) / self.num_rels
else:
new_negated_marginal_gain = -self.compute_expected_marginal_gain(u)
new_iter_flag = len(self.seeding_data['seeds'])
heapq.heappush(self.queue, (new_negated_marginal_gain, new_iter_flag, u))
def generate_seeding_data(self):
while len(self.seeding_data['seeds']) < self.k:
self.do_next_iteration()
return self.seeding_data
| 44.227723
| 120
| 0.591896
| 561
| 4,467
| 4.411765
| 0.183601
| 0.033939
| 0.035556
| 0.031111
| 0.367677
| 0.309899
| 0.198384
| 0.146667
| 0.126061
| 0.08404
| 0
| 0.001935
| 0.305798
| 4,467
| 100
| 121
| 44.67
| 0.796195
| 0
| 0
| 0.077922
| 0
| 0
| 0.019028
| 0
| 0
| 0
| 0
| 0
| 0.012987
| 1
| 0.116883
| false
| 0.025974
| 0.038961
| 0
| 0.233766
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e103652358a900837a67abd9fbc1244e03d12a88
| 2,631
|
py
|
Python
|
RedditReader/redditReader.py
|
Semicolon42/PythonProjects
|
eb6ec5d13594013a2703af43eb0d1c29406faaad
|
[
"Apache-2.0"
] | null | null | null |
RedditReader/redditReader.py
|
Semicolon42/PythonProjects
|
eb6ec5d13594013a2703af43eb0d1c29406faaad
|
[
"Apache-2.0"
] | null | null | null |
RedditReader/redditReader.py
|
Semicolon42/PythonProjects
|
eb6ec5d13594013a2703af43eb0d1c29406faaad
|
[
"Apache-2.0"
] | null | null | null |
import logging
import csv
import time
from bs4 import BeautifulSoup
import requests
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(message)s',
level=logging.INFO)
class Crawler:
def __init__(self, urls=[]):
self.visited_urls = []
self.urls_to_visit = urls
def download_url(self, url):
response = None
for x in range(1,5):
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
if response is not None and response.status_code == 200:
break
return response
def get_reddit_posts(self, url, html):
soup = BeautifulSoup(html, 'html.parser')
attrs = {'data-click-id': 'body'}
rposts = []
for post in soup.find_all('a', attrs=attrs):
post_url = 'https://www.reddit.com'+post.attrs['href']
post_text = self.get_reddit_post_text(post_url)
rposts.append((post_url, post.h3.text, post_text))
return rposts
def get_reddit_post_text(self, url):
response = self.download_url(url)
print(response.status_code, url)
soup = BeautifulSoup(response.text, 'html.parser')
temp = soup.find('div', attrs={'data-test-id': 'post-content'})
post_content = "NOT FOUND"
if temp is not None:
for div in temp.descendants:
if hasattr(div, 'attrs') and 'data-click-id' in div.attrs:
try:
for p in div.find_all('p'):
post_content = post_content + " " + p.text
except Exception:
logging.exception(f'Failed to get post content: {url}')
return post_content
def crawl(self, url):
response = self.download_url(url)
html = response.text
print("starting the crawl...")
posts = self.get_reddit_posts(url, html)
for rpost in posts:
print(f'/////////////////////////////////////')
print(rpost)
print(f'/////////////////////////////////////')
def run(self):
while self.urls_to_visit:
url = self.urls_to_visit.pop(0)
logging.info(f'Crawling: {url}')
try:
self.crawl(url)
except Exception:
logging.exception(f'Failed to crawl: {url}')
finally:
self.visited_urls.append(url)
def main():
Crawler(urls=['https://www.reddit.com/r/BoardGameExchange/new/']).run()
if __name__ == '__main__':
print('start up')
main()
print('all done')
| 30.241379
| 79
| 0.542379
| 310
| 2,631
| 4.454839
| 0.332258
| 0.047791
| 0.021723
| 0.032585
| 0.10572
| 0.10572
| 0.10572
| 0
| 0
| 0
| 0
| 0.005537
| 0.313569
| 2,631
| 87
| 80
| 30.241379
| 0.759136
| 0
| 0
| 0.117647
| 0
| 0
| 0.158055
| 0.037614
| 0
| 0
| 0
| 0
| 0
| 1
| 0.102941
| false
| 0
| 0.073529
| 0
| 0.235294
| 0.102941
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e10557e7b3374a814dff92034c545370c1354b22
| 2,605
|
py
|
Python
|
asteroid/repl.py
|
asteroid-lang/asteroid
|
537c60dd639e4f83fdefff4d36e1d63c3b4139a4
|
[
"MIT"
] | 2
|
2022-02-09T20:33:05.000Z
|
2022-02-09T20:33:08.000Z
|
asteroid/repl.py
|
asteroid-lang/asteroid
|
537c60dd639e4f83fdefff4d36e1d63c3b4139a4
|
[
"MIT"
] | 40
|
2022-01-22T02:29:51.000Z
|
2022-03-31T14:45:31.000Z
|
asteroid/repl.py
|
asteroid-lang/asteroid
|
537c60dd639e4f83fdefff4d36e1d63c3b4139a4
|
[
"MIT"
] | 2
|
2022-01-20T18:20:11.000Z
|
2022-02-12T22:35:22.000Z
|
from asteroid.interp import interp
from asteroid.version import VERSION
from asteroid.state import state
from asteroid.globals import ExpectationError
from asteroid.walk import function_return_value
from asteroid.support import term2string
from sys import stdin
import readline
def repl():
state.initialize()
print_repl_menu()
try:
run_repl()
except EOFError:
print()
pass
def print_repl_menu():
print("Asteroid Version", VERSION)
print("Run \"asteroid -h\" for help")
print("Press CTRL+D to exit")
def run_repl():
# The two different prompt types either > for a new statement
# or . for continuing one
arrow_prompt, continue_prompt = ("> ", ". ")
current_prompt = arrow_prompt
# Our line to be interpreted
line = ""
while True:
"""
Line input, breaking, and exiting
"""
try:
# Get the new input and append it to the previous line (Possibly empty)
# with a newline in between
# If the line is empty, just set the line
if line == "":
line = input(current_prompt)
# Otherwhise append a new line
else:
line += "\n" + input(current_prompt)
except KeyboardInterrupt:
line = ""
current_prompt = arrow_prompt
print()
continue
except EOFError:
print()
break
"""
Interpretation, multiline input, and exception handling
"""
try:
# Try to interpret the new statement
interp(line, initialize_state=False, exceptions=True)
# Try to
line = ""
# Check for return value
if function_return_value[-1]:
# Get the last return value (type, value)
(_, val) = function_return_value[-1]
# If it isn't none, print out the value
if val is not None:
print(term2string(function_return_value[-1]))
except ExpectationError as e:
# If we expected something but found EOF, it's a continue
if e.found_EOF:
current_prompt = continue_prompt
else:
print("error: "+str(e))
line = ""
current_prompt = arrow_prompt
except Exception as e:
# FIX THIS
print("error: "+str(e))
line = ""
current_prompt = arrow_prompt
else:
current_prompt = arrow_prompt
| 26.581633
| 83
| 0.554702
| 285
| 2,605
| 4.954386
| 0.382456
| 0.073654
| 0.063739
| 0.084986
| 0.07932
| 0.05949
| 0.05949
| 0.05949
| 0.05949
| 0
| 0
| 0.003054
| 0.371593
| 2,605
| 97
| 84
| 26.85567
| 0.859499
| 0.185413
| 0
| 0.396552
| 0
| 0
| 0.035515
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.051724
| false
| 0.017241
| 0.137931
| 0
| 0.189655
| 0.189655
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e106417c74eb34df2f46cb1cc4d7afaf1c61501e
| 1,762
|
py
|
Python
|
apis/file_state.py
|
brockpalen/ltfsee-globus
|
5cb322ef09cd4f883951de96e5cb242f876ccd9c
|
[
"MIT"
] | null | null | null |
apis/file_state.py
|
brockpalen/ltfsee-globus
|
5cb322ef09cd4f883951de96e5cb242f876ccd9c
|
[
"MIT"
] | null | null | null |
apis/file_state.py
|
brockpalen/ltfsee-globus
|
5cb322ef09cd4f883951de96e5cb242f876ccd9c
|
[
"MIT"
] | null | null | null |
"""API for eeadm file state."""
from http import HTTPStatus
from flask import request
from flask_restx import Namespace, Resource, fields
from core.eeadm.file_state import EEADM_File_State
from ltfsee_globus.auth import token_required
api = Namespace(
"file_state", description="Get state of a file in archive eeadm file state"
)
# model for returning data from eeadm file state -s
# https://www.ibm.com/support/knowledgecenter/ST9MBR_1.3.0/ee_eeadm_file_state_command_output.html
file_state_model = api.model(
"file_state",
{
"state": fields.String,
"replicas": fields.Integer,
"tapes": fields.List(fields.String),
"path": fields.String,
},
)
# model for the input of a file
# must be abolute path
file_model = api.model("file", {"path": fields.String})
# create the API
@api.route("/file_state")
class FileState(Resource):
"""API Provider class for eeadm file state.
https://www.ibm.com/support/knowledgecenter/ST9MBR_1.3.0/ee_eeadm_file_state_command_output.html
"""
@api.marshal_list_with(file_state_model, code=HTTPStatus.CREATED.value)
@api.expect(file_model, validate=True)
@api.response(HTTPStatus.NOT_FOUND.value, "No such file")
@api.response(HTTPStatus.CREATED.value, "Request for file state created")
@token_required
def post(self, **kwargs):
"""POST method to send payload of file path to check status of files."""
path = request.json["path"]
# pass in the path including wild cards to get list of file states
file_state = EEADM_File_State(path)
api.logger.debug(file_state.files)
api.logger.info(f"Checking state of {path} from {request.remote_addr}")
return file_state.files, HTTPStatus.CREATED
| 32.036364
| 100
| 0.713394
| 253
| 1,762
| 4.822134
| 0.391304
| 0.132787
| 0.103279
| 0.027869
| 0.127869
| 0.127869
| 0.127869
| 0.127869
| 0.127869
| 0.127869
| 0
| 0.005533
| 0.179342
| 1,762
| 54
| 101
| 32.62963
| 0.838174
| 0.289444
| 0
| 0
| 0
| 0
| 0.167758
| 0.017185
| 0
| 0
| 0
| 0
| 0
| 1
| 0.032258
| false
| 0
| 0.16129
| 0
| 0.258065
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e106968b5aabed3c4faf9536ea2f316b06ae7ec9
| 7,925
|
py
|
Python
|
130_html_to_csv/150_mkcsv_t_info_d.py
|
takobouzu/BOAT_RACE_DB
|
f16ed8f55aef567c0ecc6ebd3ad0e917f5c600d8
|
[
"MIT"
] | 6
|
2020-12-23T01:06:04.000Z
|
2022-01-12T10:18:36.000Z
|
130_html_to_csv/150_mkcsv_t_info_d.py
|
takobouzu/BOAT_RACE_DB
|
f16ed8f55aef567c0ecc6ebd3ad0e917f5c600d8
|
[
"MIT"
] | 15
|
2021-03-02T05:59:24.000Z
|
2021-09-12T08:12:38.000Z
|
130_html_to_csv/150_mkcsv_t_info_d.py
|
takobouzu/BOAT_RACE_DB
|
f16ed8f55aef567c0ecc6ebd3ad0e917f5c600d8
|
[
"MIT"
] | 1
|
2021-05-09T10:47:21.000Z
|
2021-05-09T10:47:21.000Z
|
'''
【システム】BOAT_RACE_DB2
【ファイル】140_mkcsv_t_info_d.py
【機能仕様】直前情報HTMLファイルから直前情報明細テーブル「t_info_d」のインポートCSVファイルを作成する
【動作環境】macOS 11.1/Raspbian OS 10.4/python 3.9.1/sqlite3 3.32.3
【来 歴】2021.02.01 ver 1.00
'''
import os
import datetime
from bs4 import BeautifulSoup
#インストールディレクトの定義
BASE_DIR = '/home/pi/BOAT_RACE_DB'
'''
【関 数】mkcsv_t_info_d
【機 能】直前HTMLファイルから直前情報明細テーブル「t_info_d」のインポートCSVファイルを作成する
【引 数】なし
【戻り値】なし
'''
def mkcsv_t_info_d():
print('直前情報明細テーブル「t_info_d」のインポートCSVファイル 開始')
in_path = BASE_DIR + '/200_html/last_info'
out_file = BASE_DIR + '/210_csv/t_info_d.csv'
fw = open(out_file, 'w')
for item in os.listdir(path=in_path):
if item != '.html' and item != '.DS_Store':
in_file = in_path + '/' + item
print("==> 処理中[%s]" % (in_file))
fb = open(in_file, 'r')
html = fb.read()
fb.close()
#データ存在チェック
flg = 0
if 'データがありません。' in html:
flg = 1
if flg == 0:
#CSVレコードフィールドの初期化(共通項目)
t_info_d_yyyymmdd = '' #開催日付
t_info_d_pool_code = '' #場コード
t_info_d_race_no = '' #レース番号
#HTMLファイルからcsvレコード項目を抽出
soup = BeautifulSoup(html, 'html.parser')
#開催日付の抽出
t_info_d_yyyymmdd = item[0:8]
#場コードの抽出
t_info_d_pool_code = item[8:10]
#レース番号
t_info_d_race_no = item[10:12]
#場名の抽出
for tag1 in soup.find_all('img'):
if '/static_extra/pc/images/text_place2' in str(tag1):
for tag2 in str(tag1).splitlines():
if '/static_extra/pc/images/text_place2' in str(tag2):
wk_arry = str(tag2).strip().split(' ')
t_race_d_pool_name = str(wk_arry[1])
t_race_d_pool_name = t_race_d_pool_name.replace('alt="','')
t_race_d_pool_name = t_race_d_pool_name.replace('"','')
#選手単位の明細項目の抽出
base_count = 0
for tag1 in soup.find_all('tbody'):
if 'is-fs12' in str(tag1):
base_count = base_count + 1
#CSVレコードフィールドの初期化(選手単位項目)
t_info_d_entry_no = '' #枠番
t_info_d_body_weight = '' #体重
t_info_d_adjusted_weight = '' #調整重量
t_info_d_rehearsal_time = '' #展示タイム
t_info_d_tilt = '' #チルト
t_info_d_start_course = '' #スタート展示コース
t_info_d_flying = '' #フライング区分
t_info_d_start_time = '' #スタート展示タイム率
#選手単位の明細項目の抽出(枠番)
t_info_d_entry_no = str(base_count)
#選手単位の明細項目の抽出(体重)
n = 0
for tag2 in str(tag1).splitlines():
n = n + 1
if n == 6:
wk_arry = str(tag2).strip().split('>')
t_info_d_body_weight = str(wk_arry[1])
t_info_d_body_weight = t_info_d_body_weight.replace('</td','')
t_info_d_body_weight = t_info_d_body_weight.replace('kg','')
t_info_d_body_weight = t_info_d_body_weight.strip()
break
#選手単位の明細項目の抽出(調整重量)
n = 0
for tag2 in str(tag1).splitlines():
n = n + 1
if n == 22:
wk_arry = str(tag2).strip().split('>')
t_info_d_adjusted_weight = str(wk_arry[1]).replace('</td','')
break
#選手単位の明細項目の抽出(展示タイム)
n = 0
for tag2 in str(tag1).splitlines():
n = n + 1
if n == 7:
wk_arry = str(tag2).strip().split('>')
t_info_d_rehearsal_time = str(wk_arry[1]).replace('</td','')
break
#選手単位の明細項目の抽出(チルト)
n = 0
for tag2 in str(tag1).splitlines():
n = n + 1
if n == 8:
wk_arry = str(tag2).strip().split('>')
t_info_d_tilt = str(wk_arry[1]).replace('</td','')
break
#選手単位の明細項目の抽出(スタート展示コース)
n = 0
for tag2 in soup.find_all('span'):
if 'table1_boatImage1Number' in str(tag2):
n = n + 1
wk_arry = str(tag2).strip().split('>')
wk_str = str(wk_arry[1]).replace('</span','')
if t_info_d_entry_no == wk_str:
t_info_d_start_course = str(n)
#選手単位の明細項目の抽出(フライング区分_スタート展示タイム)
n = 0
for tag2 in soup.find_all('span'):
if 'table1_boatImage1Time' in str(tag2):
n = n + 1
wk_arry = str(tag2).strip().split('>')
wk_str = str(wk_arry[1]).replace('</span','')
if t_info_d_start_course == str(n):
if 'F' in wk_str:
t_info_d_flying = 'F'
t_info_d_start_time = wk_str.replace('F','')
else:
t_info_d_flying = ' '
t_info_d_start_time = wk_str
#CSVレコードの生成
t_info_d_outrec = ''
t_info_d_outrec = t_info_d_outrec + '"' + t_info_d_yyyymmdd + '"' #開催日付
t_info_d_outrec = t_info_d_outrec + ',"' + t_info_d_pool_code + '"' #場コード
t_info_d_outrec = t_info_d_outrec + ',"' + t_info_d_race_no + '"' #レース番号
t_info_d_outrec = t_info_d_outrec + ',"' + t_info_d_entry_no + '"' #枠番
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_body_weight #体重
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_adjusted_weight #調整重量
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_rehearsal_time #展示タイム
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_tilt #チルト
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_start_course #スタート展示コース
t_info_d_outrec = t_info_d_outrec + ',"' + t_info_d_flying + '"' #フライング区分0: なし 1: フライング2: 出遅れ
t_info_d_outrec = t_info_d_outrec + ',' + t_info_d_start_time #スタート展示タイム
#CSVレコードファイル出力
if t_info_d_body_weight != '':
fw.write(t_info_d_outrec + '\n')
fw.close()
print('直前情報明細「t_info_d」のインポートCSVファイル 完了')
#主処理
mkcsv_t_info_d() #直前情報明細テーブル「t_info_d」のインポートCSVファイルを作成
| 48.323171
| 120
| 0.418801
| 844
| 7,925
| 3.533175
| 0.204976
| 0.130785
| 0.156942
| 0.096579
| 0.60228
| 0.546278
| 0.516767
| 0.483233
| 0.43226
| 0.293092
| 0
| 0.027347
| 0.487823
| 7,925
| 163
| 121
| 48.619632
| 0.707317
| 0.082397
| 0
| 0.282051
| 0
| 0
| 0.05391
| 0.030605
| 0
| 0
| 0
| 0
| 0
| 1
| 0.008547
| false
| 0
| 0.025641
| 0
| 0.034188
| 0.025641
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1088f7eca5eb9b2a0d3d520b6c9dd794d84bb1c
| 2,194
|
py
|
Python
|
onetabtobear.py
|
vinceblake/saveTabToBear
|
4b3a79c06e9130c95fa1f87b30999f2fbfe2e017
|
[
"MIT"
] | null | null | null |
onetabtobear.py
|
vinceblake/saveTabToBear
|
4b3a79c06e9130c95fa1f87b30999f2fbfe2e017
|
[
"MIT"
] | null | null | null |
onetabtobear.py
|
vinceblake/saveTabToBear
|
4b3a79c06e9130c95fa1f87b30999f2fbfe2e017
|
[
"MIT"
] | null | null | null |
#!/usr/local/bin/python3
from subprocess import Popen, PIPE
from urllib.parse import quote
import sqlite3, datetime, sys, re
# Global Variables
removeCheckedItems = True # Set to false if you want to keep "completed" to-do items when this is run
bearDbFile = str(sys.argv[3])
oneTabID = str(sys.argv[4])
# Methods
def create_connection(db_file): # Establish SQLITE database connection cursor
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except:
print("Failed to establish connection")
return None
return conn
def xcall(url): # Simple wrapper method to run xcalls
r = Popen(['/Applications/xcall.app/Contents/MacOS/xcall',
'-url', f'"{url}"'
], stdout=PIPE)
stdout = r.communicate()
return str(stdout[0].decode('utf-8')).strip().replace(" ","")
def getOneTab(): # Get and return OneTab note from Bear
bearNote = bear.execute(f"SELECT * FROM ZSFNOTE WHERE ZUNIQUEIDENTIFIER IS '{oneTabID}'").fetchone()
return str(bearNote[32]) # ZTEXT
def updateOneTab():
oneTab = getOneTab().replace("# BearMarks","")
if removeCheckedItems:
oneTab = re.sub(r"^\+ .*\n","",oneTab,flags=re.MULTILINE)
oneTab = re.sub(r"^\#\#\# .*\n\n","",oneTab,flags=re.MULTILINE)
if url in oneTab:
#print("URL already present. Skipping.")
return
now = datetime.datetime.now().strftime("%B %d, %Y")
prefix = f'### {now}\n'
line = f'- [{title}]({url})'
if prefix in oneTab:
oneTab = oneTab.replace(prefix,f'{prefix}{line}\n')
else:
line = f'{prefix}{line}\n'
oneTab = line + oneTab
update = f'bear://x-callback-url/add-text?id={oneTabID}&mode=replace&text={quote(oneTab.strip())}&open_note=no'
xcall(update)
# Main functionality:
if __name__ == '__main__':
title = sys.argv[1]
url = sys.argv[2]
# Connect to Bear database
beardb = create_connection(bearDbFile)
bear = beardb.cursor()
# Process tab and update database:
updateOneTab()
| 30.054795
| 115
| 0.639927
| 285
| 2,194
| 4.873684
| 0.473684
| 0.020158
| 0.014399
| 0.017279
| 0.051116
| 0
| 0
| 0
| 0
| 0
| 0
| 0.006399
| 0.2165
| 2,194
| 73
| 116
| 30.054795
| 0.801629
| 0.228806
| 0
| 0
| 0
| 0.021739
| 0.218335
| 0.086248
| 0
| 0
| 0
| 0
| 0
| 1
| 0.086957
| false
| 0
| 0.065217
| 0
| 0.26087
| 0.021739
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1093ea692aa40b78e1fe9867c9ec44b0222ae19
| 1,319
|
py
|
Python
|
defects4cpp/d++.py
|
HansolChoe/defects4cpp
|
cb9e3db239c50e6ec38127cec117865f0ee7a5cf
|
[
"MIT"
] | 10
|
2021-06-23T01:53:19.000Z
|
2022-03-31T03:14:01.000Z
|
defects4cpp/d++.py
|
HansolChoe/defects4cpp
|
cb9e3db239c50e6ec38127cec117865f0ee7a5cf
|
[
"MIT"
] | 34
|
2021-05-27T01:09:04.000Z
|
2022-03-28T07:53:35.000Z
|
defects4cpp/d++.py
|
HansolChoe/defects4cpp
|
cb9e3db239c50e6ec38127cec117865f0ee7a5cf
|
[
"MIT"
] | 6
|
2021-09-03T07:16:56.000Z
|
2022-03-29T07:30:35.000Z
|
import sys
from time import perf_counter
from command import CommandList
from errors import DppArgparseError, DppDockerError, DppError
from message import message
def _handle_cmdline_error(e: DppError):
if isinstance(e, DppArgparseError):
message.stdout_argparse_error(str(e))
elif isinstance(e, DppDockerError):
message.stdout_argparse_error(str(e))
def main():
def measure_time(func, args):
start_time = perf_counter()
func(args)
elapsed = perf_counter() - start_time
if elapsed < 100:
message.stdout_progress(f"Elapsed: {elapsed:.2f}s")
else:
minutes, seconds = divmod(elapsed, 60)
message.stdout_progress(f"Elapsed: {int(minutes)}m {seconds:.2f}s")
commands = CommandList()
try:
name = sys.argv[1]
except IndexError:
name = "help"
argv = sys.argv[2:]
if name not in commands:
message.stdout_progress_error(f"'{name}' is not a valid command")
return 1
try:
if name != "help":
measure_time(commands[name], argv)
else:
commands[name](argv)
except DppError as e:
_handle_cmdline_error(e)
if __name__ == "__main__":
from multiprocessing import freeze_support
freeze_support()
main()
| 24.425926
| 79
| 0.639121
| 158
| 1,319
| 5.139241
| 0.386076
| 0.080049
| 0.077586
| 0.046798
| 0.14532
| 0.073892
| 0
| 0
| 0
| 0
| 0
| 0.010309
| 0.264594
| 1,319
| 53
| 80
| 24.886792
| 0.826804
| 0
| 0
| 0.15
| 0
| 0
| 0.082638
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.075
| false
| 0
| 0.15
| 0
| 0.25
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e109e7b0486674fec7a7133e0f5ef96b64e2f7e2
| 9,962
|
py
|
Python
|
wz/ui/choice_grid.py
|
gradgrind/WZ
|
672d93a3c9d7806194d16d6d5b9175e4046bd068
|
[
"Apache-2.0"
] | null | null | null |
wz/ui/choice_grid.py
|
gradgrind/WZ
|
672d93a3c9d7806194d16d6d5b9175e4046bd068
|
[
"Apache-2.0"
] | null | null | null |
wz/ui/choice_grid.py
|
gradgrind/WZ
|
672d93a3c9d7806194d16d6d5b9175e4046bd068
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
ui/choice_grid.py
Last updated: 2021-05-04
Manage the grid for the puil-subject-choice-editor.
=+LICENCE=============================
Copyright 2021 Michael Towers
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.
=-LICENCE========================================
"""
### Display texts
_PUPIL = "Schüler"
_GROUPS = "Gruppen"
## Measurements are in mm ##
_SEP_SIZE = 1
_HEIGHT_LINE = 6
_WIDTH_TOGGLE = 8
COLUMNS = (35, 15, 15, _SEP_SIZE) # + ...
ROWS = (
#title
12,
# info rows
_HEIGHT_LINE, _HEIGHT_LINE, _HEIGHT_LINE, _HEIGHT_LINE,
_HEIGHT_LINE, _HEIGHT_LINE,
# header (tags)
_HEIGHT_LINE, _SEP_SIZE
) # + _HEIGHT_LINE * n
# Content of marked toggle-cells
MARK = 'X'
#####################################################
from qtpy.QtWidgets import QApplication
from qtpy.QtGui import QColor, QBrush
from qtpy.QtCore import Qt
from ui.gridbase import GridBase
class ToggleGrid(GridBase):
"""A grid of toggle-cells with column and row headers (potentially
multi-row or multi-column respectively).
Clicking on a cell will toggle its value. SHIFT-clicking marks a cell
as the starting point of a rectangle. A further SHIFT-click marks
the end-point of the rectangle and toggles all cells within the
rectangle. The marking is removed.
The mark can also be removed by clicking elsewhere (without SHIFT).
"""
def __init__(self, gview, info, pupil_data, subjects):
"""<gview> is the "View" on which this "Scene" is to be presented.
<info>: general information, [[key, value], ... ]
<pupil_data>: A list of pupil lines, only valid sids are included:
[[pid, name, groups, {sid: val, ... }], ... ]
val: true if marked
<subjects>: The list of subjects, possibly containing spacers:
[[sid, name], ... , null-value, [sid, name], ... ]
"""
# Set up grid: get number of rows and columns
row_pids = len(ROWS)
_ROWS = ROWS + (_HEIGHT_LINE,) * len(pupil_data)
col_sids = len(COLUMNS)
_COLS = list(COLUMNS)
for s in subjects:
_COLS.append(_WIDTH_TOGGLE if s else _SEP_SIZE)
super().__init__(gview, _ROWS, _COLS)
self.styles()
# Horizontal separator (after headers)
self.basic_tile(row_pids - 1, 0, tag = None, text = None,
style = 'padding', cspan = len(_COLS))
# Vertical separator (before subjects)
col = col_sids
self.basic_tile(1, col_sids - 1, tag = None, text = None,
style = 'padding', rspan = len(_ROWS) - 1)
### Title area
self.basic_tile(0, 0, tag = None, text = "Fächer(ab)wahl",
style = 'title', cspan = 2)
self.basic_tile(0, 4, tag = None,
text = ADMIN.school_data['SCHOOL_NAME'],
style = 'titleR', cspan = 10)
### General Info
line = 1
for key, value in info:
self.basic_tile(line, 0, tag = None, text = key,
style = 'info')
# Non-editable
self.basic_tile(line, 1, tag = None, text = value,
style = 'info', cspan = 2)
line += 1
### Subject headers
line = 7
rspan = line - 1
self.basic_tile(line, 0, tag = None, text = _PUPIL,
style = 'small', cspan = 2)
self.basic_tile(line, 2, tag = None, text = _GROUPS,
style = 'small')
col = col_sids
self.sids = []
for sid_name in subjects:
if sid_name:
sid, name = sid_name
self.sids.append(sid)
self.basic_tile(line, col, tag = None, text = sid,
style = 'small')
self.basic_tile(1, col, tag = None, text = name,
style = 'v', rspan = rspan)
else:
# vertical spacer
self.basic_tile(1, col, tag = None, text = None,
style = 'padding', rspan = len(_ROWS) - 1)
col += 1
### Pupil lines
row = row_pids
# The array (list of lists) <self.toggles> is a simple matrix
# of the toggle-tiles, omitting the skipped columns.
self.toggles = []
self.pids = []
self.value0 = set() # Set of initially marked cells (x, y)
y = 0
for pid, pname, groups, choices in pupil_data:
self.basic_tile(row, 0, tag = None, text = pname,
style = 'name', cspan = 2)
self.basic_tile(row, 2, tag = None, text = groups,
style = 'small')
col = col_sids
x = 0
_toggles = []
for sid_name in subjects:
if sid_name:
try:
marked = choices[sid_name[0]]
except KeyError:
# Invalid key: not editable
tag = None
style = 'padding'
val = None
else:
tag = (x, y)
style = 'toggle'
if marked:
self.value0.add(tag)
val = MARK
else:
val = ''
tile = self.basic_tile(row, col, tag = tag,
text = val, style = style)
_toggles.append(tile)
x += 1
col += 1
self.pids.append(pid)
self.toggles.append(_toggles)
y += 1
row += 1
# Need a highlighted/selected QBrush for a toggle-cell
self.mark_brush = QBrush(QColor('#80FF7200'))
self.no_mark = self.style('toggle').bgColour or QBrush(Qt.NoBrush)
# Collect changed cell tags for signalling "table changed".
self._changes = set()
self.toggle_start = None
#
def styles(self):
"""Set up the styles used in the table view.
"""
self.new_style('base', font = ADMIN.school_data['FONT'], size = 11)
self.new_style('name', base = 'base', align = 'l')
self.new_style('title', font = ADMIN.school_data['FONT'], size = 12,
align = 'l', border = 0, highlight = 'b')
self.new_style('info', base = 'base', border = 0, align = 'l')
self.new_style('underline', base = 'base', border = 2)
self.new_style('titleR', base = 'title', align = 'r')
self.new_style('small', base = 'base', size = 10)
self.new_style('v', base = 'small', align = 'b')
self.new_style('toggle', base = 'base', highlight = ':002562',
mark = 'E00000')
# self.new_style('no-toggle', bg = '666666')
self.new_style('padding', bg = '666666')
#
def tile_left_clicked(self, tile):
if isinstance(tile.tag, tuple):
# toggle-tile
kbdmods = QApplication.keyboardModifiers()
if kbdmods & Qt.ShiftModifier:
if self.toggle_start:
# toggle range
c0, r0 = self.toggle_start.tag
c1, r1 = tile.tag
r_range = range(r0, r1 + 1) if r1 >= r0 \
else range(r1, r0 + 1)
c_range = range(c0, c1 + 1) if c1 >= c0 \
else range(c1, c0 + 1)
for r in r_range:
for c in c_range:
self.toggle(self.toggles[r][c])
else:
self.toggle_start = tile
# highlight cell
tile.setBrush(self.mark_brush)
return False
else:
self.toggle(tile)
if self.toggle_start:
# remove highlight
if self.toggle_start:
self.toggle_start.setBrush(self.no_mark)
self.toggle_start = None
return False
#
def toggle(self, tile):
val = '' if tile.value() else MARK
tile.setText(val)
if val:
if tile.tag in self.value0:
self.changes_discard(tile.tag)
else:
self.changes_add(tile.tag)
else:
if tile.tag in self.value0:
self.changes_add(tile.tag)
else:
self.changes_discard(tile.tag)
#
def changes_discard(self, tag):
if self._changes:
self._changes.discard(tag)
if not self._changes:
self._gview.set_changed(False)
#
def changes_add(self, tag):
if not self._changes:
self._gview.set_changed(True)
self._changes.add(tag)
#
def changes(self):
return list(self._changes)
#
def data(self):
"""Return choice data as a list of "non-chosen" subject lists.
[(pid, [sid, ...]), ... ]
Also pupils with empty lists are included.
"""
clist = []
y = 0
for row in self.toggles:
x = 0
slist = []
for sid in self.sids:
if row[x].value():
slist.append(sid)
x += 1
clist.append((self.pids[y], slist))
y += 1
return clist
| 36.490842
| 76
| 0.511443
| 1,163
| 9,962
| 4.262253
| 0.251935
| 0.025419
| 0.036716
| 0.020173
| 0.159371
| 0.128505
| 0.104297
| 0.104297
| 0.058907
| 0.043575
| 0
| 0.020867
| 0.374624
| 9,962
| 272
| 77
| 36.625
| 0.774799
| 0.249046
| 0
| 0.248619
| 0
| 0
| 0.034111
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.044199
| false
| 0
| 0.022099
| 0.005525
| 0.093923
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e10b54355c9e418ed2013419152b910332c40ec9
| 5,585
|
py
|
Python
|
EPH_CORE_SkyObjectMgr.py
|
polsterc16/ephem
|
70ac6c079c80344b83499b96edaff57fb5881efc
|
[
"MIT"
] | null | null | null |
EPH_CORE_SkyObjectMgr.py
|
polsterc16/ephem
|
70ac6c079c80344b83499b96edaff57fb5881efc
|
[
"MIT"
] | null | null | null |
EPH_CORE_SkyObjectMgr.py
|
polsterc16/ephem
|
70ac6c079c80344b83499b96edaff57fb5881efc
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 16:25:45 2019
@author: polsterc16
==============================================================================
LICENCE INFORMATION
==============================================================================
This Software uses Code (spg4) provided by "Brandon Rhodes" under
the "MIT License". For more Information see "licence-info.txt".
Diese Software benutzt Code (spg4), welcher von "Brandon Rhodes" unter
der "MIT License" zur Verfuegung gestellt wird. Fuer weitere Information
siehe "licence-info.txt".
==============================================================================
"""
import EPH_CORE_TimeSpaceMgr as TSMgr
import EPH_SAT_SatelliteMgr as SatMgr
import EPH_PLANET_PlanetMgr as PlanetMgr
import EPH_STAR_StarMgr as StarMgr
import EPH_MOON_MoonMgr as MoonMgr
class SkyObjectMgr:
''' deals with all allowed sky objects. '''
################################################################
#### STATIC / CLASS VARIABLES
################################################################
#### INIT
def __init__(self, TSMgrObj, skyObjType:str, identifier=None ):
''' TimeSpaceManager Instance, type of sky object, identifier '''
constrString = ("Constructor for Type: '"+str(skyObjType)+
"' ("+str(identifier)+"): ")
self._cnstrMsg = (constrString+"failed immediatly.") # immediate fail
self._success = False
self._skyObject = None
self._skyObjName = identifier
self._skyObjType = skyObjType
if(type(TSMgrObj)==(TSMgr.TimeSpaceMgr)):
# Wenn TSMgrObj wirklich ein TSMgr.TimeSpaceMgr objekt ist
self._TSMgr = TSMgrObj
if (skyObjType.lower() in ["planet"]):
# TODO: implementierung
# wenn typ = planet
self._skyObjType = "planet"
self._skyObject = PlanetMgr.PlanetMgr(self._TSMgr,identifier)
elif(skyObjType.lower() in ["star"]):
# wenn typ = stern
self._skyObjType = "star"
self._skyObject = StarMgr.StarMgr(self._TSMgr,identifier)
self._skyObjName = str(self._skyObject.getName())
elif(skyObjType.lower() in ["moon"]):
# TODO: implementierung
# wenn typ = Mond
self._skyObjType = "moon"
self._skyObject = MoonMgr.MoonMgr(self._TSMgr)
elif(skyObjType.lower() in ["sat","satellite"]):
# wenn typ = satellit
self._skyObjType = "satellite"
tempID = identifier
# für den fall einer string eingabe
if type(tempID) == str:
tempID = tempID.strip()
if tempID.isnumeric():
tempID = int(tempID)
if type(tempID) == int:
# geht nur für int eingabe (bzw erkennbarer int-string)
self._skyObject = SatMgr.SatelliteMgr(self._TSMgr,tempID)
else:
# wenn typ = UNBEKANNT
self._cnstrMsg = (constrString+
"failed - unknown 'skyObjType' string.")
else:
# this is not a TSMgr object!
self._cnstrMsg = (constrString+
"failed - 'TSMgrObj' must be of type "+
str(type(TSMgr.TimeSpaceMgr()))+".")
def get_pos_spherical(self, utcTime = None):
#set TSMgr to utcTime (if None, then utcNow)
self._TSMgr.time_set_utcDateTime(utcTime)
# TODO: für alle implementieren
if self._skyObject != None:
# wenn skyObject existiert
if self._skyObjType in ["planet","star","satellite","moon"]:
# wenn type eine umsetzung hat
print(self._skyObjType)
pos = self._skyObject.getPos()
if pos != None:
return {"Ra": pos['Ra'],
"De": pos['De'],
'Success': self._skyObject.get_success()}
else:
return None
else:
return None
else:
# wenn kein skyobject existiert
return None
def write_pos_to_dict(self, destDict: dict, utcTime = None):
''' writes Ra, De and Success to a provided dictionary.
(OPTIONAL: get the pos for a specific utc datetime) '''
# get pos for specified utctime (inf none, then utcNow)
temp = self.get_pos_spherical(utcTime)
if(temp != None):
# if it has a return value, then write this to dict
destDict['Ra'] = temp['Ra']
destDict['De'] = temp['De']
destDict['Success'] = temp['Success']
else:
# if it returns none, then return default none values
destDict['Ra'] = None
destDict['De'] = None
destDict['Success'] = False
def get_type(self):
return self._skyObjType
def get_name(self):
return self._skyObjName
| 34.263804
| 78
| 0.476813
| 489
| 5,585
| 5.331288
| 0.361963
| 0.044879
| 0.026084
| 0.034522
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.004585
| 0.375112
| 5,585
| 163
| 79
| 34.263804
| 0.742407
| 0.271083
| 0
| 0.152778
| 0
| 0
| 0.062161
| 0
| 0
| 0
| 0
| 0.006135
| 0
| 1
| 0.069444
| false
| 0
| 0.069444
| 0.027778
| 0.236111
| 0.013889
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e10cde8f79b9f8a7e8e8be18b130895124b76c09
| 3,370
|
py
|
Python
|
integration-test-reports/run_reports.py
|
sutoiku/autostat
|
b0e6588e587450c4cbdb19a021d847f7571ba466
|
[
"MIT"
] | null | null | null |
integration-test-reports/run_reports.py
|
sutoiku/autostat
|
b0e6588e587450c4cbdb19a021d847f7571ba466
|
[
"MIT"
] | 1
|
2022-03-16T19:05:46.000Z
|
2022-03-16T19:05:46.000Z
|
integration-test-reports/run_reports.py
|
sutoiku/autostat
|
b0e6588e587450c4cbdb19a021d847f7571ba466
|
[
"MIT"
] | 1
|
2021-07-14T19:37:44.000Z
|
2021-07-14T19:37:44.000Z
|
from autostat.run_settings import RunSettings, Backend
from autostat.kernel_search import kernel_search, get_best_kernel_info
from autostat.dataset_adapters import Dataset
from autostat.utils.test_data_loader import load_test_dataset
from html_reports import Report
from markdown import markdown
import matplotlib.pyplot as plt
from datetime import datetime
import os
import time
import random
import numpy as np
print(os.getcwd())
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
def timestamp():
return datetime.strftime(datetime.now(), "%Y-%m-%d_%H:%M:%S")
class HtmlLogger:
def __init__(self, report: Report) -> None:
self.report = report
def print(self, s: str) -> None:
self.report.add_markdown(
s.replace("\n", "\n\n")
# .replace("<", "<").replace(">", ">")
)
def prepend(self, s: str) -> None:
md = markdown(s, extensions=["fenced_code", "codehilite"])
self.report.body = [md] + self.report.body
def show(self, fig) -> None:
plt.tight_layout(rect=(0, 0, 1, 0.95))
plt.figure(fig.number)
self.report.add_figure(options="width=100%")
plt.close(plt.gcf())
report = Report()
logger = HtmlLogger(report)
def title_separator(title):
logger.print("-----------")
logger.print("-----------")
logger.print("-----------")
logger.print(f"# ***{title}***")
matlab_data_path = "data/"
files_sorted_by_num_data_points = [
"01-airline.mat",
# "07-call-centre.mat",
# "08-radio.mat",
"04-wheat.mat",
# "02-solar.mat",
# "11-unemployment.mat",
# # "10-sulphuric.mat",
# # "09-gas-production.mat",
# "03-mauna.mat",
# # "13-wages.mat",
# # "06-internet.mat",
# "05-temperature.mat",
# "12-births.mat",
]
if __name__ == "__main__":
random.seed(1234)
np.random.seed(1234)
print("starting report")
run_settings = RunSettings(
max_search_depth=2,
expand_kernel_specs_as_sums=False,
num_cpus=12,
use_gpu=False,
use_parallel=True,
gpu_memory_share_needed=0.45,
backend=Backend.SKLEARN,
).replace_base_kernels_by_names(["PER", "LIN", "RBF"])
logger.print(str(run_settings))
logger.print("\n" + str(run_settings.asdict()))
prediction_scores = []
for file_name in files_sorted_by_num_data_points:
file_num = int(file_name[:2])
dataset = load_test_dataset(matlab_data_path, file_num, split=0.1)
run_settings = run_settings.replace_kernel_proto_constraints_using_dataset(
dataset
)
title_separator(f"Dataset: {file_name}")
tic = time.perf_counter()
kernel_scores = kernel_search(dataset, run_settings=run_settings, logger=logger)
toc = time.perf_counter()
best_kernel_info = get_best_kernel_info(kernel_scores)
prediction_scores.append(best_kernel_info.prediction_score)
logger.print(f"best_kernel_info {str(best_kernel_info)}")
logger.print(f"Total time for {file_name}: {toc-tic:.3f} s")
logger.prepend(f"prediction_scores: {str(prediction_scores)}")
logger.prepend(f"sum prediction_scores: {str(sum(prediction_scores))}")
report.write_report(filename=f"reports/report_{timestamp()}.html")
print("report done")
| 26.124031
| 88
| 0.651929
| 439
| 3,370
| 4.753986
| 0.396355
| 0.042166
| 0.040249
| 0.031624
| 0.045999
| 0.045999
| 0
| 0
| 0
| 0
| 0
| 0.019651
| 0.199703
| 3,370
| 128
| 89
| 26.328125
| 0.754171
| 0.076558
| 0
| 0.037975
| 0
| 0
| 0.132149
| 0.035218
| 0
| 0
| 0
| 0
| 0
| 1
| 0.075949
| false
| 0
| 0.151899
| 0.012658
| 0.253165
| 0.151899
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1124f5104c7b2ddd81c1b4c389bcffa152ee3a4
| 44,393
|
py
|
Python
|
srt_gc_launchGui.py
|
OrigamiAztec/LaunchGUITesting
|
e097afb075b313e13550937f450adf6653f88812
|
[
"MIT"
] | null | null | null |
srt_gc_launchGui.py
|
OrigamiAztec/LaunchGUITesting
|
e097afb075b313e13550937f450adf6653f88812
|
[
"MIT"
] | null | null | null |
srt_gc_launchGui.py
|
OrigamiAztec/LaunchGUITesting
|
e097afb075b313e13550937f450adf6653f88812
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
'''
Texas A&M University Sounding Rocketry Team
SRT-6 | 2018-2019
SRT-9 | 2021-2022
%-------------------------------------------------------------%
TAMU SRT
_____ __ _____ __ __
/ ___/______ __ _____ ___/ / / ___/__ ___ / /________ / /
/ (_ / __/ _ \/ // / _ \/ _ / / /__/ _ \/ _ \/ __/ __/ _ \/ /
\___/_/ \___/\_,_/_//_/\_,_/ \___/\___/_//_/\__/_/ \___/_/
%-------------------------------------------------------------%
Filepath:
gc/srt_gc_launchGui/srt_gc_launchGui.py
Developers:
(C) Doddanavar, Roshan 20171216
(L) Doddanavar, Roshan 20180801
Diaz, Antonio
Description:
Launch Control GUI, interfaces w/ srt_gc_launchArduino/srt_gc_launchArduino.ino
Input(s):
<None>
Output(s):
./log/*.log plain-text command log
./dat/*.dat plain-text data archive
'''
# Installed modules --> Utilities
import sys
import os
import serial, serial.tools.list_ports
from serial.serialutil import SerialException
import time
from datetime import datetime
import numpy as np
# Installed modules --> PyQt related
from PyQt5 import (QtGui, QtCore, QtSvg)
from PyQt5.QtCore import (Qt, QThread, pyqtSignal, QDate, QTime, QDateTime, QSize)
from PyQt5.QtWidgets import (QMainWindow, QWidget, QDesktopWidget, QPushButton, QApplication, QGroupBox, QGridLayout, QStatusBar, QFrame, QTabWidget,QComboBox)
import pyqtgraph as pg
# Program modules
from srt_gc_launchState import State
from srt_gc_launchThread import SerThread, UptimeThread
from srt_gc_launchTools import Tools, Object
from srt_gc_launchStyle import Style, Color
from srt_gc_launchConstr import Constr
# used to monitor wifi networks.
import subprocess
# used to get date and time in clock method.
import datetime as dt
# used to connect to ethernet socket in connect method.
import socket
# data for ethernet connection to SRT6 router
# Create a TCP/IP socket for srt router
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCP_IP = '192.168.1.177'
TCP_PORT = 23
server_address = (TCP_IP, TCP_PORT)
class Gui(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
'''
Main Window Initialization
'''
# General initialization
self.session = ''
# current date used in top of window
self.dateGlobal = QDate.currentDate()
# current time used in starting thread time in bottom of window
self.startGlobal = QTime.currentTime()
self.version = "v6.4.0"
# Container initialization
self.edit = Object() # Line edit container
self.btn = Object() # Button container
self.led = Object() # LED indicator container
self.ledClr = Object() # LED pixmap container
self.sensor = Object() # Sensor readout container
self.data = Object() # Data array container
self.plot = Object() # Plot container
ledImg = ["green","yellow","red","off"] # LED indicator image files
for name in ledImg:
# get LED Images in figs folder, green.png, yellow.png, and so on
# pixmap = QtGui.QPixmap("./figs/" + name + ".png").scaled(20, 20,
pixmap = QtGui.QPixmap("./srt_gc_launchGui/figs/" + name + ".png").scaled(20, 20,
transformMode=QtCore.Qt.SmoothTransformation)
setattr(self.ledClr,name,pixmap)
# Utility initialization
self.style = Style()
self.color = Color()
self.state = State(self.led,self.ledClr)
self.tools = Tools()
self.constr = Constr(self,self.ledClr)
# Utility states
self.state.connected = False # Serial connection
self.state.reading = False # COM port bypass
self.state.log = False # Log/data file initialization
self.state.data = False # Avionics data read
# Master grid layout management
self.gridMaster = QGridLayout()
self.gridMaster.setSpacing(10)
# Tab initialization
# name, row, col, row Span, col Span
tabSpec = [( "tabComm", 0, 2, 1, 8),
( "tabSys", 1, 0, 1, 2),
( "tabAv", 1, 2, 1, 2),
( "tabFill", 1, 4, 1, 2),
( "tabData", 2, 0, 1, 10)]
for spec in tabSpec:
tabName = spec[0]
row = spec[1]
col = spec[2]
rSpan = spec[3]
cSpan = spec[4]
tab = QTabWidget()
setattr(self,tabName,tab)
self.gridMaster.addWidget(tab,row,col,rSpan,cSpan)
# kind, grid, title, row, col, row Span, col Span
groupSpec = [( "box", "groupTitle", "gridTitle", "", 0, 0, 1, 2),
( "tab", "groupComm", "gridComm", "Communication", "tabComm"),
( "tab", "groupSess", "gridSess", "Session Control", "tabComm"),
( "tab", "groupSys", "gridSys", "System State", "tabSys"),
( "tab", "groupPwr", "gridPwr", "Power Telemetry", "tabSys"),
( "tab", "groupDaq", "gridDaq", "Avionics DAQ", "tabAv"),
( "tab", "groupDiag", "gridDiag", "Diagnostics", "tabAv"),
( "tab", "groupFill", "gridFill", "Fill Control", "tabFill"),
( "tab", "groupAuto", "gridAuto", "Auto Fill", "tabFill"),
( "box", "groupIgn", "gridIgn", "Igniter Control", 1, 6, 1, 2),
( "box", "groupVal", "gridVal", "Valve Control", 1, 8, 1, 2),
( "tab", "groupPlot", "gridPlot", "Engine Diagnostics", "tabData"),
( "tab", "groupOut", "gridOut", "Serial Output", "tabData"),]
for spec in groupSpec:
kind = spec[0]
groupName = spec[1]
gridName = spec[2]
title = spec[3]
if (kind == "tab"):
parent = spec[4]
group = QWidget()
grid = QGridLayout()
# Widget initialization
setattr(self,groupName,group)
# GridLayout object initialization
setattr(self,gridName,grid)
group.setLayout(grid)
group.setAutoFillBackground(True)
# Tab assignment
getattr(self,parent).addTab(group,title)
elif (kind == "box"):
row = spec[4]
col = spec[5]
rSpan = spec[6]
cSpan = spec[7]
# GroupBox object initialization
group = QGroupBox(title)
group.setStyleSheet(self.style.css.group)
# GridLayout object initialization
grid = QGridLayout()
group.setLayout(grid)
# Assign to parent objects
setattr(self,gridName,grid)
setattr(self,groupName,group)
self.gridMaster.addWidget(group,row,col,rSpan,cSpan)
# Call initialization routines
self.titleInit() # Title bar
self.barInit() # Bottom statusbar
self.commInit() # Communication toolbar
self.sessInit() # Session toolbar
self.btnCtrlInit() # Buttons for control panel
self.ledCtrlInit() # LED inidicators " "
self.plotInit() # Engine diagnostics, plots
self.dataInit() # Engine diagnostics, readouts
self.outInit() # Raw serial output
# Row & column stretching in master grid
rowStr = [1, 4, 8]
colStr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
self.tools.resize(self.gridMaster,rowStr,colStr)
# Finalize widget
mainWidget = QWidget()
mainWidget.setLayout(self.gridMaster)
self.setCentralWidget(mainWidget)
# Window management
self.setWindowTitle("SRT Ground Control " + self.version + " " + self.dateGlobal.toString(Qt.TextDate))
self.setWindowIcon(QtGui.QIcon("./figs/desktop_icon.png"))
self.showMaximized()
# Window centering
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
# Window formatting
#self.setStyleSheet(self.style.css.window)
# Final initialization
self.show()
def titleInit(self):
'''
Window Title Initialization
'''
# QLabel --> SRT logo
#titImg = "./figs/srt_black.svg"
titImg = "./srt_gc_launchGui/figs/srt_black.svg"
pixmap = QtGui.QPixmap(titImg).scaled(50,50,transformMode=QtCore.Qt.SmoothTransformation)
self.logo = self.constr.image(self.gridTitle,pixmap,[0,0,2,1])
# QLabel --> Main window title
text = "SRT Ground Control" + " " + self.version
self.title = self.constr.label(self.gridTitle,"title",text,"Bottom",[0,1,1,1])
# QLabel --> Main window subtitle
text = "Remote Launch System [tamusrt/gc]"
self.subtitle = self.constr.label(self.gridTitle,"subtitle",text,"Top",[1,1,1,1])
# Row & column stretching in title grid
rowStr = [5, 1]
colStr = [1, 2]
self.tools.resize(self.gridTitle,rowStr,colStr)
def barInit(self):
'''
Initialize strings and inputs in bottom status bar.
'''
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)
barFrame = QFrame()
gridStatus = QGridLayout()
barFrame.setLayout(gridStatus)
self.statusBar.addPermanentWidget(barFrame,1)
# Event log
self.constr.label(gridStatus,"label","EVENT LOG","Center",[0,0,1,1])
self.statusBar.log = self.constr.readout(gridStatus,"statusBar",[0,1,1,1])
# Last sent
self.constr.label(gridStatus,"label","LAST SENT","Center",[0,2,1,1])
self.statusBar.sent = self.constr.readout(gridStatus,"statusBar",[0,3,1,1])
# Last recieved
self.constr.label(gridStatus,"label","LAST RCVD","Center",[0,4,1,1])
self.statusBar.recieved = self.constr.readout(gridStatus,"statusBar",[0,5,1,1])
# Session name
self.constr.label(gridStatus,"label","SESSION","Center",[0,6,1,1])
self.statusBar.session = self.constr.readout(gridStatus,"statusBar",[0,7,1,1])
# Uptime counter
self.constr.label(gridStatus,"label","UPTIME","Center",[0,8,1,1])
self.statusBar.uptime = self.constr.readout(gridStatus,"statusBar",[0,9,1,1])
# Uptime thread management
self.uptimeThread = UptimeThread(self.startGlobal,self.statusBar.uptime)
self.uptimeThread.start()
# Row & column stretching in comm grid
rowStr = []
colStr = [1, 4, 1, 2, 1, 2, 1, 2, 1, 2]
self.tools.resize(gridStatus,rowStr,colStr)
def commInit(self):
'''
Communication Toolbar Initialization
'''
# set communication and reading status as false initially.
self.state.connected = False
self.state.reading = False
if (os.name == "posix"):
prefix = "/dev/tty"
elif (os.name == "nt"):
prefix = "COM"
else:
prefix = ""
# LED indicator for connection
self.led.commConn = self.constr.led(self.gridComm,[0,0,1,1])
# CONNECT button
method = "btnClkConn"
color = self.color.comm
self.btn.commConn = self.constr.button(self.gridComm,"CONNECT",method,color,[0,1,1,1])
# SEARCH button
method = "btnClkSearch"
color = self.color.comm
self.btn.commSearch = self.constr.button(self.gridComm,"SEARCH",method,color,[0,2,1,1])
# COM Port label & input
self.labPort = self.constr.label(self.gridComm,"label","Data Port:","Center",[0,3,1,1])
self.portMenu = self.constr.dropDown(self.gridComm,[0,4,1,1])
# Baud rate label & input
self.labBaud = self.constr.label(self.gridComm,"label","Baud Rate","Center",[0,5,1,1])
self.baudMenu = self.constr.dropDown(self.gridComm,[0,6,1,1])
self.baudMenu.addItems(["9600","14400","19200","28800","38400","57600","115200"])
# LED indicator for bypass
self.led.commByp = self.constr.led(self.gridComm,[0,7,1,1])
# BYPASS button. Function of bypass is to force GUI to send commands over xbee even if xbee port isn't showing.
method = "btnClkByp"
color = self.color.comm
self.btn.commByp = self.constr.button(self.gridComm,"BYPASS",method,color,[0,8,1,1])
# RESET button. Function of reset is to stop thread sorting, turn off all LEDs and disconnect xbees. May want to add more functionality such as returning to a safe state of the engine.
method = "btnClkRes"
color = self.color.comm
self.btn.commRes = self.constr.button(self.gridComm,"RESET",method,color,[0,9,1,1])
# Row & column stretching in comm grid
rowStr = []
colStr = [1, 3, 3, 2, 5, 2, 2, 1, 3, 3]
self.tools.resize(self.gridComm,rowStr,colStr)
def sessInit(self):
# Session name
self.led.sess = self.constr.led(self.gridSess,[0,0,1,1])
self.btn.sessNew = self.constr.button(self.gridSess,"NEW","btnClkSessNew",self.color.comm,[0,1,1,1])
self.btn.sessRename = self.constr.button(self.gridSess,"RENAME","btnClkSessRename",self.color.comm,[0,2,1,1])
self.labSess = self.constr.label(self.gridSess,"label","Session","Center",[0,3,1,1])
self.edit.session = self.constr.edit(self.gridSess,"test",[0,4,1,1])
# Clock control
self.led.clock = self.constr.led(self.gridSess,[0,5,1,1])
self.btn.sessClock = self.constr.button(self.gridSess,"SET CLOCK","btnClkClock",self.color.comm,[0,6,1,1])
self.labDateYr = self.constr.label(self.gridSess,"label","Date","Center",[0,7,1,1])
self.edit.dateYYYY = self.constr.edit(self.gridSess,"YYYY",[0,8,1,1])
self.edit.dateMM = self.constr.edit(self.gridSess,"MM",[0,9,1,1])
self.edit.dateDD = self.constr.edit(self.gridSess,"DD",[0,10,1,1])
self.labTime = self.constr.label(self.gridSess,"label","Time","Center",[0,11,1,1])
self.edit.timeHH = self.constr.edit(self.gridSess,"HH",[0,12,1,1])
self.edit.timeMM = self.constr.edit(self.gridSess,"MM",[0,13,1,1])
self.edit.timeSS = self.constr.edit(self.gridSess,"SS",[0,14,1,1])
# Row & column stretching in sess grid
rowStr = []
colStr = [1, 2, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1]
self.tools.resize(self.gridSess,rowStr,colStr)
def btnClkSearch(self):
# set the port menu to be cleared initially.
self.portMenu.clear()
# check the number of serial ports available.
ports = serial.tools.list_ports.comports()
# if ports exist, add it to drop down menu in GUI
if (ports):
for port in ports:
entry = "Serial: " + port.device + " - " + port.description
self.portMenu.addItem(entry)
# uses subprocess package to check for connected wifi networks.
devices = subprocess.check_output(['netsh','wlan','show','network']).decode('ascii').replace("\r","")
numOfWifiDevices = len(devices.split("SSID"))
# check to see the number of wifi networks we can connect to
if numOfWifiDevices:
for deviceNum in range(1, numOfWifiDevices):
entry = "Wifi Network: " + devices.split("SSID")[deviceNum].split(" ")[3]
self.portMenu.addItem(entry)
else:
self.portMenu.setCurrentText("NO DEVICE(S) FOUND")
def btnClkClock(self):
'''
"CLOCK" Button Event Handling
'''
# probably better to replace these with QDate class to reduce number of packages you have to import.
year = str(dt.datetime.now().year)
month = str(dt.datetime.now().month)
day = str(dt.datetime.now().day)
hour = str(datetime.now().hour)
minute = str(dt.datetime.now().minute)
seconds = str(dt.datetime.now().second)
# automatically update date and time log when button clicked
self.edit.dateYYYY = self.constr.edit(self.gridSess,year,[0,8,1,1])
self.edit.dateMM = self.constr.edit(self.gridSess,month,[0,9,1,1])
self.edit.dateDD = self.constr.edit(self.gridSess,day,[0,10,1,1])
self.edit.timeHH = self.constr.edit(self.gridSess,hour,[0,12,1,1])
self.edit.timeMM = self.constr.edit(self.gridSess,minute,[0,13,1,1])
self.edit.timeSS = self.constr.edit(self.gridSess,seconds,[0,14,1,1])
# I think this was meant to pull up exact date and time on a separate window for user to type in manually.
# This command below with os.system doesn't work. sudo command not recognized on windows.
# dateStr = self.edit.dateYYYY.text() + '-' + self.edit.dateMM.text() + '-' + self.edit.dateDD.text()
# timeStr = self.edit.timeHH.text() + ':' + self.edit.timeMM.text() + ':' + self.edit.timeSS.text()
# cmdStr = "sudo date -s"
# System command
# sudo date -s 'YYYY-MM-DD HH:MM:SS'
#os.system('cmdStr' + ' ' + '\'' + dateStr + ' ' + timeStr + '\'')
self.led.clock.setPixmap(self.ledClr.yellow)
def btnClkConn(self):
'''
"CONNECT" Button Event Handling. Attempts to connect to SRT Router and Serial
'''
if (self.state.connected):
self.logEvent("ERROR","ALREADY CONNECTED")
else:
# User input --> Port name & baud rate
text = str(self.portMenu.currentText())
text = text.split(' ')
self.port = text[0]
self.baud = int(str(self.baudMenu.currentText()))
if (self.port == "/dev/tty"):
self.logEvent("ERROR","INVALID PORT")
else:
if (self.port == "Wifi"):
try:
# Attempt to connect to router/ethernet over ubiquity
sock.connect(server_address)
self.ser = sock
# Set connected Status true, change LED, log connected status if connected to Ethernet
self.state.connected = True
self.logEvent("CONNECTED",self.port)
self.led.commConn.setPixmap(self.ledClr.yellow)
# must send a command initially for it to stay connected and read data over ethernet.
missionCMD = 'b'
missionCMD = bytes(missionCMD, 'utf-8')
sock.sendall(missionCMD)
# Thread handling
self.serThread = SerThread(self.ser)
self.serThread.outSig.connect(self.outUpdate)
self.serThread.stateSig.connect(self.stateUpdate)
self.serThread.dataSig.connect(self.dataUpdate)
self.serThread.resetSig.connect(self.readFail)
# Test for bypass condition
text = self.ser.recv(100)
if (len(text) > 0):
# Check for empty packet
self.state.reading = True
self.logEvent("READING",self.port)
self.led.commByp.setPixmap(self.ledClr.yellow)
self.serThread.start()
except (TimeoutError, OSError):
self.logEvent("ERROR","INVALID PORT")
else:
try:
# Attempt to connect to serial
self.ser = serial.Serial(self.port,self.baud,timeout=1)
self.state.connected = True
self.logEvent("CONNECTED",self.port)
self.led.commConn.setPixmap(self.ledClr.yellow)
# trying to send a command initially to see if that makes it easy to get connected.
missionCMD = 'b'
missionCMD = bytes(missionCMD, 'utf-8')
self.ser.write(missionCMD)
# Thread handling
self.serThread = SerThread(self.ser)
self.serThread.outSig.connect(self.outUpdate)
self.serThread.stateSig.connect(self.stateUpdate)
self.serThread.dataSig.connect(self.dataUpdate)
self.serThread.resetSig.connect(self.readFail)
# Test for bypass condition
text = self.ser.readline()
if (len(text) > 0):
# Check for empty packet
self.state.reading = True
self.logEvent("READING",self.port)
self.led.commByp.setPixmap(self.ledClr.yellow)
self.serThread.start()
except:
self.logEvent("ERROR","INVALID PORT")
def btnClkByp(self):
# haven't updated bypass method for ubiquity, just Xbee
'''
"BYPASS" Button Event Handling --> XBee (old) firmware quirk
'''
if (self.state.reading):
self.logEvent("ERROR","ALREADY READING")
elif (not self.state.connected):
self.logEvent("ERROR","NO CONNECTION")
else:
# enter, enter, (wait), 'b' --> bypass XBee dongle w/ ascii encoding
self.ser.write(b'\r\n\r\n')
time.sleep(2)
self.ser.write(b'b\r\n')
# Test for bypass condition
text = self.ser.readline()
if (len(text) > 0):
# Check for empty packet
self.state.reading = True
self.logEvent("READING",self.port)
self.led.commByp.setPixmap(self.ledClr.yellow)
self.serThread.start()
def btnClkRes(self):
'''
"RESET" Button Event Handling
'''
if (self.state.connected):
# This is discouraged but thread.quit() and thread.exit() don't work [brute force method]
self.serThread.terminate()
self.state.reading = False
self.led.commByp.setPixmap(self.ledClr.off)
self.ser.close()
self.state.connected = False
self.logEvent("DISCONNECTED",self.port)
self.led.commConn.setPixmap(self.ledClr.off)
# Reset all control status LEDs
ledName = list(self.led.__dict__)
for name in ledName:
if (name == "sess"): # Don't reset session LED
continue
else:
getattr(self.led,name).setPixmap(self.ledClr.off)
else:
self.logEvent("ERROR","NO CONNECTION")
def btnCtrlInit(self):
'''
Control Button Initialization
'''
rSp = 1 # Row span multiplier
cSp = 2 # Column span mutilplier
# Control button specification
# grid, name, text, comm, color, row, col, row span, col span
# System state
btnSpec = [( "gridSys", "sysArm", "SYS ARM", "btnClkCtrl", "sys", 0, 0, 1, 1),
( "gridSys", "sysDisarm", "SYS DISARM", "btnClkCtrl", "sys", 0, 1, 1, 1),
( "gridSys", "ready1", "READY 1", "btnClkCtrl", "abt", 1, 0, 1, 1),
( "gridSys", "ready2", "READY 2", "btnClkCtrl", "abt", 2, 0, 1, 1),
( "gridSys", "abort", "ABORT", "btnClkCtrl", "abt", 1, 1, 2, 1),
( "gridSys", "buzzOn", "BUZZ ON", "btnClkCtrl", "sys", 3, 0, 1, 1),
( "gridSys", "buzzOff", "BUZZ OFF", "btnClkCtrl", "sys", 3, 1, 1, 1),
# Data acquisition
( "gridDaq", "dataState", "DATA STATE", "btnClkCtrl", "daq", 0, 0, 1, 1),
( "gridDaq", "avPwrOff", "AV PWR OFF", "btnClkCtrl", "av", 0, 1, 1, 1),
( "gridDaq", "dataStart", "DATA START", "btnClkCtrl", "daq", 1, 0, 1, 1),
( "gridDaq", "dataStop", "DATA STOP", "btnClkCtrl", "daq", 1, 1, 1, 1),
# Fill control
( "gridFill", "supplyOpen", "SUPPLY OPEN", "btnClkCtrl", "n2o", 0, 0, 1, 1),
( "gridFill", "supplyClose", "SUPPLY CLOSE", "btnClkCtrl", "n2o", 0, 1, 1, 1),
( "gridFill", "supplyVtOpen", "SUPPLY VT OPEN", "btnClkCtrl", "n2o", 1, 0, 1, 1),
( "gridFill", "supplyVtClose", "SUPPLY VT CLOSE", "btnClkCtrl", "n2o", 1, 1, 1, 1),
( "gridFill", "runVtOpen", "RUN VT OPEN", "btnClkCtrl", "n2o", 2, 0, 1, 1),
( "gridFill", "runVtClose", "RUN VT CLOSE", "btnClkCtrl", "n2o", 2, 1, 1, 1),
( "gridFill", "motorOn", "MOTOR ON", "btnClkCtrl", "qd", 3, 0, 1, 1),
( "gridFill", "motorOff", "MOTOR OFF", "btnClkCtrl", "qd", 3, 1, 1, 1),
# Igniter control
( "gridIgn", "ignCont", "IGN CONT", "btnClkCtrl", "ign", 0, 0, 1, 2),
( "gridIgn", "ignArm", "IGN ARM", "btnClkCtrl", "ign", 1, 0, 1, 1),
( "gridIgn", "ignDisarm", "IGN DISARM", "btnClkCtrl", "ign", 1, 1, 1, 1),
( "gridIgn", "oxOpen", "OX OPEN", "btnClkCtrl", "o2", 2, 0, 1, 1),
( "gridIgn", "oxClose", "OX CLOSE", "btnClkCtrl", "o2", 2, 1, 1, 1),
( "gridIgn", "ignOn", "IGN ON", "btnClkCtrl", "ign", 3, 0, 1, 1),
( "gridIgn", "ignOff", "IGN OFF", "btnClkCtrl", "ign", 3, 1, 1, 1),
# Valve control
( "gridVal", "bvPwrOn", "BV PWR ON", "btnClkCtrl", "bvas", 0, 0, 1, 1),
( "gridVal", "bvPwrOff", "BV PWR OFF", "btnClkCtrl", "bvas", 0, 1, 1, 1),
( "gridVal", "bvOpen", "BV OPEN", "btnClkCtrl", "bvas", 1, 0, 1, 1),
( "gridVal", "bvClose", "BV CLOSE", "btnClkCtrl", "bvas", 1, 1, 1, 1),
( "gridVal", "bvState", "BV STATE", "btnClkCtrl", "bvas", 2, 0, 1, 1),
( "gridVal", "mdot", "MDOT", "btnClkCtrl", "mdot", 2, 1, 1, 1)]
for spec in btnSpec:
grid = getattr(self,spec[0])
name = spec[1]
text = spec[2]
method = spec[3]
color = getattr(self.color,spec[4])
row = spec[5]*rSp
col = spec[6]*cSp
rSpan = spec[7]*rSp
cSpan = spec[8]*cSp
# Construct button
btn = self.constr.button(grid,text,method,color,[row,col,rSpan,cSpan])
btn.comm = self.state.btnMap(name) # Find & set character command
btn.led = [] # Create empty list of associated LEDs
# Assign to container
setattr(self.btn,name,btn)
def btnClkCtrl(self):
'''
Control Button Event Handling
'''
sender = self.sender()
self.statusBar.sent.setText(sender.text()) # Update statusbar
self.logEvent(sender.text(),sender.comm)
# Trigger red LED state
if (self.state.connected):
for led in sender.led:
led.setPixmap(self.ledClr.red)
try:
comm = sender.comm.encode("ascii")
try:
self.ser.sendall(comm)
except:
self.ser.write(comm)
except:
if (self.state.connected):
self.logEvent("ERROR","WRITE FAIL")
else:
self.logEvent("ERROR","NO CONNECTION")
def btnClkSessRename(self):
if (self.state.log):
self.session = self.edit.session.text()
self.statusBar.session.setText(self.session)
else:
self.logEvent("ERROR","FILE IO")
def btnClkSessNew(self):
try:
# Close log & data files if initialized
self.closeLog()
# Update session name
self.session = self.edit.session.text()
self.statusBar.session.setText(self.session)
# Generate file date & time stamp(s)
dateLocal = QDate.currentDate()
dateStr = dateLocal.toString(Qt.ISODate)
startLocal = QTime.currentTime()
startStr = startLocal.toString("HH:mm:ss")
# Control & data log initialization
fileObj = ["logFile","dataFile"]
fileDir = ["./log/","./data/"]
fileExt = [".log",".dat"]
for i in range(len(fileObj)):
fileName = dateStr.replace('-','') + '_' + startStr.replace(':','') + fileExt[i]
if (not os.path.exists(fileDir[i])):
os.makedirs(fileDir[i])
setattr(self,fileObj[i],open(fileDir[i] + fileName,'w'))
self.state.log = True
self.led.sess.setPixmap(self.ledClr.yellow)
except:
self.logEvent("ERROR","FILE IO")
def ledCtrlInit(self):
'''
LED Inidicator Initialization
'''
rSp = 1 # Row span multiplier
cSp = 2 # Column span multiplier
# LED indicator specification
# grid, name, row, col, row Span, col Span, buttons ...
# System state
ledSpec = [( "gridSys", "sysArm", 0, 2, 1, 1, "sysArm", "sysDisarm"),
( "gridSys", "ready1", 1, 2, 1, 1, "ready1", "abort"),
( "gridSys", "ready2", 2, 2, 1, 1, "ready2", "abort"),
( "gridSys", "buzz", 3, 2, 1, 1, "buzzOn", "buzzOff"),
# Data acquisition
( "gridDaq", "avPwr", 0, 2, 1, 1, "avPwrOff"),
( "gridDaq", "data", 1, 2, 1, 1, "dataStart", "dataStop", "dataState"),
# Fill control
( "gridFill", "supply", 0, 2, 1, 1, "supplyOpen", "supplyClose"),
( "gridFill", "supplyVt", 1, 2, 1, 1, "supplyVtOpen", "supplyVtClose"),
( "gridFill", "runVt", 2, 2, 1, 1, "runVtOpen", "runVtClose"),
( "gridFill", "motor", 3, 2, 1, 1, "motorOn", "motorOff"),
# Igniter control
( "gridIgn", "ignCont", 0, 2, 1, 1, "ignCont"),
( "gridIgn", "ignArm", 1, 2, 1, 1, "ignArm", "ignDisarm"),
( "gridIgn", "ox", 2, 2, 1, 1, "oxOpen", "oxClose"),
( "gridIgn", "ign", 3, 2, 1, 1, "ignOn", "ignOff"),
# Valve control
( "gridVal", "bvPwr", 0, 2, 1, 1, "bvPwrOn", "bvPwrOff", "bvState", "mdot"),
( "gridVal", "bv", 1, 2, 1, 1, "bvOpen", "bvClose", "bvState", "mdot")]
for spec in ledSpec:
grid = getattr(self,spec[0])
name = spec[1]
row = spec[2]*rSp
col = spec[3]*cSp
rSpan = spec[4]*rSp
cSpan = spec[5]*cSp/2
btn = spec[6:]
# Construct LED
led = self.constr.led(grid,[row,col,rSpan,cSpan])
# Attach LEDs to associated buttons
for btnName in btn:
getattr(self.btn,btnName).led.append(led)
# Assign to container
setattr(self.led,name,led)
def dataInit(self):
'''
Data Array & Sensor Readout Initialization
'''
# Data storage initialization
# time stamp, run tank press, chamber press, run tank temp, chamber temp, aux temp
self.dataTime = 1*60 # Data array length (sec)
self.dataName = ["st","pt","pc","tt","tc","ta"]
self.dataDict = {}
for name in self.dataName:
# looks like it sets dataDict[st], dataDict[pt], ... and so on to none in initialization
setattr(self.data,name,np.array([]))
self.dataDict[name] = None
# Sensor readout specification
# name, text, unit, code, row, col, row span, col span
# Pressure column
sensorSpec = [( "pRun", "Press\nRun", "[ psi ]", "pt", 0, 0, 2, 1, 1),
( "pRun30s", "Extrap\n30 sec", "[ psi ]", "pt", 30, 1, 2, 1, 1),
( "pRun1m", "Extrap\n1 min", "[ psi ]", "pt", 1*60, 2, 2, 1, 1),
( "pRun5m", "Extrap\n5 min", "[ psi ]", "pt", 5*60, 3, 2, 1, 1),
( "pChamb", "Press\nChamb", "[ psi ]", "pc", 0, 4, 2, 1, 1),
# Temperature column
( "tRun", "Temp\nRun", "[ °F ]", "tt", 0, 0, 6, 1, 1),
( "tRun30s", "Extrap\n30 sec", "[ °F ]", "tt", 30, 1, 6, 1, 1),
( "tRun1m", "Extrap\n1 min", "[ °F ]", "tt", 1*60, 2, 6, 1, 1),
( "tRun5m", "Extrap\n5 min", "[ °F ]", "tt", 5*60, 3, 6, 1, 1),
( "pRunVap", "Press\nVapor", "[ psi ]", "tt", 0, 4, 6, 1, 1)]
for spec in sensorSpec:
name = spec[0]
text = spec[1]
unit = spec[2]
code = spec[3]
extrap = spec[4]
row = spec[5]
col = spec[6]
rSpan = spec[7]
cSpan = spec[8]
# Construct sensor & assign to container
sensor = self.constr.readout(self.gridPlot,"sensor",[row,col,rSpan,cSpan])
sensor.code = code # Data code
sensor.extrap = extrap # Forward extrapolation time
# Assign to container
setattr(self.sensor,name,sensor)
# Sensor text & unit labels
self.constr.label(self.gridPlot,"label",text,"Center",[row,col-1,1,1])
self.constr.label(self.gridPlot,"label",unit,"Center",[row,col+1,1,1])
# Generate sensor list
self.sensorName = list(self.sensor.__dict__)
# Row & column stretching in plotGrid
rowStr = []
colStr = [8, 1, 1, 1, 8, 1, 1, 1]
self.tools.resize(self.gridPlot,rowStr,colStr)
def plotInit(self):
'''
Live Plot Initialization
'''
self.plot = [None] * 2
# Pressure plot
yRange = [0,950]
xLabel = ["Time","sec"]
yLabel = ["Run Tank Pressure","psi"]
hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [400,432,434,432,433,431,429,432,435,445]
self.plot[0] = self.constr.plot(self.gridPlot,yRange,xLabel,yLabel,[0,0,5,1])
self.plotPress = self.plot[0].plot()
# Temperature plot
yRange = [0,150]
xLabel = ["Time","sec"]
yLabel = ["Run Tank Temperature","°F"]
hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [100,90,80,90,90,90,100,100,100,100]
self.plot[1] = self.constr.plot(self.gridPlot,yRange,xLabel,yLabel,[0,4,5,1])
self.plotTemp = self.plot[1].plot()
def outInit(self):
# Create scroll box for raw serial output
self.serialOut = self.constr.scrollBox(self.gridOut,[0,0,1,1])
def outUpdate(self,text):
self.serialOut.moveCursor(QtGui.QTextCursor.End)
self.serialOut.insertPlainText(text + "\n")
sb = self.serialOut.verticalScrollBar()
sb.setValue(sb.maximum())
def stateUpdate(self,text):
'''
Control State Update
'''
# Update statusbar
self.statusBar.recieved.setText(text)
try:
# Logs state event, update state object, update PID graphic (eventually)
self.logEvent("STATE",text)
# QUICK FIX FOR ABORT STATE
if (text == "xLBabo"):
self.state.update("xLBrl10")
self.state.update("xLBrl20")
else:
self.state.update(text)
except:
self.logEvent("ERROR","STATE FAIL")
def dataUpdate(self,text):
print("gets here, right?")
'''
Plot & Sensor Update
'''
try:
# Write to data log
if self.state.log:
self.dataFile.write(text + '\n')
print("writing")
# Process data packet
raw = text.split(',')
nEnd = len(self.data.st)
print(raw, nEnd)
# Update dictionary --> maps code to reading
for field in raw:
self.dataDict[field[0:2]] = field[2:]
# Convert time stamps to elapsed from AV start (first packet)
if (self.state.data):
stamp = self.dataDict["st"]
nowData = datetime.strptime(stamp,"%H:%M:%S.%f")
delta = nowData - self.startData
elapsed = delta.total_seconds()
self.dataDict["st"] = elapsed
else:
stamp = self.dataDict["st"]
self.startData = datetime.strptime(stamp,"%H:%M:%S.%f")
self.state.data = True
self.dataDict["st"] = 0
# Establish extrapolation time step
if (len(self.data.st) < 2):
step = 1 # Arbitrary value; can't be zero
else:
step = self.data.st[-1] - self.data.st[-2]
nData = np.floor(self.dataTime/step)
# Populate data arrays: after filling array, delete first element & append to end
if (nEnd < nData): # Case: array not full
for name in self.dataName:
value = float(self.dataDict[name])
setattr(self.data,name,np.append(getattr(self.data,name),value))
else: # Case: array full
for name in self.dataName:
value = float(self.dataDict[name])
getattr(self.data,name,np.roll(getattr(self.data,name),-1))
getattr(self.data,name)[-1] = value
# Sensor readout update
for name in self.sensorName:
sensor = getattr(self.sensor,name)
data = getattr(self.data,sensor.code)
value = self.tools.extrap(self.data.st,data,sensor.extrap,step)
if (name == "pRunVap"): # Vapor pressure from run tank temp
value = self.tools.vapPress(value)
sensor.setText(str(round(value,2)))
# Live plot update
#xTime = self.data.st - self.data.st[-1] # Center time scale at present reading
xTime = [1,2,3,4,5,6,7,8,9,10]
yPress = [400,432,434,432,433,431,429,432,435,445]
print(xTime)
print("YPress:")
print(yPress)
#yPress = self.data.pt # Tank pressure array
yTemp = self.data.tt # Tank temperature array
print("yTemp:")
print(yTemp)
self.plotPress.setData(xTime,yPress,pen=self.style.pen.press)
self.plotTemp.setData(xTime,yTemp,pen=self.style.pen.temp)
except:
# Throws error if failure to read data packet
self.logEvent("ERROR","DAQ FAIL")
if (self.state.log):
self.dataFile.write("ERROR: " + text + '\n')
def readFail(self,text):
'''
Log Read Fail & Reset Connection
'''
self.btnClkRes()
self.logEvent("ERROR",text)
def logEvent(self,event,text):
'''
Log Event Management
'''
# Build, print stamp to statusbar & log
now = QTime.currentTime()
stamp = now.toString("HH:mm:ss.zzz")
pad = ' ' * 5
# Print to statusbar, format if necessary
self.statusBar.log.setText(stamp + pad + event + pad + "\"" + text + "\"")
if (event == "ERROR"):
self.statusBar.log.setStyleSheet(self.style.css.error)
else:
self.statusBar.log.setStyleSheet(self.style.css.statusBar)
# Print to log file
if (self.state.log):
self.logFile.write(stamp + ", " + event + ", " + "\"" + text + "\"" + "\n")
def closeLog(self):
'''
File Close Management
'''
if (self.state.log):
self.state.log = False # Protects thread issues; writing to closed file
fileObj = ["logFile","dataFile"]
for logName in fileObj:
# Close & rename file(s)
filePath = getattr(self,logName).name.split('/')
filePath[2] = self.session + '_' + filePath[2]
filePath = '/'.join(filePath)
getattr(self,logName).close()
os.rename(getattr(self,logName).name,filePath)
def closeEvent(self,event):
'''
GUI Exit Management
'''
# Close log & data files if initialized
self.closeLog()
# Exit GUI safely
event.accept()
if (__name__ == '__main__'):
'''
Executive Control
'''
app = QApplication(sys.argv) # Utility for window exit condition
gui = Gui() # Creates instance of "Gui" class
sys.exit(app.exec_()) # Window exit condition
| 39.530721
| 193
| 0.493974
| 4,647
| 44,393
| 4.686034
| 0.186142
| 0.013685
| 0.005786
| 0.003123
| 0.238933
| 0.197144
| 0.13919
| 0.116504
| 0.104197
| 0.096115
| 0
| 0.032256
| 0.375667
| 44,393
| 1,123
| 194
| 39.530721
| 0.753247
| 0.182799
| 0
| 0.217886
| 0
| 0
| 0.109502
| 0.002438
| 0.001626
| 0
| 0
| 0
| 0
| 1
| 0.042276
| false
| 0.001626
| 0.030894
| 0
| 0.074797
| 0.013008
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e11508b726f072695da36af59f196eefb588d2a7
| 1,359
|
py
|
Python
|
setup.py
|
charettes/cricket
|
ed3ef911e0776e225291a370220f0d9476afdd4e
|
[
"BSD-3-Clause"
] | 1
|
2015-11-06T07:51:04.000Z
|
2015-11-06T07:51:04.000Z
|
setup.py
|
charettes/cricket
|
ed3ef911e0776e225291a370220f0d9476afdd4e
|
[
"BSD-3-Clause"
] | null | null | null |
setup.py
|
charettes/cricket
|
ed3ef911e0776e225291a370220f0d9476afdd4e
|
[
"BSD-3-Clause"
] | null | null | null |
#/usr/bin/env python
import sys
from setuptools import setup
from cricket import VERSION
try:
readme = open('README.rst')
long_description = str(readme.read())
finally:
readme.close()
required_pkgs = [
'tkreadonly',
]
if sys.version_info < (2, 7):
required_pkgs.extend(['argparse', 'unittest2', 'pyttk'])
setup(
name='cricket',
version=VERSION,
description='A graphical tool to assist running test suites.',
long_description=long_description,
author='Russell Keith-Magee',
author_email='russell@keith-magee.com',
url='http://pybee.org/cricket',
packages=[
'cricket',
'cricket.django',
'cricket.unittest',
],
install_requires=required_pkgs,
scripts=[],
entry_points={
'console_scripts': [
'cricket-django = cricket.django.__main__:main',
'cricket-unittest = cricket.unittest.__main__:main',
]
},
license='New BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Software Development',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
],
test_suite='tests'
)
| 25.641509
| 66
| 0.61663
| 138
| 1,359
| 5.927536
| 0.623188
| 0.055012
| 0.041565
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.004883
| 0.246505
| 1,359
| 52
| 67
| 26.134615
| 0.793945
| 0.013981
| 0
| 0.042553
| 0
| 0
| 0.429425
| 0.060493
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.06383
| 0
| 0.06383
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e117f67f0c631749e3bd721fb7eedb16a22bb6f3
| 2,701
|
py
|
Python
|
experimentation/tools/sorald/legacy/violation_scraper_apache_commons.py
|
gothius/sorald
|
4c8761da495e528389c033660fae1f3c3a18cac3
|
[
"MIT"
] | 49
|
2020-06-04T20:30:20.000Z
|
2022-03-16T01:30:20.000Z
|
experimentation/tools/sorald/legacy/violation_scraper_apache_commons.py
|
gothius/sorald
|
4c8761da495e528389c033660fae1f3c3a18cac3
|
[
"MIT"
] | 551
|
2020-06-02T13:33:56.000Z
|
2022-03-31T15:58:17.000Z
|
experimentation/tools/sorald/legacy/violation_scraper_apache_commons.py
|
gothius/sorald
|
4c8761da495e528389c033660fae1f3c3a18cac3
|
[
"MIT"
] | 12
|
2020-06-04T11:39:43.000Z
|
2022-03-27T20:04:30.000Z
|
import requests;
import json;
from collections import Counter # Counts and orders the list of violations
import sys;
from urllib.parse import quote_plus # Make sysarg url-safe
# List of Apache Commons libraries which I know can be analyzed (without crashing/failing their tests)
commonsList = ["bcel",
"beanutils",
"cli",
"codec",
"collections",
"compress",
"configuration",
"crypto",
"csv",
"daemon",
"dbcp",
"dbutils",
"exec",
"fileupload",
"geometry",
"imaging",
"io",
"jexl",
"lang",
"logging",
"math",
"net",
"ognl",
"pool",
"scxml",
"statistics",
"text",
"validator",
"vfs"];
# Number of issues per page (Max 500)
pageSize = 500;
def set_cmd_values():
# Url to SQ instance (overwritten by cmd arguments).
url = "http://127.0.0.1:9000/";
# If a SQ instance with multiple projects is specified (such as OW2 containing Spoon-Core), the specific project can be chosen (overwritten by cmd args).
project_key= "";
if(len(sys.argv) > 1):
url = sys.argv[1];
if(not url.endswith("/")):
url += "/";
if(len(sys.argv) > 2):
project_key = quote_plus(sys.argv[2]);
return (url, project_key);
# Fill array with SQ violations. Keep making calls until all (up to 10000 since SQ doesn't support more) issues have been caught.
def get_violations(url, project_key):
violated_rules = [];
for lib in commonsList:
violations_remaining = True;
pageIndex = 1;
project_key = "commons-" + lib;
while(violations_remaining):
request_string = url + 'api/issues/search?resolved=false';
if (not project_key == ""):
request_string += '&componentKeys=' + project_key;
request_string += '&ps=' + str(pageSize) + '&pageIndex=' + str(pageIndex);
request = requests.get(request_string);
if(request.status_code == 200):
request_json = request.json();
issues = request_json['issues'];
if(len(issues) == 0):
violations_remaining = False;
for issue in issues:
if(issue['type'] == "BUG"):
violated_rules.append(issue['rule']);
pageIndex += 1;
return violated_rules;
# Pretty prints a list, printing every object on its own line
def pretty_print(listVar):
f = open("ordered_violations_list.txt", "w");
for obj in listVar:
print(obj);
f.write(convertTuple(obj));
def convertTuple(tup):
string = tup[0] + ", " + str(tup[1]) + "\n";
return string;
def main():
init_values = set_cmd_values();
ordered_violations = (Counter(get_violations(init_values[0], init_values[1])).most_common());
pretty_print(ordered_violations);
if __name__ == "__main__":
main();
| 28.734043
| 157
| 0.640133
| 345
| 2,701
| 4.878261
| 0.524638
| 0.041592
| 0.01426
| 0.01426
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.017013
| 0.216586
| 2,701
| 93
| 158
| 29.043011
| 0.778355
| 0.218067
| 0
| 0
| 0
| 0
| 0.153115
| 0.028055
| 0
| 0
| 0
| 0
| 0
| 1
| 0.061728
| false
| 0
| 0.061728
| 0
| 0.160494
| 0.037037
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e11b19ef6b4d98bab620857b523abf42ea96c9a9
| 8,782
|
py
|
Python
|
train.py
|
genisplaja/tf-diffwave
|
32b0b403e7ca157f015f9af9f7dcdfa79e312a6a
|
[
"MIT"
] | 23
|
2020-09-29T08:38:09.000Z
|
2022-03-16T03:00:44.000Z
|
train.py
|
genisplaja/tf-diffwave
|
32b0b403e7ca157f015f9af9f7dcdfa79e312a6a
|
[
"MIT"
] | 1
|
2020-10-03T08:36:48.000Z
|
2020-10-03T08:36:48.000Z
|
train.py
|
genisplaja/tf-diffwave
|
32b0b403e7ca157f015f9af9f7dcdfa79e312a6a
|
[
"MIT"
] | 7
|
2020-09-29T19:11:53.000Z
|
2022-01-06T14:29:21.000Z
|
import argparse
import json
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tqdm
from config import Config
from dataset import LJSpeech
from model import DiffWave
class Trainer:
"""WaveGrad trainer.
"""
def __init__(self, model, lj, config):
"""Initializer.
Args:
model: DiffWave, diffwave model.
lj: LJSpeech, LJ-speec dataset
which provides already batched and normalized speech dataset.
config: Config, unified configurations.
"""
self.model = model
self.lj = lj
self.config = config
self.split = config.train.split // config.data.batch
self.trainset = self.lj.dataset().take(self.split) \
.shuffle(config.train.bufsiz) \
.prefetch(tf.data.experimental.AUTOTUNE)
self.testset = self.lj.dataset().skip(self.split) \
.prefetch(tf.data.experimental.AUTOTUNE)
self.optim = tf.keras.optimizers.Adam(
config.train.lr(),
config.train.beta1,
config.train.beta2,
config.train.eps)
self.eval_intval = config.train.eval_intval // config.data.batch
self.ckpt_intval = config.train.ckpt_intval // config.data.batch
self.train_log = tf.summary.create_file_writer(
os.path.join(config.train.log, config.train.name, 'train'))
self.test_log = tf.summary.create_file_writer(
os.path.join(config.train.log, config.train.name, 'test'))
self.ckpt_path = os.path.join(
config.train.ckpt, config.train.name, config.train.name)
self.alpha_bar = np.cumprod(1 - config.model.beta())
self.cmap = tf.constant(plt.get_cmap('viridis').colors, dtype=tf.float32)
def compute_loss(self, signal, logmel):
"""Compute loss for noise estimation.
Args:
signal: tf.Tensor, [B, T], raw audio signal segment.
logmel: tf.Tensor, [B, T // hop, mel], mel-spectrogram.
Returns:
loss: tf.Tensor, [], L1-loss between noise and estimation.
"""
# [B]
bsize = tf.shape(signal)[0]
# [B]
timesteps = tf.random.uniform(
[bsize], 1, self.config.model.iter + 1, dtype=tf.int32)
# [B]
noise_level = tf.gather(self.alpha_bar, timesteps - 1)
# [B, T], [B, T]
noised, noise = self.model.diffusion(signal, noise_level)
# [B, T]
eps = self.model.pred_noise(noised, timesteps, logmel)
# []
loss = tf.reduce_mean(tf.abs(eps - noise))
return loss
def train(self, step=0, ir_unit=5):
"""Train wavegrad.
Args:
step: int, starting step.
ir_unit: int, log ir units.
"""
for _ in tqdm.trange(step // self.split, self.config.train.epoch):
with tqdm.tqdm(total=self.split, leave=False) as pbar:
for signal, logmel in self.trainset:
with tf.GradientTape() as tape:
tape.watch(self.model.trainable_variables)
loss = self.compute_loss(signal, logmel)
grad = tape.gradient(loss, self.model.trainable_variables)
self.optim.apply_gradients(
zip(grad, self.model.trainable_variables))
norm = tf.reduce_mean([tf.norm(g) for g in grad])
del grad
step += 1
pbar.update()
pbar.set_postfix(
{'loss': loss.numpy().item(),
'step': step,
'grad': norm.numpy().item()})
with self.train_log.as_default():
tf.summary.scalar('loss', loss, step)
tf.summary.scalar('grad norm', norm, step)
if step % self.eval_intval == 0:
pred, _ = self.model(logmel)
tf.summary.audio(
'train', pred[..., None], self.config.data.sr, step)
tf.summary.image(
'train mel', self.mel_img(pred), step)
del pred
if step % self.ckpt_intval == 0:
self.model.write(
'{}_{}.ckpt'.format(self.ckpt_path, step),
self.optim)
loss = [
self.compute_loss(signal, logmel).numpy().item()
for signal, logmel in self.testset
]
loss = sum(loss) / len(loss)
with self.test_log.as_default():
tf.summary.scalar('loss', loss, step)
gt, pred, ir = self.eval()
tf.summary.audio(
'gt', gt[None, :, None], self.config.data.sr, step)
tf.summary.audio(
'eval', pred[None, :, None], self.config.data.sr, step)
tf.summary.image(
'gt mel', self.mel_img(gt[None]), step)
tf.summary.image(
'eval mel', self.mel_img(pred[None]), step)
for i in range(0, len(ir), ir_unit):
tf.summary.audio(
'ir_{}'.format(i),
np.clip(ir[i][None, :, None], -1., 1.),
self.config.data.sr, step)
del gt, pred, ir
def mel_img(self, signal):
"""Generate mel-spectrogram images.
Args:
signal: tf.Tensor, [B, T], speech signal.
Returns:
tf.Tensor, [B, mel, T // hop, 3], mel-spectrogram in viridis color map.
"""
# [B, T // hop, mel]
_, mel = self.lj.mel_fn(signal)
# [B, mel, T // hop]
mel = tf.transpose(mel, [0, 2, 1])
# minmax norm in range(0, 1)
mel = (mel - tf.reduce_min(mel)) / (tf.reduce_max(mel) - tf.reduce_min(mel))
# in range(0, 255)
mel = tf.cast(mel * 255, tf.int32)
# [B, mel, T // hop, 3]
mel = tf.gather(self.cmap, mel)
# make origin lower
mel = tf.image.flip_up_down(mel)
return mel
def eval(self):
"""Generate evaluation purpose audio.
Returns:
speech: np.ndarray, [T], ground truth.
pred: np.ndarray, [T], predicted.
ir: List[np.ndarray], config.model.iter x [T],
intermediate represnetations.
"""
# [T]
speech = next(iter(lj.rawset))
# [1, T // hop, mel]
_, logmel = lj.mel_fn(speech[None])
# [1, T], iter x [1, T]
pred, ir = self.model(logmel)
# [T]
pred = tf.squeeze(pred, axis=0).numpy()
# config.model.iter x [T]
ir = [np.squeeze(i, axis=0) for i in ir]
return speech.numpy(), pred, ir
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--config', default=None)
parser.add_argument('--load-step', default=0, type=int)
parser.add_argument('--ir-unit', default=10, type=int)
parser.add_argument('--data-dir', default=None)
parser.add_argument('--download', default=False, action='store_true')
parser.add_argument('--from-raw', default=False, action='store_true')
args = parser.parse_args()
config = Config()
if args.config is not None:
print('[*] load config: ' + args.config)
with open(args.config) as f:
config = Config.load(json.load(f))
log_path = os.path.join(config.train.log, config.train.name)
if not os.path.exists(log_path):
os.makedirs(log_path)
ckpt_path = os.path.join(config.train.ckpt, config.train.name)
if not os.path.exists(ckpt_path):
os.makedirs(ckpt_path)
lj = LJSpeech(config.data, args.data_dir, args.download, not args.from_raw)
diffwave = DiffWave(config.model)
trainer = Trainer(diffwave, lj, config)
if args.load_step > 0:
super_path = os.path.join(config.train.ckpt, config.train.name)
ckpt_path = '{}_{}.ckpt'.format(config.train.name, args.load_step)
ckpt_path = next(
name for name in os.listdir(super_path)
if name.startswith(ckpt_path) and name.endswith('.index'))
ckpt_path = os.path.join(super_path, ckpt_path[:-6])
print('[*] load checkpoint: ' + ckpt_path)
trainer.model.restore(ckpt_path, trainer.optim)
with open(os.path.join(config.train.ckpt, config.train.name + '.json'), 'w') as f:
json.dump(config.dump(), f)
trainer.train(args.load_step, args.ir_unit)
| 37.370213
| 86
| 0.535186
| 1,060
| 8,782
| 4.341509
| 0.216981
| 0.059757
| 0.029335
| 0.024337
| 0.260756
| 0.17123
| 0.126467
| 0.126467
| 0.119079
| 0.059539
| 0
| 0.007885
| 0.335687
| 8,782
| 234
| 87
| 37.529915
| 0.780939
| 0.131861
| 0
| 0.073826
| 0
| 0
| 0.032626
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.033557
| false
| 0
| 0.067114
| 0
| 0.127517
| 0.013423
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1215b8a95ad1e693c4f500b1993173740393e02
| 14,101
|
py
|
Python
|
cogs/fun.py
|
Der-Eddy/discord_bot
|
bc2511e6d030ee2e099410bd846ea871fe3f109d
|
[
"MIT"
] | 122
|
2016-08-05T02:27:31.000Z
|
2022-03-21T07:53:10.000Z
|
cogs/fun.py
|
Der-Eddy/discord_bot
|
bc2511e6d030ee2e099410bd846ea871fe3f109d
|
[
"MIT"
] | 15
|
2017-12-07T14:28:20.000Z
|
2021-11-19T13:03:37.000Z
|
cogs/fun.py
|
Der-Eddy/discord_bot
|
bc2511e6d030ee2e099410bd846ea871fe3f109d
|
[
"MIT"
] | 100
|
2016-08-21T18:12:29.000Z
|
2022-02-19T11:21:23.000Z
|
import random
import urllib.parse
import sqlite3
import asyncio
import aiohttp
import discord
from discord.ext import commands
import loadconfig
class fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_command_error(self, ctx, error):
print('Error in {0.command.qualified_name}: {1}'.format(ctx, error))
def userOnline(self, memberList):
online = []
for i in memberList:
if i.status == discord.Status.online and i.bot == False:
online.append(i)
return online
@commands.command(aliases=['javascript', 'nodejs', 'js'])
async def java(self, ctx):
'''Weil Java != Javscript'''
await ctx.send(':interrobang: Meintest du jQuery, Javascript oder Node.js? https://abload.de/img/2016-05-102130191kzpu.png')
@commands.command(aliases=['c++', 'c#', 'objective-c'])
async def csharp(self, ctx):
'''Wie soll man da überhaupt durchblicken???'''
await ctx.send(':interrobang: Meintest du C, C++, C# oder Objective-C? https://i.imgur.com/Nd4aAXO.png')
@commands.command()
async def praise(self, ctx):
'''Praise the Sun'''
await ctx.send('https://i.imgur.com/K8ySn3e.gif')
@commands.command()
async def css(self, ctx):
'''Counter Strike: Source'''
await ctx.send('http://i.imgur.com/TgPKFTz.gif')
@commands.command()
async def countdown(self, ctx):
'''It's the final countdown'''
countdown = ['five', 'four', 'three', 'two', 'one']
for num in countdown:
await ctx.send('**:{0}:**'.format(num))
await asyncio.sleep(1)
await ctx.send('**:ok:** DING DING DING')
@commands.command(aliases=['cat', 'randomcat'])
async def neko(self, ctx):
'''Zufällige Katzen Bilder nyan~'''
#http://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
async with aiohttp.ClientSession() as cs:
async with cs.get('http://aws.random.cat/meow') as r:
res = await r.json()
emojis = [':cat2: ', ':cat: ', ':heart_eyes_cat: ']
await ctx.send(random.choice(emojis) + res['file'])
@commands.command(aliases=['rand'])
async def random(self, ctx, *arg):
'''Gibt eine zufällige Zahl oder Member aus
Benutzung:
-----------
:random
Gibt eine zufällige Zahl zwischen 1 und 100 aus
:random coin
Wirft eine Münze (Kopf oder Zahl)
:random 6
Gibt eine zufällige Zahl zwischen 1 und 6 aus
:random 10 20
Gibt eine zufällige Zahl zwischen 10 und 20 aus
:random user
Gibt einen zufällige Benutzer der gerade online ist aus
:random choice Dani Eddy Shinobu
Wählt aus der vorgegebenen Liste einen Namen aus
'''
if ctx.invoked_subcommand is None:
if not arg:
start = 1
end = 100
elif arg[0] == 'flip' or arg[0] == 'coin':
coin = ['Kopf', 'Zahl']
await ctx.send(f':arrows_counterclockwise: {random.choice(coin)}')
return
elif arg[0] == 'choice':
choices = list(arg)
choices.pop(0)
await ctx.send(f':congratulations: The winner is {random.choice(choices)}')
return
elif arg[0] == 'user':
online = self.userOnline(ctx.guild.members)
randomuser = random.choice(online)
if ctx.channel.permissions_for(ctx.author).mention_everyone:
user = randomuser.mention
else:
user = randomuser.display_name
await ctx.send(f':congratulations: The winner is {user}')
return
elif len(arg) == 1:
start = 1
end = int(arg[0])
elif len(arg) == 2:
start = int(arg[0])
end = int(arg[1])
await ctx.send(f'**:arrows_counterclockwise:** Zufällige Zahl ({start} - {end}): {random.randint(start, end)}')
@commands.command()
async def steinigt(self, ctx, member:str):
'''Monty Python'''
await ctx.send(f'R.I.P. {member}\nhttps://media.giphy.com/media/l41lGAcThnMc29u2Q/giphy.gif')
@commands.command(aliases=['hypu', 'train'])
async def hype(self, ctx):
'''HYPE TRAIN CHOO CHOO'''
hypu = ['https://cdn.discordapp.com/attachments/102817255661772800/219514281136357376/tumblr_nr6ndeEpus1u21ng6o1_540.gif',
'https://cdn.discordapp.com/attachments/102817255661772800/219518372839161859/tumblr_n1h2afSbCu1ttmhgqo1_500.gif',
'https://gfycat.com/HairyFloweryBarebirdbat',
'https://i.imgur.com/PFAQSLA.gif',
'https://abload.de/img/ezgif-32008219442iq0i.gif',
'https://i.imgur.com/vOVwq5o.jpg',
'https://i.imgur.com/Ki12X4j.jpg',
'https://media.giphy.com/media/b1o4elYH8Tqjm/giphy.gif']
msg = f':train2: CHOO CHOO {random.choice(hypu)}'
await ctx.send(msg)
@commands.command()
async def xkcd(self, ctx, *searchterm: str):
'''Zeigt den letzten oder zufälligen XKCD Comic
Beispiel:
-----------
:xkcd
:xkcd random
'''
apiUrl = 'https://xkcd.com{}info.0.json'
async with aiohttp.ClientSession() as cs:
async with cs.get(apiUrl.format('/')) as r:
js = await r.json()
if ''.join(searchterm) == 'random':
randomComic = random.randint(0, js['num'])
async with cs.get(apiUrl.format('/' + str(randomComic) + '/')) as r:
if r.status == 200:
js = await r.json()
comicUrl = 'https://xkcd.com/{}/'.format(js['num'])
date = '{}.{}.{}'.format(js['day'], js['month'], js['year'])
msg = '**{}**\n{}\nAlt Text:```{}```XKCD Link: <{}> ({})'.format(js['safe_title'], js['img'], js['alt'], comicUrl, date)
await ctx.send(msg)
@commands.command(aliases=['witz', 'joke'])
async def pun(self, ctx):
'''Weil jeder schlechte Witze mag'''
#ToDo: Add some way to fetch https://github.com/derphilipp/Flachwitze
puns = ['Was sagt das eine Streichholz zum anderen Streichholz?\n Komm, lass uns durchbrennen',
'Wieviele Deutsche braucht man um eine Glühbirne zu wechseln?\n Einen, wir sind humorlos und effizient.',
'Wo wohnt die Katze?\n Im Miezhaus.',
'Wie begrüßen sich zwei plastische Chirurgen?\n "Was machst du denn heute für ein Gesicht?"',
'Warum essen Veganer kein Huhn?\n Könnte Ei enthalten',
'85% der Frauen finden ihren Arsch zu dick, 10% zu dünn, 5% finden ihn so ok, wie er ist und sind froh, dass sie ihn geheiratet haben...',
'Meine Freundin meint, ich wär neugierig...\n...zumindest\' steht das in ihrem Tagebuch.',
'"Schatz, Ich muss mein T-Shirt waschen! Welches Waschmaschinen Programm soll ich nehmen?" - "Was steht denn auf dem T-Shirt drauf?"\n "Slayer!"',
'Gestern erzählte ich meinem Freund, dass ich schon immer dieses Ding aus Harry Potter reiten wollte.\n"einen Besen?" "nein, Hermine."',
'Warum gehen Ameisen nicht in die Kirche?\nSie sind in Sekten.',
'Was steht auf dem Grabstein eines Mathematikers?\n"Damit hat er nicht gerechnet."',
'Wenn ein Yogalehrer seine Beine senkrecht nach oben streckt und dabei furzt, welche Yoga Figur stellt er da?\n Eine Duftkerze',
'Warum ging der Luftballon kaputt?\n Aus Platzgründen.',
'Ich wollte Spiderman anrufen, aber er hatte kein Netz und beim Bäcker war alles belegt.',
'Was vermisst eine Schraube am meisten? Einen Vater',
'Geht ein Panda über die Straße. Bam....Bus!',
'Unterhalten sich zwei Gletscher. Sagt der eine: "Was meinst du, was wird die Zukunft bringen?" Sagt der Andere: "Naja, wir werden Seen."',
'Wenn sich ein Professor ein Brot macht ist das dann wissenschaftlich belegt?',
'Knabbern zwei Männern an einer Eisenbahnschiene. Sagt der eine: "Ganz schön hart, oder?"\nSagt der andere: "Aber guck mal, da drübern ist ne Weiche"',
'Warum sind bei IKEA Pfeile auf dem Boden?\nWeil es ein Einrichtungshaus ist',
'Was macht die Security in der Nudelfabrik?\nDie Pasta auf.',
'Wie nennt man einen kleinwüchsigen Securitymenschen?\nSicherheitshalber',
'Habe bei Weight Watchers angerufen. Hat keiner abgenommen.\nDanach beim DJ. Hat aber aufgelegt.'
'Meine Schwester hat eine Tochter bekommen.\nDa wurde mein Wunsch nach einem Neffen zur Nichte gemacht.',
'Praktizieren sie Inzest?\n"Mitnichten"',
'Wann sinkt ein U-Boot?\nAm Tag der offenen Tür.',
'Auf St. Pauli wurde letztens ein Sarg gefunden. Er konnte aber nicht geöffnet werden, war ein Zuhälter drin!',
'Treffen sich zwei Anwälte. Fragt der eine "Na, wie geht\'s?" Antwortet der andere "Schlecht. Ich kann nicht klagen"',
'Treffen sich zwei Jäger. Beide tot.',
'Treffen sich zwei Päpste.',
'Treffen sich zwei Psychologen, sagt der eine: "Dir geht\'s gut, wie geht\'s mir?"',
'Treffen sich zwei Linksextreme in einer Bar, kommen drei Splittergruppen raus.',
'Was macht man mit nem Hund ohne Beine?\nUm die Häuser ziehen.',
'Wo findest du nen Hund ohne Beine?\nDa wo du ihn liegen lassen hast.',
'Was macht eine Bombe im Bordell?\nPuff',
'Und was macht eine Bombe im Treppenhaus?\nHochgehen',
'Wo war Lucy nach der Explosion?\nÜberall',
'Egal, wie dicht du bist. Göthe war dichter!',
'Egal, wie gut du fährst. Züge fahren Güter!',
'Egal, wie sauer du bist, Dinos sind Saurier!',
'Egal, wie leer du bist, es gibt Menschen die sind Lehrer.',
'Wissenschaftler haben herausgefunden\nund sind dann wieder reingegangen.',
'Was ist klein, braun, rund und sitzt hinter Gittern? Eine Knastanie.',
'Was liegt am Strand und kann nicht richtig reden? - Eine Nuschel!',
'Was ist grün und klopft an die Tür? - Klopfsalat',
'Was ist rot und steht am Straßenrand? Eine Hagenutte',
'Und was ist blau und steht am Wegesrand? Eine Frostituierte',
'Was ist rosa und schwimmt durchs Meer? Eine Meerjungsau.',
'Was ist braun und schwimmt auch im Meer? Ein U-Brot.',
'Was raucht und springt durch den Wald? Ein Kaminchen.',
'Was machen Bits am liebsten? Busfahren.',
'Warum ist der Programmierer in der Dusche gestorben? Auf der Flasche stand “einschäumen, ausspülen, wiederholen"',
'Wo gehen Datenspeicher hin, wenn sie sich prügeln wollen? In den Byte Club.\n Und Regel Nummer Eins: Ihr verliert kein dword über den Byte Club!',
'Wer wohnt im Dschungel und schummelt? Mogli',
'Geht ein Mann zum Arzt weil er sich schlecht fühlt. Sagt der Arzt: "Sie müssen mit dem Masturbieren aufhören!"\nSagt der Mann: "Wieso das denn?!".\nSagt der Arzt: "Ja, sonst kann ich Sie nicht untersuchen."',
'Wie heißt ein Spanier ohne Auto?\nCarlos',
'Wie nennt man ein Cowboy ohne Pferd?\nSattelschlepper',
'Kommt ein Cowboy aus dem Frisiersalon heraus\nPony weg',
'Wie nennt man einen Schäfer, der seine Schafe schlägt?\nMähdrescher',
'Was trinkt die Chefin?\nLeitungswasser',
'Vampir in der Verkehrskontrolle.\n"Haben Sie was getrunken?"\n"Ja, zwei Radler."',
'Wie nennt man jemanden, der DIN A4 Blätter scannt?\nScandinavier',
'Wie nennt man einen Europäer aus Lettland?\nEuropalette',
'Hab nem Hipster ins Bein geschossen\nJetzt hopster',
'Wie viel wiegt ein Influencer?\nEin Instagramm',
'Was ist gelb und kann nicht schwimmen?\nEin Bagger\nUnd warum nicht?\nHat nur einen Arm',
'Was hat ein Mann ohne Beine?\nErdnüsse',
'Welcher Vogel hat Darth Vader auf denn Kopf geschissen?\nDer Star wars',
'Wie heißt ein Veganer Russe?\nMooskauer',
'Was ist der Unterschied zwischen Grießbrei und einem Epileptiker?\nDer Grießbrei liegt in Zucker und Zimt, der Epileptiker liegt im Zimmer und zuckt.',
'Was macht ein Clown im Büro?\nFaxen',
'Was ist grūn und nuschelt im Gurkensalat?\nDill Schweiger',
'Was ist die Vergangenheitsform von Tomate? Passierte Tomate',
'Gehören abgetriebene Babys eigentlich auch zu den entfernen Verwandten?',
'Kommt ein Dachdecker in ne Bar\nDa sagt der Barkeeper: "Der geht aufs Haus!"',
'Was spricht man in der Sauna? Schwitzerdeutsch.',
'Was ist grün und wird auf Knopfdruck rot?\nEin Frosch im Mixer',
'Was ist weiß und fliegt über die Wiese?\nBiene Majo',
'Warum trinken Veganer kein Leitungswasser?\nWeil es aus dem Hahn kommt']
emojis = [':laughing:', ':smile:', ':joy:', ':sob:', ':rofl:']
msg = f'{random.choice(emojis)} {random.choice(puns)}'
await ctx.send(msg)
def setup(bot):
bot.add_cog(fun(bot))
| 55.956349
| 226
| 0.582654
| 1,700
| 14,101
| 4.820588
| 0.441176
| 0.014643
| 0.021965
| 0.008542
| 0.08432
| 0.069799
| 0.029042
| 0.020988
| 0.01147
| 0.01147
| 0
| 0.018271
| 0.309127
| 14,101
| 251
| 227
| 56.179283
| 0.822932
| 0.009999
| 0
| 0.088542
| 0
| 0.041667
| 0.556054
| 0.039285
| 0
| 0
| 0
| 0.003984
| 0
| 1
| 0.015625
| false
| 0.005208
| 0.041667
| 0
| 0.083333
| 0.005208
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e122eb0c0e3191c6ed28f670de3cb045fb8a32e8
| 1,866
|
py
|
Python
|
asconnect/models/beta_detail.py
|
guojiubo/asconnect
|
1c725dc2036f0617854f19b9a310a91c42239c72
|
[
"MIT"
] | 14
|
2020-09-30T14:45:38.000Z
|
2022-03-04T09:49:26.000Z
|
asconnect/models/beta_detail.py
|
guojiubo/asconnect
|
1c725dc2036f0617854f19b9a310a91c42239c72
|
[
"MIT"
] | 8
|
2020-09-30T14:50:18.000Z
|
2022-01-25T06:18:20.000Z
|
asconnect/models/beta_detail.py
|
guojiubo/asconnect
|
1c725dc2036f0617854f19b9a310a91c42239c72
|
[
"MIT"
] | 7
|
2020-10-09T18:06:18.000Z
|
2022-01-25T05:21:12.000Z
|
"""Build beta detail models for the API"""
import enum
from typing import Dict, Optional
import deserialize
from asconnect.models.common import BaseAttributes, Links, Relationship, Resource
class ExternalBetaState(enum.Enum):
"""External beta state."""
PROCESSING = "PROCESSING"
PROCESSING_EXCEPTION = "PROCESSING_EXCEPTION"
MISSING_EXPORT_COMPLIANCE = "MISSING_EXPORT_COMPLIANCE"
READY_FOR_BETA_TESTING = "READY_FOR_BETA_TESTING"
IN_BETA_TESTING = "IN_BETA_TESTING"
EXPIRED = "EXPIRED"
READY_FOR_BETA_SUBMISSION = "READY_FOR_BETA_SUBMISSION"
IN_EXPORT_COMPLIANCE_REVIEW = "IN_EXPORT_COMPLIANCE_REVIEW"
WAITING_FOR_BETA_REVIEW = "WAITING_FOR_BETA_REVIEW"
IN_BETA_REVIEW = "IN_BETA_REVIEW"
BETA_REJECTED = "BETA_REJECTED"
BETA_APPROVED = "BETA_APPROVED"
class InternalBetaState(enum.Enum):
"""Internal beta state."""
PROCESSING = "PROCESSING"
PROCESSING_EXCEPTION = "PROCESSING_EXCEPTION"
MISSING_EXPORT_COMPLIANCE = "MISSING_EXPORT_COMPLIANCE"
READY_FOR_BETA_TESTING = "READY_FOR_BETA_TESTING"
IN_BETA_TESTING = "IN_BETA_TESTING"
EXPIRED = "EXPIRED"
IN_EXPORT_COMPLIANCE_REVIEW = "IN_EXPORT_COMPLIANCE_REVIEW"
@deserialize.key("identifier", "id")
class BuildBetaDetail(Resource):
"""Represents a build localization."""
@deserialize.key("auto_notify_enabled", "autoNotifyEnabled")
@deserialize.key("external_build_state", "externalBuildState")
@deserialize.key("internal_build_state", "internalBuildState")
class Attributes(BaseAttributes):
"""Represents beta build localization attributes."""
auto_notify_enabled: bool
external_build_state: ExternalBetaState
internal_build_state: InternalBetaState
identifier: str
attributes: Attributes
relationships: Optional[Dict[str, Relationship]]
links: Links
| 32.172414
| 81
| 0.758307
| 201
| 1,866
| 6.661692
| 0.283582
| 0.095594
| 0.053771
| 0.056759
| 0.40478
| 0.356983
| 0.356983
| 0.356983
| 0.285288
| 0.285288
| 0
| 0
| 0.156484
| 1,866
| 57
| 82
| 32.736842
| 0.850699
| 0.084673
| 0
| 0.368421
| 0
| 0
| 0.275862
| 0.116528
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.105263
| 0
| 0.815789
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1284d4bbaf6bf582868bfb66265b4397932b66a
| 385
|
py
|
Python
|
scripts/compile-tests.py
|
PENGUINLIONG/liella
|
d0d4bc3e05419705712384b15d1c5db00ee12f73
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
scripts/compile-tests.py
|
PENGUINLIONG/liella
|
d0d4bc3e05419705712384b15d1c5db00ee12f73
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
scripts/compile-tests.py
|
PENGUINLIONG/liella
|
d0d4bc3e05419705712384b15d1c5db00ee12f73
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
from os import listdir
import subprocess
for f in listdir("tests/vulkan"):
if f.endswith(".spv"):
continue
print(f"-- compiling test {f}")
p = subprocess.run(["glslangValidator", f"tests/vulkan/{f}", "-H", "-o", f"tests/vulkan/{f}.spv"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.returncode != 0:
print(bytes.decode(p.stdout))
| 29.615385
| 162
| 0.644156
| 54
| 385
| 4.592593
| 0.574074
| 0.133065
| 0.096774
| 0.104839
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.003145
| 0.174026
| 385
| 12
| 163
| 32.083333
| 0.77673
| 0
| 0
| 0
| 0
| 0
| 0.241558
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.222222
| 0
| 0.222222
| 0.222222
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e1297aff417ed953bdd6f0365aac41a401e15814
| 5,769
|
py
|
Python
|
collections/nemo_asr/nemo_asr/parts/dataset.py
|
petermartigny/NeMo
|
b20821e637314940e36b63d32c601c43d1b74051
|
[
"Apache-2.0"
] | 1
|
2020-03-22T11:23:11.000Z
|
2020-03-22T11:23:11.000Z
|
collections/nemo_asr/nemo_asr/parts/dataset.py
|
petermartigny/NeMo
|
b20821e637314940e36b63d32c601c43d1b74051
|
[
"Apache-2.0"
] | null | null | null |
collections/nemo_asr/nemo_asr/parts/dataset.py
|
petermartigny/NeMo
|
b20821e637314940e36b63d32c601c43d1b74051
|
[
"Apache-2.0"
] | 1
|
2020-08-25T06:43:34.000Z
|
2020-08-25T06:43:34.000Z
|
# Taken straight from Patter https://github.com/ryanleary/patter
# TODO: review, and copyright and fix/add comments
import torch
from torch.utils.data import Dataset
from .manifest import Manifest
def seq_collate_fn(batch):
def find_max_len(seq, index):
max_len = -1
for item in seq:
if item[index].size(0) > max_len:
max_len = item[index].size(0)
return max_len
batch_size = len(batch)
audio_signal, audio_lengths = None, None
if batch[0][0] is not None:
max_audio_len = find_max_len(batch, 0)
audio_signal = torch.zeros(batch_size, max_audio_len,
dtype=torch.float)
audio_lengths = []
for i, s in enumerate(batch):
audio_signal[i].narrow(0, 0, s[0].size(0)).copy_(s[0])
audio_lengths.append(s[1])
audio_lengths = torch.tensor(audio_lengths, dtype=torch.long)
max_transcript_len = find_max_len(batch, 2)
transcript = torch.zeros(batch_size, max_transcript_len, dtype=torch.long)
transcript_lengths = []
for i, s in enumerate(batch):
transcript[i].narrow(0, 0, s[2].size(0)).copy_(s[2])
transcript_lengths.append(s[3])
transcript_lengths = torch.tensor(transcript_lengths, dtype=torch.long)
return audio_signal, audio_lengths, transcript, transcript_lengths
def audio_seq_collate_fn(batch):
"""
collate a batch (iterable of (sample tensor, label tensor) tuples) into
properly shaped data tensors
:param batch:
:return: inputs (batch_size, num_features, seq_length), targets,
input_lengths, target_sizes
"""
# sort batch by descending sequence length (for packed sequences later)
batch.sort(key=lambda x: -x[0].size(0))
minibatch_size = len(batch)
# init tensors we need to return
inputs = torch.zeros(minibatch_size, batch[0][0].size(0))
input_lengths = torch.zeros(minibatch_size, dtype=torch.long)
target_sizes = torch.zeros(minibatch_size, dtype=torch.long)
targets = []
metadata = []
# iterate over minibatch to fill in tensors appropriately
for i, sample in enumerate(batch):
input_lengths[i] = sample[0].size(0)
inputs[i].narrow(0, 0, sample[0].size(0)).copy_(sample[0])
target_sizes[i] = len(sample[1])
targets.extend(sample[1])
metadata.append(sample[2])
targets = torch.tensor(targets, dtype=torch.long)
return inputs, targets, input_lengths, target_sizes, metadata
class AudioDataset(Dataset):
def __init__(self, manifest_filepath, labels, featurizer,
max_duration=None,
min_duration=None, max_utts=0, normalize=True,
trim=False, eos_id=None, logger=False, load_audio=True):
"""
Dataset that loads tensors via a json file containing paths to audio
files, transcripts, and durations
(in seconds). Each new line is a different sample. Example below:
{"audio_filepath": "/path/to/audio.wav", "text_filepath":
"/path/to/audio.txt", "duration": 23.147}
...
{"audio_filepath": "/path/to/audio.wav", "text": "the
transcription", offset": 301.75, "duration": 0.82, "utt":
"utterance_id",
"ctm_utt": "en_4156", "side": "A"}
Args:
manifest_filepath: Path to manifest json as described above. Can
be coma-separated paths.
labels: String containing all the possible characters to map to
featurizer: Initialized featurizer class that converts paths of
audio to feature tensors
max_duration: If audio exceeds this length, do not include in
dataset
min_duration: If audio is less than this length, do not include
in dataset
max_utts: Limit number of utterances
normalize: whether to normalize transcript text (default): True
eos_id: Id of end of sequence symbol to append if not None
load_audio: Boolean flag indicate whether do or not load audio
"""
m_paths = manifest_filepath.split(',')
self.manifest = Manifest(m_paths, labels,
max_duration=max_duration,
min_duration=min_duration, max_utts=max_utts,
normalize=normalize)
self.featurizer = featurizer
self.trim = trim
self.eos_id = eos_id
self.load_audio = load_audio
if logger:
logger.info(
"Dataset loaded with {0:.2f} hours. Filtered {1:.2f} "
"hours.".format(
self.manifest.duration / 3600,
self.manifest.filtered_duration / 3600))
def __getitem__(self, index):
sample = self.manifest[index]
if self.load_audio:
duration = sample['duration'] if 'duration' in sample else 0
offset = sample['offset'] if 'offset' in sample else 0
features = self.featurizer.process(sample['audio_filepath'],
offset=offset,
duration=duration,
trim=self.trim)
f, fl = features, torch.tensor(features.shape[0]).long()
# f = f / (torch.max(torch.abs(f)) + 1e-5)
else:
f, fl = None, None
t, tl = sample["transcript"], len(sample["transcript"])
if self.eos_id is not None:
t = t + [self.eos_id]
tl += 1
return \
f, fl, \
torch.tensor(t).long(), torch.tensor(tl).long()
def __len__(self):
return len(self.manifest)
| 39.244898
| 78
| 0.600277
| 722
| 5,769
| 4.648199
| 0.282548
| 0.011919
| 0.02503
| 0.008045
| 0.123361
| 0.075685
| 0.075685
| 0
| 0
| 0
| 0
| 0.017318
| 0.299359
| 5,769
| 146
| 79
| 39.513699
| 0.812964
| 0.281678
| 0
| 0.023256
| 0
| 0
| 0.031026
| 0
| 0
| 0
| 0
| 0.006849
| 0
| 1
| 0.069767
| false
| 0
| 0.034884
| 0.011628
| 0.174419
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e129ccfbd3be47531b273fb3289a20523a49c675
| 5,277
|
py
|
Python
|
HandSComp.py
|
CRZaug/NonlinearWaves
|
2adfc2cc5e0c18576c6b73420a913ef1ce23000d
|
[
"MIT"
] | null | null | null |
HandSComp.py
|
CRZaug/NonlinearWaves
|
2adfc2cc5e0c18576c6b73420a913ef1ce23000d
|
[
"MIT"
] | null | null | null |
HandSComp.py
|
CRZaug/NonlinearWaves
|
2adfc2cc5e0c18576c6b73420a913ef1ce23000d
|
[
"MIT"
] | null | null | null |
"""
~~~ IMPORT EXPERIMENTAL DATA, PROCESS, AND NONDIMENSIONALIZE ~~~
This code reads in the rescaled Snodgrass data and compares parameters
to known parameters found in the Henderson and Segur paper.
1. Get distances
2. Read in the gauge data for each event (get frequencies and Fourier magnitudes)
3. Adjust the y axis units
4. Get the k vector using integer division and clean up
5. Get the carrier wave location (requires some restricting)
6. Factor out carrier wave
7. Get the energies at each gauge
8. Get nondimensionalization constants
"""
import numpy as np
import os
import glob
import matplotlib.pyplot as plt
from numpy.fft import fft, ifft
import NLS
import random as rand
from scipy import interpolate
### STEP 1: Get distance information
distv = np.array([0.0,2400000.0,4200000.0,8700000.0]) # Distances between gauges in METERS
### STEP 2: Read in information at each gauge for each event
subdirs = ['Aug1Data','Aug2Data','JulyData']
# Define something that will list directories that are not hidden
def listdirNH(path):
return glob.glob(os.path.join(path, '*'))
# Read in the data
j = 0
for sd in subdirs:
files = listdirNH(sd+'/Rescaled')
# Initialize some values
n = 0
pi =0
fig1,ax1 = plt.subplots(4,1)
plt.suptitle(sd)
# Get files
Deltavals = []
for f in files:
datavals = np.transpose(np.loadtxt(f).view(float))
N = len(datavals[1])
x = datavals[0] # Frequencies
sly = datavals[1] # Magnitudes
#ly = np.sqrt(sly*x)*0.01 #MULTIPLY VERSION (get the amplitude in meters)
mns = []
for w in range(N-1):
mns.append(np.abs(x[w+1]-x[w]))
#mns.append(np.mean(mns))
### STEP 3: Adjust the y axis units
ly = np.sqrt(sly*np.mean(mns))*0.01 # INTEGRATED VERSION
### STEP 4: Get the k vector using integer division and clean up
L = 3600*3 # The period
k = (x*0.001)//(2*np.pi/L) # Convert to mHz, then divide by 2pi/L to get the k vector
# REMOVE DUPLICATE VALUES
ndk = np.array(())
for fi in range(len(k)):
num = k[fi]
if num not in ndk:
ndk = np.append(ndk,num)
lll =[]
for h in ndk:
l1=np.where(k==h)[0]
lll.append(l1)
ndy = np.array(())
for ar in lll:
val = np.mean(ly[ar])
ndy=np.append(ndy,val)
### STEP 5: Get the location of the carrier wave (defined by the first gauge)
if n == 0:
m = max(ndy)
i = np.where(ndy == m)
if len(i[0]) > 1:
newi = i[0][len(i[0])//2]
carriermode = np.array(newi)
carrierloc = ndk[carriermode]
else:
newi = i[0][0]
carriermode = np.array(newi)
carrierloc = ndk[carriermode]
# First, find the carrier mode in ANY file, not just the first one
loc = np.where(np.logical_and(ndk>carrierloc*0.99, ndk<carrierloc*1.001))
#loc = np.where(np.logical_and(ndk>carrierloc-1, ndk<carrierloc+1))
# Be a little more restrictive
if len(loc[0])>1:
loc = loc[0][0]
else:
loc = loc[0][0]
### STEP 6: Redefine the k vector so that the carrier mode is at 0 (factor it out)
knew = ndk-ndk[loc]
xnew = x-x[loc]
### STEP 7: Get the "Energy" integrals
fnc = interpolate.interp1d(x, sly,kind ='cubic')
longx = np.linspace(x[0],x[-1],1000)
newy = fnc(longx)
A0 = np.sqrt(2*NLS.trapezoid(newy,(x[-1]-x[0])))*0.01
figg,axx = plt.subplots()
axx.plot(x,sly,'.',markersize=7)
axx.plot(longx,newy)
plt.show()
M000 = NLS.trapezoid(newy[np.where(np.logical_and(longx>41.2,longx<75.6))],(74.6-41.2))
Deltavals.append(M000)
### STEP 8: Get nondimensionalization constants
g = 9.81 #(m/s^2)
if n==0:
w0 = (2*np.pi)**2/L*ndk[loc] # Get the value from the integer
k0 = w0**2/g # The carrier wavenumber
m = max(ndy)
epsilon = 2*m*k0 # The nondimensionalization constant epsilon
heps = A0*k0
print(f,'Special Values')
print('2A0',A0)
print('Maximum value',m)
print('Carrier frequency',w0)
print('Wavenumber',k0)
print('MY epsilon',epsilon)
print('HENDERSON EPSILON', heps)
print('period',L)
n = n+1
M0 = Deltavals[0]
MX = Deltavals/M0
energyy = np.log(MX)
# Get the fit and define a new y vector
A = np.vstack([distv, np.ones(len(distv))]).T
m, b = np.linalg.lstsq(A, energyy,rcond=-1)[0] # m is delta
hdeltab = -m
hdeltas = hdeltab/(2*heps**2*k0)
xplot = np.linspace(distv[0],distv[-1],100)
newy = m*xplot+b
print('HENDERSON BIG Delta ',hdeltab, 'b ', b)
print('HENDERSON LITTLE delta', hdeltas)
print()
| 28.370968
| 95
| 0.548607
| 744
| 5,277
| 3.887097
| 0.33871
| 0.020747
| 0.013831
| 0.013485
| 0.106846
| 0.100277
| 0.086445
| 0.054633
| 0.030429
| 0.030429
| 0
| 0.047416
| 0.332575
| 5,277
| 185
| 96
| 28.524324
| 0.773708
| 0.312299
| 0
| 0.12
| 0
| 0
| 0.048699
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.01
| false
| 0
| 0.08
| 0.01
| 0.1
| 0.11
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e12b12da65a67d3755d54e62e2738980186e27db
| 15,542
|
py
|
Python
|
src/services/explorer/core.py
|
solomonricky/epic-awesome-gamer
|
a6ecff90a716bb145931bb4042f9510e68698694
|
[
"Apache-2.0"
] | null | null | null |
src/services/explorer/core.py
|
solomonricky/epic-awesome-gamer
|
a6ecff90a716bb145931bb4042f9510e68698694
|
[
"Apache-2.0"
] | null | null | null |
src/services/explorer/core.py
|
solomonricky/epic-awesome-gamer
|
a6ecff90a716bb145931bb4042f9510e68698694
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# Time : 2022/1/17 15:20
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import os.path
import time
from hashlib import sha256
from typing import List, Optional, Union, Dict
import cloudscraper
import yaml
from lxml import etree # skipcq: BAN-B410 - Ignore credible sources
from selenium.common.exceptions import WebDriverException, InvalidCookieDomainException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from services.settings import DIR_EXPLORER, EPIC_EMAIL
from services.settings import logger
from services.utils import ToolBox, ChallengerContext, StandardContext
from .exceptions import DiscoveryTimeoutException, ProtocolOutdatedWarning
class EpicAwesomeExplorer:
"""游戏商店探索者 获取免费游戏数据以及促销信息"""
# 平台对象参数
URL_STORE_HOME = "https://store.epicgames.com/zh-CN/"
URL_FREE_GAMES = "https://store.epicgames.com/zh-CN/free-games"
URL_STORE_PREFIX = "https://store.epicgames.com/zh-CN/browse?"
URL_STORE_FREE_GAME = (
f"{URL_STORE_PREFIX}sortBy=releaseDate&sortDir=DESC&priceTier=tierFree&count=40"
)
URL_STORE_FREE_DLC = f"{URL_STORE_PREFIX}sortBy=releaseDate&sortDir=DESC&priceTier=tierFree&category=GameAddOn&count=40&start=0" # noqa
URL_PROMOTIONS = (
"https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=zh-CN"
)
URL_PRODUCT_PAGE = "https://store.epicgames.com/zh-CN/p/"
def __init__(self, silence: bool = None):
self.silence = True if silence is None else silence
# 驱动参数
self.action_name = "AwesomeFreeGirl"
# 运行缓存
self.runtime_workspace = None
self.path_free_games = "ctx_store.yaml"
self.game_objs = {} # {index0:{name:value url:value}, }
self.category_details = {
"game": {"url": self.URL_STORE_FREE_GAME, "flag": "免费游戏"},
"dlc": {"url": self.URL_STORE_FREE_DLC, "flag": "免费附加内容"},
}
# 初始化工作空间
self._init_workspace()
def _init_workspace(self) -> None:
"""初始化工作目录 缓存游戏商店数据"""
self.runtime_workspace = "." if not os.path.exists(DIR_EXPLORER) else DIR_EXPLORER
self.path_free_games = os.path.join(self.runtime_workspace, self.path_free_games)
def _discovery_free_games(
self,
ctx: Union[ChallengerContext, StandardContext],
ctx_cookies: List[dict],
category: str = "game",
) -> None:
"""发现玩家所属地区可视的常驻免费游戏数据"""
url = self.category_details[category]["url"]
flag = self.category_details[category]["flag"]
# 重载玩家令牌
if ctx_cookies:
ctx.get(self.URL_STORE_FREE_GAME)
for cookie_dict in ctx_cookies:
try:
ctx.add_cookie(cookie_dict)
except InvalidCookieDomainException:
pass
_mode = "(深度搜索)" if ctx_cookies else "(广度搜索)"
logger.debug(
ToolBox.runtime_report(
motive="DISCOVERY",
action_name=self.action_name,
message=f"📡 正在为玩家搜集{flag}{_mode}...",
)
)
# 获取免费游戏链接
_start = time.time()
_url_store_free = url
while True:
ctx.get(_url_store_free)
time.sleep(1)
WebDriverWait(ctx, 10, ignored_exceptions=WebDriverException).until(
EC.presence_of_element_located(
(By.XPATH, "//section[@data-testid='section-wrapper']")
)
)
# 滑到底部
action = ActionChains(ctx)
action.send_keys(Keys.END)
action.perform()
# 判断异常跳转
if "tierFree" not in ctx.current_url:
break
if time.time() - _start > 80:
raise DiscoveryTimeoutException(f"获取{flag}链接超时")
# 断言最后一页
WebDriverWait(ctx, 5, ignored_exceptions=WebDriverException).until(
EC.element_to_be_clickable((By.XPATH, "//a[@data-component='PaginationItem']"))
)
page_switcher = ctx.find_elements(By.XPATH, "//a[@data-component='PaginationItem']")[-1]
# 提取价值信息
game_objs = ctx.find_elements(By.XPATH, "//a[@class='css-1jx3eyg']")
for game_obj in game_objs:
name = game_obj.get_attribute("aria-label")
url = game_obj.get_attribute("href")
self.game_objs.update(
{
self.game_objs.__len__(): {
"name": name.split(",")[0].replace("\n", "").strip(),
"url": url.strip(),
"in_library": None,
}
}
)
# 页面跳转判断
page_end = page_switcher.get_attribute("href")
if page_end in ctx.current_url:
break
# 更新跳转链接
_url_store_free = page_end
logger.success(
ToolBox.runtime_report(
motive="DISCOVERY",
action_name=self.action_name,
message=f"{flag}搜集完毕",
qsize=len(self.game_objs),
)
)
def stress_expressions(self, ctx: Union[ChallengerContext, StandardContext]) -> Dict[str, str]:
"""应力表达式的主要实现"""
logger.debug(
ToolBox.runtime_report(
motive="DISCOVERY", action_name=self.action_name, message="📡 使用应力表达式搜索周免游戏..."
)
)
# 访问链接 游戏名称
pending_games = {}
for i in range(2):
try:
ctx.get(self.URL_STORE_HOME)
time.sleep(3)
# 定位周免游戏的绝对位置
WebDriverWait(ctx, 45, ignored_exceptions=WebDriverException).until(
EC.presence_of_element_located((By.XPATH, "//a[contains(string(),'当前免费')]"))
)
# 周免游戏基本信息
stress_operator = ctx.find_elements(By.XPATH, "//a[contains(string(),'当前免费')]")
title_seq = ctx.find_elements(
By.XPATH,
"//a[contains(string(),'当前免费')]//span[@data-testid='offer-title-info-title']",
)
# 重组周免游戏信息
for index, _ in enumerate(stress_operator):
href = stress_operator[index].get_attribute("href")
try:
pending_games[href] = f"{title_seq[index].text}".strip()
except AttributeError as err:
if i == 0:
raise AttributeError from err
pending_games[href] = "null"
break
except (WebDriverException, AttributeError):
continue
return pending_games
class GameLibManager(EpicAwesomeExplorer):
"""游戏对象管理 缓存商城数据以及判断游戏在库状态"""
def __init__(self):
super().__init__()
self.action_name = "GameLibManager"
self.email = EPIC_EMAIL
self.auth_str = "explorer"
def _z(self) -> str:
return (
sha256(f"{self.email[-3::-2]}{self.auth_str}".encode("utf-8")).hexdigest()
if self.email
else ""
)
def _check_protocol(self):
"""
读取协议文件,检查协议头
:except ProtocolOutdatedWarning: 缓存文件异常,请返回空数据
:return: stream
"""
try:
with open(self.path_free_games, "r", encoding="utf8") as file:
ctx_protocol = yaml.safe_load(file)
except FileNotFoundError as err:
raise ProtocolOutdatedWarning from err
else:
if not ctx_protocol or not isinstance(ctx_protocol, dict):
raise ProtocolOutdatedWarning
return ctx_protocol
@staticmethod
def _update_status(game_objs, ctx_content=None, runtime: bool = False):
"""
更新实体信息
- case1 文件不存在 空文件 过时 协议。 跳过读取,初始化协议对象,创建并写入内容。
- case2 缓存协议镜像,扩建实体,并逐条比对更新实体信息 加入新增内容,更新 ``in_library`` 状态
:param game_objs: 详见 `Game Object`
:param ctx_content: 实际上就是上一次保存的 game_objs
:param runtime: 默认False,是否为运行时更新实例状态。
一个显然的认知是,``IF runtime is False`` 为全量更新,应进行全库实例比对
`` IF runtime is True `` 为局部更新,此时 new_objs 数量一般会远少于 memory_objs 的数量,
应在比对后将 new_objs 的缺省实例补回。
:type game_objs: List[Dict[str, str|bool]]
:type ctx_content: List[Dict[str, str|bool]]
:return:
"""
if not ctx_content:
return game_objs
runtime = bool(runtime)
new_objs_map = {game["url"]: game for game in game_objs}
memory_objs_map = {c["url"]: c for c in ctx_content}
new_content_objs = []
# 对新内容迭代会自动丢弃过期的周免实例
for flag in new_objs_map.keys():
# 添加上一轮未发现的新游戏
if not memory_objs_map.get(flag):
new_content_objs.append(new_objs_map[flag])
# 逐条对比 更新实体在库状态
else:
memory = memory_objs_map[flag]
new_obj = new_objs_map[flag]
if new_obj.get("in_library") is None:
new_obj["in_library"] = memory.get("in_library")
# 添加更新在库状态后的实例
new_content_objs.append(new_obj)
# 将 new_objs 的缺省实例补回
if runtime is True:
for flag in memory_objs_map.keys():
if not new_objs_map.get(flag):
new_content_objs.append(memory_objs_map[flag])
return new_content_objs
def save_game_objs(self, game_objs, category: str, runtime: Optional[bool] = None):
"""
缓存免费商城数据
:param runtime:
:param game_objs:
:param category:
:type game_objs: List[Dict[str, str|bool]]
:return:
"""
if not game_objs:
return
try:
ctx_protocol = self._check_protocol()
except ProtocolOutdatedWarning:
content = {self._z(): {category: game_objs}}
with open(self.path_free_games, "w", encoding="utf8") as file:
yaml.dump(content, file, allow_unicode=True)
logger.success(
ToolBox.runtime_report(
motive="SAVE",
action_name=self.action_name,
message="Cache Epic store information.",
)
)
else:
# 切换账号 键值补全
if not ctx_protocol.get(self._z()):
ctx_protocol[self._z()] = {}
# 键值比对更新
merged_content = self._update_status(
game_objs=game_objs,
ctx_content=ctx_protocol[self._z()].get(category),
runtime=runtime,
)
ctx_protocol[self._z()].update({category: merged_content})
# 缓存更新
with open(self.path_free_games, "w", encoding="utf8") as file:
yaml.dump(ctx_protocol, file, allow_unicode=True)
logger.success(
ToolBox.runtime_report(
motive="MERGE",
action_name=self.action_name,
message="Update Epic store information.",
)
)
def load_game_objs(self, category: str, only_url: bool = None):
"""
加载缓存在本地的免费游戏对象
:param category:
:param only_url:
:return:
"""
try:
ctx_protocol = self._check_protocol()
except ProtocolOutdatedWarning:
return []
else:
ctx_content = ctx_protocol.get(self._z(), {}).get(category, [])
if not ctx_content:
return []
if only_url is True:
return [obj["url"] for obj in ctx_content]
return ctx_content
@staticmethod
def is_my_game(ctx_cookies, page_link: str, pre_assert_content: bytes = None) -> Optional[dict]:
"""
判断游戏在库状态
:param pre_assert_content: 前置协同响应流,将耗时的网络请求操作前置,
封装成协程任务,而仅将此函数用于解析上游模块的静态返回值。
:param ctx_cookies:
:param page_link:
:type ctx_cookies: List[dict]|str
:return:
None 异常状态
True 跳过任务
False 继续任务
仅当返回值为 False 时可以继续任务,并可以进一步筛选掉 AjaxLoadingReject 目标。
"""
def response_wrapper(new_params: dict):
resp_ = {"assert": "", "status": None, "warning": ""}
resp_.update(new_params)
return resp_
# 模式匹配 --> 上下文呈递|重新握手
if pre_assert_content is None:
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36",
"cookie": ctx_cookies
if isinstance(ctx_cookies, str)
else ToolBox.transfer_cookies(ctx_cookies),
}
scraper = cloudscraper.create_scraper()
response = scraper.get(page_link, headers=headers)
content = response.content
else:
content = pre_assert_content
# 清洗页面的促销信息
tree = etree.HTML(content)
assert_obj = tree.xpath(
"//span[@data-component='PurchaseCTA']//span[@data-component='Message']"
)
# 模式匹配 --> 向下游呈递资源对象的状态
# 1. 剔除已在库的、付费的、未推出的资源;
# 2. 剔除被限制的免费资源;
# 3. 呈递待领取的免费资源;
# 🚧 异常状态 忽略尚未发布的游戏对象
if not assert_obj:
return response_wrapper({"assert": "AssertObjectNotFound", "status": None})
assert_message = assert_obj[0].text
# 🚧 跳过 `无法认领` 的日志信息
if assert_message in ["已在游戏库中", "已在库中", "立即购买", "购买", "即将推出"]:
return response_wrapper({"assert": assert_message, "status": True})
# 🚧 惰性加载,前置节点不处理动态加载元素
if assert_message in ["正在载入"]:
return response_wrapper({"assert": "AjaxLoadingReject", "status": False})
# 🍟 未领取的免费游戏
if assert_message in ["获取"]:
# 無遮挡警告 繼續任務
warning_obj = tree.xpath("//h1[@class='css-1gty6cv']//span")
if not warning_obj:
return response_wrapper({"assert": assert_message, "status": False})
# 成人内容可获取
warning_message = warning_obj[0].text
if warning_message in ["成人内容"]:
return response_wrapper(
{"assert": assert_message, "warning": warning_message, "status": False}
)
# 地区限制無法獲取
return response_wrapper(
{"assert": assert_message, "warning": warning_message, "status": None}
)
class _Game:
"""基础游戏对象"""
# 游戏名称
name: str = "《堡垒之夜》"
# 商城访问链接
url: str = "https://store.epicgames.com/zh-CN/p/fortnite"
# 在库情况 True在库 False不在 None不到啊(初始化状态)
in_library: bool = None
class _Dlc:
"""游戏附加内容对象"""
# 附加内容名称
name: str = "《消逝的光芒》-《求生之路 2》Weapon Pack"
# 商城访问链接
url: str = "https://store.epicgames.com/zh-CN/p/dying-light--left-4-dead-2-weapon-pack"
# 在库情况 True在库 False不在 None不到啊(初始化状态)
in_library: bool = None
class _Report:
"""消息推送|资源封装对象"""
# 资源名称
name: str = ""
# 资源链接
url: str = ""
# 执行结果
status: str = ""
| 33.786957
| 140
| 0.559452
| 1,631
| 15,542
| 5.133047
| 0.272839
| 0.020067
| 0.011467
| 0.015767
| 0.26517
| 0.218586
| 0.182155
| 0.167941
| 0.147874
| 0.122312
| 0
| 0.009858
| 0.334256
| 15,542
| 459
| 141
| 33.860566
| 0.798686
| 0.11929
| 0
| 0.160279
| 0
| 0.020906
| 0.128864
| 0.048296
| 0
| 0
| 0
| 0
| 0.055749
| 1
| 0.041812
| false
| 0.003484
| 0.059233
| 0.003484
| 0.233449
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
e12b30211ce2a1a3e4ccda61c62066c6b101ba25
| 7,312
|
py
|
Python
|
model/utils.py
|
Tiamat-Tech/VAENAR-TTS
|
69b6b5be1ab5168cfd3c6ab902075638e76a3b8d
|
[
"MIT"
] | 62
|
2021-07-15T10:09:56.000Z
|
2022-03-31T02:53:09.000Z
|
model/utils.py
|
Tiamat-Tech/VAENAR-TTS
|
69b6b5be1ab5168cfd3c6ab902075638e76a3b8d
|
[
"MIT"
] | 3
|
2021-07-19T14:45:26.000Z
|
2022-03-31T02:38:57.000Z
|
model/utils.py
|
Tiamat-Tech/VAENAR-TTS
|
69b6b5be1ab5168cfd3c6ab902075638e76a3b8d
|
[
"MIT"
] | 10
|
2021-07-19T03:20:44.000Z
|
2022-02-21T07:07:38.000Z
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class LinearNorm(nn.Module):
def __init__(self, in_features, out_features, activation=None,
use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros'):
super(LinearNorm, self).__init__()
self.linear = nn.Linear(
in_features=in_features,
out_features=out_features,
bias=use_bias)
# init weight
if kernel_initializer == 'glorot_uniform':
nn.init.xavier_uniform_(self.linear.weight)
elif kernel_initializer == 'zeros':
nn.init.zeros_(self.linear.weight)
# init bias
if use_bias:
if bias_initializer == 'zeros':
nn.init.constant_(self.linear.bias, 0.0)
else:
raise NotImplementedError
self.activation = activation if activation is not None else nn.Identity()
def forward(self, x):
x = self.activation(self.linear(x))
return x
class ConvNorm(nn.Module):
def __init__(
self, in_channels, out_channels, kernel_size=1, stride=1,
padding=None, dilation=1, activation=None,
use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros'):
super(ConvNorm, self).__init__()
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, bias=use_bias
)
# init weight
if kernel_initializer == 'glorot_uniform':
nn.init.xavier_uniform_(self.conv.weight)
elif kernel_initializer == 'zeros':
nn.init.zeros_(self.conv.weight)
# init bias
if use_bias:
if bias_initializer == 'zeros':
nn.init.constant_(self.conv.bias, 0.0)
def forward(self, signal):
conv_signal = self.conv(signal)
return conv_signal
class PreNet(nn.Module):
def __init__(self, in_features, units, drop_rate, activation):
super(PreNet, self).__init__()
self.dense1 = LinearNorm(
in_features, units, activation=activation)
self.dense2 = LinearNorm(
units, units, activation=activation)
self.dropout_layer = nn.Dropout(p=drop_rate)
def forward(self, inputs):
dense1_out = self.dense1(inputs)
dense1_out = self.dropout_layer(dense1_out)
dense2_out = self.dense2(dense1_out)
dense2_out = self.dropout_layer(dense2_out)
return dense2_out
class ConvPreNet(nn.Module):
def __init__(self, nconv, hidden, conv_kernel, drop_rate,
activation=nn.ReLU(), bn_before_act=True):
super(ConvPreNet, self).__init__()
self.conv_stack = nn.ModuleList(
[
Conv1D(in_channels=hidden, out_channels=hidden, kernel_size=conv_kernel, activation=activation,
drop_rate=drop_rate, bn_before_act=bn_before_act)
for i in range(nconv)
]
)
self.projection = LinearNorm(hidden, hidden)
def forward(self, inputs, mask=None):
conv_outs = inputs
for conv in self.conv_stack:
conv_outs = conv(conv_outs, mask)
projections = self.projection(conv_outs)
return projections
class FFN(nn.Module):
def __init__(self, in_features, hidden1, hidden2):
super(FFN, self).__init__()
self.dense1 = LinearNorm(in_features, hidden1, activation=nn.ReLU())
self.dense2 = LinearNorm(hidden1, hidden2, activation=None)
self.layer_norm = nn.LayerNorm(hidden2)
def forward(self, inputs, mask=None):
dense1_outs = self.dense1(inputs)
dense2_outs = self.dense2(dense1_outs)
outs = dense2_outs + inputs
outs = self.layer_norm(outs)
if mask is not None:
outs = outs.masked_fill(mask.unsqueeze(-1), 0.0)
return outs
class Conv1D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, activation, drop_rate,
bn_before_act=False, strides=1):
super(Conv1D, self).__init__()
self.conv1d = ConvNorm(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=int((kernel_size - 1) / 2),
dilation=1,
activation=None)
self.activation = activation if activation is not None else nn.Identity()
self.bn = nn.BatchNorm1d(out_channels)
self.dropout = nn.Dropout(p=drop_rate)
self.bn_before_act = bn_before_act
def forward(self, inputs, mask=None):
conv_outs = inputs.contiguous().transpose(1, 2)
conv_outs = self.conv1d(conv_outs)
if self.bn_before_act:
conv_outs = self.bn(conv_outs)
conv_outs = self.activation(conv_outs)
else:
conv_outs = self.activation(conv_outs)
conv_outs = self.bn(conv_outs)
dropouts = self.dropout(conv_outs)
dropouts = dropouts.contiguous().transpose(1, 2)
if mask is not None:
dropouts = dropouts.masked_fill(mask.unsqueeze(-1), 0.0)
return dropouts
class PostNet(nn.Module):
def __init__(self, n_conv, hidden, conv_filters, conv_kernel,
drop_rate):
super(PostNet, self).__init__()
activations = [nn.Tanh()] * (n_conv - 1) + [nn.Identity()]
self.conv_stack = nn.ModuleList(
[
Conv1D(in_channels=hidden if i == 0 else conv_filters, out_channels=conv_filters,
kernel_size=conv_kernel,
activation=activations[i], drop_rate=drop_rate)
for i in range(n_conv)
]
)
def forward(self, inputs, mask=None):
conv_out = inputs
for conv in self.conv_stack:
conv_out = conv(conv_out, mask)
return conv_out
class PositionalEncoding(nn.Module):
def __init__(self):
super(PositionalEncoding, self).__init__()
@staticmethod
def positional_encoding(len, dim, device, step=1.):
"""
:param len: int scalar
:param dim: int scalar
:param device:
:param step:
:return: position embedding
"""
pos_mat = torch.tile(
(torch.arange(0, len, dtype=torch.float32, device=device) * step).unsqueeze(-1),
[1, dim])
dim_mat = torch.tile(
torch.arange(0, dim, dtype=torch.float32, device=device).unsqueeze(0),
[len, 1])
dim_mat_int = dim_mat.type(torch.int32)
pos_encoding = torch.where( # [time, dims]
torch.eq(torch.fmod(dim_mat_int, 2), 0),
torch.sin(pos_mat / torch.pow(10000., dim_mat / float(dim))),
torch.cos(pos_mat / torch.pow(10000., (dim_mat - 1) / float(dim))))
return pos_encoding
| 37.88601
| 112
| 0.583425
| 841
| 7,312
| 4.812128
| 0.154578
| 0.031628
| 0.021745
| 0.029652
| 0.475167
| 0.398073
| 0.342229
| 0.28169
| 0.229306
| 0.162095
| 0
| 0.016677
| 0.319338
| 7,312
| 192
| 113
| 38.083333
| 0.796464
| 0.021745
| 0
| 0.183007
| 0
| 0
| 0.012462
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.104575
| false
| 0
| 0.019608
| 0
| 0.228758
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0100201d7067edc12b14792aa66df0f99a8f5f65
| 2,306
|
py
|
Python
|
lib/galaxy/webapps/galaxy/services/jobs.py
|
itisAliRH/galaxy
|
b3b693ea0788f773442c8481472a87f43ccb10d7
|
[
"CC-BY-3.0"
] | null | null | null |
lib/galaxy/webapps/galaxy/services/jobs.py
|
itisAliRH/galaxy
|
b3b693ea0788f773442c8481472a87f43ccb10d7
|
[
"CC-BY-3.0"
] | 6
|
2021-11-11T20:57:49.000Z
|
2021-12-10T15:30:33.000Z
|
lib/galaxy/webapps/galaxy/services/jobs.py
|
itisAliRH/galaxy
|
b3b693ea0788f773442c8481472a87f43ccb10d7
|
[
"CC-BY-3.0"
] | null | null | null |
from enum import Enum
from typing import (
Any,
Dict,
)
from galaxy import (
exceptions,
model,
)
from galaxy.managers import hdas
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.jobs import (
JobManager,
JobSearch,
view_show_job,
)
from galaxy.schema.fields import EncodedDatabaseIdField
from galaxy.schema.schema import JobIndexQueryPayload
class JobIndexViewEnum(str, Enum):
collection = "collection"
admin_job_list = "admin_job_list"
class JobIndexPayload(JobIndexQueryPayload):
view: JobIndexViewEnum = JobIndexViewEnum.collection
class JobsService:
job_manager: JobManager
job_search: JobSearch
hda_manager: hdas.HDAManager
def __init__(
self,
job_manager: JobManager,
job_search: JobSearch,
hda_manager: hdas.HDAManager,
):
self.job_manager = job_manager
self.job_search = job_search
self.hda_manager = hda_manager
def show(
self,
trans: ProvidesUserContext,
id: EncodedDatabaseIdField,
full: bool = False,
) -> Dict[str, Any]:
id = trans.app.security.decode_id(id)
job = self.job_manager.get_accessible_job(trans, id)
return view_show_job(trans, job, bool(full))
def index(
self,
trans: ProvidesUserContext,
payload: JobIndexPayload,
):
security = trans.security
is_admin = trans.user_is_admin
if payload.view == JobIndexViewEnum.admin_job_list:
payload.user_details = True
user_details = payload.user_details
if payload.view == JobIndexViewEnum.admin_job_list and not is_admin:
raise exceptions.AdminRequiredException("Only admins can use the admin_job_list view")
query = self.job_manager.index_query(trans, payload)
out = []
view = payload.view
for job in query.yield_per(model.YIELD_PER_ROWS):
job_dict = job.to_dict(view, system_details=is_admin)
j = security.encode_all_ids(job_dict, True)
if view == JobIndexViewEnum.admin_job_list:
j["decoded_job_id"] = job.id
if user_details:
j["user_email"] = job.get_user_email()
out.append(j)
return out
| 28.469136
| 98
| 0.662186
| 265
| 2,306
| 5.532075
| 0.30566
| 0.040928
| 0.049113
| 0.057299
| 0.162347
| 0.140518
| 0.140518
| 0.084584
| 0.084584
| 0.084584
| 0
| 0
| 0.262359
| 2,306
| 80
| 99
| 28.825
| 0.861846
| 0
| 0
| 0.101449
| 0
| 0
| 0.039462
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.043478
| false
| 0
| 0.115942
| 0
| 0.318841
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0101f0c173a9caa73adb1fcaf5f05657435355f6
| 1,984
|
py
|
Python
|
tests/deephub/trainer/test_early_stopping.py
|
deeplab-ai/deephub
|
b1d271436fab69cdfad14f19fa2e29c5338f18d6
|
[
"Apache-2.0"
] | 8
|
2019-10-17T12:46:13.000Z
|
2020-03-12T08:09:40.000Z
|
tests/deephub/trainer/test_early_stopping.py
|
deeplab-ai/deephub
|
b1d271436fab69cdfad14f19fa2e29c5338f18d6
|
[
"Apache-2.0"
] | 12
|
2019-10-22T13:11:56.000Z
|
2022-02-10T00:23:30.000Z
|
tests/deephub/trainer/test_early_stopping.py
|
deeplab-ai/deephub
|
b1d271436fab69cdfad14f19fa2e29c5338f18d6
|
[
"Apache-2.0"
] | 1
|
2019-10-17T13:21:27.000Z
|
2019-10-17T13:21:27.000Z
|
import pytest
import numpy as np
from deephub.models.registry.toy import DebugToyModel
from deephub.models.feeders import MemorySamplesFeeder
from deephub.trainer import Trainer
@pytest.mark.slow
def test_early_stopping(tmpdir):
model_params = {
'type': 'toy:DebugToyModel',
'model_dir': str(tmpdir / 'test_early_stopping/'),
'learning_rate': 0.01,
'num_classes': 2,
'num_steps_per_epoch': 1,
'hidden_neurons': 512
}
# Initialize the model
model = DebugToyModel(**model_params)
# Read training data
train_feeder = MemorySamplesFeeder(np.asarray(np.arange(0, 10).reshape(10, 1), dtype=np.float32),
np.array([int(0 if i < 5 else 1)
for i in range(10)], dtype=np.int64, ndmin=1),
batch_size=10, feed_as_dict=False)
# Read validation data
validation_feeder = MemorySamplesFeeder(np.asarray(np.arange(10, 20).reshape(10, 1), dtype=np.float32),
np.array([int(0 if i < 5 else 1)
for i in range(10)], dtype=np.int64, ndmin=1),
batch_size=10, feed_as_dict=False)
# Initialize the Trainer
trainer = Trainer()
train_params = {
'epochs': 12,
'save_summary_steps': 1,
'save_checkpoint_steps': 1,
'early_stopping_metric': 'loss',
'early_stopping_steps_without_decrease': 3,
'early_stopping_min_steps': 1,
'early_stopping_hook_run_every_steps': 1
}
# Start training process
trainer.train(model=model, train_feeder=train_feeder, eval_feeder=validation_feeder,
**train_params)
# Grab global step from model.estimator object
global_step = model.estimator().get_variable_value('global_step')
assert global_step < train_params['epochs']
| 36.072727
| 107
| 0.594758
| 232
| 1,984
| 4.866379
| 0.418103
| 0.069088
| 0.030115
| 0.06023
| 0.253322
| 0.253322
| 0.178919
| 0.178919
| 0.178919
| 0.178919
| 0
| 0.037846
| 0.30746
| 1,984
| 54
| 108
| 36.740741
| 0.783843
| 0.076109
| 0
| 0.157895
| 0
| 0
| 0.158817
| 0.075575
| 0
| 0
| 0
| 0
| 0.026316
| 1
| 0.026316
| false
| 0
| 0.131579
| 0
| 0.157895
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0104208de3be81be65db916a9965b3d5c0b060ef
| 10,742
|
py
|
Python
|
hf/protocol/frame.py
|
HashFast/hashfast-tools
|
9617691ac997f12085b688c3ecc6746e8510976d
|
[
"BSD-3-Clause"
] | 1
|
2020-12-15T02:49:36.000Z
|
2020-12-15T02:49:36.000Z
|
hf/protocol/frame.py
|
HashFast/hashfast-tools
|
9617691ac997f12085b688c3ecc6746e8510976d
|
[
"BSD-3-Clause"
] | null | null | null |
hf/protocol/frame.py
|
HashFast/hashfast-tools
|
9617691ac997f12085b688c3ecc6746e8510976d
|
[
"BSD-3-Clause"
] | 3
|
2015-09-02T00:31:06.000Z
|
2020-12-15T02:52:06.000Z
|
# Copyright (c) 2014, HashFast Technologies LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. 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.
# 3. Neither the name of HashFast Technologies LLC 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 HASHFAST TECHNOLOGIES LLC 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.
from abc import ABCMeta, abstractmethod
from ..load import crc
from ..util import with_metaclass, int_to_lebytes, lebytes_to_int
# Operation codes from hf_protocol.h.
opcodes = {
# Serial protocol operation codes (Second header byte)
'OP_NULL': 0,
'OP_ROOT': 1,
'OP_RESET': 2,
'OP_PLL_CONFIG': 3,
'OP_ADDRESS': 4,
'OP_READDRESS': 5,
'OP_HIGHEST': 6,
'OP_BAUD': 7,
'OP_UNROOT': 8,
'OP_HASH': 9,
'OP_NONCE': 10,
'OP_ABORT': 11,
'OP_STATUS': 12,
'OP_GPIO': 13,
'OP_CONFIG': 14,
'OP_STATISTICS': 15,
'OP_GROUP': 16,
'OP_CLOCKGATE': 17,
# Factory Codes
'OP_SERIAL': 50, # Serial number read/write
'OP_LIMITS': 51, # Operational limits read/write
'OP_HISTORY': 52, # Read operational history data
'OP_CHARACTERIZE': 53, # Characterize one or more die
'OP_CHAR_RESULT': 54, # Characterization result
'OP_SETTINGS': 55, # Read or write settings
'OP_FAN_SETTINGS': 56,
'OP_POWER': 57,
'OP_BAD_CORE': 58, # Set or clear bad core status
# USB interface specific operation codes
'OP_USB_INIT': 128, # Initialize USB interface details
'OP_GET_TRACE': 129, # Send back the trace buffer if present
'OP_LOOPBACK_USB': 130,
'OP_LOOPBACK_UART': 131,
'OP_DFU': 132, # Jump into the boot loader
'OP_USB_SHUTDOWN': 133, # Initialize USB interface details
'OP_DIE_STATUS': 134, # Die status. There are 4 die per ASIC
'OP_GWQ_STATUS': 135, # Global Work Queue protocol status
'OP_WORK_RESTART': 136, # Stratum work restart regime
'OP_USB_STATS1': 137, # Statistics class 1
'OP_USB_GWQSTATS': 138, # GWQ protocol statistics
'OP_USB_NOTICE': 139, # Asynchronous notification event
'OP_PING': 140, # Echo
'OP_CORE_MAP': 141, # Return core map
'OP_VERSION': 142, # Version information
'OP_FAN': 143, # Set Fan Speed
'OP_NAME': 144, # System name write/read
'OP_USB_DEBUG': 255
}
opnames = {}
for opcode_name, opcode in opcodes.items():
assert opcode not in opnames
opnames[opcode] = opcode_name
known_opcodes = set(opcodes.keys())
known_opnames = set(opnames.keys())
def check_framebytes(framebytes):
assert {x >= 0 and x < 256 for x in framebytes} == set([True])
assert len(framebytes) >= 8
assert framebytes[0] == 0xaa
assert framebytes[7] == crc.crc8(framebytes[1:7])
if framebytes[6] == 0:
assert len(framebytes) == 8
else:
data_length = 4 * framebytes[6]
# Eight byte frame header, data, plus 4 crc32 bytes.
# Fix: Restore when using serial line directly
# expected_framebytes_length = 8 + data_length + 4
expected_framebytes_length = 8 + data_length
assert expected_framebytes_length == len(framebytes)
data = framebytes[8:8+data_length]
# Fix: Restore when using serial line directly
# crc32 = framebytes[-4:]
# if crc32 != crc.crc32_to_bytelist(crc.crc32(data)):
# raise HF_Error("Bad CRC32 checksum.")
class hf_frame_data(with_metaclass(ABCMeta, object)):
def __init__(self, bytes=None):
self.initialize()
if bytes is None:
self.generate_frame_data()
else:
self.parse_frame_data(bytes)
@abstractmethod
def initialize(self):
pass
@abstractmethod
def parse_frame_data(self, bytes):
pass
@abstractmethod
def generate_frame_data(self):
pass
class hf_frame_data_base(hf_frame_data):
LENGTH = 0
def intialize(self):
pass
def parse_frame_data(self, bytes):
assert len(bytes) >= self.LENGTH
def generate_frame_data(self):
self.frame_data = [0x00]
return self.frame_data
# Fix: Document terminology: frame is the whole thing and consists of up to
# three parts: the header, the data, and the CRC32 checksum.
# Fix: Wants to verify checksums and throw exception if they are not right.
# And check for 0xaa.
# Fix: Wants to make all the fields of the header accessible, but also provide raw bytes.
# Fix: Should be able to initialize with stream of bytes or by filling in fields
# and asking for the bytes. Throw exception if field values are out of bounds.
# Fix: Maybe want something which checks for known opcode and whether fields are
# plausible for that opcode -- problem is that if we are using this to report
# what was seen on the wire, we need to make those assumptions, maybe.
# Fix: The really pure way to do this is to create a subclass for every opcode type
# and then have specific methods for that type. Probably more trouble than
# its worth, but it would also let us have specific methods for parameters
# that just occupy a couple bits.
class HF_Frame():
def __init__(self, initial_state):
self.initialize()
if initial_state is None:
pass
elif isinstance(initial_state, list):
self.off_the_wire(initial_state)
elif isinstance(initial_state, dict):
self.buildframe(initial_state)
else:
raise HF_Error("Argument type not supported: %s" % (inital_state))
def initialize(self):
self.framebytes = []
self.operation_code = None
self.chip_address = 0
self.core_address = 0
self.hdata = 0
self.data_length_field = 0
self.crc8 = 0
self.data = None
# Fix: Restore when using serial line directly
# self.crc32 = None
self.data_length = 0;
def off_the_wire(self, framebytes):
check_framebytes(framebytes)
self.framebytes = framebytes
self.operation_code = framebytes[1]
self.chip_address = framebytes[2]
self.core_address = framebytes[3]
self.hdata = lebytes_to_int(framebytes[4:6])
self.data_length_field = framebytes[6]
self.data_length = 4 * self.data_length_field
self.crc8 = framebytes[7]
if self.data_length > 0:
assert {x >= 0 and x < 256 for x in framebytes} == set([True])
self.data = framebytes[8:8+self.data_length]
# Fix: Restore when using serial line directly
# self.crc32 = framebytes[8+self.data_length:]
def set_data(self, data):
self.data = data
self.data_length = len(data)
self.data_length_field = int(self.data_length / 4)
# Fix: Restore when using serial line directly
# self.crc32 = crc.crc32(self.data)
def construct_framebytes(self):
crc8_input = [self.operation_code]
crc8_input += [self.chip_address]
crc8_input += [self.core_address]
crc8_input += int_to_lebytes(self.hdata, 2)
crc8_input += [self.data_length_field]
self.crc8 = crc.crc8(crc8_input)
frameheader = [0xaa, self.operation_code, self.chip_address, self.core_address] + \
int_to_lebytes(self.hdata, 2) + [self.data_length_field, self.crc8]
if self.data_length > 0:
# Fix: Restore when using serial line directly
# return frameheader + self.data + crc.crc32_to_bytelist(self.crc32)
self.framebytes = frameheader + self.data
else:
self.framebytes = frameheader
return self.framebytes
def buildframe(self, framedict):
legal_fields = set(['operation_code', 'chip_address', 'core_address', 'hdata', 'data'])
received_fields = set(framedict.keys())
assert received_fields.issubset(legal_fields)
assert 'operation_code' in framedict
assert framedict['operation_code'] in opnames
self.operation_code = framedict['operation_code']
if 'chip_address' in framedict:
if framedict['chip_address'] < 0 or framedict['chip_address'] > 255:
raise HF_Error("chip_address is out of range: %d" % (framedict['chip_address']))
self.chip_address = framedict['chip_address']
if 'core_address' in framedict:
if framedict['core_address'] < 0 or framedict['core_address'] > 255:
raise HF_Error("core_address is out of range: %d" % (framedict['core_address']))
self.core_address = framedict['core_address']
if 'hdata' in framedict:
if framedict['hdata'] < 0 or framedict['hdata'] > 65535:
raise HF_Error("hdata is out of range: %d" % (framedict['hdata']))
self.hdata = framedict['hdata']
if 'data' in framedict:
assert len(framedict['data']) == 0 or {x >= 0 and x < 256 for x in framedict['data']} == set([True])
assert len(framedict['data']) <= 1020 and len(framedict['data']) % 4 == 0
if len(framedict['data']) > 0:
self.set_data(framedict['data'])
return self.construct_framebytes()
def __str__(self):
string = ""
#string += "framebytes: {}\n".format(self.framebytes)
string += "operation_code: {:#x}\n".format(self.operation_code)
string += "chip_address: {:#x}\n".format(self.chip_address)
string += "core_address: {:#x}\n".format(self.core_address)
string += "hdata: {:#x}\n".format(self.hdata)
string += "data_length_field: {}\n".format(self.data_length)
#string += "data: {}\n".format(self.data)
return string
| 41.474903
| 106
| 0.67129
| 1,465
| 10,742
| 4.771331
| 0.279181
| 0.026323
| 0.030043
| 0.016309
| 0.165236
| 0.11774
| 0.079256
| 0.060372
| 0.058226
| 0.030329
| 0
| 0.027394
| 0.231987
| 10,742
| 259
| 107
| 41.474903
| 0.819879
| 0.37749
| 0
| 0.134831
| 0
| 0
| 0.150621
| 0
| 0
| 0
| 0.001817
| 0
| 0.078652
| 1
| 0.08427
| false
| 0.02809
| 0.016854
| 0
| 0.146067
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
010633c8fe4a1f8f50f2cbc160f034fdd91b60e5
| 11,162
|
py
|
Python
|
src/command.py
|
2minchul/chip-helper
|
437d33938a19bab7e7380ff9dd0e7e98ec26fdb7
|
[
"Apache-2.0"
] | 2
|
2020-05-12T06:11:39.000Z
|
2020-07-17T10:45:20.000Z
|
src/command.py
|
2minchul/chip-helper
|
437d33938a19bab7e7380ff9dd0e7e98ec26fdb7
|
[
"Apache-2.0"
] | 3
|
2021-06-08T21:30:59.000Z
|
2022-03-12T00:28:26.000Z
|
src/command.py
|
2minchul/chip-helper
|
437d33938a19bab7e7380ff9dd0e7e98ec26fdb7
|
[
"Apache-2.0"
] | null | null | null |
import argparse
import os
import re
import sys
from operator import itemgetter
from typing import Optional
import sentry_sdk
import youtube_dl
from selenium.common.exceptions import SessionNotCreatedException
from cmd_tool import (
get_execution_path,
exit_enter,
get_input_path_or_exit,
get_chrome_driver_path_or_exit,
get_resource_path,
cd
)
from imagetools import Size
from qrcode import NaverQrCode, make_qr_image, make_redirect_html
from thumbnail import composite_thumbnail, capture_video
from youtube_uploader import YoutubeUploader, YoutubeUploaderException
sentry_sdk.init("https://1ff694f9169a4fa383a867fe10ed9329@o342398.ingest.sentry.io/5243685")
def make_dirs():
os.chdir(get_execution_path())
print(os.path.abspath(os.curdir))
print('폴더 생성기')
print('존재하는 폴더는 건너뜀')
path = input('생성할 경로: ')
if not os.path.isdir(path):
print('없는 경로입니다')
exit_enter(1)
s, e = map(int, (input('시작할 숫자: '), input('끝나는 숫자: ')))
for i in range(s, e + 1):
os.makedirs(os.path.join(path, f'{i:04}'), exist_ok=True)
print('완료')
exit_enter()
def make_thumbnail():
input_path = os.path.join(get_execution_path(), 'input')
for cur_dir, _, files in os.walk(input_path):
dir_name = os.path.basename(cur_dir)
def _is_mp4(filename):
_, ext = os.path.splitext(filename)
return ext == '.mp4'
mp4_files = tuple(filter(_is_mp4, files))
if 1 < len(mp4_files):
print(f'pass: "{dir_name}" 안에 한개 이상의 mp4 파일이 존재합니다')
if not dir_name.isnumeric():
print(f'skip: "{dir_name}" 는 숫자로 구성된 폴더이름이 아닙니다')
continue
idx_text = f'{int(dir_name):04}'
mp4_filename = mp4_files[0]
jpg_filename = f'{idx_text}.jpg'
jpg_filepath = os.path.join(cur_dir, jpg_filename)
print(f'capture:\t{mp4_filename} to {jpg_filename}')
capture_video(os.path.join(cur_dir, mp4_filename), jpg_filepath)
target_filename = f'p{idx_text}.jpg'
print(f'composite:\t{jpg_filename} to {target_filename} ...')
composite_thumbnail(jpg_filepath, os.path.join(cur_dir, target_filename))
print('완료되었습니다!')
exit_enter()
def upload_videos():
path = get_execution_path()
chrome_driver_path = get_chrome_driver_path_or_exit()
input_path = get_input_path_or_exit()
cookie_path = os.path.join(get_execution_path(), 'cookies.txt')
if not os.path.isfile(cookie_path):
print('최상위 폴더에 cookies.txt 를 작성해야 합니다')
exit_enter(1)
uploader = None
video_dirs = {}
to_upload = {}
for cur_dir, _, files in os.walk(input_path):
dir_name = os.path.basename(cur_dir)
video_path = video_name = thumbnail_path = None
if 1 < len(tuple(filter(lambda s: s.endswith('.mp4'), files))):
print(f'"{cur_dir}" 에 여러개의 .mp4 파일이 존재합니다!')
continue
for filename in files:
if filename == 'youtube_url.txt':
video_path = thumbnail_path = None
print(f'already uploaded: {dir_name}')
break
current_video_name, ext = os.path.splitext(filename)
if ext == '.mp4':
if not dir_name.isnumeric():
print(f'skip: "{dir_name}" 는 숫자로 구성된 폴더이름이 아닙니다')
break
video_name = f'{int(dir_name):04}'
video_path = os.path.join(cur_dir, f'{video_name}.mp4')
if current_video_name != video_name:
print(f'rename "{filename}" to "{video_name}.mp4"')
os.rename(os.path.join(cur_dir, filename), video_path)
video_dirs[video_name] = cur_dir
elif ext == '.jpg' and re.match(r'^\d+[.]jpg$', filename):
thumbnail_path = os.path.join(cur_dir, filename)
if not (video_path and thumbnail_path):
continue
to_upload[int(dir_name)] = (video_name, video_path, thumbnail_path)
for dir_number, (video_name, video_path, thumbnail_path) in sorted(to_upload.items(), key=lambda e: e[0]):
# if not uploader:
uploader = YoutubeUploader()
try:
my_channel_id = uploader.init(chrome_driver_path, cookie_path)
except SessionNotCreatedException as e:
print(e)
print('컴퓨터에 설치된 chrome 과 chromedriver 의 버전이 일치하지 않습니다.')
print('https://chromedriver.chromium.org/downloads 에서 다시 chromedriver 를 다운로드 해주세요.')
break
with open(os.path.join(path, '.mychannelid'), 'w') as f:
f.write(my_channel_id)
print(f'uploading {video_name}')
try:
if uploader.upload_video(video_path, thumbnail_path):
print(f'success: {video_name}')
else:
print(f'failure: {video_name}')
except YoutubeUploaderException as e:
print(e)
print(f'failure: {video_name}')
try:
uploader.browser.close()
except:
pass
print('모든 업로드 작업을 마쳤습니다.')
exit_enter()
def update_youtube_urls(my_channel_id=None):
path = get_execution_path()
input_path = get_input_path_or_exit()
cookie_path = os.path.join(get_execution_path(), 'cookies.txt')
if not my_channel_id:
mychannelid_path = os.path.join(path, '.mychannelid')
if os.path.isfile(mychannelid_path):
with open(mychannelid_path, 'r') as f:
my_channel_id = f.read()
else:
print('youtube upload 를 먼저 실행해주세요')
exit_enter(1)
yn = input('기존에 존재하는 youtube_url.txt 도 덮어쓰시겠습니까? [y/n]: ')
overwrite = yn == 'y'
video_dirs = {}
for cur_dir, _, files in os.walk(input_path):
if not overwrite and os.path.isfile(os.path.join(cur_dir, 'youtube_url.txt')):
continue
dir_name = os.path.basename(cur_dir)
for filename in files:
name, ext = os.path.splitext(filename)
if ext == '.mp4' and dir_name.isnumeric():
video_dirs[name] = cur_dir
yt = youtube_dl.YoutubeDL(dict(cookiefile=cookie_path))
my_channel_playlist = yt.extract_info(
f'https://www.youtube.com/channel/{my_channel_id}', download=False, process=False
).get('url')
is_created = False
video_urls = {}
for video in yt.extract_info(my_channel_playlist, download=False, process=False).get('entries'):
title = video['title']
if title.isnumeric() and video_dirs.get(title):
is_created = True
video_urls[int(title)] = (title, f"https://www.youtube.com/watch?v={video['id']}")
if not is_created:
print('새로 업로드 된 동영상이 없거나, 아직 업로드가 완전히 완료되지 않았습니다.')
print('잠시 후 다시 시도해주세요.')
else:
for _, (title, url) in sorted(video_urls.items(), key=itemgetter(0)):
print(f'make youtube_url.txt: {title}')
with open(os.path.join(video_dirs[title], 'youtube_url.txt'), 'w') as f:
f.write(url)
exit_enter()
def qrcode():
input_path = get_input_path_or_exit()
chrome_driver_path = get_chrome_driver_path_or_exit()
resource_path = get_resource_path()
if not os.path.isfile(os.path.join(resource_path, 'DXGulimB-KSCpc-EUC-H.ttf')):
print('폰트 파일을 찾을 수 없습니다.')
print('DXGulimB-KSCpc-EUC-H.ttf 파일을 "font/" 안에 넣어주세요!')
exit_enter(1)
naver_qr: Optional[NaverQrCode] = None
def walk_dir():
walk_dirs = {}
for cur_dir, dirs, files in os.walk(input_path):
dir_name = os.path.basename(cur_dir)
if not dir_name.isnumeric():
continue
if 'youtube_url.txt' not in files:
continue
if 'qrcode.html' in files:
print(f'already created: {dir_name}')
continue
walk_dirs[int(dir_name)] = (cur_dir, dirs, files)
return (v for k, v in sorted(walk_dirs.items(), key=itemgetter(0)))
for cur_dir, _, files in walk_dir():
dir_name = os.path.basename(cur_dir)
idx = int(dir_name)
idx_text = f'{idx:04}'
with open(os.path.join(cur_dir, 'youtube_url.txt'), 'r') as f:
youtube_url = f.read()
if not naver_qr:
naver_qr = NaverQrCode()
naver_qr.init(chrome_driver_path)
print('waiting login ...')
naver_qr.login()
print('login success')
qr_data = naver_qr.create_qr(idx_text, youtube_url).get('QRCodeData', {})
qr_url = qr_data.get('qrCodeUrl')
qr_id = qr_data.get('qrcdNo')
if not qr_url:
print(f'{idx_text}: QR CODE 생성에 실패했습니다')
continue
with cd(resource_path):
print(f'creating "{idx_text}.png"')
image = make_qr_image(Size(591, 738), qr_url, idx) # 5cm x 6.25cm (300dpi)
with open(os.path.join(cur_dir, f'{idx_text}.png'), 'wb') as f:
image.save(f, format='PNG', dpi=(300, 300))
make_redirect_html(
os.path.join(cur_dir, 'qrcode.html'),
f'https://qr.naver.com/code/updateForm.nhn?qrcdNo={qr_id}'
)
if naver_qr:
naver_qr.visit_admin_page()
print('모든 작업이 끝났습니다.')
input('press enter to exit...')
if naver_qr:
naver_qr.close()
sys.exit(0)
def organize():
input_path = get_input_path_or_exit()
for filename in os.listdir(input_path):
filepath = os.path.join(input_path, filename)
if not os.path.isfile(filepath) or 'README.txt' == filename:
continue
name, _ = os.path.splitext(filename)
if not name.isnumeric():
print(f'pass: "{filename}" 은 숫자로 이루어진 이름이 아닙니다')
continue
dir_path = os.path.join(input_path, f'{int(name)}')
os.makedirs(dir_path, exist_ok=True)
try:
os.rename(filepath, os.path.join(dir_path, filename))
print(f'move "{filename}" to "{int(name)}/{filename}"')
except Exception as e:
print(f'"{filename}" 을 옮기는데 실패하였습니다: {e}')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Chip Helper')
subparsers = parser.add_subparsers(help='commands', dest='command', required=True)
subparsers.add_parser('makedirs', help='Create dirs like "nnnn" format in a specific path')
subparsers.add_parser('organize', help='Create numeric dirs and move video files in it')
subparsers.add_parser('thumbnail', help='Create thumbnails')
subparsers.add_parser('upload', help='Upload videos to youtube')
subparsers.add_parser('youtube-url', help='Make youtube_url.txt in input dirs')
subparsers.add_parser('qrcode', help='Generate Naver QR and composite qr image')
args = parser.parse_args()
func = {
'makedirs': make_dirs,
'thumbnail': make_thumbnail,
'upload': upload_videos,
'youtube-url': update_youtube_urls,
'qrcode': qrcode,
'organize': organize,
}.get(args.command)
func()
print('모든 작업이 완료되었습니다.')
exit_enter()
| 34.450617
| 110
| 0.610554
| 1,497
| 11,162
| 4.336673
| 0.213761
| 0.034196
| 0.032348
| 0.020025
| 0.255083
| 0.168361
| 0.138324
| 0.10382
| 0.094886
| 0.066081
| 0
| 0.010888
| 0.267694
| 11,162
| 323
| 111
| 34.557276
| 0.783337
| 0.003404
| 0
| 0.237548
| 0
| 0
| 0.186044
| 0.01097
| 0
| 0
| 0
| 0
| 0
| 1
| 0.030651
| false
| 0.011494
| 0.05364
| 0
| 0.091954
| 0.153257
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01092c860365112e2ab6bab4644a012763fb75a9
| 3,729
|
py
|
Python
|
Soccer_league_project1.py
|
denisela1/Soccer_League_P1
|
5bc6de71259643ed2a6d9791ddbc70773f1c259d
|
[
"BSD-3-Clause-Clear"
] | 1
|
2018-02-26T08:47:15.000Z
|
2018-02-26T08:47:15.000Z
|
Soccer_league_project1.py
|
denisela1/Soccer_League_P1
|
5bc6de71259643ed2a6d9791ddbc70773f1c259d
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
Soccer_league_project1.py
|
denisela1/Soccer_League_P1
|
5bc6de71259643ed2a6d9791ddbc70773f1c259d
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
import csv
#global variables for teams:
sharks = []
dragons = []
raptors = []
#read the csv file with the player info and create a player dictionary:
def read_players():
player_reader = csv.reader(open('soccer_players.csv'))
player_dictionary = {}
for row in player_reader:
key = row[0]
player_dictionary[key] = row[1:]
#deleting the first row with column titles:
del player_dictionary['Name']
return player_dictionary
#distribute kids based on experience:
def experienced_players():
exp_kids = []
#calling the previous function to use the player dictionary:
player_list = read_players()
for keys, values in player_list.items():
if values[1] == "YES":
exp_kids.append(keys)
return exp_kids
def inexperienced_players():
inexp_kids = []
#calling the previous function to use the player dictionary:
player_list = read_players()
for keys, values in player_list.items():
if values[1] == "NO":
inexp_kids.append(keys)
return inexp_kids
#finalize teams:
def make_teams():
#calling a previous function to generate 2 separate lists for experienced and inexperienced kids:
ek = experienced_players()
iek = inexperienced_players()
sharks.extend(ek[0:3])
sharks.extend(iek[0:3])
dragons.extend(ek[3:6])
dragons.extend(iek[3:6])
raptors.extend(ek[6:9])
raptors.extend(iek[6:9])
return sharks, dragons, raptors
#update the player dictionary to include the assigned teams:
def final_league():
#calling the function to create a player dictionary
letter_info = read_players()
for keys, values in letter_info.items():
if keys in sharks:
values.append("Sharks")
if keys in dragons:
values.append("Dragons")
if keys in raptors:
values.append("Raptors")
return letter_info
#write the league info into the text file:
def create_textfile():
files = final_league()
with open("teams.txt", "w") as textfile:
textfile.write("Sharks" + "\n")
for keys,values in files.items():
if values[3] == "Sharks":
textfile.write(str(keys) + ", " + str(values[1]) + ", " + str(values[2]) + "\n")
textfile.write("\n")
textfile.write("Dragons" + "\n")
for keys, values in files.items():
if values[3] == "Dragons":
textfile.write(str(keys) + ", " + str(values[1]) + ", " + str(values[2]) + "\n")
textfile.write("\n")
textfile.write("Raptors" + "\n")
for keys, values in files.items():
if values[3] == "Raptors":
textfile.write(str(keys) + ", " + str(values[1]) + ", " + str(values[2]) + "\n")
textfile.write("\n")
#generate letters to send the guardians:
def letter_generator():
letters = final_league()
for keys, values in letters.items():
if values[3] == "Sharks":
practice_start = '8am'
if values[3] == "Dragons":
practice_start = '9am'
if values[3] == "Raptors":
practice_start = '10am'
for keys, values in letters.items():
letter = ("Dear {},\n"
"Congratulations! Your child, {}, is selected to play on the {} team. "
"The first practice is at {} next Saturday, July 1st."
"Thanks,\n"
"Coach Deniz".format(values[2],keys,values[3],practice_start))
with open("{}.txt".format((keys.lower()).replace(" ", "_")), "w") as textfile:
textfile.write(letter)
if __name__ == "__main__":
read_players()
experienced_players()
inexperienced_players()
make_teams()
create_textfile()
final_league()
letter_generator()
| 33.594595
| 97
| 0.61196
| 467
| 3,729
| 4.770878
| 0.246253
| 0.058348
| 0.046679
| 0.05386
| 0.302065
| 0.271095
| 0.235189
| 0.235189
| 0.235189
| 0.235189
| 0
| 0.01295
| 0.254492
| 3,729
| 110
| 98
| 33.9
| 0.788489
| 0.159024
| 0
| 0.235955
| 0
| 0
| 0.104033
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.078652
| false
| 0
| 0.011236
| 0
| 0.146067
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
010b4ad2a97b357a77ffe35ad3089e6223aec664
| 2,312
|
py
|
Python
|
Gobot-Mecanum/robot.py
|
FRC1076/2019-Parade
|
3824449ed10e33b401efb646fd2e6470c3941c8b
|
[
"MIT"
] | null | null | null |
Gobot-Mecanum/robot.py
|
FRC1076/2019-Parade
|
3824449ed10e33b401efb646fd2e6470c3941c8b
|
[
"MIT"
] | 2
|
2019-06-17T23:38:23.000Z
|
2019-06-17T23:39:43.000Z
|
Gobot-Mecanum/robot.py
|
FRC1076/2019-Parade
|
3824449ed10e33b401efb646fd2e6470c3941c8b
|
[
"MIT"
] | null | null | null |
import wpilib
import wpilib.drive
import ctre
import robotmap
from wpilib.interfaces import GenericHID
RIGHT_HAND = GenericHID.Hand.kRight
LEFT_HAND = GenericHID.Hand.kLeft
class Robot(wpilib.TimedRobot):
def robotInit(self):
front_left_motor = ctre.WPI_TalonSRX(robotmap.mecanum['front_left_motor'])
back_left_motor = ctre.WPI_TalonSRX(robotmap.mecanum['back_left_motor'])
front_right_motor = ctre.WPI_TalonSRX(robotmap.mecanum['front_right_motor'])
back_right_motor = ctre.WPI_TalonSRX(robotmap.mecanum['back_right_motor'])
front_left_motor.setInverted(True)
#back_left_motor.setInverted(True)
self.drive = wpilib.drive.MecanumDrive(
front_left_motor,
back_left_motor,
front_right_motor,
back_right_motor
)
self.drive.setExpiration(0.1)
self.lstick = wpilib.XboxController(0)
self.rstick = wpilib.XboxController(1)
self.gyro = wpilib.AnalogGyro(1)
#def teleopInit(self):
# self.xforward = 0
# self.yforward = 0
"""def operatorControl(self):
Called when operation control mode is enabled
while self.isOperatorControl() and self.isEnabled():
self.drive.driveCartesian(
self.lstick.getX(), self.lstick.getY(), self.rstick.getX(), 0
)
wpilib.Timer.delay(0.04)
"""
def teleopPeriodic(self):
"""Called when operation control mode is enabled"""
if not self.rstick.getXButton() or not self.lstick.getXButton():
lspeed = deadzone(self.lstick.getX(LEFT_HAND), 0.2)
rspeed = deadzone(self.lstick.getY(LEFT_HAND), 0.2)
rotate = self.lstick.getX(RIGHT_HAND)
else:
rotate = 0
lspeed = 0
rspeed = 0
self.drive.driveCartesian(
lspeed, rspeed, rotate, self.gyro.getAngle()
)
def deadzone(val, deadzone):
if abs(val) < deadzone:
return 0
elif val < (0):
x = ((abs(val) - deadzone)/(1-deadzone))
return (-x)
else:
x = ((val - deadzone)/(1-deadzone))
return (x)
if __name__ == "__main__":
wpilib.run(Robot,physics_enabled=True)
| 27.2
| 86
| 0.608564
| 263
| 2,312
| 5.174905
| 0.296578
| 0.052902
| 0.041146
| 0.05878
| 0.303453
| 0.303453
| 0.192506
| 0.063189
| 0
| 0
| 0
| 0.013333
| 0.286332
| 2,312
| 85
| 87
| 27.2
| 0.811515
| 0.061419
| 0
| 0.042553
| 0
| 0
| 0.03913
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.06383
| false
| 0
| 0.106383
| 0
| 0.255319
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0118814a3663bee91c59984af98f47d72c8f9e4c
| 2,555
|
py
|
Python
|
machine-learning-and-ai/handwriting-classifier/neural_network_handwriting_classifier.py
|
fraserlove/python
|
b449259c02e73102e37a4cd42018dbcc6b04d0ba
|
[
"Apache-2.0"
] | 16
|
2020-06-11T16:54:55.000Z
|
2022-01-07T01:36:05.000Z
|
machine-learning-and-ai/handwriting-classifier/neural_network_handwriting_classifier.py
|
fraserlove/python-projects
|
b449259c02e73102e37a4cd42018dbcc6b04d0ba
|
[
"Apache-2.0"
] | null | null | null |
machine-learning-and-ai/handwriting-classifier/neural_network_handwriting_classifier.py
|
fraserlove/python-projects
|
b449259c02e73102e37a4cd42018dbcc6b04d0ba
|
[
"Apache-2.0"
] | 15
|
2020-06-14T08:29:50.000Z
|
2021-08-05T17:25:42.000Z
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
# Network hyperparameters
learning_rate = 0.0001 # 1.95 for sigmoid activation function
batch_size = 10
update_step = 10
input_nodes = 784 # 28x38 images as input
layer_1_nodes = 500
layer_2_nodes = 500
layer_3_nodes = 500
output_nodes = 10
network_input = tf.placeholder(tf.float32, [None, input_nodes])
target_output = tf.placeholder(tf.float32, [None, output_nodes])
# Network model, weights and biases
layer_1 = tf.Variable(tf.random_normal([input_nodes, layer_1_nodes]))
layer_2 = tf.Variable(tf.random_normal([layer_1_nodes, layer_2_nodes]))
layer_3 = tf.Variable(tf.random_normal([layer_2_nodes, layer_3_nodes]))
output_layer = tf.Variable(tf.random_normal([layer_3_nodes, output_nodes]))
layer_1_bias = tf.Variable(tf.random_normal([layer_1_nodes]))
layer_2_bias = tf.Variable(tf.random_normal([layer_2_nodes]))
layer_3_bias = tf.Variable(tf.random_normal([layer_3_nodes]))
output_layer_bias = tf.Variable(tf.random_normal([output_nodes]))
# Feedforward calculations
layer_1_out = tf.nn.relu(tf.matmul(network_input, layer_1) + layer_1_bias)
layer_2_out = tf.nn.relu(tf.matmul(layer_1_out, layer_2) + layer_2_bias)
layer_3_out = tf.nn.relu(tf.matmul(layer_2_out, layer_3) + layer_3_bias)
network_out_1 = tf.matmul(layer_3_out, output_layer) + output_layer_bias
network_out_2 = tf.nn.softmax(network_out_1)
cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = network_out_1, labels = target_output))
training_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)
predicitions = tf.equal(tf.argmax(network_out_2, 1), tf.argmax(target_output, 1))
accuracy = tf.reduce_mean(tf.cast(predicitions, tf.float32))
# Running the neural network
with tf.Session() as session:
session.run(tf.global_variables_initializer())
no_epochs = 10
for epoch in range(no_epochs):
total_cost = 0
no_batches = int(mnist.train.num_examples / batch_size)
for batch in range(no_batches):
input_data, labels = mnist.train.next_batch(batch_size)
step, cost = session.run([training_step, cost_function], feed_dict = {network_input: input_data, target_output: labels})
total_cost += cost
print('Epoch {} out of {} completed, loss: {}'.format(epoch, no_epochs, total_cost))
print('Accuracy: {}'.format(accuracy.eval({network_input: mnist.test.images, target_output: mnist.test.labels})))
| 46.454545
| 132
| 0.768689
| 400
| 2,555
| 4.58
| 0.26
| 0.032751
| 0.052402
| 0.078603
| 0.260917
| 0.192686
| 0.167031
| 0.134279
| 0.134279
| 0.08952
| 0
| 0.033718
| 0.117808
| 2,555
| 54
| 133
| 47.314815
| 0.779059
| 0.065753
| 0
| 0
| 0
| 0
| 0.02521
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.047619
| 0
| 0.047619
| 0.047619
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
011929cc6bf535432cf049cfeb608476447f32f5
| 1,157
|
py
|
Python
|
202_happyNumber.py
|
stuti-rastogi/leetcode-python-solutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | 4
|
2018-07-24T08:36:42.000Z
|
2019-08-25T17:48:47.000Z
|
202_happyNumber.py
|
stuti-rastogi/leetcodesolutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | null | null | null |
202_happyNumber.py
|
stuti-rastogi/leetcodesolutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | null | null | null |
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seen = set()
while (True):
sumOfSquaredDigits = 0
while n > 0:
digit = n % 10
n = n // 10
sumOfSquaredDigits += digit**2
if sumOfSquaredDigits == 1:
return True
if sumOfSquaredDigits in seen:
return False
seen.add(sumOfSquaredDigits)
n = sumOfSquaredDigits
# seen = []
# while (True):
# print (seen)
# digits = self.getDigits(n)
# total = 0
# print ("Digits: " + str(digits))
# for i in digits:
# total += int(pow(i,2))
# if (total in seen):
# return False
# if (total == 1):
# return True
# seen.append(total)
# n = total
# def getDigits(self, n):
# digits = []
# while (n > 0):
# digits.append(n%10)
# n = n//10
# return digits
| 26.906977
| 46
| 0.395851
| 103
| 1,157
| 4.446602
| 0.339806
| 0.026201
| 0.030568
| 0.021834
| 0.030568
| 0
| 0
| 0
| 0
| 0
| 0
| 0.027586
| 0.498704
| 1,157
| 43
| 47
| 26.906977
| 0.762069
| 0.503889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.066667
| false
| 0
| 0
| 0
| 0.266667
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
011b749c0cb7168d1d612e734d1940a1245eb56c
| 9,091
|
py
|
Python
|
entity.py
|
PIRXrav/pyhack
|
af5c86fb721053d8a3e819ab772c8144a23b86bf
|
[
"MIT"
] | null | null | null |
entity.py
|
PIRXrav/pyhack
|
af5c86fb721053d8a3e819ab772c8144a23b86bf
|
[
"MIT"
] | null | null | null |
entity.py
|
PIRXrav/pyhack
|
af5c86fb721053d8a3e819ab772c8144a23b86bf
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# pylint: disable=C0103
"""
Définie la classe entity
Permet de modeliser le personnage et des monstre
"""
from random import choice
from vect import Vect
from astar import calc_path_astart
import chars
class Player():
"""
Classe Player :
"""
BULLET_MAX = 10
HP_MAX = 10
START_MONEY = 0
def __init__(self):
"""
Personnage
"""
self.pos = Vect(0, 0)
self.direction = Vect(1, 0)
self.distance_view = 7
self.bullet = self.BULLET_MAX
self.hp = self.HP_MAX
self.level = 0
self.money = self.START_MONEY
self.sword_damage = 1
self.gun_damage = 2
def level_up(self, pos):
"""
Le personnage gagne un level
"""
self.level += 1
self.pos = pos
def g_case_visible(self, mat_collide):
"""
retourne sur toutes les cases visibles
par self dans mat_collide
"""
# Nb : prend les segments depuis un cercle et non un rect
# n'est pas OK
border = self.pos.g_rect(Vect(self.distance_view, self.distance_view))
for bordure_pos in border:
for pos in self.pos.g_bresenham_line(bordure_pos):
if self.pos.distance(pos) >= self.distance_view:
break
if not Vect(0, 0) <= pos < Vect(len(mat_collide),
len(mat_collide[0])):
break
if not mat_collide[pos.x][pos.y]:
yield pos
break
yield pos
def shoot(self):
"""
Tire une nouvelle balle
"""
self.bullet -= 1
return Bullet(self.pos, self.direction, self.gun_damage)
def strike(self, mat_collide):
"""
Donne un coup d'épée
"""
return Sword(self.pos + self.direction, self.sword_damage)
def add_money(self, value):
"""
Ajoute des pièces au Player
"""
assert value >= 0
self.money += value
return True
def add_hp(self, value):
"""
Ajoute des HP au Player
"""
assert value >= 0
if self.hp == self.HP_MAX:
return False
self.hp = min(self.hp + value, self.HP_MAX)
return True
def add_bullets(self, value):
"""
Ajoute des balles au Player
"""
assert value >= 0
if self.bullet == self.BULLET_MAX:
return False
self.bullet = min(self.bullet + value, self.BULLET_MAX)
return True
def update(self, mat_collide, depl_vect):
"""
Met à jour la position du personnage en fonction des evenements
et de mat_collide
"""
if depl_vect != Vect(0, 0):
self.direction = depl_vect
new_pos = self.pos + depl_vect
# Tests de collision (Diagonales)
if mat_collide[new_pos.x][self.pos.y]:
# premier chemin libre en x
if mat_collide[new_pos.x][new_pos.y]:
# deuxieme chemin libre en y
self.pos = new_pos
else:
# deuxieme chemin bloque en y
self.pos.x = new_pos.x
elif mat_collide[self.pos.x][new_pos.y]:
# premier chemin libre en y
if mat_collide[new_pos.x][new_pos.y]:
# deuxieme chemin libre en x
self.pos = new_pos
else:
# deuxieme chemin bloque en x
self.pos.y = new_pos.y
else:
# Aucun chemin libre
# Do nothind
pass
def render(self):
"""
Retourne le char à afficher
"""
return chars.C_PLAYER
def __str__(self):
"""
Retourne une chaine d'affichage
"""
heal_str = ('\u2665' * int(self.hp / self.HP_MAX * 10)
+ ' ' * (10-int(self.hp / self.HP_MAX * 10)))
bullet_str = ('|' * int(self.bullet)
+ ' ' * int(self.BULLET_MAX - self.bullet))
return ('Position : {} | HP : ['
+ heal_str
+ '] | Bullets ['
+ bullet_str + ']')
class Bullet:
"""
Classe Bullet :
"""
def __init__(self, pos, directions, dammage):
"""
Personnage
"""
self.pos = pos
self.direction = directions
self.dammage = dammage
def update(self, mat_collide):
"""
Met à jour la balle
Retourne 1 si elle touche un obstacle
"""
self.pos += self.direction
return mat_collide[self.pos.x][self.pos.y]
def render(self):
"""
Retourne le char à afficher
"""
return chars.C_BULLETS[int(self.direction.angle()/2/3.1415 * 8)]
def __str__(self):
return "(*:{})".format(self.pos)
class Monster:
"""
Monster
"""
IDLE = 0
RUN = 1
DECOMPOSITION = 2
SHOCKED = 3
def __init__(self, pos, dammage, health):
"""
Personnage
"""
self.pos = pos
self.dammage = dammage
self.health = health
self.shocked = 0
self.state = self.IDLE
self.ttd = 8 # TIme to die
# TEMP
# Le chemin du monstre au joueur
self.path = []
def update(self, mat_collide, player_pos):
"""
Met à jour l'enemie
"""
if self.state == self.SHOCKED:
if self.shocked:
self.shocked -= 1
else:
self.state = self.IDLE
return False
if self.state == self.IDLE or self.state == self.RUN:
if self.pos.distance(player_pos) <= 10:
self.state = self.RUN
else:
self.state = self.IDLE
if self.state == self.RUN:
self.path = calc_path_astart(mat_collide, self.pos, player_pos)
if self.path != []:
self.pos = self.path[0]
if self.state == self.IDLE:
# TODO: Depl aléatoire
pass
return False
self.ttd -= 1
return self.ttd == 0 # Mort
def render(self):
"""
Retourne le char à afficher
"""
if self.state == self.RUN:
return chars.C_MONSTER_RUN
return chars.C_MONSTERS[self.ttd % len(chars.C_MONSTERS)]
def kill(self):
"""
Elimine le mechant
"""
if self.health <= 0:
self.state = self.DECOMPOSITION
else:
self.state = self.SHOCKED
self.shocked = 4
def __str__(self):
return "(*:{})".format(self.pos)
class Treasure:
"""
Trésor, peut contenir 3 types d'objet différents :
* des sous
* des munitions
* de la vie
"""
HEART = 0
BULLET = 1
GOLD = 2
STRENGH = 3
POWER = 4
CHARS = [chars.C_HEART, chars.C_BULLET_CHRG, chars.C_MONEY]
def __init__(self, pos, value):
"""
Init
"""
self.pos = pos
if value == 1:
self.object = choice([self.HEART, self.BULLET, self.GOLD])
else:
self.cpt = -1
if value == 2:
self.object = self.STRENGH
else:
self.object = self.POWER
self.value = value
def render(self):
"""
Render
"""
if self.value == 1:
return self.CHARS[self.object]
self.cpt += 1
if self.value == 2:
return chars.C_TRE_WEAPON[self.cpt % len(chars.C_TRE_WEAPON)]
return chars.C_TRE_GUN[self.cpt % len(chars.C_TRE_GUN)]
def get_value(self):
"""
Retourne la valeur du contenue du coffre
"""
return self.value
class Sword:
"""
coup d'épée venant du joueur
"""
DELTA_POSS = list(Vect(0, 0).g_rect(Vect(1, 1)))
def __init__(self, pos, dammage):
self.pos = pos
self.cpt = len(self.DELTA_POSS)-1
self.dammage = dammage
def update(self, mat_collide, player_pos):
"""
Met à jour l'enemie
"""
if self.cpt < 0:
return True
self.pos = player_pos + self.DELTA_POSS[self.cpt]
self.cpt -= 1
return False
def render(self):
"""
render
"""
return chars.C_SWORDS[- self.cpt % len(chars.C_SWORDS)]
class Door:
"""
La porte de sortie
"""
def __init__(self, pos):
"""
Init
"""
self.pos = pos
self.cpt = 0
def update(self):
"""
Update
"""
def render(self):
"""
Render
"""
self.cpt += 1
return chars.C_DOORS[self.cpt % len(chars.C_DOORS)]
def main():
"""
Test unitaire
"""
if __name__ == '__main__':
main()
| 24.438172
| 79
| 0.494995
| 1,066
| 9,091
| 4.082552
| 0.206379
| 0.054688
| 0.035846
| 0.016085
| 0.29136
| 0.168658
| 0.144531
| 0.123392
| 0.085938
| 0.068015
| 0
| 0.014882
| 0.401276
| 9,091
| 371
| 80
| 24.504043
| 0.784678
| 0.146739
| 0
| 0.3125
| 0
| 0
| 0.009295
| 0
| 0
| 0
| 0
| 0.002695
| 0.015625
| 1
| 0.15625
| false
| 0.010417
| 0.020833
| 0.010417
| 0.416667
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
011dbd3f8e4f3dc4a3cd128fe4d90224e86d26f2
| 3,488
|
py
|
Python
|
apps/Ipo.py
|
KiloSat/FirstNivesh
|
0fe200e08bb9f7d89de91f59eb14448fa7b972b9
|
[
"MIT"
] | null | null | null |
apps/Ipo.py
|
KiloSat/FirstNivesh
|
0fe200e08bb9f7d89de91f59eb14448fa7b972b9
|
[
"MIT"
] | null | null | null |
apps/Ipo.py
|
KiloSat/FirstNivesh
|
0fe200e08bb9f7d89de91f59eb14448fa7b972b9
|
[
"MIT"
] | 2
|
2021-04-03T16:39:23.000Z
|
2021-08-15T08:09:21.000Z
|
import streamlit as st
def app():
import plotly.express as px
import plotly.graph_objects as go
from textblob import TextBlob
import tweepy
import sys
import pandas as pd
api_key = 'q7QHHHAKEwd5igoUvVrx5sCiw'
api_secret_key = 'i7uhcFirM38bnbYscv32beJnMpsmMxFdYSHitwfSCPIeMj7Lcs'
access_token = '916414257993879552-kWKlelyL9e6HGH40wcdawT8CiCvO3Hz'
access_token_secret= 'zYflOPrxysrdOsQiAhp8gmJjAtwRMUcSyX6KlexMk03eB'
auth_handler = tweepy.OAuthHandler(consumer_key = api_key,consumer_secret=api_secret_key)
auth_handler.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth_handler)
searchwhat = st.sidebar.text_input("Search Term", 'Zomato IPO')
tweet_amount = int(st.sidebar.text_input('Tweet Amount', '50'))
tweets = tweepy.Cursor(api.search,q=searchwhat,lang='en').items(tweet_amount)
polarity,positive,negative,neutral = 0,0,0,0
tweetlist = []
polaritylist = []
for tweet in tweets:
final_text = tweet.text.replace('RT','')
if final_text.startswith(' @'):
position = final_text.index(':')
final_text = final_text[position+2:]
if final_text.startswith('@'):
position = final_text.index('')
final_text = final_text[position+2:]
analysis = TextBlob(final_text)
tweet_polarity = analysis.polarity
if tweet_polarity>0:
positive+=1
polaritylist.append('positive')
elif tweet_polarity<0:
negative+=1
polaritylist.append('negative')
else:
neutral+=1
polaritylist.append('neutral')
polarity += tweet_polarity
tweetlist.append(final_text)
labels = ['Positive','Negative','Neutral']
values = [positive,negative,neutral]
st.write(f'The Sentiment Analysis for Search Term : {searchwhat}')
# Use `hole` to create a donut-like pie chart
fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5)])
st.plotly_chart(fig)
# tweetcontainer = pd.DataFrame(list(zip(tweetlist,polaritylist)),columns=['Tweets','Sentiment'])
# st.write(tweetcontainer)
if len(tweetlist)<10:
def showTweets(index=0,limit=len(tweetlist)):
while(index<limit):
st.write(tweetlist[index])
st.write(polaritylist[index])
index+=1
with st.beta_expander('See the Tweets'):
showTweets()
else:
def showTweets(index=0,limit=10):
while(index<limit):
st.write(tweetlist[index])
st.write(polaritylist[index])
index+=1
with st.beta_expander('See the Tweets'):
showTweets()
st.subheader('RHP Analysis')
#st.write('Enter any text from the RHP here')
user_input = st.text_area('Enter any section from the RHP here')
rhpanalysis = TextBlob(user_input)
rhppolarity = rhpanalysis.polarity
if rhppolarity>0:
ipo_outlook = 'Positve'
elif rhppolarity<0:
ipo_outlook = 'Negative'
else:
ipo_outlook = 'Neutral'
with st.beta_expander('See the Analysis'):
st.subheader(f'Outlook of the Particular IPO is {ipo_outlook} with polarity :{rhppolarity}')
| 35.591837
| 109
| 0.610952
| 375
| 3,488
| 5.549333
| 0.322667
| 0.047573
| 0.033157
| 0.025949
| 0.203748
| 0.180682
| 0.169149
| 0.169149
| 0.169149
| 0.169149
| 0
| 0.024537
| 0.287271
| 3,488
| 97
| 110
| 35.958763
| 0.81255
| 0.059633
| 0
| 0.253333
| 0
| 0
| 0.157332
| 0.053493
| 0
| 0
| 0
| 0
| 0
| 1
| 0.04
| false
| 0
| 0.093333
| 0
| 0.133333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
011ec6d9a369d9cd8fa960e87d7fc5aabbdb09f6
| 2,447
|
py
|
Python
|
tests/test_unit_varfilter.py
|
gomibaya/pyVarfilter
|
098414223e575dda3fabe7b8ccb1b16f6f8da3a0
|
[
"MIT"
] | null | null | null |
tests/test_unit_varfilter.py
|
gomibaya/pyVarfilter
|
098414223e575dda3fabe7b8ccb1b16f6f8da3a0
|
[
"MIT"
] | null | null | null |
tests/test_unit_varfilter.py
|
gomibaya/pyVarfilter
|
098414223e575dda3fabe7b8ccb1b16f6f8da3a0
|
[
"MIT"
] | null | null | null |
import unittest
import logging
from varfilter import varfilter, filter
class TestVarfilter(unittest.TestCase):
def setUp(self):
print("Preparando el contexto")
self.source1 = {"teststr1": "Value teststr1",
"testint1": 10}
self.source2 = {"teststr2": "Value teststr2",
"testint2": 10,
"teststr": "Value str"}
def test_fVar_default_nonexistent(self):
print("fVar con valor por defecto no existente")
t = varfilter.fVar("test1",
"default value",
None,
self.source1)
self.assertEqual(t, "default value")
def test_fVar_default_nonexistent_int(self):
print("fVar con valor por defecto no existente de tipo int")
t = varfilter.fVar("test1",
0,
"int",
self.source1)
self.assertEqual(t, 0)
def test_fVar_default_existent(self):
print("fVar con valor por defecto")
t = varfilter.fVar("teststr1",
"default value",
None,
self.source1)
self.assertEqual(t, "Value teststr1")
def test_fVar_default_existent_int(self):
print("fVar con valor por defecto existente de tipo int")
t = varfilter.fVar("testint1",
0,
"int",
self.source1)
self.assertEqual(t, 10)
def test_fVar_default_existent_int_filtererror(self):
print("fVar con valor por defecto erroneo existente de tipo int")
self.assertRaises(filter.IntegerError,
varfilter.fVar,
'test1',
'error',
'int',
self.source1)
def test_fVar_existent_severalsources(self):
print("fVar con valor existente varios sources")
t = varfilter.fVar("teststr",
"default value",
None,
self.source1,
self.source2)
self.assertEqual(t, "Value str")
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s - %(message)s',
level=logging.DEBUG)
unittest.main()
| 34.464789
| 73
| 0.495709
| 224
| 2,447
| 5.28125
| 0.28125
| 0.053254
| 0.05579
| 0.08115
| 0.487743
| 0.398986
| 0.326289
| 0.174979
| 0.071006
| 0
| 0
| 0.021008
| 0.416428
| 2,447
| 70
| 74
| 34.957143
| 0.807423
| 0
| 0
| 0.288136
| 0
| 0
| 0.211279
| 0
| 0
| 0
| 0
| 0
| 0.101695
| 1
| 0.118644
| false
| 0
| 0.050847
| 0
| 0.186441
| 0.118644
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01203f70632858bfabcba480840b28432e8c773f
| 4,989
|
py
|
Python
|
tests/test_extensions/test_arithmatex.py
|
pawamoy/pymdown-extensions
|
90de4c0c52456751141e898af3941c729914a80e
|
[
"MIT"
] | null | null | null |
tests/test_extensions/test_arithmatex.py
|
pawamoy/pymdown-extensions
|
90de4c0c52456751141e898af3941c729914a80e
|
[
"MIT"
] | null | null | null |
tests/test_extensions/test_arithmatex.py
|
pawamoy/pymdown-extensions
|
90de4c0c52456751141e898af3941c729914a80e
|
[
"MIT"
] | null | null | null |
"""Test cases for Arithmatex."""
from .. import util
class TestArithmatexLimit(util.MdCase):
"""Test limiting Arithmatex inline and block inputs."""
extension = [
'pymdownx.arithmatex'
]
extension_configs = {'pymdownx.arithmatex': {'inline_syntax': ['round'], 'block_syntax': ['square']}}
def test_round_only(self):
"""Test round only."""
self.check_markdown(
"\\(1 + 2 + 3\\)",
"""<p><span class="arithmatex"><span class="MathJax_Preview">1 + 2 + 3</span><script type="math/tex">1 + 2 + 3</script></span></p>""" # noqa: E501
)
def test_square_only(self):
"""Test square only."""
self.check_markdown(
r"""
\[
1 + 2 + 3
\]
""",
r"""
<div class="arithmatex">
<div class="MathJax_Preview">
1 + 2 + 3
</div>
<script type="math/tex; mode=display">
1 + 2 + 3
</script>
</div>
""",
True
)
class TestArithmatexBlockEscapes(util.MdCase):
"""Test escaping cases for Arithmatex blocks."""
extension = [
'pymdownx.arithmatex'
]
extension_configs = {}
def test_escaped_dollar_block(self):
"""Test escaping a dollar."""
self.check_markdown(
r'''
$$3+2\$$
''',
r'''
<p>$<span class="arithmatex"><span class="MathJax_Preview">3+2\$</span><script type="math/tex">3+2\$</script></span></p>
''', # noqa: E501
True
)
def test_escaped_dollar_dollar_block(self):
"""Test escaping both dollars."""
self.check_markdown(
r'''
$$3+2\$\$
''',
r'''
<p>$$3+2$$</p>
''',
True
)
def test_double_escaped_dollar_block(self):
"""Test double escaping a dollar."""
self.check_markdown(
r'''
$$3+2\\$$
''',
r'''
<div class="arithmatex">
<div class="MathJax_Preview">3+2\\</div>
<script type="math/tex; mode=display">3+2\\</script>
</div>
''',
True
)
def test_escaped_end_block(self):
"""Test escaping an end."""
self.check_markdown(
r'''
\begin{align}3+2\\end{align}
''',
r'''
<p>\begin{align}3+2\end{align}</p>
''',
True
)
def test_double_escaped_end_block(self):
"""Test double escaping an end."""
self.check_markdown(
r'''
\begin{align}3+2\\\end{align}
''',
r'''
<div class="arithmatex">
<div class="MathJax_Preview">\begin{align}3+2\\\end{align}</div>
<script type="math/tex; mode=display">\begin{align}3+2\\\end{align}</script>
</div>
''',
True
)
def test_escaped_bracket_block(self):
"""Test escaping a bracket."""
self.check_markdown(
r'''
\[3+2\\]
''',
r'''
<p>[3+2\]</p>
''',
True
)
def test_double_escaped_bracket_block(self):
"""Test double escaping a bracket."""
self.check_markdown(
r'''
\[3+2\\\]
''',
r'''
<div class="arithmatex">
<div class="MathJax_Preview">3+2\\</div>
<script type="math/tex; mode=display">3+2\\</script>
</div>
''',
True
)
class TestArithmatexHang(util.MdCase):
"""Test hang cases."""
def test_hang_dollar(self):
"""
We are just making sure this works.
Previously this pattern would hang. It isn't supposed to match due to the space before the last dollar,
but it definitely shouldn't hang the process.
"""
self.check_markdown(
r'''
$z^{[1]} = \begin{bmatrix}w^{[1]T}_1 \\ w^{[1]T}_2 \\ w^{[1]T}_3 \\ w^{[1]T}_4 \end{bmatrix} \begin{bmatrix}x_1 \\ x_2 \\ x_3 \end{bmatrix} + \begin{bmatrix}b^{[1]}_1 \\ b^{[1]}_2 \\ b^{[1]}_3 \\ b^{[1]}_4 \end{bmatrix}= \begin{bmatrix}w^{[1]T}_1 x + b^{[1]}_1 \\ w^{[1]T}_2 x + b^{[1]}_2\\ w^{[1]T}_3 x + b^{[1]}_3 \\ w^{[1]T}_4 x + b^{[1]}_4 \end{bmatrix} $
''', # noqa: E501
r'''
<p>$z^{[1]} = \begin{bmatrix}w^{[1]T}_1 \ w^{[1]T}_2 \ w^{[1]T}_3 \ w^{[1]T}_4 \end{bmatrix} \begin{bmatrix}x_1 \ x_2 \ x_3 \end{bmatrix} + \begin{bmatrix}b^{[1]}_1 \ b^{[1]}_2 \ b^{[1]}_3 \ b^{[1]}_4 \end{bmatrix}= \begin{bmatrix}w^{[1]T}_1 x + b^{[1]}_1 \ w^{[1]T}_2 x + b^{[1]}_2\ w^{[1]T}_3 x + b^{[1]}_3 \ w^{[1]T}_4 x + b^{[1]}_4 \end{bmatrix} $</p>
''', # noqa: E501
True
)
| 28.83815
| 371
| 0.453999
| 596
| 4,989
| 3.651007
| 0.152685
| 0.016544
| 0.022059
| 0.074449
| 0.692096
| 0.557904
| 0.479779
| 0.451287
| 0.37454
| 0.37454
| 0
| 0.043044
| 0.357386
| 4,989
| 172
| 372
| 29.005814
| 0.635683
| 0.119062
| 0
| 0.585714
| 0
| 0
| 0.060268
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.142857
| false
| 0
| 0.014286
| 0
| 0.257143
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0121afa2ee5440a70a9a651bed1ddda312a2e7ae
| 891
|
py
|
Python
|
code/roman2int.py
|
wp-lai/xpython
|
3d90362e56173052d8dd66817feffd67dc07db91
|
[
"MIT"
] | 5
|
2016-11-17T07:35:05.000Z
|
2018-04-07T16:34:16.000Z
|
code/roman2int.py
|
wp-lai/xpython
|
3d90362e56173052d8dd66817feffd67dc07db91
|
[
"MIT"
] | null | null | null |
code/roman2int.py
|
wp-lai/xpython
|
3d90362e56173052d8dd66817feffd67dc07db91
|
[
"MIT"
] | null | null | null |
"""
Task:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Symbol Value
I 1 (unus)
V 5 (quinque)
X 10 (decem)
L 50 (quinquaginta)
C 100 (centum)
D 500 (quingenti)
M 1,000 (mille)
>>> roman_to_int("DCXXI")
621
>>> roman_to_int("VI")
6
>>> roman_to_int("LXXVI")
76
>>> roman_to_int("XIII")
13
>>> roman_to_int("MMMCMXCIX")
3999
>>> roman_to_int("")
0
"""
def roman_to_int(s):
values = {'M': 1000, 'D': 500, 'C': 100, 'L': 50,
'X': 10, 'V': 5, 'I': 1}
result = 0
for i in range(len(s)):
if i == len(s) - 1:
result += values[s[i]]
else:
if values[s[i]] < values[s[i + 1]]:
result -= values[s[i]]
else:
result += values[s[i]]
return result
if __name__ == '__main__':
import doctest
doctest.testmod()
| 18.183673
| 62
| 0.539843
| 139
| 891
| 3.302158
| 0.496403
| 0.106754
| 0.152505
| 0.091503
| 0.082789
| 0.082789
| 0
| 0
| 0
| 0
| 0
| 0.083861
| 0.290685
| 891
| 48
| 63
| 18.5625
| 0.642405
| 0.464646
| 0
| 0.25
| 0
| 0
| 0.031983
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.0625
| false
| 0
| 0.0625
| 0
| 0.1875
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01243d69b6f9b70a1311214737f35975b0a644a4
| 2,082
|
py
|
Python
|
test/test_upstream.py
|
bninja/rump
|
3b6c4ff29974b3c04a260d8275567beebb296e5d
|
[
"0BSD"
] | 6
|
2015-07-27T09:02:36.000Z
|
2018-07-18T11:11:33.000Z
|
test/test_upstream.py
|
bninja/rump
|
3b6c4ff29974b3c04a260d8275567beebb296e5d
|
[
"0BSD"
] | null | null | null |
test/test_upstream.py
|
bninja/rump
|
3b6c4ff29974b3c04a260d8275567beebb296e5d
|
[
"0BSD"
] | null | null | null |
import mock
import pytest
from rump import parser, Server, Upstream, Selection, exc
@pytest.fixture
def parse():
return parser.for_upstream()
def test_upstream_valid(parse):
cases = [
('hi',
Upstream(Selection(Server('http', 'hi'), 1))),
('https://hi',
Upstream(Selection(Server('https', 'hi'), 1))),
('https://hi,23',
Upstream(Selection(Server('https', 'hi'), 23))),
('https://hi,23 http://there/you,33 bye',
Upstream([
Selection(Server('https', 'hi'), 23),
Selection(Server('http', 'there/you'), 33),
Selection(Server('http', 'bye'), 1),
])),
]
for raw, expected in cases:
parsed = parse(raw)
assert expected == parsed
def test_upstream_invalid(parse):
cases = [
('hi,nope', exc.ParseException),
('hi,-1', exc.ParseException),
('', exc.ParseException),
]
for raw, ex in cases:
with pytest.raises(ex):
parse(raw)
def test_upstream_select(parse):
upstream = parse('http://1:81,1 http://2:82,5 https://4:84,3')
assert not upstream.uniform
servers = [selection.server for selection in upstream]
for _ in xrange(20):
server = upstream()
assert server in servers
def test_upstream_select_uniform(parse):
upstream = parse('http://1:81 http://2:82 https://4:84')
assert [
Server('http', '1:81'),
Server('http', '2:82'),
Server('https', '4:84')
] == upstream.servers
assert upstream.uniform
servers = [selection.server for selection in upstream]
for _ in xrange(20):
server = upstream()
assert server in servers
def test_upstream_select_impossible(parse):
upstream = parse('http://1:81,1 http://2:825 https://4:84,3')
with mock.patch('rump.upstream.random.randint') as randint:
randint.return_value = upstream.total
with pytest.raises(Exception):
upstream()
randint.return_value = upstream.total - 1
upstream()
| 28.135135
| 66
| 0.583573
| 250
| 2,082
| 4.792
| 0.24
| 0.100167
| 0.062604
| 0.070117
| 0.416528
| 0.339733
| 0.265442
| 0.265442
| 0.265442
| 0.213689
| 0
| 0.041069
| 0.263208
| 2,082
| 73
| 67
| 28.520548
| 0.739896
| 0
| 0
| 0.2
| 0
| 0.016667
| 0.14073
| 0.013449
| 0
| 0
| 0
| 0
| 0.1
| 1
| 0.1
| false
| 0
| 0.05
| 0.016667
| 0.166667
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
012579b5541f7896f0ff2928c89b8dec890eb8d1
| 414
|
py
|
Python
|
Ago-Dic-2020/sena-martinez-angel-david/Primer Parcial/Gui.py
|
bryanbalderas/DAS_Sistemas
|
1e31f088c0de7134471025a5730b0abfc19d936e
|
[
"MIT"
] | 41
|
2017-09-26T09:36:32.000Z
|
2022-03-19T18:05:25.000Z
|
Ago-Dic-2020/sena-martinez-angel-david/Primer Parcial/Gui.py
|
bryanbalderas/DAS_Sistemas
|
1e31f088c0de7134471025a5730b0abfc19d936e
|
[
"MIT"
] | 67
|
2017-09-11T05:06:12.000Z
|
2022-02-14T04:44:04.000Z
|
Ago-Dic-2020/sena-martinez-angel-david/Primer Parcial/Gui.py
|
bryanbalderas/DAS_Sistemas
|
1e31f088c0de7134471025a5730b0abfc19d936e
|
[
"MIT"
] | 210
|
2017-09-01T00:10:08.000Z
|
2022-03-19T18:05:12.000Z
|
from tkinter import *
from tkinter.ttk import *
# creando ventana tkinter
root = Tk()
# Agregando herramientas a la ventana
Label(root, text = 'PuntosExtra', font =(
'Verdana', 15)).pack(side = TOP, pady = 10)
# Insertando la imagen de login
foto = PhotoImage(file = r"C:\Users\david\OneDrive\Imágenes\login.png")
Button(root, text = 'Click Me !', image = foto).pack(side = TOP)
mainloop()
| 25.875
| 72
| 0.669082
| 56
| 414
| 4.946429
| 0.75
| 0.079422
| 0.079422
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.012012
| 0.195652
| 414
| 16
| 73
| 25.875
| 0.81982
| 0.217391
| 0
| 0
| 0
| 0
| 0.218069
| 0.130841
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.25
| 0
| 0.25
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
012711b60afee7420df0f399f035f95d78d3df36
| 2,200
|
py
|
Python
|
custom/ewsghana/urls.py
|
johan--/commcare-hq
|
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
|
[
"BSD-3-Clause"
] | null | null | null |
custom/ewsghana/urls.py
|
johan--/commcare-hq
|
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
|
[
"BSD-3-Clause"
] | 1
|
2022-03-12T01:03:25.000Z
|
2022-03-12T01:03:25.000Z
|
custom/ewsghana/urls.py
|
johan--/commcare-hq
|
86ee99c54f55ee94e4c8f2f6f30fc44e10e69ebd
|
[
"BSD-3-Clause"
] | null | null | null |
from django.conf.urls import patterns, url, include
from corehq.apps.api.urls import CommCareHqApi
from custom.ewsghana.resources.v0_1 import EWSLocationResource
from custom.ewsghana.views import EWSConfigView, EWSGlobalStats, InputStockView, EWSUserExtensionView, \
DashboardRedirectReportView
hq_api = CommCareHqApi(api_name='v0.3')
hq_api.register(EWSLocationResource())
urlpatterns = patterns('custom.ewsghana.views',
url(r'^ews_config/$', EWSConfigView.as_view(), name=EWSConfigView.urlname),
url(r'^sync_ewsghana/$', 'sync_ewsghana', name='sync_ewsghana'),
url(r'^global_stats/$', EWSGlobalStats.as_view(), name=EWSGlobalStats.urlname),
# for testing purposes
url(r'^ews_sync_stock_data/$', 'ews_sync_stock_data', name='ews_sync_stock_data'),
url(r'^ews_clear_stock_data/$', 'ews_clear_stock_data', name='ews_clear_stock_data'),
url(r'^configure_in_charge/$', 'configure_in_charge', name='configure_in_charge'),
url(r'^ews_resync_web_users/$', 'ews_resync_web_users', name='ews_resync_web_users'),
url(r'^inventory_managment/$', 'inventory_management', name='inventory_managment'),
url(r'^stockouts_product/$', 'stockouts_product', name='stockouts_product'),
url(r'^ews_fix_locations/$', 'ews_fix_locations', name='ews_fix_locations'),
url(r'^ews_add_products_to_locs/$', 'ews_add_products_to_locs', name='ews_add_products_to_locs'),
url(r'^migrate_email_settings/$', 'migrate_email_settings_view', name='migrate_email_settings'),
url(r'^fix_sms_users/$', 'fix_sms_users', name='fix_sms_users'),
url(r'^delete_last_stock_data/$', 'delete_last_stock_data', name='delete_last_stock_data'),
url(r'^(?P<site_code>\w+)/input_stock/$', InputStockView.as_view(), name='input_stock'),
url(r'^', include(hq_api.urls)),
url(r'^convert_user_data_fields/$', 'convert_user_data_fields', name='convert_user_data_fields'),
url(r'^non_administrative_locations/$', 'non_administrative_locations_for_select2'),
url(r'^user_settings/(?P<user_id>[ \w-]+)/$', EWSUserExtensionView.as_view(), name='ews_user_settings'),
url(r'^dashboard/(?P<site_code>\w+)/', DashboardRedirectReportView.as_view(), name='dashboard_report')
)
| 64.705882
| 108
| 0.753636
| 299
| 2,200
| 5.150502
| 0.270903
| 0.051948
| 0.027273
| 0.031169
| 0.038961
| 0
| 0
| 0
| 0
| 0
| 0
| 0.002481
| 0.084091
| 2,200
| 33
| 109
| 66.666667
| 0.761787
| 0.009091
| 0
| 0
| 0
| 0
| 0.487144
| 0.269972
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.137931
| 0
| 0.137931
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01274e1a8dfe413246f9258fed40ee9356e14195
| 9,288
|
py
|
Python
|
ee559/hw2/classifier.py
|
chenying-wang/usc-ee-coursework-public
|
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
|
[
"MIT"
] | 1
|
2021-03-24T10:46:20.000Z
|
2021-03-24T10:46:20.000Z
|
ee559/hw2/classifier.py
|
chenying-wang/usc-ee-coursework-public
|
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
|
[
"MIT"
] | null | null | null |
ee559/hw2/classifier.py
|
chenying-wang/usc-ee-coursework-public
|
5bc94c2350bcebf1036fb058fe7dc4f7e31e1de1
|
[
"MIT"
] | 1
|
2021-03-25T09:18:45.000Z
|
2021-03-25T09:18:45.000Z
|
import numpy as np
from scipy.spatial.distance import cdist
import sys
from plot_area import plot_area
COLOR = ['tab:blue', 'tab:orange', 'tab:green']
class BaseClassifier:
d = -1
c = -1
def __init__(self, d):
super().__init__()
if (d <= 0):
raise RuntimeError("Classifier.D/C cannot be negative or zero")
self.d = d
def evaluate(self, feature):
if (np.shape(feature)[1] != self.d):
raise RuntimeError("Size of feature does not fit")
if (self.c < 0):
raise RuntimeError("Evaluate with an untrained classifier")
return 0
def train(self, data):
return self
class NearestMeanClassifier(BaseClassifier):
training_features = np.array([])
training_classifications = np.array([])
feature_means = np.array([])
classifications = np.array([])
num_of_classifications = np.array([])
weights_group = np.array([])
def __init__(self, d):
super().__init__(d)
def evaluate(self, feature):
if (super().evaluate(feature) or np.size(self.weights_group) == 0):
return None
length = np.shape(feature)[0]
min_distance = np.full(length, sys.maxsize)
classification = np.full(length, None)
for i in range(self.c):
weights = self.weights_group[i]
result = np.matmul(weights, np.transpose(np.insert(feature, 0, 1, axis = 1)))
classification[np.all(result > 0, axis = 0)] = self.classifications[i]
return classification
def test(self, feature, classification):
eval_classification = self.evaluate(feature)
return np.count_nonzero(eval_classification == classification) / \
np.size(classification)
def train_by_weights_group(self, weights_group, classifications):
self.weights_group = weights_group
self.classifications = classifications
self.c = len(self.classifications)
def train(self, data, training_type = 'ovo'):
self.training_features = data[:, :-1]
self.training_classifications = data[:, -1]
if (np.shape(self.training_features)[1] != self.d):
raise RuntimeError("Size of training data does not fit")
self.classifications = np.unique(self.training_classifications)
self.c = len(self.classifications)
self.feature_means = np.zeros([self.c, self.d])
self.num_of_classifications, _ = np.histogram(self.training_classifications, \
bins = np.append(self.classifications, np.max(self.classifications) + 1))
for i in range(self.c):
self.feature_means[i] = np.mean(\
self.training_features[self.training_classifications == self.classifications[i]], \
axis = 0)
if (training_type == 'ovo' or training_type == 'mvm'):
weights_group = np.array([])
for i in range(self.c):
classification = self.classifications[i]
weights = np.array([])
for j in range(self.c):
if (i == j):
continue
another_classification = self.classifications[j]
weight = self.get_boundary_weight_by_ovo(classification, another_classification)
if (np.size(weights) == 0):
weights = np.array([weight])
else:
weights = np.append(weights, [weight], axis = 0)
if (np.size(weights_group) == 0):
weights_group = np.array([weights])
else:
weights_group = np.append(weights_group, [weights], axis = 0)
self.weights_group = weights_group
elif (training_type == 'ovr'):
weights = np.array([])
for classification in self.classifications:
weight = self.get_boundary_weight_by_ovr(classification)
if (np.size(weights) == 0):
weights = np.array([weight])
else:
weights = np.append(weights, [weight], axis = 0)
weights_group = np.tile(-weights, (self.c, 1, 1))
for i in range(self.c):
weights_group[i][i] = -weights_group[i][i]
self.weights_group = weights_group
return self
def get_boundary_weight_by_ovo(self, classification, another_classification):
if (self.c < 0):
raise RuntimeError("Get boundary with an untrained classifier")
return self._get_boundary_weight_by_two_means(\
self.feature_means[self.classifications == classification], \
self.feature_means[self.classifications == another_classification])
def get_boundary_weight_by_ovr(self, classification):
if (self.c < 0):
raise RuntimeError("Get boundary with an untrained classifier")
i = np.argwhere(self.classifications == classification)
feature_mean = self.feature_means[i]
non_feature_means = np.delete(self.feature_means, i, axis = 0)
num_of_non_classifications = np.delete(self.num_of_classifications, i)
non_feature_mean = np.average(non_feature_means, weights = num_of_non_classifications, axis = 0)
return self._get_boundary_weight_by_two_means(feature_mean, non_feature_mean)
def plot_features(self, ax):
if (np.size(self.training_features) == 0 or self.c < 0):
raise RuntimeError('Plot with an untrained classifier or not applicable')
for i in range(self.c):
features = self.training_features[self.training_classifications == self.classifications[i], :]
ax.scatter(features[:, 0], features[:, 1], label = 'Class ' + str(int(self.classifications[i])), \
marker = 'x', alpha = 0.8, color = COLOR[i])
def plot_means(self, ax):
if (np.size(self.feature_means) == 0 or self.c < 0):
raise RuntimeError('Plot with an untrained classifier or not applicable')
for i in range(self.c):
ax.scatter(self.feature_means[i][0], self.feature_means[i][1], label = 'Class ' + str(self.classifications[i]) + ' Mean', \
linewidth = 8, marker = 'o', color = COLOR[i])
def plot_decision_regions_boundaries(self, ax):
if (self.c < 0):
raise RuntimeError('Plot with an untrained classifier')
for i in range(self.c):
plot_area(ax, [self.weights_group[i]], self.get_plot_linespace(), \
label = 'Gamma_' + str(int(self.classifications[i])), \
color = COLOR[i], alpha = 0.6)
def plot_indeterminate_regions(self, ax):
if (self.c < 0):
raise RuntimeError('Plot with an untrained classifier')
indeterminate_weights_group = self._get_complement_weights_group(self.weights_group)
plot_area(ax, indeterminate_weights_group, self.get_plot_linespace(), \
label = 'Indeterminate', \
color = 'tab:grey')
def get_plot_linespace(self):
linespace_lim = self._get_plot_limit()[0]
linespace = np.arange(linespace_lim[0], linespace_lim[1], 0.002)
return linespace
def plot_setlim(self, ax):
plot_limit = self._get_plot_limit()
ax.set_xlim(plot_limit[0][0], plot_limit[0][1])
ax.set_ylim(plot_limit[1][0], plot_limit[1][1])
def plot_legend(self, ax, **kwargs):
handles, labels = ax.get_legend_handles_labels()
newLabels, newHandles = [], []
for handle, label in zip(handles, labels):
if label not in newLabels:
newLabels.append(label)
newHandles.append(handle)
ax.legend(newHandles, newLabels, **kwargs)
def _get_plot_limit(self):
if (np.size(self.training_features) == 0):
return np.array([[0, 6], [0, 6]])
min = np.min(self.training_features, axis = 0)
max = np.max(self.training_features, axis = 0)
min = min - np.maximum((max - min) * 0.25, [0.5, 0.5])
max = max + np.maximum((max - min) * 0.25, [0.5, 0.5])
return np.transpose([min, max])
def _get_boundary_weight_by_two_means(self, a, b):
return np.append(np.sum(np.square(b)) - np.sum(np.square(a)), 2 * (a - b))
def _get_complement_weights_group(self, weights_group, complement_weights_group = np.array([]), weights = np.array([])):
_weights = weights
for weight in weights_group[0]:
if (np.size(_weights) == 0):
weights = np.array([-weight])
else:
weights = np.append(_weights, [-weight], axis = 0)
if (np.shape(weights_group)[0] > 1):
complement_weights_group = self._get_complement_weights_group(weights_group = weights_group[1:, :, :], \
complement_weights_group = complement_weights_group,
weights = weights)
else:
if (np.size(complement_weights_group) == 0):
complement_weights_group = np.array([weights])
else:
complement_weights_group = np.append(complement_weights_group, [weights], axis = 0)
return complement_weights_group
| 42.605505
| 135
| 0.602498
| 1,117
| 9,288
| 4.815577
| 0.135184
| 0.089236
| 0.04908
| 0.017847
| 0.429634
| 0.32032
| 0.242052
| 0.176427
| 0.16267
| 0.137758
| 0
| 0.013461
| 0.280146
| 9,288
| 217
| 136
| 42.801843
| 0.791056
| 0
| 0
| 0.25
| 0
| 0
| 0.051141
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.111111
| false
| 0
| 0.022222
| 0.011111
| 0.261111
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0127942a3e99b818d3bf03948c616cc5027b74c1
| 1,920
|
py
|
Python
|
Web/discussManager.py
|
cmd2001/Open-TesutoHime
|
2c30aa35650383adfb99496aebd425dffd287eda
|
[
"MIT"
] | 11
|
2020-11-28T16:45:35.000Z
|
2021-08-31T07:56:26.000Z
|
Web/discussManager.py
|
cmd2001/Open-TesutoHime
|
2c30aa35650383adfb99496aebd425dffd287eda
|
[
"MIT"
] | null | null | null |
Web/discussManager.py
|
cmd2001/Open-TesutoHime
|
2c30aa35650383adfb99496aebd425dffd287eda
|
[
"MIT"
] | 2
|
2021-05-16T03:09:58.000Z
|
2021-08-21T07:24:58.000Z
|
import sys
from utils import *
class DiscussManager:
def add_discuss(self, problem_id: int, username: str, data: str):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute("INSERT INTO Discuss(Problem_ID, Username, Data, Time) VALUES(%s, %s, %s, %s)",
(problem_id, username, data, unix_nano()))
db.commit()
except pymysql.Error:
db.rollback()
sys.stderr.write("SQL Error in DiscussManager: Add_Discuss\n")
db.close()
return
def modify_discuss(self, discuss_id: int, new_data: str):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute("UPDATE Discuss SET DATA = %s WHERE ID = %s", (new_data, discuss_id))
db.commit()
except pymysql.Error:
db.rollback()
sys.stderr.write("SQL Error in DiscussManager: Modify_Discuss\n")
db.close()
return
def get_author(self, discuss_id: int):
db = db_connect()
cursor = db.cursor()
cursor.execute("SELECT Username FROM Discuss WHERE ID = %s", discuss_id)
ret = cursor.fetchone()
return ret[0]
def get_discuss_for_problem(self, problem_id: int):
db = db_connect()
cursor = db.cursor()
cursor.execute("SELECT ID, Username, DATA, Time FROM Discuss WHERE Problem_ID = %s", problem_id)
ret = cursor.fetchall()
db.close()
return ret
def delete_discuss(self, discuss_id: int):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute("DELETE FROM Discuss WHERE ID = %s", discuss_id)
db.commit()
except pymysql.Error:
db.rollback()
sys.stderr.write("SQL Error in DiscussManager: Erase_Discuss\n")
db.close()
return
Discuss_Manager = DiscussManager()
| 32
| 106
| 0.577604
| 231
| 1,920
| 4.666667
| 0.242424
| 0.050093
| 0.05102
| 0.07885
| 0.601113
| 0.553803
| 0.509276
| 0.465677
| 0.465677
| 0.450835
| 0
| 0.000758
| 0.3125
| 1,920
| 59
| 107
| 32.542373
| 0.815909
| 0
| 0
| 0.568627
| 0
| 0.019608
| 0.203125
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.098039
| false
| 0
| 0.039216
| 0
| 0.254902
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0128d2dc205aef3ebf52d764565e44d09f889dd0
| 1,977
|
py
|
Python
|
casimir/force_calc/force_calc_mc.py
|
charlesblakemore/opt_lev_analysis
|
704f174e9860907de349688ed82b5812bbb07c2d
|
[
"MIT"
] | null | null | null |
casimir/force_calc/force_calc_mc.py
|
charlesblakemore/opt_lev_analysis
|
704f174e9860907de349688ed82b5812bbb07c2d
|
[
"MIT"
] | null | null | null |
casimir/force_calc/force_calc_mc.py
|
charlesblakemore/opt_lev_analysis
|
704f174e9860907de349688ed82b5812bbb07c2d
|
[
"MIT"
] | 1
|
2019-11-27T19:10:25.000Z
|
2019-11-27T19:10:25.000Z
|
import math, sys, random, mcint
from scipy import integrate
import numpy as np
gap = float(sys.argv[1])
lam = float(sys.argv[2])
print(gap, lam)
## calculate the yukawa force over a distributed test mass assumed to be cube
D = 5 # diameter of bead (um)
rhob = 2e3 # density bead (kg/m^3)
rhoa = 19.3e3 # density attractor
rhosi = 2.3e3 # density attractor
a = 10 # length of attractor cube side (um)
a_depth = 200 # depth of attractor cube side (um)
au_thick = 0.2 # shield layer thickness (um)
def dV(phi,theta,r):
return r**2 * math.sin(theta)
alpha = 1.0
G = 6.67398e-11
#def Fg(phi, theta, r, currx, curry, currz):
def integrand(xin):
r = xin[0]
theta = xin[1]
phi = xin[2]
currx = xin[3]
curry = xin[4]
currz = xin[5]
## distance between r,theta,phi point and currx,curry,currz measured relative to center of cube at (gap + a/2, 0, 0)
dx = r*math.sin(theta)*math.cos(phi) - (gap + a_depth/2.0 + currx)
dy = r*math.sin(theta)*math.sin(phi) - curry
dz = r*math.cos(theta) - currz
dist = math.sqrt( dx**2 + dy**2 + dz**2 )
##only want component in x direction (all others cancel)
rhat_dot_xhat = abs(dx)/dist
return (alpha*G*(rhoa-rhosi)/dist**2)*math.exp(-dist/lam)*(1.0 + dist/lam)*rhob*dV(phi,theta,r)*rhat_dot_xhat
def sampler():
while True:
r = random.uniform(0.,D/2.)
theta = random.uniform(0.,2.*math.pi)
phi = random.uniform(0.,math.pi)
x = random.uniform(-a_depth/2.0+au_thick,a_depth/2.0+au_thick)
y = random.uniform(-a/2., a/2.)
z = random.uniform(-a/2., a/2.)
yield (r, theta, phi, x, y, z)
nmc = 100000000
domainsize = D * math.pi**2 * a_depth * a**2
random.seed(1)
result, error = mcint.integrate(integrand, sampler(), measure=domainsize, n=nmc)
print("integral is: ", result, error)
#fname = 'data/lam_arr_%.3f_%.3f.npy' % (gap*1e6,lam*1e6)
#np.save(fname,intval)
| 27.082192
| 121
| 0.616591
| 335
| 1,977
| 3.59403
| 0.39403
| 0.009967
| 0.022425
| 0.019934
| 0.116279
| 0.053156
| 0
| 0
| 0
| 0
| 0
| 0.051735
| 0.227618
| 1,977
| 72
| 122
| 27.458333
| 0.736739
| 0.273141
| 0
| 0
| 0
| 0
| 0.009168
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.068182
| false
| 0
| 0.068182
| 0.022727
| 0.181818
| 0.045455
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
012a1022a18b104991ad25c5bfeca0df7e5858c1
| 8,823
|
py
|
Python
|
robot-server/robot_server/robot/calibration/tip_length/user_flow.py
|
Axel-Jacobsen/opentrons
|
c543d95c25003f2e784560efaa6a91f051d4cd33
|
[
"Apache-2.0"
] | 1
|
2022-03-17T20:38:04.000Z
|
2022-03-17T20:38:04.000Z
|
robot-server/robot_server/robot/calibration/tip_length/user_flow.py
|
Axel-Jacobsen/opentrons
|
c543d95c25003f2e784560efaa6a91f051d4cd33
|
[
"Apache-2.0"
] | null | null | null |
robot-server/robot_server/robot/calibration/tip_length/user_flow.py
|
Axel-Jacobsen/opentrons
|
c543d95c25003f2e784560efaa6a91f051d4cd33
|
[
"Apache-2.0"
] | null | null | null |
import logging
from typing import (
Dict, Awaitable, Callable, Any, Set, List, Optional,
TYPE_CHECKING)
from opentrons.types import Mount, Point, Location
from opentrons.config import feature_flags as ff
from opentrons.hardware_control import ThreadManager, CriticalPoint
from opentrons.protocol_api import labware
from opentrons.protocols.geometry import deck
from robot_server.robot.calibration import util
from robot_server.service.errors import RobotServerError
from robot_server.service.session.models.command import CalibrationCommand
from ..errors import CalibrationError
from ..helper_classes import RequiredLabware, AttachedPipette
from ..constants import (
TIP_RACK_LOOKUP_BY_MAX_VOL,
SHORT_TRASH_DECK,
STANDARD_DECK,
CAL_BLOCK_SETUP_BY_MOUNT,
MOVE_TO_TIP_RACK_SAFETY_BUFFER,
)
from .constants import TipCalibrationState as State, TIP_RACK_SLOT
from .state_machine import TipCalibrationStateMachine
if TYPE_CHECKING:
from opentrons_shared_data.labware import LabwareDefinition
MODULE_LOG = logging.getLogger(__name__)
"""
A collection of functions that allow a consumer to prepare and update
calibration data associated with the combination of a pipette tip type and a
unique (by serial number) physical pipette.
"""
# TODO: BC 2020-07-08: type all command logic here with actual Model type
COMMAND_HANDLER = Callable[..., Awaitable]
COMMAND_MAP = Dict[str, COMMAND_HANDLER]
class TipCalibrationUserFlow:
def __init__(self,
hardware: ThreadManager,
mount: Mount,
has_calibration_block: bool,
tip_rack: 'LabwareDefinition'):
self._hardware = hardware
self._mount = mount
self._has_calibration_block = has_calibration_block
self._hw_pipette = self._hardware._attached_instruments[mount]
if not self._hw_pipette:
raise RobotServerError(
definition=CalibrationError.NO_PIPETTE_ON_MOUNT,
mount=mount)
self._tip_origin_pt: Optional[Point] = None
self._nozzle_height_at_reference: Optional[float] = None
deck_load_name = SHORT_TRASH_DECK if ff.short_fixed_trash() \
else STANDARD_DECK
self._deck = deck.Deck(load_name=deck_load_name)
self._tip_rack = self._get_tip_rack_lw(tip_rack)
self._initialize_deck()
self._current_state = State.sessionStarted
self._state_machine = TipCalibrationStateMachine()
self._command_map: COMMAND_MAP = {
CalibrationCommand.load_labware: self.load_labware,
CalibrationCommand.jog: self.jog,
CalibrationCommand.pick_up_tip: self.pick_up_tip,
CalibrationCommand.invalidate_tip: self.invalidate_tip,
CalibrationCommand.save_offset: self.save_offset,
CalibrationCommand.move_to_reference_point: self.move_to_reference_point, # noqa: E501
CalibrationCommand.move_to_tip_rack: self.move_to_tip_rack, # noqa: E501
CalibrationCommand.exit: self.exit_session,
}
def _set_current_state(self, to_state: State):
self._current_state = to_state
@property
def current_state(self) -> State:
return self._current_state
def get_pipette(self) -> AttachedPipette:
# TODO(mc, 2020-09-17): s/tip_length/tipLength
return AttachedPipette( # type: ignore[call-arg]
model=self._hw_pipette.model,
name=self._hw_pipette.name,
tip_length=self._hw_pipette.config.tip_length,
mount=str(self._mount),
serial=self._hw_pipette.pipette_id
)
def get_required_labware(self) -> List[RequiredLabware]:
slots = self._deck.get_non_fixture_slots()
lw_by_slot = {s: self._deck[s] for s in slots if self._deck[s]}
return [
RequiredLabware.from_lw(lw, s) # type: ignore
for s, lw in lw_by_slot.items()]
async def handle_command(self,
name: Any,
data: Dict[Any, Any]):
"""
Handle a client command
:param name: Name of the command
:param data: Data supplied in command
:return: None
"""
next_state = self._state_machine.get_next_state(self._current_state,
name)
handler = self._command_map.get(name)
if handler is not None:
await handler(**data)
self._set_current_state(next_state)
MODULE_LOG.debug(f'TipCalUserFlow handled command {name}, transitioned'
f'from {self._current_state} to {next_state}')
async def load_labware(self):
pass
async def move_to_tip_rack(self):
# point safely above target tip well in tip rack
pt_above_well = self._tip_rack.wells()[0].top().point + \
MOVE_TO_TIP_RACK_SAFETY_BUFFER
if self._tip_origin_pt is not None:
# use jogged to x and y offsets only if returning tip to rack
await self._move(Location(Point(self._tip_origin_pt.x,
self._tip_origin_pt.y,
pt_above_well.z),
None))
else:
await self._move(Location(pt_above_well, None))
async def save_offset(self):
if self._current_state == State.measuringNozzleOffset:
# critical point would default to nozzle for z height
cur_pt = await self._get_current_point(
critical_point=None)
self._nozzle_height_at_reference = cur_pt.z
elif self._current_state == State.measuringTipOffset:
assert self._hw_pipette.has_tip
assert self._nozzle_height_at_reference is not None
# set critical point explicitly to nozzle
cur_pt = await self._get_current_point(
critical_point=CriticalPoint.NOZZLE)
util.save_tip_length_calibration(
pipette_id=self._hw_pipette.pipette_id,
tip_length_offset=cur_pt.z - self._nozzle_height_at_reference,
tip_rack=self._tip_rack)
def _get_default_tip_length(self) -> float:
tiprack: labware.Labware = self._deck[TIP_RACK_SLOT] # type: ignore
full_length = tiprack.tip_length
overlap_dict: Dict = \
self._hw_pipette.config.tip_overlap
default = overlap_dict['default']
overlap = overlap_dict.get(tiprack.uri, default)
return full_length - overlap
def _get_critical_point_override(self) -> Optional[CriticalPoint]:
return (CriticalPoint.FRONT_NOZZLE if
self._hw_pipette.config.channels == 8 else None)
async def _get_current_point(
self,
critical_point: CriticalPoint = None) -> Point:
return await self._hardware.gantry_position(self._mount,
critical_point)
async def jog(self, vector):
await self._hardware.move_rel(mount=self._mount,
delta=Point(*vector))
async def move_to_reference_point(self):
ref_loc = util.get_reference_location(
mount=self._mount,
deck=self._deck,
has_calibration_block=self._has_calibration_block)
await self._move(ref_loc)
async def pick_up_tip(self):
await util.pick_up_tip(self, tip_length=self._get_default_tip_length())
async def invalidate_tip(self):
await util.invalidate_tip(self)
async def exit_session(self):
await self.move_to_tip_rack()
await self._return_tip()
def _get_tip_rack_lw(self,
tip_rack_def: 'LabwareDefinition') -> labware.Labware:
try:
return labware.load_from_definition(
tip_rack_def,
self._deck.position_for(TIP_RACK_SLOT))
except Exception:
raise RobotServerError(definition=CalibrationError.BAD_LABWARE_DEF)
def _get_alt_tip_racks(self) -> Set[str]:
pip_vol = self._hw_pipette.config.max_volume
return set(TIP_RACK_LOOKUP_BY_MAX_VOL[str(pip_vol)].alternatives)
def _initialize_deck(self):
self._deck[TIP_RACK_SLOT] = self._tip_rack
if self._has_calibration_block:
cb_setup = CAL_BLOCK_SETUP_BY_MOUNT[self._mount]
self._deck[cb_setup.slot] = labware.load(
cb_setup.load_name,
self._deck.position_for(cb_setup.slot))
async def _return_tip(self):
await util.return_tip(self, tip_length=self._get_default_tip_length())
async def _move(self, to_loc: Location):
await util.move(self, to_loc)
| 38.867841
| 99
| 0.656693
| 1,070
| 8,823
| 5.062617
| 0.217757
| 0.031013
| 0.026398
| 0.014399
| 0.1235
| 0.062212
| 0.045228
| 0.03286
| 0.03286
| 0.017353
| 0
| 0.003733
| 0.271336
| 8,823
| 226
| 100
| 39.039823
| 0.838855
| 0.043749
| 0
| 0.011696
| 0
| 0
| 0.016605
| 0.002602
| 0
| 0
| 0
| 0.004425
| 0.011696
| 1
| 0.05848
| false
| 0.005848
| 0.093567
| 0.017544
| 0.204678
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
012c3b0eb2f715797ab316942c7962c44dea54d6
| 1,885
|
py
|
Python
|
dj_warning_forms/forms.py
|
dnmellen/dj-warning-forms
|
25213821f41ad6864cb7eda7bd2f6640d4418561
|
[
"BSD-3-Clause"
] | 3
|
2022-03-15T09:09:08.000Z
|
2022-03-23T12:30:47.000Z
|
dj_warning_forms/forms.py
|
dnmellen/dj-warning-forms
|
25213821f41ad6864cb7eda7bd2f6640d4418561
|
[
"BSD-3-Clause"
] | 1
|
2022-03-16T08:04:07.000Z
|
2022-03-18T21:18:38.000Z
|
dj_warning_forms/forms.py
|
dnmellen/dj-warning-forms
|
25213821f41ad6864cb7eda7bd2f6640d4418561
|
[
"BSD-3-Clause"
] | null | null | null |
from collections import namedtuple
import inspect
from django import forms
FormFieldWarning = namedtuple("FormFieldWarning", ["message", "description"])
class WarningFormMixin:
"""Classes using WarningFormMixin should implement methods to catch warnings
>>> def warning_mailboxes(self) -> List[FormFieldWarning]:
if some condition:
return FormFieldWarning(message, description)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["ignore_warnings"] = forms.BooleanField(
required=False, initial=False, widget=forms.HiddenInput()
)
self.warnings = []
def get_warnings(self):
self.warnings = []
if self.cleaned_data.get("ignore_warnings"):
return []
else:
warning_methods = [
(method_name, method)
for method_name, method in inspect.getmembers(
self, predicate=inspect.ismethod
)
if method_name.startswith("warning_")
]
for method_name, method in warning_methods:
warnings = method()
if warnings:
self.warnings.extend(
[
{
"field": method_name.split("warning_")[1],
"message": warning.message,
"description": warning.description,
}
for warning in warnings
]
)
self.data._mutable = True
self.data["ignore_warnings"] = True
self.data._mutable = False
return self.warnings
def is_valid(self):
return super().is_valid() and not self.get_warnings()
| 33.660714
| 80
| 0.523607
| 158
| 1,885
| 6.06962
| 0.398734
| 0.052138
| 0.050052
| 0.039625
| 0.043796
| 0
| 0
| 0
| 0
| 0
| 0
| 0.000867
| 0.388329
| 1,885
| 55
| 81
| 34.272727
| 0.830876
| 0.111406
| 0
| 0.047619
| 0
| 0
| 0.071429
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.071429
| false
| 0
| 0.071429
| 0.02381
| 0.238095
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01314db002cc9b5ea847e74d9af1164332434719
| 8,791
|
py
|
Python
|
ai/ai.py
|
TED-996/pro-evolution-foosball
|
ced46dd7340664d7c7ca7679c6582c7636e2c2a8
|
[
"MIT"
] | null | null | null |
ai/ai.py
|
TED-996/pro-evolution-foosball
|
ced46dd7340664d7c7ca7679c6582c7636e2c2a8
|
[
"MIT"
] | null | null | null |
ai/ai.py
|
TED-996/pro-evolution-foosball
|
ced46dd7340664d7c7ca7679c6582c7636e2c2a8
|
[
"MIT"
] | null | null | null |
from numpy import array, arange, argmax
from numpy.random import choice
from itertools import product
from ai.NN import NN
import pickle
from random import random, randrange, randint
from collections import deque
from math import floor
class AI:
MEMORY_DIMENSION = 90000
def __init__(self, load: bool = False,
state_size: int = 0,
rods_number: int = 0,
offset=None,
angle_velocity=None,
hidden_layers=(100, 100),
log_size=10,
nn_file: str = "save.model",
actions_file: str = "save.actions"):
"""
:param load: specify if model should be load
:param state_size: how many attributes has a state
:param rods_number: number of rods of a player
:param offset: represents a vector with scalars that will move rod to left/right
:param angle_velocity: represents a vector with rates of change of a rodsman angle
:param hidden_layers: a vector of values that represents how many units have each layer
:param nn_file: file to save neural network
:param actions_file: file to save actions_file
"""
self.actions = None
self.model = None
self.last_predictions = deque(maxlen=2 * log_size)
self.last_states = deque(maxlen=2 * log_size)
self.last_actions_index = deque(maxlen=2 * log_size)
self.last_reward_sums = deque([0, 0], maxlen=2 * log_size + 2)
self.log_size = log_size
self.lamda = 0.6
self.alpha = 0.9
self.epsilon = 0.5 # greedy policy
self.__epsilon_backup = self.epsilon
# decreasing_rate will decrease epsilon such that in the future, when nn learned something
# to not make anymore random choices
self.__decreasing_rate = 0.99997
# memory replay
self.memory_state = deque(maxlen=AI.MEMORY_DIMENSION)
self.memory_target = deque(maxlen=AI.MEMORY_DIMENSION)
# with save_probability save a memory with consist of a state and a target
self.save_probability = 0.3
if load:
self.__load(nn_file, actions_file)
return
self.rods_number = rods_number
self.actions = array(
[action for action in product(arange(rods_number),
offset,
angle_velocity)]
)
self.batch_size = int(floor((2 * log_size) ** 0.5))
self.model = NN(input_dim=state_size,
hidden_layers=hidden_layers,
output_dim=len(self.actions),
batch_size=self.batch_size)
self.model.compile()
def __load(self, nn_file, actions_file):
self.model = NN(load_file=nn_file)
fd = open(actions_file, "rb")
self.rods_number, self.actions, self.epsilon, self.lamda, self.batch_size = pickle.load(fd)
self.model.batch_size = self.batch_size
fd.close()
def save(self, nn_file: str="save.model", actions_file: str="save.actions"):
self.model.save(nn_file)
print("saving ai...")
fd = open(actions_file, "wb")
to_save = (self.rods_number, self.actions, self.epsilon, self.lamda, self.batch_size)
pickle.dump(to_save, fd, protocol=0) # protocol 0 for compatibility
fd.close()
def __compute_and_backup(self, state):
self.last_predictions.append(self.model.predict_action(state))
self.last_states.append(state)
# noinspection PyMethodMayBeStatic
def one_action(self, q_values):
return [argmax(q_values)]
def multiple_actions(self, q_values):
actions_idxs = []
slice_size = int(len(self.actions) // self.rods_number)
for i in range(self.rods_number):
actions_idxs.append(i * slice_size + argmax(q_values[i * slice_size:(i + 1) * slice_size]))
return actions_idxs
def get_action(self, state, action_selector):
"""
:param state: a state of the current game
:param action_selector: may be one of the following functions: ane_action, multiple_actions
:return:
"""
self.__compute_and_backup(state)
self.last_actions_index.append(action_selector(self.last_predictions[-1]))
return [self.actions[i] for i in self.last_actions_index[-1]]
def one_action_off_policy(self, rand, q_values):
if rand:
return [randrange(0, len(self.actions))]
else:
return self.one_action(q_values)
def multiple_actions_off_policy(self, rand, q_values):
slice_size = int(len(self.actions) // self.rods_number)
if rand:
return [i * slice_size + randrange(0, slice_size)
for i
in range(self.rods_number)]
else:
return self.multiple_actions(q_values)
def get_action_off_policy(self, state, action_selector):
self.__compute_and_backup(state)
if random() < self.epsilon: # should choose an action random
self.epsilon *= self.__decreasing_rate
self.last_actions_index.append(action_selector(True, None))
return [self.actions[i] for i in self.last_actions_index[-1]]
self.last_actions_index.append(action_selector(False, self.last_predictions[-1]))
return [self.actions[i] for i in self.last_actions_index[-1]]
def update(self, action_based_reward, new_states):
assert len(action_based_reward) == len(new_states), "must have reward for each new_state"
assert len(action_based_reward) == 2, "exactly 2 players supported ATM"
for idx in range(0, len(self.last_reward_sums), 2):
self.last_reward_sums[idx] += action_based_reward[0]
self.last_reward_sums[idx + 1] += action_based_reward[1]
self.last_reward_sums.extend(action_based_reward)
q_values = [[self.last_predictions[i][j]
for j in self.last_actions_index[i]]
for i in range(len(self.last_actions_index))]
action_selector = self.one_action if len(q_values[0]) == 1 else self.multiple_actions
for i in range(len(q_values) - 2):
next_q_values = q_values[i + 2]
q_values_updated = [
# TODO: not sure about self.last_rewards[i]
(1 - self.alpha) * q + self.alpha * (self.last_reward_sums[i] / ((len(q_values) + 1 - i) // 2)
+ (self.lamda * next_q))
for q, next_q
in zip(q_values[i], next_q_values)]
for j, update in zip(self.last_actions_index[i], q_values_updated):
self.last_predictions[i][j] = update
for i in range(len(new_states)):
next_max_q_values = action_selector(self.model.predict_action(new_states[i]))
q_values_updated = [
(1 - self.alpha) * q + self.alpha * (action_based_reward[i] + self.lamda * next_q)
for q, next_q
in zip(q_values[-2 + i], next_max_q_values)]
for j, update in zip(self.last_actions_index[-2 + i], q_values_updated):
self.last_predictions[-2 + i][j] = update
if random() < self.save_probability:
self.memory_state.append(self.last_states[-1])
self.memory_target.appendleft(self.last_predictions[-1])
if random() <= 0.5:
self.model.update(self.last_states, self.last_predictions)
else:
self.from_memory_update()
# we trust more in next move when network learn more
self.lamda += self.lamda * 1.e-7
if self.lamda > 1:
print("lambda = {}".format(self.lamda))
self.lamda = 1
def predict_action(self, state, action_selector):
actions_idxs = action_selector(self.model.predict_action(state))
return [self.actions[i] for i in actions_idxs]
def flush_last_actions(self):
self.last_states.clear()
self.last_actions_index.clear()
self.last_predictions.clear()
def switch_random_action(self, activate):
if not activate:
self.__epsilon_backup = self.epsilon
self.epsilon = 0
else:
self.epsilon = self.__epsilon_backup
def from_memory_update(self):
if len(self.memory_state) < 1000:
return
idxs = arange(len(self.memory_state))
size = randint(200, 1000)
sample = choice(idxs, size, replace=False)
self.model.update(array([self.memory_state[i] for i in sample]),
array([self.memory_target[i] for i in sample]),
False, 3)
| 41.079439
| 110
| 0.615402
| 1,167
| 8,791
| 4.407883
| 0.17395
| 0.052877
| 0.034992
| 0.046656
| 0.335148
| 0.220062
| 0.188958
| 0.122278
| 0.122278
| 0.106726
| 0
| 0.014098
| 0.289956
| 8,791
| 213
| 111
| 41.2723
| 0.809997
| 0.118303
| 0
| 0.144654
| 0
| 0
| 0.017972
| 0
| 0
| 0
| 0
| 0.004695
| 0.012579
| 1
| 0.09434
| false
| 0
| 0.050314
| 0.006289
| 0.232704
| 0.012579
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01343ef465fcba8903301425b1e7414924d1fd27
| 1,686
|
py
|
Python
|
Shared_Files/Music_Pallete.py
|
EricCacciavillani/LyreBird
|
858657faef39d1adcba19ff0213210ba490b4afa
|
[
"MIT"
] | 1
|
2019-05-04T02:34:20.000Z
|
2019-05-04T02:34:20.000Z
|
Shared_Files/Music_Pallete.py
|
EricCacciavillani/LyreBird
|
858657faef39d1adcba19ff0213210ba490b4afa
|
[
"MIT"
] | null | null | null |
Shared_Files/Music_Pallete.py
|
EricCacciavillani/LyreBird
|
858657faef39d1adcba19ff0213210ba490b4afa
|
[
"MIT"
] | 1
|
2019-04-04T19:14:09.000Z
|
2019-04-04T19:14:09.000Z
|
import pretty_midi
import sys
import numpy as np
from tqdm import tqdm
from collections import Counter
sys.path.append('..')
from Pre_Production.Midi_Pre_Processor import *
from Shared_Files.Global_Util import *
class MusicPallete:
def __init__(self, pre_processor_obj):
self.__all_possible_instr_note_pairs = pre_processor_obj.return_all_possible_instr_note_pairs()
self.__centroid_instr_note = None
self.__instr_note_pair_attributes = dict()
set_test_eval = set()
full_matrix = []
count = 0
for instr_note_pair_str in (self.__all_possible_instr_note_pairs):
if "True" in instr_note_pair_str:
count += 1
instr_note_pair_obj = convert_string_to_instr_note_pair(instr_note_pair_str)
# Evaluate instr/note pair
fluid_synth, synth, note_hz = extract_instr_note_pair_attributes(instr_note_pair_obj)
# print(fluid_synth)
# ---
print(fluid_synth)
if self.__centroid_instr_note is None:
self.__centroid_instr_note = fluid_synth
self.__instr_note_pair_attributes[
instr_note_pair_str] = float(calculate_wave_mse(self.__centroid_instr_note, fluid_synth))
set_test_eval.add(calculate_wave_mse(self.__centroid_instr_note, fluid_synth))
print(len(set_test_eval))
print(count)
cnt = Counter([v for k,v in self.__instr_note_pair_attributes.items()])
print(cnt.most_common()[:20])
print()
print([k for k,v in self.__instr_note_pair_attributes.items() if v in set([test[0] for test in cnt.most_common()[:20]])])
| 33.058824
| 129
| 0.682681
| 230
| 1,686
| 4.491304
| 0.317391
| 0.182962
| 0.163601
| 0.101646
| 0.376573
| 0.322362
| 0.236205
| 0.166505
| 0.166505
| 0.075508
| 0
| 0.00546
| 0.23962
| 1,686
| 51
| 129
| 33.058824
| 0.800312
| 0.027877
| 0
| 0
| 0
| 0
| 0.003667
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.030303
| false
| 0
| 0.212121
| 0
| 0.272727
| 0.181818
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0139cdb76dae20ff11cf54b33120c3d867395d2f
| 9,566
|
py
|
Python
|
GoogleCalendar.py
|
InRong/Glance
|
cc15659436bba2b4bee396b4a3e595a157f31401
|
[
"Apache-2.0"
] | null | null | null |
GoogleCalendar.py
|
InRong/Glance
|
cc15659436bba2b4bee396b4a3e595a157f31401
|
[
"Apache-2.0"
] | null | null | null |
GoogleCalendar.py
|
InRong/Glance
|
cc15659436bba2b4bee396b4a3e595a157f31401
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
#
# Module for adding Google Calendar Functionality.
#
# by Peter Juett
# References:https://developers.google.com/calendar/quickstart/python
#
# Copyright 2018
#
# 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 httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import logging
from logging.handlers import RotatingFileHandler
import paho.mqtt.client as mqtt
import DB
import datetime
import time
import pytz
import os
from dateutil import parser
SLEEP_TIME = 60
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
class Calendar(object):
def __init__(self, main_app_log):
if main_app_log is None:
self.log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
self.logFile = 'logs/GoogleCalendar.log'
self.my_handler = RotatingFileHandler(self.logFile, mode='a', maxBytes=5*1024*1024, backupCount=1, encoding=None, delay=0)
self.my_handler.setFormatter(self.log_formatter)
self.my_handler.setLevel(logging.INFO)
self.app_log = logging.getLogger('root')
self.app_log.setLevel(logging.INFO)
self.app_log.addHandler(self.my_handler)
else:
self.app_log = main_app_log
self._db = DB.DB()
self._db.load_settings()
self.start_mosquito()
self.process_loop()
def on_connect(self, mosclient, userdata, flags, rc):
self.app_log.info("Subscribing to topic: " + self._db.get_value("mostopic"))
mosclient.subscribe(self._db.get_value("mostopic"))
def on_disconnect(self, client, userdata, rc):
if rc != 0:
self.app_log.info("Unexpected disconnection")
def on_publish(self, client, userdata, mid):
self.app_log.info("on_publish - published " + str(mid))
def start_mosquito(self):
self.mos_client = mqtt.Client()
self.mos_client.on_connect = self.on_connect
self.mos_client.on_disconnect = self.on_disconnect
self.mos_client.on_publish = self.on_publish
if len(self._db.get_value("mospassword"))>0:
self.mos_client.username_pw_set(self._db.get_value("mosusername"),self._db.get_value("mospassword"))
mos_broker_address = self._db.get_value("mosbrokeraddress")
self.app_log.info("Connecting to: " + mos_broker_address)
self.mos_client.connect(mos_broker_address, int(self._db.get_value("mosbrokerport")), 60)
self.app_log.info("Connected")
self.mos_client.loop_start()
def broadcast_send(self, data_item, value):
result = 0
mid = 0
if data_item is None:
self.app_log.info("data_item is None")
return
if value is None:
self.app_log.info("value is None")
return
self.app_log.info("publishing: " + data_item + " " + value)
try:
message = self._db.get_value("name") + "/" + data_item + "/" + value
result, mid = self.mos_client.publish(self._db.get_value("mostopic"), message)
if result == mqtt.MQTT_ERR_SUCCESS:
self.app_log.info("published OK, Message ID = " + str(mid))
elif result == mqtt.MQTT_ERR_NO_CONN:
self.app_log.info("publish failed, no connection")
else:
self.app_log.info("publish failed, result code = " + str(result))
except Exception as e:
self.app_log.exception('Exception: %s', e)
def process_loop(self):
while(1):
try:
self.get()
except Exception as e:
self.app_log.exception('Exception: %s', e)
finally:
time.sleep(SLEEP_TIME)
def get_credentials(self):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def get(self):
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
credentials = self.get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
self.app_log.info('Getting the upcoming 5 events')
eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=5, singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.get('items', [])
x = 1
if not events:
self.app_log.info('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
next_event = self.process_text(start, event['summary'])
self.broadcast_send('Calendar' + str(x), next_event)
if x == 1:
next_two_events = next_event
elif x == 2:
next_two_events = next_two_events + ", " + next_event
self.broadcast_send('Calendar1and2', next_two_events)
x = x + 1
def process_text(self, start_time, summary):
self.app_log.info(start_time)
this_time = parser.parse(start_time)
self.app_log.info(this_time.strftime("%a %b %d %Y %H:%M:%S --- %z"))
tz_len = len(this_time.strftime("%z"))
out_text = start_time[5:16].replace("T"," ")
if tz_len > 0:
tz = pytz.timezone(self._db.get_value("pytztimezone"))
now = datetime.datetime.now(tz)
else:
now = datetime.datetime.now() #daily events can have no timezone info....
self.app_log.info (now.strftime("%a %b %d %Y %H:%M:%S --- %z"))
today_date = now.strftime("%m-%d")
tomorrow_date = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%m-%d")
delta = this_time - now
#Replace with today or tomorrow, as applicable
out_text = out_text.replace(today_date,"").replace(tomorrow_date,"Tomorrow")
if (delta.days < 7): #if it is soon, then use the day of the week instead of date...
out_text = out_text.replace(this_time.strftime("%m-%d"),this_time.strftime("%a"))
out_text = out_text + " " + summary
return out_text
def run_program(main_app_log):
Calendar(main_app_log)
if __name__ == '__main__':
run_program(None)
| 37.810277
| 146
| 0.569935
| 1,094
| 9,566
| 4.817185
| 0.294333
| 0.03074
| 0.041746
| 0.042505
| 0.098292
| 0.053131
| 0.024288
| 0.024288
| 0.024288
| 0.018216
| 0
| 0.008301
| 0.332532
| 9,566
| 252
| 147
| 37.960317
| 0.817071
| 0.147292
| 0
| 0.096774
| 0
| 0.006452
| 0.105112
| 0.009726
| 0
| 0
| 0
| 0
| 0
| 1
| 0.070968
| false
| 0.012903
| 0.109677
| 0
| 0.212903
| 0.006452
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
013c7f4681cad6f22cf85afe8bfe0932af367f65
| 6,940
|
py
|
Python
|
postprocessing/science/compute_diff_seissol_data.py
|
jrekoske/SeisSol
|
63087cf5fabc6e1b09a4d6b1e0ac46aaee2a1dfe
|
[
"BSD-3-Clause"
] | null | null | null |
postprocessing/science/compute_diff_seissol_data.py
|
jrekoske/SeisSol
|
63087cf5fabc6e1b09a4d6b1e0ac46aaee2a1dfe
|
[
"BSD-3-Clause"
] | null | null | null |
postprocessing/science/compute_diff_seissol_data.py
|
jrekoske/SeisSol
|
63087cf5fabc6e1b09a4d6b1e0ac46aaee2a1dfe
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env python3
import h5py
import numpy as np
import argparse
import os
import seissolxdmf as sx
import seissolxdmfwriter as sw
# These 2 latter modules are on pypi (e.g. pip install seissolxdmf)
def read_reshape2d(sx, dataname):
"""read seissol dataset
and if there is only one time stamp
create a second dimension of size 1"""
myData = sx.ReadData(dataname)
if len(myData.shape) == 1:
myData = myData.reshape((1, myData.shape[0]))
return myData
def fuzzysort(arr, idx, dim=0, tol=1e-6):
"""
return indexes of sorted points robust to small perturbations of individual components.
https://stackoverflow.com/questions/19072110/numpy-np-lexsort-with-fuzzy-tolerant-comparisons
note that I added dim<arr.shape[0]-1 in some if statement (else it will crash sometimes)
"""
arrd = arr[dim]
srtdidx = sorted(idx, key=arrd.__getitem__)
i, ix = 0, srtdidx[0]
for j, jx in enumerate(srtdidx[1:], start=1):
if arrd[jx] - arrd[ix] >= tol:
if j - i > 1 and dim < arr.shape[0] - 1:
srtdidx[i:j] = fuzzysort(arr, srtdidx[i:j], dim + 1, tol)
i, ix = j, jx
if i != j and dim < arr.shape[0] - 1:
srtdidx[i:] = fuzzysort(arr, srtdidx[i:], dim + 1, tol)
return srtdidx
def lookup_sorted_geom(geom):
"""return the indices to sort the
geometry array by x, then y, then z
and the associated inverse look-up table
"""
ind = fuzzysort(geom.T, list(range(0, geom.shape[0])), tol=1e-4)
# generate inverse look-up table
dic = {i: index for i, index in enumerate(ind)}
ind_inv = np.zeros_like(ind)
for k, v in dic.items():
ind_inv[v] = k
return ind, ind_inv
def read_geom_connect(sx):
return sx.ReadGeometry(), sx.ReadConnect()
def return_sorted_geom_connect(sx):
"""sort geom array and reindex connect array to match the new geom array"""
geom, connect = read_geom_connect(sx)
nv = geom.shape[0]
try:
import pymesh
geom, connect, inf = pymesh.remove_duplicated_vertices_raw(
geom, connect, tol=1e-4
)
print(f"removed {inf['num_vertex_merged']} duplicates out of {nv}")
except ModuleNotFoundError:
print("pymesh not found, trying trimesh...")
import trimesh
trimesh.tol.merge = 1e-4
mesh = trimesh.Trimesh(geom, connect)
mesh.merge_vertices()
geom = mesh.vertices
connect = mesh.faces
print(f"removed {nv-geom.shape[0]} duplicates out of {nv}")
ind, ind_inv = lookup_sorted_geom(geom)
geom = geom[ind, :]
connect = np.array([ind_inv[x] for x in connect.flatten()]).reshape(connect.shape)
# sort along line (then we can use multidim_intersect)
connect = np.sort(connect, axis=1)
return geom, connect
def multidim_intersect(arr1, arr2):
"""find indexes of same triangles in 2 connect arrays
(associated with the same geom array)
generate 1D arrays of tuples and use numpy function
https://stackoverflow.com/questions/9269681/intersection-of-2d-numpy-ndarrays
"""
arr1_view = arr1.view([("", arr1.dtype)] * arr1.shape[1])
arr2_view = arr2.view([("", arr2.dtype)] * arr2.shape[1])
intersected, ind1, ind2 = np.intersect1d(arr1_view, arr2_view, return_indices=True)
ni, n1, n2 = intersected.shape[0], arr1.shape[0], arr2.shape[0]
print(
f"{ni} faces in common, n faces connect 1:{n1}, 2:{n2} (diff: {n1-ni}, {n2-ni})"
)
return ind1, ind2
def same_geometry(sx1, sx2):
geom1 = sx1.ReadGeometry()
geom2 = sx2.ReadGeometry()
if geom1.shape[0] != geom2.shape[0]:
return False
else:
return np.all(np.isclose(geom1, geom2, rtol=1e-3, atol=1e-4))
parser = argparse.ArgumentParser(
description="make difference between 2 (paraview) output files: f2-f1. \
The output must be from the same mesh, but the partionning may differ."
)
parser.add_argument("xdmf_filename1", help="filename1")
parser.add_argument("xdmf_filename2", help="filename2")
parser.add_argument(
"--idt",
nargs="+",
required=True,
help="list of time step to differenciate (1st = 0); -1 = all",
type=int,
)
parser.add_argument(
"--Data",
nargs="+",
required=True,
metavar=("variable"),
help="Data to differenciate (example SRs); all for all stored quantities",
)
parser.add_argument(
"--ratio",
dest="ratio",
default=False,
action="store_true",
help="compute relative ratio (f1-f2)/f1 instead of f2-f1",
)
args = parser.parse_args()
sx1 = sx.seissolxdmf(args.xdmf_filename1)
sx2 = sx.seissolxdmf(args.xdmf_filename2)
same_geom = same_geometry(sx1, sx2)
if same_geom:
print("same indexing detected, no need to reindex arrays")
geom1, connect1 = read_geom_connect(sx1)
geom2, connect2 = read_geom_connect(sx2)
else:
geom1, connect1 = return_sorted_geom_connect(sx1)
geom2, connect2 = return_sorted_geom_connect(sx2)
if not np.all(np.isclose(geom1, geom2, rtol=1e-3, atol=1e-4)):
raise ValueError("geometry arrays differ")
ind1, ind2 = multidim_intersect(connect1, connect2)
connect1 = connect1[ind1, :]
if args.idt[0] == -1:
args.idt = list(range(0, sx1.ndt))
aData = []
if args.Data == ["all"]:
variable_names = set()
for elem in sx1.tree.iter():
if elem.tag == "Attribute":
variable_names.add(elem.get("Name"))
variable_names2 = set()
for elem in sx2.tree.iter():
if elem.tag == "Attribute":
variable_names2.add(elem.get("Name"))
# return only variables in common
variable_names = variable_names.intersection(variable_names2)
for to_remove in ["partition", "locationFlag"]:
if to_remove in variable_names:
variable_names.remove(to_remove)
else:
variable_names = args.Data
for dataname in variable_names:
print(dataname)
myData1 = read_reshape2d(sx1, dataname)
myData2 = read_reshape2d(sx2, dataname)
ndt = min(myData1.shape[0], myData2.shape[0])
if same_geom:
myData = myData1[0:ndt, :] - myData2[0:ndt, :]
if args.ratio:
myData = myData / myData1[0:ndt, :]
else:
myData = myData1[0:ndt, ind1] - myData2[0:ndt, ind2]
if args.ratio:
myData = myData / myData1[0:ndt, ind1]
for idt in args.idt:
if idt < ndt:
print(idt, np.amin(myData[idt, :]), np.amax(myData[idt, :]))
else:
print(f"removing idt={idt}>{ndt} from args.idt")
args.idt.pop(idt)
aData.append(myData)
prefix, ext = os.path.splitext(args.xdmf_filename1)
add2prefix = "ratio" if args.ratio else "diff"
fname = f"{add2prefix}_{os.path.basename(prefix)}"
try:
dt = sx1.ReadTimeStep()
except NameError:
dt = 0.0
out_names = ["diff_" + name for name in variable_names]
sw.write_seissol_output(fname, geom1, connect1, out_names, aData, dt, args.idt)
| 31.689498
| 97
| 0.65072
| 987
| 6,940
| 4.488349
| 0.303951
| 0.018962
| 0.019187
| 0.01535
| 0.079458
| 0.058691
| 0.058691
| 0.043341
| 0.017156
| 0.017156
| 0
| 0.034987
| 0.221614
| 6,940
| 218
| 98
| 31.834862
| 0.78508
| 0.138905
| 0
| 0.125
| 0
| 0.00625
| 0.116978
| 0.011036
| 0
| 0
| 0
| 0
| 0
| 1
| 0.04375
| false
| 0
| 0.05
| 0.00625
| 0.14375
| 0.05
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
013f03299525978dd3d212a41f6f91fa29b63b14
| 1,262
|
py
|
Python
|
classes/announcement.py
|
jamflcjamflc/TopRace
|
5c02941c8787884302a91f33f6b26bbdc13d79ce
|
[
"Apache-2.0"
] | null | null | null |
classes/announcement.py
|
jamflcjamflc/TopRace
|
5c02941c8787884302a91f33f6b26bbdc13d79ce
|
[
"Apache-2.0"
] | null | null | null |
classes/announcement.py
|
jamflcjamflc/TopRace
|
5c02941c8787884302a91f33f6b26bbdc13d79ce
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf8 -*-
# announcement
# helper class for toprace
# Alfredo Martin 2021
import pygame
version = 'announcement.v.1.0.0'
class Announcement:
def __init__(self, screen=None, text='', time=5, color=(255, 0, 0)):
"""initiallizes the Announcement instance
screen: pygame canvas instance
text: str
time: int (number of frames during which the announcement will be active
color: color of the text"""
_, _, sw, sh = screen.get_rect()
self.t = 0
self.color = color
self.time = time
self.active = True
style = pygame.font.SysFont('comicsans', 70)
self.text = style.render(text, False, self.color)
_, _, w, h = self.text.get_rect()
text_x = (sw / 2) - (w / 2)
text_y = (sh / 2) - (h / 2)
self.pos = (text_x, text_y)
def update(self, screen):
"""updates the announcements (whether they are active or not) and blits
announcements in the screen
screen: pygame canvas instance
returns: screen after being updated"""
self.t += 1
self.active = self.t <= self.time
screen.blit(self.text, self.pos)
return screen
if __name__ == '__main__':
print(version)
| 28.681818
| 80
| 0.594295
| 164
| 1,262
| 4.439024
| 0.487805
| 0.020604
| 0.049451
| 0.071429
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.024636
| 0.292393
| 1,262
| 43
| 81
| 29.348837
| 0.790594
| 0.333597
| 0
| 0
| 0
| 0
| 0.04799
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.090909
| false
| 0
| 0.045455
| 0
| 0.227273
| 0.045455
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
013f53227578c72e73628747ce0b65e0ad1aa92b
| 3,633
|
py
|
Python
|
policies/regularizers.py
|
IST-DASLab/ACDC
|
ac53210b6adc1f2506ff909de08172ed9cad25d5
|
[
"Apache-2.0"
] | 6
|
2021-11-26T01:21:03.000Z
|
2022-01-10T15:41:50.000Z
|
policies/regularizers.py
|
IST-DASLab/ACDC
|
ac53210b6adc1f2506ff909de08172ed9cad25d5
|
[
"Apache-2.0"
] | 1
|
2021-11-28T10:51:08.000Z
|
2021-11-30T01:30:29.000Z
|
policies/regularizers.py
|
IST-DASLab/ACDC
|
ac53210b6adc1f2506ff909de08172ed9cad25d5
|
[
"Apache-2.0"
] | 1
|
2021-12-21T13:25:43.000Z
|
2021-12-21T13:25:43.000Z
|
"""
Implement regularization policies here
"""
import torch
import torch.nn as nn
from policies.policy import PolicyBase
import logging
def build_reg_from_config(model, reg_config):
"""
This function build regularizer given the model (only need for weigths typically)
and regularizer configuration.
"""
reg_class = reg_config['class']
reg_args = {k: v for k, v in reg_config.items() if k != 'class'}
reg = globals()[reg_class](model, **reg_args)
return reg
def build_regs_from_config(model, config):
"""
This function takes *general* config file for current run and model
and returns a list of regularizers which are build by build_reg_from_config.
Example config.yaml for pruner instances:
>>> regularizers:
>>> reg1:
>>> class: Hoyer # regularization method to use
>>> lambda: 1e-6 # regularization coefficient
>>> modules: [net.0] # modules to apply regularization
>>> weight_only: True # if regularizer is applied only to weights of module (no bias)
>>> reg2:
>>> class: HoyerSquare
>>> lambda: 1e-6
>>> modules: [net.2]
>>> weight_only: True
"""
if 'regularizers' not in config: return []
regs_config = config['regularizers']
regs = [build_reg_from_config(model, reg_config)
for reg_config in regs_config.values()]
return regs
class Regularizer(PolicyBase):
def __init__(self, model, **kwargs):
self._model = model
if not isinstance(self._model, nn.Module):
raise ValueError('model should be an instance of nn.Module')
modules_dict = dict(self._model.named_modules())
self._weight_only, self._lambda = kwargs['weight_only'], float(kwargs['lambda'])
prefix = ''
if isinstance(self._model, torch.nn.DataParallel):
prefix = 'module.'
self._module_names = [prefix + _name for _name in kwargs['modules']]
self._modules = [
modules_dict[module_name] for module_name in self._module_names
]
logging.debug(f'Constructed {self.__class__.__name__} with config:')
logging.debug('\n'.join([f' -{k}:{v}' for k,v in kwargs.items()]) + '\n')
def on_minibatch_begin(self, **kwargs):
reg_loss = self._lambda * self._compute_penalty()
return reg_loss
def _compute_penalty(self):
"""
Base regularizer method which computes regularization penalty.
"""
raise ValueError('Implement in a child class')
class Hoyer(Regularizer):
def __init__(self, model, **kwargs):
super(Hoyer, self).__init__(model, **kwargs)
def _compute_penalty(self):
penalty = 0.
for module in self._modules:
dim = module.weight.numel()
vector = module.weight.view(-1)
if not self._weight_only and module.bias:
dim += self.module.bias.numel()
vector = torch.cat([vector, module.bias])
penalty += (dim ** 0.5 - vector.abs().sum() / vector.norm()) / (dim ** 0.5 - 1)
return penalty
class SquaredHoyer(Regularizer):
def __init__(self, model, **kwargs):
super(SquaredHoyer, self).__init__(model, **kwargs)
def _compute_penalty(self):
penalty = 0.
for module in self._modules:
vector = module.weight.view(-1)
if not self._weight_only and module.bias:
vector = torch.cat([vector, module.bias])
penalty += vector.abs().sum().pow(2) / vector.norm().pow(2)
return penalty
if __name__ == '__main__':
pass
| 33.330275
| 93
| 0.624002
| 444
| 3,633
| 4.880631
| 0.290541
| 0.029072
| 0.016613
| 0.024919
| 0.23258
| 0.222427
| 0.214121
| 0.115367
| 0.115367
| 0.115367
| 0
| 0.007061
| 0.25929
| 3,633
| 109
| 94
| 33.330275
| 0.798216
| 0.219378
| 0
| 0.290323
| 0
| 0
| 0.075368
| 0.009191
| 0
| 0
| 0
| 0
| 0
| 1
| 0.145161
| false
| 0.016129
| 0.064516
| 0
| 0.33871
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014128990469de76bed3ac346da105ea98a96243
| 5,527
|
py
|
Python
|
web_api/bearings/resources/inventory.py
|
zhanghe06/flask_restful
|
6ef54f3f7efbbaff6169e963dcf45ab25e11e593
|
[
"MIT"
] | 1
|
2020-12-04T03:15:47.000Z
|
2020-12-04T03:15:47.000Z
|
web_api/bearings/resources/inventory.py
|
zhanghe06/flask_restful
|
6ef54f3f7efbbaff6169e963dcf45ab25e11e593
|
[
"MIT"
] | 1
|
2021-06-01T22:24:27.000Z
|
2021-06-01T22:24:27.000Z
|
web_api/bearings/resources/inventory.py
|
zhanghe06/flask_restful
|
6ef54f3f7efbbaff6169e963dcf45ab25e11e593
|
[
"MIT"
] | 2
|
2020-12-04T03:16:18.000Z
|
2021-09-04T14:10:12.000Z
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: inventory.py
@time: 2018-06-28 00:22
"""
from __future__ import unicode_literals
from flask import jsonify, make_response
from flask_restful import Resource, marshal, reqparse
from web_api.bearings.outputs.inventory import fields_item_inventory
from web_api.bearings.reqparsers.inventory import (
request_parser,
request_parser_item_post,
request_parser_item_put,
structure_key_item,
structure_key_items,
)
from web_api.commons.exceptions import BadRequest, NotFound
from web_api.bearings.apis.inventory import (
get_inventory_row_by_id,
edit_inventory,
delete_inventory,
get_inventory_limit_rows_by_last_id,
add_inventory,
get_inventory_pagination,
)
from web_api.commons.http_token_auth import token_auth
from web_api import app
SUCCESS_MSG = app.config['SUCCESS_MSG']
FAILURE_MSG = app.config['FAILURE_MSG']
class InventoryResource(Resource):
"""
InventoryResource
"""
decorators = [token_auth.login_required]
def get(self, pk):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventory/1
:param pk:
:return:
"""
data = get_inventory_row_by_id(pk)
if not data:
raise NotFound
result = marshal(data, fields_item_inventory, envelope=structure_key_item)
return jsonify(result)
def delete(self, pk):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventory/1 -X DELETE
:param pk:
:return:
"""
result = delete_inventory(pk)
if result:
success_msg = SUCCESS_MSG.copy()
return make_response(jsonify(success_msg), 204)
else:
failure_msg = FAILURE_MSG.copy()
return make_response(jsonify(failure_msg), 400)
def put(self, pk):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventory/1 -H "Content-Type: application/json" -X PUT -d '
{
"inventory": {
"product_id": 1,
"warehouse_id": 1,
"rack_id": 1,
"stock_qty": 101
}
}'
:param pk:
:return:
"""
request_args = request_parser.parse_args()
request_item_args = request_parser_item_put.parse_args(req=request_args)
if not request_item_args:
raise BadRequest('Bad request.')
request_data = request_item_args
result = edit_inventory(pk, request_data)
if result:
success_msg = SUCCESS_MSG.copy()
return make_response(jsonify(success_msg), 200)
else:
failure_msg = FAILURE_MSG.copy()
return make_response(jsonify(failure_msg), 400)
class InventoryListResource(Resource):
"""
InventoryListResource
"""
decorators = [token_auth.login_required]
def get(self):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventories
curl http://0.0.0.0:5000/bearings/inventories?last_pk=2&limit_num=2
:return:
"""
# 条件参数
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('last_pk', type=int, default=0, location='args')
filter_parser.add_argument('limit_num', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
data = get_inventory_limit_rows_by_last_id(**filter_parser_args)
result = marshal(data, fields_item_inventory, envelope=structure_key_items)
return jsonify(result)
def post(self):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventories -H "Content-Type: application/json" -X POST -d '
{
"inventory": {
"product_id": 1,
"warehouse_id": 1,
"rack_id": "1",
"stock_qty": 100,
"note": "SNFA"
}
}'
:return:
"""
request_args = request_parser.parse_args()
request_item_args = request_parser_item_post.parse_args(req=request_args)
if not request_item_args:
raise BadRequest('Bad request.')
request_data = request_item_args
result = add_inventory(request_data)
if result:
SUCCESS_MSG['id'] = result
return make_response(jsonify(SUCCESS_MSG), 201)
raise NotFound
class InventoryPaginationResource(Resource):
"""
InventoryPaginationResource
"""
decorators = [token_auth.login_required]
def get(self):
"""
Example:
curl http://0.0.0.0:5000/bearings/inventories/pagination
curl http://0.0.0.0:5000/bearings/inventories/pagination?page=2&per_page=2
:return:
"""
# 条件参数
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('page', type=int, default=1, location='args')
filter_parser.add_argument('per_page', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
pagination_obj = get_inventory_pagination(**filter_parser_args)
result = marshal(pagination_obj.items, fields_item_inventory, envelope=structure_key_items)
result['total'] = pagination_obj.total
return jsonify(result)
| 30.368132
| 106
| 0.616971
| 636
| 5,527
| 5.089623
| 0.216981
| 0.014829
| 0.014829
| 0.024714
| 0.612913
| 0.587272
| 0.525178
| 0.492122
| 0.480383
| 0.434971
| 0
| 0.029486
| 0.28207
| 5,527
| 181
| 107
| 30.535912
| 0.78629
| 0.227248
| 0
| 0.388235
| 0
| 0
| 0.025493
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.070588
| false
| 0
| 0.105882
| 0
| 0.341176
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01417896f15a60c73ebefea3a8b55b1d8117b7c4
| 2,141
|
py
|
Python
|
bob/db/swan/query_bio.py
|
bioidiap/bob.db.swan
|
676510d47cb08b65be04f51d45746127c36bf2ce
|
[
"BSD-3-Clause"
] | null | null | null |
bob/db/swan/query_bio.py
|
bioidiap/bob.db.swan
|
676510d47cb08b65be04f51d45746127c36bf2ce
|
[
"BSD-3-Clause"
] | null | null | null |
bob/db/swan/query_bio.py
|
bioidiap/bob.db.swan
|
676510d47cb08b65be04f51d45746127c36bf2ce
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env python
# from bob.bio.spear.database import AudioBioFile
import bob.bio.base
import bob.io.base
import bob.io.video
from bob.extension import rc
from .common import SwanVideoFile, SwanAudioFile, SwanVideoDatabase
# class SwanAudioBioFile(SwanAudioFile, AudioBioFile):
# """SwanAudioBioFile are video files actually"""
class SwanVideoBioFile(SwanVideoFile):
"""SwanVideoBioFile are video files actually"""
class Database(bob.bio.base.database.FileListBioDatabase, SwanVideoDatabase):
"""Wrapper class for the SWAN database for speaker recognition
(http://www.idiap.ch/dataset/swan). This class defines a simple protocol
for training, dev and and by splitting the audio files of the database in
three main parts.
"""
def __init__(self, original_directory=rc['bob.db.swan.directory'],
bio_file_class=SwanVideoBioFile,
annotation_directory=rc['bob.db.swan.annotation_dir'],
annotation_extension='.json',
annotation_type='json',
name='swan', **kwargs):
# call base class constructor
from pkg_resources import resource_filename
folder = resource_filename(__name__, 'lists')
super(Database, self).__init__(
folder, name=name, bio_file_class=bio_file_class,
annotation_directory=annotation_directory,
annotation_extension=annotation_extension,
annotation_type=annotation_type,
original_directory=original_directory,
training_depends_on_protocol=False, models_depend_on_protocol=True,
**kwargs
)
def objects(self, groups=None, protocol=None, purposes=None,
model_ids=None, classes=None, filter_samples=None, **kwargs):
files = super(Database, self).objects(
groups=groups, protocol=protocol, purposes=purposes,
model_ids=model_ids, classes=classes, **kwargs)
files = self.update_files(files)
if filter_samples is None:
return files
files = list(filter(filter_samples, files))
return files
| 38.927273
| 79
| 0.683793
| 239
| 2,141
| 5.92887
| 0.401674
| 0.012703
| 0.025406
| 0.021171
| 0.064926
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.229799
| 2,141
| 54
| 80
| 39.648148
| 0.859309
| 0.218589
| 0
| 0.058824
| 0
| 0
| 0.03961
| 0.028641
| 0
| 0
| 0
| 0
| 0
| 1
| 0.058824
| false
| 0
| 0.176471
| 0
| 0.352941
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014639d9ec97c6ecdda8d9da8e1c9b7abc9b6d28
| 2,008
|
py
|
Python
|
scripts/smilx_pv_visualisation.py
|
aneube/smili-spine
|
3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b
|
[
"BSD-2-Clause"
] | 17
|
2015-03-09T19:22:07.000Z
|
2021-05-24T20:25:08.000Z
|
scripts/smilx_pv_visualisation.py
|
oddway/smili
|
4205b08e5fdcf5ae4fa94747a6dbeac0bb5e0cf0
|
[
"BSD-2-Clause"
] | 16
|
2015-08-20T03:30:15.000Z
|
2019-10-22T12:21:14.000Z
|
scripts/smilx_pv_visualisation.py
|
oddway/smili
|
4205b08e5fdcf5ae4fa94747a6dbeac0bb5e0cf0
|
[
"BSD-2-Clause"
] | 11
|
2015-06-22T00:11:01.000Z
|
2021-12-26T21:29:52.000Z
|
#!/usr/bin/smilx
'''=========================================================================
The Software is copyright (c) Commonwealth Scientific and Industrial Research Organisation (CSIRO)
ABN 41 687 119 230.
All rights reserved.
Licensed under the CSIRO BSD 3-Clause License
You may not use this file except in compliance with the License.
You may obtain a copy of the License in the file LICENSE.md or at
https://stash.csiro.au/projects/SMILI/repos/smili/browse/license.txt
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.
========================================================================='''
'''
This script opens a pv map and its corresponding image, thresholds and overlays the two, loads camera view, links windows and disables interpolation.
To use it, run smilx, in python console type "execfile('smilx_pv_visualisation.py')"
'''
#names of images, set them to empty string to get popup dialogs
imageName = "PAVEL_FLAWS_INV2.nii.gz"
pvImageName = "PAVEL_BiExp_Combined_PV_GM.nii.gz"
tmpOutName = "thresholded_pvimage.nii.gz"
MainWindow.loadFile(imageName) # load image
image = MainWindow.activeImage() # get pointer to image window
MainWindow.loadFile(pvImageName) # load image
pvImage = MainWindow.activeImage() # get pointer to image window
#process pv map for display
belowLevel = 0.01
aboveLevel = 0.25
pvImage.binaryThreshold(255, belowLevel, aboveLevel)
milxQtFile.saveImage(tmpOutName, pvImage) # save result
#overlay the pv processed result
pvImage.viewToSagittal()
pvImage.loadView("camera.cam")
pvImage.interpolateDisplay()
image.overlay(tmpOutName)
image.viewToSagittal()
image.loadView("camera.cam")
image.interpolateDisplay()
MainWindow.tileTab()
MainWindow.link() #link all the windows
| 38.615385
| 149
| 0.728586
| 264
| 2,008
| 5.507576
| 0.590909
| 0.034388
| 0.017882
| 0.042641
| 0.060523
| 0.060523
| 0.060523
| 0
| 0
| 0
| 0
| 0.012557
| 0.12749
| 2,008
| 51
| 150
| 39.372549
| 0.817352
| 0.553287
| 0
| 0
| 0
| 0
| 0.159375
| 0.128125
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0148eac89948dbf7e99bb94cb77565537c9937b2
| 6,869
|
py
|
Python
|
binary_eight_queens_enhanced_num.py
|
MiniMarvin/oito-rainhas
|
67be60d798a99ac218b2bbc53eabf47a563dce7b
|
[
"MIT"
] | null | null | null |
binary_eight_queens_enhanced_num.py
|
MiniMarvin/oito-rainhas
|
67be60d798a99ac218b2bbc53eabf47a563dce7b
|
[
"MIT"
] | null | null | null |
binary_eight_queens_enhanced_num.py
|
MiniMarvin/oito-rainhas
|
67be60d798a99ac218b2bbc53eabf47a563dce7b
|
[
"MIT"
] | null | null | null |
import random
import math
from collections import OrderedDict
class BinaryEightQueensEnhancedNum:
def __init__(self, populationSize, crossOverMethod=1, selectMethod=1, mutationMethod=1, entireFit=False):
'''
inicializa a classe.
@params populationSize o tamanho da população.
'''
self.populationSize = populationSize
self.population = []
self.crossOverMethod = self.crossOver
if crossOverMethod == 2:
self.crossOverMethod = self.crossOver2
self.selectionMethod = self.selectParents
if selectMethod == 2:
self.selectionMethod = self.selectRoulette
self.mutate = self.mutate1
if mutationMethod == 2:
self.mutate = self.mutate2
while len(self.population) < populationSize:
gen = list(range(0,8))
random.shuffle(gen)
if gen not in self.population:
self.population.append(gen)
self.history = [self.population]
if not entireFit:
self.checkSolution = self.checkSolution1
else:
self.checkSolution = self.checkSolution2
def buildFenotype(self, gen):
'''
Constroi o fenotipo a partir do genoma (posição das rainhas).
@params gen string o gene a ser calculado.
'''
return gen
def mutate1(self, gen):
# swap
# todo: verificar se vale trocar o fitness
mutationProbability = 0.4
for i in range(len(gen)):
if random.random() < mutationProbability:
a = random.randrange(len(gen))
gen[i] = a
output = gen
return output
def mutate2(self, gen):
# swap
# todo: verificar se vale trocar o fitness
mutationProbability = 0.4
if random.random() < mutationProbability:
a = random.randrange(len(gen))
b = random.randrange(len(gen))
gen[a], gen[b] = gen[b], gen[a]
output = gen
return output
def crossOver(self, gen1, gen2):
pos = random.randrange(len(gen1))
child1 = gen1[:pos] + gen2[pos:]
child2 = gen2[:pos] + gen1[pos:]
return child1, child2
def crossOver2(self, gen1, gen2):
pos = random.randrange(len(gen1))
child1 = gen1[:pos] + gen2[pos:] + gen2[:pos]
child2 = gen2[:pos] + gen1[pos:] + gen1[:pos]
# remove repetitions
child1 = list(OrderedDict.fromkeys(child1))
child2 = list(OrderedDict.fromkeys(child2))
return child1, child2
def selectRoulette(self, population):
fitnesses = [self.fitness(gen) for gen in population]
total = sum(fitnesses)
roulette = []
prevProb = 0
for fit in fitnesses:
roulette.append(prevProb + fit/total)
prevProb += fit/total
prob1 = random.random()
prob2 = random.random()
prev = 0
parents = []
# print(prob1, prob2)
for i in range(len(roulette)):
if prev <= prob1 and prob1 <= roulette[i]:
parents.append(population[i])
if prev <= prob2 and prob2 <= roulette[i]:
parents.append(population[i])
prev = roulette[i]
# print(parents)
return parents[:2]
def selectParents(self, population):
gens = random.sample(population, 5)
fenotypes = [(self.buildFenotype(gen), gen) for gen in gens]
fitness = [(self.fitness(fen), gen) for fen, gen in fenotypes]
fitness.sort(reverse=True)
selectedGens = [gen for fitness, gen in fitness]
return selectedGens[:2]
def checkSolution1(self, population):
found = False
ans = []
for gen in population:
if self.fitness(gen) == 28:
found = True
ans = gen
break
return found, ans
def checkSolution2(self, population):
found = True
ans = []
for gen in population:
if self.fitness(gen) != 28:
found = False
ans = gen
break
return found, ans
def fitness(self, gen):
maxHits = 8*(8-1)//2
fenotypes = self.buildFenotype(gen)
hits = 0
for i in range(len(fenotypes)):
for j in range(i):
# print(fenotypes[i], fenotypes[j])
if fenotypes[i] == fenotypes[j]:
hits += 1
elif abs(fenotypes[i] - fenotypes[j]) == abs(i - j):
hits += 1
return maxHits - hits
def fit(self):
didFinish = False
countGenerations = 0
populationFitness = []
convergentNumber = 0
for i in range(10000):
found, gen = self.checkSolution(self.population)
if found:
print('alcançou a solução com ' + str(i) + ' iterações')
# print(self.population)
values = [(self.fitness(gen), self.buildFenotype(gen)) for gen in self.population if self.fitness(gen) == 28]
# print(values)
##############################
## measurement of metrics
##############################
countGenerations = i
didFinish = True
populationFitness = [self.fitness(gen) for gen in self.population]
convergentNumber = len(values)
##############################
break
fitElements = [(self.fitness(gen), gen) for gen in self.population]
fitElements.sort(reverse=True)
if i%100 == 0:
print('passo', i)
# print(fitElements[0][0], self.buildFenotype(fitElements[0][1]))
limit = math.floor(0.9*len(fitElements))
newPopulation = []
for i in range(limit, -1, -2):
parents = self.selectionMethod(self.population)
# aaa|bbbbbbb
# bbb|aaaaaaa
# print(parents)
gens = self.crossOverMethod(parents[0], parents[1])
m1, m2 = self.mutate(gens[0]), self.mutate(gens[1])
newPopulation.append(m1)
newPopulation.append(m2)
population = [gen for fitness,gen in fitElements]
population = population[:len(population) - limit] + newPopulation
self.population = population
return didFinish, countGenerations, populationFitness, convergentNumber
# print('finalizou com:', [self.buildFenotype(gen) for gen in self.population])
| 32.709524
| 125
| 0.526569
| 676
| 6,869
| 5.344675
| 0.217456
| 0.065873
| 0.017714
| 0.018267
| 0.27152
| 0.234154
| 0.174094
| 0.158594
| 0.122336
| 0.09189
| 0
| 0.023624
| 0.365264
| 6,869
| 209
| 126
| 32.866029
| 0.805046
| 0.086767
| 0
| 0.232394
| 0
| 0
| 0.006225
| 0
| 0
| 0
| 0
| 0.004785
| 0
| 1
| 0.084507
| false
| 0.007042
| 0.021127
| 0
| 0.190141
| 0.014085
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014a513ce67d34f43fbb3d224139ad39fdd0d756
| 639
|
py
|
Python
|
problems/07/solution_07.py
|
r1cc4rdo/daily_coding_problem
|
6ac85309fad2f64231ac7ab94aa4158e18bdec40
|
[
"Unlicense"
] | 158
|
2018-01-25T06:33:30.000Z
|
2022-03-14T23:18:05.000Z
|
problems/07/solution_07.py
|
r1cc4rdo/daily_coding_problem
|
6ac85309fad2f64231ac7ab94aa4158e18bdec40
|
[
"Unlicense"
] | 9
|
2018-07-04T00:31:57.000Z
|
2020-05-16T21:02:30.000Z
|
problems/07/solution_07.py
|
r1cc4rdo/daily_coding_problem
|
6ac85309fad2f64231ac7ab94aa4158e18bdec40
|
[
"Unlicense"
] | 50
|
2018-06-22T16:48:44.000Z
|
2022-01-11T16:45:48.000Z
|
def coding_problem_07(s):
"""
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
Examples:
>>> coding_problem_07('111') # possible interpretations: 'aaa', 'ka', 'ak'
3
>>> coding_problem_07('2626') # 'zz', 'zbf', 'bfz', 'bfbf'
4
"""
symbols = map(str, range(1, 27))
if not s:
return 1
matches = filter(lambda symbol: s.startswith(symbol), symbols)
encodings = [coding_problem_07(s[len(m):]) for m in matches]
return sum(encodings)
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| 26.625
| 115
| 0.610329
| 89
| 639
| 4.202247
| 0.741573
| 0.139037
| 0.160428
| 0.085562
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.051653
| 0.242567
| 639
| 23
| 116
| 27.782609
| 0.721074
| 0.410016
| 0
| 0
| 0
| 0
| 0.02346
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.1
| false
| 0
| 0.1
| 0
| 0.4
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014ca2e3d1790bdd33dbe16cd9e24261132907eb
| 5,160
|
py
|
Python
|
ph5/utilities/tests/test_seg2toph5.py
|
iris-edu-int/PH5
|
2056191ec3db1dbcbbd18facba56750d3c5cc5b4
|
[
"MIT"
] | 21
|
2016-12-07T20:09:31.000Z
|
2022-03-07T22:23:57.000Z
|
ph5/utilities/tests/test_seg2toph5.py
|
iris-edu-int/PH5
|
2056191ec3db1dbcbbd18facba56750d3c5cc5b4
|
[
"MIT"
] | 395
|
2016-11-03T03:43:55.000Z
|
2022-03-08T20:54:22.000Z
|
ph5/utilities/tests/test_seg2toph5.py
|
iris-edu-int/PH5
|
2056191ec3db1dbcbbd18facba56750d3c5cc5b4
|
[
"MIT"
] | 6
|
2016-10-25T22:22:38.000Z
|
2021-05-10T18:19:45.000Z
|
'''
Tests for seg2toph5
'''
import os
import sys
import unittest
import logging
from mock import patch
from testfixtures import OutputCapture, LogCapture
from ph5.utilities import seg2toph5, initialize_ph5
from ph5.core.tests.test_base import LogTestCase, TempDirTestCase,\
initialize_ex
from ph5.core import ph5api
class TestSeg2toPH5_main(TempDirTestCase, LogTestCase):
def tearDown(self):
self.ph5object.ph5close()
super(TestSeg2toPH5_main, self).tearDown()
def test_main(self):
# check external links created
data_nodes = ['Das_g_0000SV01', 'Das_g_0000SV02', 'Das_g_0000SV03',
'Das_g_0000SV04', 'Das_g_0000SV05', 'Das_g_0000SV06',
'Das_g_0000SV07', 'Das_g_0000SV08', 'Das_g_0000SV09',
'Das_g_0000SV10', 'Das_g_0000SV11', 'Das_g_0000SV12',
'Das_g_0000SV13', 'Das_g_0000SV14', 'Das_g_0000SV15',
'Das_g_0000SV16', 'Das_g_0000SV17', 'Das_g_0000SV18',
'Das_g_0000SV19', 'Das_g_0000SV20', 'Das_g_0000SV21',
'Das_g_0000SV22', 'Das_g_0000SV23', 'Das_g_0000SV24',
'Das_g_0000SV25', 'Das_g_0000SV26', 'Das_g_0000SV27',
'Das_g_0000SV28', 'Das_g_0000SV29', 'Das_g_0000SV30',
'Das_g_0000SV31', 'Das_g_0000SV32', 'Das_g_0000SV33',
'Das_g_0000SV34', 'Das_g_0000SV35', 'Das_g_0000SV36',
'Das_g_0000SV37', 'Das_g_0000SV38', 'Das_g_0000SV39',
'Das_g_0000SV40', 'Das_g_0000SV41', 'Das_g_0000SV42',
'Das_g_0000SV43', 'Das_g_0000SV44', 'Das_g_0000SV45',
'Das_g_0000SV46', 'Das_g_0000SV47', 'Das_g_0000SV48',
'Das_g_0000SV49', 'Das_g_0000SV50', 'Das_g_0000SV51',
'Das_g_0000SV52', 'Das_g_0000SV53', 'Das_g_0000SV54',
'Das_g_0000SV55', 'Das_g_0000SV56', 'Das_g_0000SV57',
'Das_g_0000SV58', 'Das_g_0000SV59', 'Das_g_0000SV60']
testargs = ['initialize_ph5', '-n', 'master.ph5']
with patch.object(sys, 'argv', testargs):
initialize_ph5.main()
# add seg2 to ph5
testargs = ['seg2toph5', '-n', 'master.ph5', '-r',
os.path.join(self.home, "ph5/test_data/seg2/15001.dat")]
with patch.object(sys, 'argv', testargs):
with OutputCapture():
with LogCapture() as log:
log.setLevel(logging.ERROR)
seg2toph5.main()
# before commit caf6978, there would be 1 error log if run this in
# environment that uses Obspy 1.2.2
self.assertEqual(len(log.records), 0)
self.ph5object = ph5api.PH5(path=self.tmpdir, nickname='master.ph5')
target_p1 = 'miniPH5_00001.ph5:/Experiment_g/Maps_g/'
targets = [target_p1 + n for n in data_nodes]
node = self.ph5object.ph5.get_node("/Experiment_g/Maps_g/")
i = 0
ret_targets = []
for n in self.ph5object.ph5.list_nodes(node):
if hasattr(n, 'target'):
ret_targets.append(n.target)
i += 1
self.assertEqual(ret_targets, targets)
target_p1 = 'miniPH5_00001.ph5:/Experiment_g/Receivers_g/'
targets = [target_p1 + n for n in data_nodes]
node = self.ph5object.ph5.get_node("/Experiment_g/Receivers_g/")
i = 0
ret_targets = []
for n in self.ph5object.ph5.list_nodes(node):
if hasattr(n, 'target'):
ret_targets.append(n.target)
i += 1
self.assertEqual(ret_targets, targets)
def test_update_external_references(self):
self.ph5object = seg2toph5.EX = \
initialize_ex('master.ph5', '.', True)
keys = ['external_file_name_s', 'hdf5_path_s', 'serial_number_s']
INDEX_T_DAS_rows = \
[{'external_file_name_s': './miniPH5_00001.ph5',
'hdf5_path_s': '/Experiment_g/Receivers_g/Das_g_0000SV01'}]
seg2toph5.INDEX_T_DAS = seg2toph5.Rows_Keys(INDEX_T_DAS_rows, keys)
INDEX_T_MAP_rows = \
[{'external_file_name_s': './miniPH5_00001.ph5',
'hdf5_path_s': '/Experiment_g/Maps_g/Das_g_0000SV01'}]
seg2toph5.INDEX_T_MAP = seg2toph5.Rows_Keys(INDEX_T_MAP_rows, keys)
seg2toph5.update_external_references()
# check if external links are created
node = self.ph5object.ph5.get_node("/Experiment_g/Receivers_g/")
target = 'miniPH5_00001.ph5:/Experiment_g/Receivers_g/Das_g_0000SV01'
for n in self.ph5object.ph5.list_nodes(node):
if hasattr(n, 'target'):
self.assertEqual(n.target, target)
break
node = self.ph5object.ph5.get_node("/Experiment_g/Maps_g/")
target = 'miniPH5_00001.ph5:/Experiment_g/Maps_g/Das_g_0000SV01'
for n in self.ph5object.ph5.list_nodes(node):
if hasattr(n, 'target'):
self.assertEqual(n.target, target)
break
if __name__ == "__main__":
unittest.main()
| 43
| 77
| 0.605426
| 640
| 5,160
| 4.517188
| 0.270313
| 0.088551
| 0.044275
| 0.027672
| 0.39744
| 0.386372
| 0.352473
| 0.273954
| 0.273954
| 0.273954
| 0
| 0.137931
| 0.28062
| 5,160
| 119
| 78
| 43.361345
| 0.640894
| 0.03876
| 0
| 0.340426
| 0
| 0
| 0.300525
| 0.079022
| 0
| 0
| 0
| 0
| 0.053191
| 1
| 0.031915
| false
| 0
| 0.095745
| 0
| 0.138298
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014d7f5347c2db899cb4f07a82d8e90ce6a5c1f4
| 1,251
|
py
|
Python
|
zcash/test_node.py
|
gwynethallwright/cs291d_project
|
7d9bbb32acec855e777b93b88153869393d458d3
|
[
"Apache-2.0"
] | null | null | null |
zcash/test_node.py
|
gwynethallwright/cs291d_project
|
7d9bbb32acec855e777b93b88153869393d458d3
|
[
"Apache-2.0"
] | null | null | null |
zcash/test_node.py
|
gwynethallwright/cs291d_project
|
7d9bbb32acec855e777b93b88153869393d458d3
|
[
"Apache-2.0"
] | null | null | null |
import time
from zcash.node import *
node1 = Node(8002, "node 1")
node1.start()
# wait for string
time.sleep(2)
node1.print_blockchain()
time.sleep(2)
node2 = Node(8003, "node 2")
node2.start()
# wait for string
time.sleep(2)
node2.print_blockchain()
node1.get_balance()
node2.get_balance()
# node1 mint and pour to send to node2
tx1 = node1.mint_coin(1)
node1.broadcast_new_transaction(tx1)
# waiting for tx broadcast
time.sleep(2)
node1.show_coin()
tx2 = node1.mint_coin(1)
node1.broadcast_new_transaction(tx2)
# waiting for tx broadcast
time.sleep(2)
node1.show_coin()
coin_old_1 = list(node1.coin_set)[0]
coin_old_2 = list(node1.coin_set)[1]
tx3 = node1.pour_coin(coin_old_1, coin_old_2, node1.addr_sk, node1.addr_sk, 1, 1, node2.addr_pk, node2.addr_pk, 0, "")
sn_list = [tx3.tx_pour[1], tx3.tx_pour[2]]
# tx = Transaction(sender=node1.wallet.address, receiver=node2.wallet.address, amount=0.3)
# sig = node1.wallet.sign(str(tx))
# tx.set_sign(node1.wallet.pubkey, sig)
node1.broadcast_new_transaction(tx3)
# waiting for tx broadcast
time.sleep(2)
node1.show_coin()
node2.show_coin()
node2.receive_coin(node2.addr_pk, node2.addr_sk)
node2.print_blockchain()
node2.get_balance()
node1.get_balance()
node1.print_blockchain()
| 18.397059
| 118
| 0.751399
| 211
| 1,251
| 4.255924
| 0.255924
| 0.060134
| 0.066815
| 0.066815
| 0.347439
| 0.302895
| 0.302895
| 0.240535
| 0.146993
| 0.146993
| 0
| 0.068284
| 0.110312
| 1,251
| 67
| 119
| 18.671642
| 0.738544
| 0.242206
| 0
| 0.5
| 0
| 0
| 0.012793
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.058824
| 0
| 0.058824
| 0.117647
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
014f313e34df031bf86f179460a6096cdeb0e1a1
| 535
|
py
|
Python
|
hr_timesheet_invoice_release/account_invoice.py
|
sunflowerit/odoo-modules
|
77e11c4868c3f94c031542b48e5d83797cf4a28d
|
[
"MIT"
] | null | null | null |
hr_timesheet_invoice_release/account_invoice.py
|
sunflowerit/odoo-modules
|
77e11c4868c3f94c031542b48e5d83797cf4a28d
|
[
"MIT"
] | 4
|
2016-10-19T17:01:04.000Z
|
2018-01-12T18:34:58.000Z
|
hr_timesheet_invoice_release/account_invoice.py
|
sunflowerit/odoo-modules
|
77e11c4868c3f94c031542b48e5d83797cf4a28d
|
[
"MIT"
] | 1
|
2018-03-08T16:23:52.000Z
|
2018-03-08T16:23:52.000Z
|
# -*- coding: utf-8 -*-
# © 2017 Sunflower IT (http://sunflowerweb.nl)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import fields, models, api, _
from openerp.exceptions import Warning
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.multi
def release_timesheet_lines(self):
self.ensure_one()
self.env['hr.analytic.timesheet'].search([
('invoice_id', '=', self.id)
]).with_context(override_check=True).write({'invoice_id': None})
| 29.722222
| 72
| 0.665421
| 69
| 535
| 5.043478
| 0.782609
| 0.063218
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.015909
| 0.17757
| 535
| 17
| 73
| 31.470588
| 0.772727
| 0.239252
| 0
| 0
| 0
| 0
| 0.141439
| 0.052109
| 0
| 0
| 0
| 0
| 0
| 1
| 0.1
| false
| 0
| 0.2
| 0
| 0.5
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01507b0361d9bced76109c780b90eccee027d206
| 4,205
|
py
|
Python
|
blocklenium/selenium_worker.py
|
jpunkt/blocklenium
|
dbe81b900d9c9781443d2cac2920815cb5f0a779
|
[
"MIT"
] | null | null | null |
blocklenium/selenium_worker.py
|
jpunkt/blocklenium
|
dbe81b900d9c9781443d2cac2920815cb5f0a779
|
[
"MIT"
] | 1
|
2020-07-17T10:11:42.000Z
|
2020-07-17T14:44:59.000Z
|
blocklenium/selenium_worker.py
|
jpunkt/blocklenium
|
dbe81b900d9c9781443d2cac2920815cb5f0a779
|
[
"MIT"
] | null | null | null |
import configparser
import logging
import threading
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
logger = logging.getLogger(__name__)
class SeleniumWorker(threading.Thread):
def __init__(self, queue, config):
threading.Thread.__init__(self)
self.chromedriver_path = config['CHROMEDRIVER_PATH']
self.desk_url = config['DESK_URL']
self.login_required = config['DESK_LOGIN_REQUIRED']
self.queue = queue
self.chromedriver = None
# Set options for chromedriver
self.chromecaps = webdriver.DesiredCapabilities.CHROME.copy()
# Accept insecure connections
self.chromecaps['acceptInsecureCerts'] = \
config['BROWSER_INSECURE_CERTS']
# Load javascript file
# If the filename ends with '.url', read with config-parser
bookmarklet_path = config['BOOKMARKLET_PATH']
if bookmarklet_path.endswith('.url'):
# parse with config parser
parser = configparser.ConfigParser()
parser.read(bookmarklet_path)
if 'InternetShortcut' in parser:
self.js = parser['InternetShortcut']['URL']
else:
raise ValueError('Bookmarklet file must be a web link!')
else:
with open(bookmarklet_path, "r") as f:
self.js = f.read()
def run(self):
"""Runs in an endless loop until False was put on the queue.
If True is on the queue, opens a browser and runs bookmarklet.
If None is on the queue, closes the browser."""
logger.debug('Thread running.')
while True:
q = self.queue.get()
if q:
logger.info('Starting browser...')
# Instantiate driver (opens browser)
if self.chromedriver is None:
logger.debug('No browser running. Starting browser...')
self.chromedriver = webdriver.Chrome(
self.chromedriver_path,
desired_capabilities=self.chromecaps)
# Open a website
logger.debug('Calling url')
self.chromedriver.get(self.desk_url)
# Log in if needed
if self.login_required:
self.desk_login()
# Execute JavaScript
if self.js is not None:
logger.info('Executing JavaScript...')
# Execute javascript
self.chromedriver.execute_script(self.js)
else:
logger.info('Closing browser...')
# Close browser
if self.chromedriver is not None:
self.chromedriver.quit()
self.chromedriver = None
if q is False:
logger.info('Exiting worker loop...')
break
def desk_login(self):
logger.info('attempting login to desk...')
# the user-input fields have weird ids, so we need to select
# them by searching for ids containing 'Username' or 'Password'
userfields = self.chromedriver.find_elements_by_css_selector(
"input[id*='Username']")
pwdfields = self.chromedriver.find_elements_by_css_selector(
"input[id*='Password']")
if (len(userfields) > 0) and (len(pwdfields) > 0):
userfields[0].send_keys(self.desk_username)
pwdfields[0].send_keys(self.desk_password)
loginbtn = self.chromedriver.find_element_by_xpath(
"//button[@type='submit']")
loginbtn.click()
# Wait for the new page to be fully loaded
WebDriverWait(self.chromedriver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME,
"timeline-header"))
)
else:
logger.info(
'Expected Login page but found no login fields. Ignored')
| 36.885965
| 75
| 0.572889
| 435
| 4,205
| 5.416092
| 0.37931
| 0.095076
| 0.02674
| 0.023769
| 0.078098
| 0.040747
| 0.040747
| 0.040747
| 0.040747
| 0
| 0
| 0.002171
| 0.342687
| 4,205
| 113
| 76
| 37.212389
| 0.850217
| 0.14459
| 0
| 0.08
| 0
| 0
| 0.13644
| 0.024705
| 0
| 0
| 0
| 0
| 0
| 1
| 0.04
| false
| 0.026667
| 0.093333
| 0
| 0.146667
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0150a51530726ef3c2430cedd19b6ce0d322142d
| 1,595
|
py
|
Python
|
setup.py
|
LaudateCorpus1/evohome-async
|
333223df05b7881d6d9b831eb41d209846dd9a98
|
[
"Apache-2.0"
] | 2
|
2020-11-18T14:33:49.000Z
|
2021-12-27T14:52:54.000Z
|
setup.py
|
LaudateCorpus1/evohome-async
|
333223df05b7881d6d9b831eb41d209846dd9a98
|
[
"Apache-2.0"
] | 4
|
2021-03-10T16:54:31.000Z
|
2022-01-21T10:16:33.000Z
|
setup.py
|
LaudateCorpus1/evohome-async
|
333223df05b7881d6d9b831eb41d209846dd9a98
|
[
"Apache-2.0"
] | 9
|
2020-12-06T08:07:45.000Z
|
2022-02-08T07:03:53.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""The setup.py file."""
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.install import install
VERSION = "0.3.15"
URL = "https://github.com/zxdavb/evohome-async"
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
class VerifyVersionCommand(install):
"""Custom command to verify that the git tag matches our VERSION."""
def run(self):
tag = os.getenv("CIRCLE_TAG")
if tag != VERSION:
info = f"The git tag: '{tag}' does not match the package ver: '{VERSION}'"
sys.exit(info)
setup(
name="evohome-async",
description="An async client for connecting to Honeywell's TCC RESTful API.",
keywords=["evohome", "total connect comfort", "round thermostat"],
author="Andrew Stock & David Bonnes",
author_email="zxdavb@gmail.com",
url=URL,
download_url=f"{URL}/archive/{VERSION}.tar.gz",
install_requires=[val.strip() for val in open("requirements.txt")],
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
packages=find_packages(exclude=["test", "docs"]),
version=VERSION,
license="Apache 2",
python_requires=">=3.7",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.7",
"Topic :: Home Automation",
],
cmdclass={
"verify": VerifyVersionCommand,
},
)
| 28.482143
| 86
| 0.648276
| 195
| 1,595
| 5.235897
| 0.651282
| 0.058766
| 0.01763
| 0.058766
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.008703
| 0.207524
| 1,595
| 55
| 87
| 29
| 0.799051
| 0.077743
| 0
| 0
| 0
| 0
| 0.387517
| 0.020576
| 0
| 0
| 0
| 0
| 0
| 1
| 0.025
| false
| 0
| 0.1
| 0
| 0.15
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01584c384f8f8eea463542d1db5fde7c51f316cc
| 3,166
|
py
|
Python
|
yubin/__init__.py
|
mritu301/NLP-Labeling
|
403b06c25984646be9ed8f37c5777d32acc3dec1
|
[
"MIT"
] | 3
|
2019-10-28T00:07:25.000Z
|
2020-01-17T05:25:08.000Z
|
yubin/__init__.py
|
alvations/yubin
|
403b06c25984646be9ed8f37c5777d32acc3dec1
|
[
"MIT"
] | null | null | null |
yubin/__init__.py
|
alvations/yubin
|
403b06c25984646be9ed8f37c5777d32acc3dec1
|
[
"MIT"
] | null | null | null |
import re
from itertools import chain
from collections import defaultdict, namedtuple
import pandas as pd
from tqdm import tqdm
Address = namedtuple('Address', ['to', 'kai', 'ku', 'mune', 'chome', 'ban',
'go', 'postal', 'endgo', 'tokens'])
class Postman:
"""
Converts Japanese address in raw string to structured object.
"""
to_regex = r'(({})都)'.format('|'.join(['東京']))
ku_regex = r'#TO# (.*区(佃)?)'
postal_regex = r'((〒?[0-90-9]+([ー-‐-])){1,}([0-90-9]+))'
chome_ban_go = r'([0-90-9一⼀⼆三四五六七⼋九⼗ー]+([{}]+))' # Generic pattern for chome, ban and go.
chome_regex = chome_ban_go.format('丁目')
ban_regex = chome_ban_go.format('番街目')
go_regex = chome_ban_go.format('号棟室館')
endgo_regex = r'(([0-90-9一⼀⼆三四五六七⼋九⼗]+$))' # Number at the end.
ban_go_regex = ban_regex + go_regex + '?' # Not useful?
mune_regex = r'([0-90-9A-Z一⼀⼆三四五六七⼋九⼗]+([号]?[棟]))'
kai_regex = r'(([0-90-9ー]+|[一⼀⼆三四五六七⼋九⼗]+)[階F])'
JAPANESE_ADDRESS_REGEXES = [
(to_regex, ' #TO# '),
(kai_regex, ' #KAI# '),
(ku_regex, ' #KU# '),
(mune_regex, ' #MUNE# '),
(chome_regex, ' #CHOME# '), # Catch chome / ban / go individually.
(ban_regex, ' #BAN# '),
(go_regex, ' #GO# '),
(postal_regex, ' #POSTAL# '),
(endgo_regex, ' #ENDGO# ')
]
def __init__(self):
pass
def normalize(self, pattern, substitution, text):
matches = [match[0] for match in re.findall(pattern, text)]
for match in matches:
text = text.replace(match, substitution)
return matches, ' '.join(text.split()).strip()
def tokenize(self, addr, use_char=False, return_str=False):
"""
Returns an address object.
"""
# Go through the regex and keep the group matches.
regex_matches = defaultdict(list)
for pattern, substitute in self.JAPANESE_ADDRESS_REGEXES:
matches, addr = self.normalize(pattern, substitute, addr)
regex_matches[substitute.strip()] = matches
# Options to return different tokens.
if use_char: # Split the non-captured groups by characters.
tokens = list(chain(*[[token] if token.strip().startswith('#')
and token.strip().endswith('#')
else list(token)
for token in addr.split()]))
else: # Simply return the tokens split by spaces.
tokens = addr.split()
# Replace the placeholders back.
for k in regex_matches:
for v in regex_matches[k]:
tokens[tokens.index(k)] = v
address = Address(to=regex_matches['#TO#'], kai=regex_matches['#KAI#'],
ku=regex_matches['#KU#'], mune=regex_matches['#MUNE#'],
chome=regex_matches['#CHOME#'], ban=regex_matches['#BAN#'],
go=regex_matches['#GO#'], postal=regex_matches['#POSTAL#'],
endgo=regex_matches['#ENDGO#'], tokens=tokens)
return ' '.join(address.tokens) if return_str else address
| 40.075949
| 93
| 0.549905
| 372
| 3,166
| 4.580645
| 0.317204
| 0.091549
| 0.035211
| 0.026408
| 0.036972
| 0
| 0
| 0
| 0
| 0
| 0
| 0.01153
| 0.287745
| 3,166
| 78
| 94
| 40.589744
| 0.736142
| 0.126027
| 0
| 0
| 0
| 0
| 0.132721
| 0.058824
| 0
| 0
| 0
| 0
| 0
| 1
| 0.051724
| false
| 0.017241
| 0.086207
| 0
| 0.396552
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015973c0cde41c6d39371ea08957e73b3b7deff2
| 476
|
py
|
Python
|
setup.py
|
vmraid/vitalpbx
|
3debc302763e53393ccb9610cb117a7d4872d59a
|
[
"MIT"
] | null | null | null |
setup.py
|
vmraid/vitalpbx
|
3debc302763e53393ccb9610cb117a7d4872d59a
|
[
"MIT"
] | null | null | null |
setup.py
|
vmraid/vitalpbx
|
3debc302763e53393ccb9610cb117a7d4872d59a
|
[
"MIT"
] | null | null | null |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in vitalpbx/__init__.py
from vitalpbx import __version__ as version
setup(
name='vitalpbx',
version=version,
description='Something',
author='Someone',
author_email='someone@somewhere.com',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=install_requires
)
| 23.8
| 63
| 0.781513
| 62
| 476
| 5.66129
| 0.645161
| 0.128205
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.105042
| 476
| 19
| 64
| 25.052632
| 0.823944
| 0.128151
| 0
| 0
| 0
| 0
| 0.152542
| 0.050847
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.133333
| 0
| 0.133333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015a892c046052f40a511917cfd969000101e5c9
| 8,215
|
py
|
Python
|
onionstudio.py
|
jarret/onionstudio
|
5ebf0a75cf1e7960822c96a987668be5ed82aa41
|
[
"MIT"
] | 11
|
2020-01-09T19:48:20.000Z
|
2020-11-21T19:59:36.000Z
|
onionstudio.py
|
jarret/onionstudio
|
5ebf0a75cf1e7960822c96a987668be5ed82aa41
|
[
"MIT"
] | null | null | null |
onionstudio.py
|
jarret/onionstudio
|
5ebf0a75cf1e7960822c96a987668be5ed82aa41
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) 2020 Jarret Dyrbye
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php
import time
import sys
import json
import argparse
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from autobahn.twisted.websocket import WebSocketServerProtocol
from autobahn.twisted.websocket import WebSocketServerFactory
from txzmq import ZmqEndpoint, ZmqEndpointType
from txzmq import ZmqFactory
from txzmq import ZmqSubConnection
from bolt.util import h2b
from onionstudio.art_db import ArtDb
from onionstudio.compressor import compressor
from onionstudio.extension import Extension, PIXEL_TLV_TYPE
UNPAID_PRUNE_CHECK = 60
UNPAID_PRUNE_SECONDS = 120
###############################################################################
class AppClient(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
def onOpen(self):
print("WebSocket client connection open.")
self.server.clients.append(self)
art_bin = self.server.app.art_db.to_bin()
compressed_bin = compressor(art_bin)
print("compressed art bin len: %d" % len(compressed_bin))
self.sendMessage(compressed_bin, isBinary=True)
def onMessage(self, payload, isBinary):
print("got message?")
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
###############################################################################
class AppServer(WebSocketServerFactory):
def __init__(self, port, app):
ws_url = u"ws://0.0.0.0:%d" % port
super().__init__()
self.setProtocolOptions(openHandshakeTimeout=15, autoPingInterval=30,
autoPingTimeout=5)
self.protocol = AppClient
self.protocol.server = self
self.clients = []
print("listening on websocket %s" % ws_url)
reactor.listenTCP(port, self)
self.app = app
def echo_to_clients(self, pixels):
pixels = [{'x': p.x, 'y': p.y, 'rgb': p.rgb} for p in pixels]
message = {'pixels': pixels}
message = json.dumps(message)
print("echoing to clients: %s" % message)
for c in self.clients:
c.sendMessage(message.encode("utf8"))
###############################################################################
HTLC_ACCEPTED_TAG = "htlc_accepted".encode("utf8")
FORWARD_EVENT_TAG = "forward_event".encode("utf8")
class App(object):
def __init__(self, endpoint, mock_endpoint, port, art_db_dir):
self.endpoint = endpoint
self.mock_endpoint = mock_endpoint
self.port = port
self.art_db_dir = art_db_dir
self.unpaid_htlcs = {}
self.prune_loop = LoopingCall(self.prune_unpaid)
self.prune_loop.start(interval=UNPAID_PRUNE_CHECK, now=False)
###########################################################################
def setup_art_db(self):
self.art_db = ArtDb(self.art_db_dir)
###########################################################################
def setup_websocket(self):
self.ws_server = AppServer(self.port, self)
###########################################################################
def setup_zmq(self):
zmq_factory = ZmqFactory()
print("subscribing on: %s" % self.endpoint)
sub_endpoint = ZmqEndpoint(ZmqEndpointType.connect, self.endpoint)
sub_connection = ZmqSubConnection(zmq_factory, sub_endpoint)
sub_connection.gotMessage = self.zmq_message
sub_connection.subscribe(FORWARD_EVENT_TAG)
sub_connection.subscribe(HTLC_ACCEPTED_TAG)
print("subscribing on: %s" % self.mock_endpoint)
sub_mock_endpoint = ZmqEndpoint(ZmqEndpointType.connect,
self.mock_endpoint)
sub_mock_connection = ZmqSubConnection(zmq_factory, sub_mock_endpoint)
sub_mock_connection.gotMessage = self.zmq_message
sub_mock_connection.subscribe(FORWARD_EVENT_TAG)
sub_mock_connection.subscribe(HTLC_ACCEPTED_TAG)
def forward_event_message(self, message):
d = json.loads(message.decode('utf8'))['forward_event']
print("got %s" % json.dumps(d, indent=1))
if d['status'] != 'settled':
print("invoice is not settled")
return
if d['payment_hash'] in self.unpaid_htlcs.keys():
self.finish_htlc(d['payment_hash'])
def htlc_accepted_message(self, message):
d = json.loads(message.decode('utf8'))
payment_hash = d['htlc']['payment_hash']
amount = int(d['htlc']['amount'][:-4])
forward_amount = int(d['onion']['forward_amount'][:-4])
payload_hex = d['onion']['payload']
payload = h2b(payload_hex)
paid = amount - forward_amount
parsed_payload, err = Extension.parse(payload)
if err:
print("could not parse payload: %s" % err)
return
print("parsed payload %s" % parsed_payload)
pixels = parsed_payload['tlvs'][PIXEL_TLV_TYPE]['pixels']
if (amount - forward_amount) < len(pixels) * 1000:
print("forward fee not enough")
return
self.unpaid_htlcs[payment_hash] = {'payload_hex': payload_hex,
'recv_time': time.time()}
def finish_htlc(self, payment_hash):
payload_hex = self.unpaid_htlcs.pop(payment_hash)['payload_hex']
payload = h2b(payload_hex)
parsed_payload, err = Extension.parse(payload)
assert err is None, "could not parse the second time?"
pixels = parsed_payload['tlvs'][PIXEL_TLV_TYPE]['pixels']
self.art_db.record_pixels(payload_hex, pixels)
self.ws_server.echo_to_clients( pixels)
def zmq_message(self, message, tag):
if tag == FORWARD_EVENT_TAG:
self.forward_event_message(message)
elif tag == HTLC_ACCEPTED_TAG:
self.htlc_accepted_message(message)
else:
sys.exit("unknown tag: %s" % tag)
###########################################################################
def prune_unpaid(self):
now = time.time()
new = {k: v for k, v in self.unpaid_htlcs.items() if
(now - v['recv_time']) < UNPAID_PRUNE_SECONDS}
#print("pruning: %d to %d" % (len(self.unpaid_htlcs), len(new)))
self.unpaid_htlcs = new
###########################################################################
def run(self):
self.setup_websocket()
self.setup_zmq()
self.setup_art_db()
def stop(self):
self.art_db.unmap_art_bin()
###############################################################################
DEFAULT_WEBSOCKET_PORT = 9000
DEFAULT_ZMQ_SUBSCRIBE_ENDPOINT = "tcp://127.0.0.1:6666"
DEFAULT_MOCK_ZMQ_SUBSCRIBE_ENDPOINT = "tcp://127.0.0.1:5557"
DEFAULT_ART_DB_DIR = "/tmp/onionstudio/"
parser = argparse.ArgumentParser(prog="onionstudio.py")
parser.add_argument("-e", "--endpoint", type=str,
default=DEFAULT_ZMQ_SUBSCRIBE_ENDPOINT,
help="endpoint to subscribe to for zmq notifications from "
"c-lightning via cl-zmq.py plugin")
parser.add_argument("-m", "--mock-endpoint", type=str,
default=DEFAULT_MOCK_ZMQ_SUBSCRIBE_ENDPOINT,
help="endpoint to subscribe to zmq notifcations from a "
"test script such as mock-png.py")
parser.add_argument("-w", "--websocket-port", type=int,
default=DEFAULT_WEBSOCKET_PORT,
help="port to listen for incoming websocket connections")
parser.add_argument("-a", "--art-db-dir", type=str, default=DEFAULT_ART_DB_DIR,
help="directory to save the image state and logs")
settings = parser.parse_args()
a = App(settings.endpoint, settings.mock_endpoint, settings.websocket_port,
settings.art_db_dir)
a.run()
reactor.addSystemEventTrigger("before", "shutdown", a.stop)
reactor.run()
| 37.340909
| 79
| 0.597687
| 925
| 8,215
| 5.100541
| 0.262703
| 0.015897
| 0.013565
| 0.012081
| 0.228487
| 0.114879
| 0.067825
| 0.067825
| 0.019076
| 0
| 0
| 0.009352
| 0.21899
| 8,215
| 219
| 80
| 37.511416
| 0.725998
| 0.03031
| 0
| 0.057325
| 0
| 0
| 0.136039
| 0
| 0
| 0
| 0
| 0
| 0.006369
| 1
| 0.10828
| false
| 0
| 0.095541
| 0
| 0.242038
| 0.089172
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015a901776e9ca3956396eb5890b4a755eb6a932
| 4,078
|
py
|
Python
|
mavsim_holodeck/rosflight_holodeck.py
|
sethmnielsen/mavsim_template_files
|
453ec4f7d38fc2d1162198b554834b5bdb7de96f
|
[
"MIT"
] | null | null | null |
mavsim_holodeck/rosflight_holodeck.py
|
sethmnielsen/mavsim_template_files
|
453ec4f7d38fc2d1162198b554834b5bdb7de96f
|
[
"MIT"
] | null | null | null |
mavsim_holodeck/rosflight_holodeck.py
|
sethmnielsen/mavsim_template_files
|
453ec4f7d38fc2d1162198b554834b5bdb7de96f
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
from __future__ import print_function
from rosflight_holodeck_interface import ROSflightHolodeck
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import time
import holodeck
from holodeck import agents
from holodeck.environments import *
from holodeck import sensors
from IPython.core.debugger import Pdb
import os
import cv2
print( '\nHOLODECK PATH: {}\n'.format( os.path.dirname( holodeck.__file__ ) ) )
np.set_printoptions(precision=3, suppress=True, sign=' ', floatmode='fixed')
if __name__ == '__main__':
env = holodeck.make("Ocean")
RF = ROSflightHolodeck()
env.reset()
env.tick()
# wave intensity: 1-13(int), wave size: 1-8(int), wave direction: 0-360 degreese (float)
env.set_ocean_state(3, 3, 90)
env.set_aruco_code(False)
x0 = np.array([0, 0, 0, # position [0-2]
1, 0, 0, 0, # attitude [3-6]
0, 0, 0, # velocity [7-9]
0, 0, 0, # omega [10-12]
0, 0, 0], dtype=np.float64) # acc [13-15]
h0 = 41 # initial altitude [m]
x0[2] = -h0
# x0[0] = -34.5
RF.init()
RF.setState(x0)
RF.setTime(10)
uav_cmd = np.array([0, 0, 0, 0])
boat_cmd = 0
env.act("uav0", uav_cmd)
env.act("boat0", boat_cmd)
pos0 = x0[:3] * [100, 100, -100] # convert to cm, negate z
env.teleport("uav0", location=pos0, rotation=[0,0,0])
env.teleport("boat0", location=[-2000,0,0], rotation=[0,0,0])
frate = 30 # frame rate of camera/rendering [Hz]
simrate = 800 # rate of simulated dynamics [Hz]
n = simrate//frate # Number of sim iterations between frames
dt = 1.0/simrate
#'F' order because eigen matrices are column-major while numpy are row-major
# x_arr = np.zeros((16, n), order='F')
x = np.zeros(16)
t = np.zeros(n)
rf_outputs = np.zeros(4)
state = np.array([])
pos = np.zeros(3)
att = np.zeros(3)
ground = -0.1
collision = False
count = 0
while 1: # Main loop: 1 iteration = 1 rendered frame
if not collision:
for i in range(n): # Loop between frames (dynamics/control)
RF.run(dt)
time.sleep(dt)
RF.getState(x)
# Make sure mav doesn't fall through ground
if x[2] > ground and x[9] > 0:
# at ground level and not gaining altitude
x_ground = np.copy(x0)
x_ground[:3] = [x[0], x[1], ground]
att_eul = Quaternion2Euler(x[3:7])
ground_eul = np.array([0, 0, att_eul[2]])
x_ground[3:7] = Euler2Quaternion(ground_eul)
pos = x_ground[:3] * [100,100,-100]
att = ground_eul * 180/np.pi
RF.setState(x_ground)
state = env.set_state("uav0", pos, att, [0,0,0], [0,0,0])["uav0"]
else:
# format state for holodeck
pos = x[:3] * [100,100,-100] # cm, negate z to convert to LH frame
att = Quaternion2Euler(x[3:7]) * 180/np.pi
vel = x[7:10] * [100,100,-100]
angvel = np.copy(x[10:13])
state = env.set_state("uav0", pos, att, vel, angvel)["uav0"]
collision = state['CollisionSensor']
elif collision:
# Use position given by holodeck
state = env.tick()["uav0"]
x = np.copy(x0)
x[:3] = state['LocationSensor'] * [1,1,-1]
x[7:10] = state['VelocitySensor'] * [1,1,-1]
RF.setState(x)
for k in range(10):
RF.run(dt)
time.sleep(dt*(n/10))
RF.getState(x)
RF.getOutputs(rf_outputs)
if x[9] < 0:
# gaining altitude, switch back to RF dynamics
collision = False
# Show UAV's camera feed
# frame = state['RGBCamera']
# cv2.imshow('Camera', frame)
# cv2.waitKey(1)
# For debugging
RF.getState(x)
| 34.268908
| 92
| 0.540216
| 563
| 4,078
| 3.83659
| 0.358792
| 0.022222
| 0.018056
| 0.007407
| 0.052778
| 0.040741
| 0.024074
| 0
| 0
| 0
| 0
| 0.076166
| 0.327121
| 4,078
| 119
| 93
| 34.268908
| 0.711006
| 0.212849
| 0
| 0.101124
| 0
| 0
| 0.038014
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.146067
| 0
| 0.146067
| 0.033708
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015c37dadd907a823b8a57e0e66db4c591cdd0d4
| 3,294
|
py
|
Python
|
pyinsar/processing/discovery/coherence.py
|
MITeaps/pyinsar
|
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
|
[
"MIT"
] | 8
|
2019-03-15T19:51:27.000Z
|
2022-02-16T07:27:36.000Z
|
pyinsar/processing/discovery/coherence.py
|
MITeaps/pyinsar
|
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
|
[
"MIT"
] | 1
|
2022-02-08T03:48:56.000Z
|
2022-02-09T01:33:27.000Z
|
pyinsar/processing/discovery/coherence.py
|
MITeaps/pyinsar
|
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
|
[
"MIT"
] | 2
|
2021-01-12T05:32:21.000Z
|
2021-01-13T08:35:26.000Z
|
# The MIT License (MIT)
# Copyright (c) 2017 Massachusetts Institute of Technology
#
# Authors: Cody Rude
# This software is part of the NSF DIBBS Project "An Infrastructure for
# Computer Aided Discovery in Geoscience" (PI: V. Pankratius) and
# NASA AIST Project "Computer-Aided Discovery of Earth Surface
# Deformation Phenomena" (PI: V. Pankratius)
#
# 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.
# Standard library imports
from collections import OrderedDict
# scikit discovery imports
from skdiscovery.data_structure.framework.base import PipelineItem
# Pyinsar imports
from pyinsar.processing.utilities.generic import coherence
# Scikit data access imports
from skdaccess.utilities.support import progress_bar
class Coherence(PipelineItem):
''' Calculate coherence between single-look complex SAR images '''
def __init__(self, str_description, window, pairing='neighbor', use_progress_bar = False):
'''
Initialize coherence pipeline item
@param str_description: Short string describing item
@param window: Tuple indicating the y and x window size
@param pairing: How to pair slc images. "neighbor" computes
coherence between neighboring images
@param use_progress_bar: Display progress using a progress bar
'''
self.window = window
self.pairing = pairing
self.use_progress_bar = use_progress_bar
super(Coherence, self).__init__(str_description,[])
def process(self, obj_data):
'''
Compute the coherency between two
@param obj_data: Data wrapper
'''
results_dict = OrderedDict()
if self.pairing == 'neighbor':
first_image_it = obj_data.getIterator()
second_image_it = obj_data.getIterator()
next(second_image_it)
for (label1, image1), (label2, image2) in progress_bar(zip(first_image_it, second_image_it),
total = len(obj_data)-1,
enabled = self.use_progress_bar):
results_dict[label2] = coherence(image1, image2, self.window)
obj_data.addResult(self.str_description, results_dict)
| 38.302326
| 104
| 0.697936
| 415
| 3,294
| 5.433735
| 0.489157
| 0.039024
| 0.031042
| 0.015965
| 0.022173
| 0
| 0
| 0
| 0
| 0
| 0
| 0.00479
| 0.239526
| 3,294
| 85
| 105
| 38.752941
| 0.895409
| 0.575896
| 0
| 0
| 0
| 0
| 0.012618
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.095238
| false
| 0
| 0.190476
| 0
| 0.333333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015dfc2575ba43d461c6f8e236abfb9df3bf731f
| 997
|
py
|
Python
|
conf.py
|
Kurento/doc-fiware
|
053537edec34fff65e7044f0310ac8c539e011a7
|
[
"Apache-2.0"
] | null | null | null |
conf.py
|
Kurento/doc-fiware
|
053537edec34fff65e7044f0310ac8c539e011a7
|
[
"Apache-2.0"
] | 1
|
2018-11-22T12:48:37.000Z
|
2018-11-22T12:48:37.000Z
|
conf.py
|
Kurento/doc-fiware
|
053537edec34fff65e7044f0310ac8c539e011a7
|
[
"Apache-2.0"
] | 3
|
2018-05-13T09:46:50.000Z
|
2018-12-31T13:06:48.000Z
|
# -*- coding: utf-8 -*-
#
# on_rtd is whether we are on readthedocs.org
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.append(os.path.abspath('extensions'))
extensions = [
'sphinx.ext.graphviz',
'sphinx.ext.todo',
'wikipedia',
'examplecode'
]
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
html_theme_path = ['doc/themes']
html_theme = 'sphinx_rtd_theme'
# otherwise, readthedocs.org uses their theme by default, so no need to specify it
# Using downloaded sphinx_rtd_theme
# import sphinx_rtd_theme
# html_theme = "sphinx_rtd_theme"
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
project = 'FIWARE-Stream-Oriented-GE'
master_doc = 'index'
html_context = {
'css_files': [
'_static/css/theme.css',
'https://fiware.org/style/fiware_readthedocs.css',
'https://fiware.org/style/fiware_readthedocs_media_streams.css'
]
}
| 24.925
| 82
| 0.706118
| 143
| 997
| 4.713287
| 0.503497
| 0.066766
| 0.103858
| 0.053412
| 0.218101
| 0.115727
| 0.115727
| 0
| 0
| 0
| 0
| 0.002384
| 0.158475
| 997
| 39
| 83
| 25.564103
| 0.800954
| 0.357071
| 0
| 0
| 0
| 0
| 0.434231
| 0.0729
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.086957
| 0
| 0.086957
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
015e1ccb959f266ccad863b921198255b5930975
| 2,372
|
py
|
Python
|
Day21/dice.py
|
squidbot/aoc2021
|
aae5cf2017562150ec01d6cce5200ebc2b02f19d
|
[
"MIT"
] | null | null | null |
Day21/dice.py
|
squidbot/aoc2021
|
aae5cf2017562150ec01d6cce5200ebc2b02f19d
|
[
"MIT"
] | null | null | null |
Day21/dice.py
|
squidbot/aoc2021
|
aae5cf2017562150ec01d6cce5200ebc2b02f19d
|
[
"MIT"
] | null | null | null |
test_input = [4, 8]
puzzle_input = [4, 9]
def part1():
position = puzzle_input
score = [0,0]
die_roll = 0
num_rolls = 0
cur_player = 0
while True:
die_total = 0
for _ in range(3):
num_rolls += 1
die_roll += 1
if die_roll > 100:
die_roll = 1
die_total += die_roll
for _ in range(die_total):
position[cur_player] += 1
if position[cur_player] > 10:
position[cur_player] = 1
score[cur_player] += position[cur_player]
if score[cur_player] >= 1000:
print("Game over, p1 score", score[0], "p2 score", score[1], "magic number", num_rolls * min(score[0],score[1]))
break
if cur_player == 0:
cur_player = 1
else:
cur_player = 0
#part1()
import collections
def part2():
position = puzzle_input
roll_dist = collections.Counter(i + j + k for i in range(1,4) for j in range(1,4) for k in range(1,4))
p1_wins = 0
p2_wins = 0
game_states = collections.defaultdict(int)
game_states[(position[0], 0, position[1], 0)] = 1
while game_states:
updated_game_states = collections.defaultdict(int)
for game_state in game_states:
for roll in roll_dist:
(pos1, score1, pos2, score2) = game_state
pos1 = (pos1 + roll - 1) % 10 + 1
score1 += pos1
if score1 >= 21:
p1_wins += game_states[game_state] * roll_dist[roll]
else:
updated_game_states[(pos1, score1, pos2, score2)] += game_states[game_state] * roll_dist[roll]
game_states = updated_game_states
updated_game_states = collections.defaultdict(int)
for game_state in game_states:
for roll in roll_dist:
(pos1, score1, pos2, score2) = game_state
pos2 = (pos2 + roll - 1) % 10 + 1
score2 += pos2
if score2 >= 21:
p2_wins += game_states[game_state] * roll_dist[roll]
else:
updated_game_states[(pos1, score1, pos2, score2)] += game_states[game_state] * roll_dist[roll]
game_states = updated_game_states
print("p1 wins", p1_wins, "p2 wins", p2_wins)
part2()
| 32.493151
| 124
| 0.544266
| 304
| 2,372
| 4.013158
| 0.190789
| 0.139344
| 0.083607
| 0.068852
| 0.459836
| 0.411475
| 0.411475
| 0.411475
| 0.411475
| 0.411475
| 0
| 0.063523
| 0.356239
| 2,372
| 72
| 125
| 32.944444
| 0.735429
| 0.002951
| 0
| 0.311475
| 0
| 0
| 0.022429
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.032787
| false
| 0
| 0.016393
| 0
| 0.04918
| 0.032787
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0163e63b0f0a4b6a54cef6dce6ac42cdbc68fb82
| 1,200
|
py
|
Python
|
tests/test_write_simple.py
|
ZELLMECHANIK-DRESDEN/fcswrite
|
3b696a0fd4a34f7d3999d4e28bd7981fe38494d2
|
[
"BSD-3-Clause"
] | 8
|
2018-03-15T00:04:47.000Z
|
2021-11-15T09:32:18.000Z
|
tests/test_write_simple.py
|
ZELLMECHANIK-DRESDEN/fcswrite
|
3b696a0fd4a34f7d3999d4e28bd7981fe38494d2
|
[
"BSD-3-Clause"
] | 6
|
2017-05-03T10:19:55.000Z
|
2021-11-17T01:57:56.000Z
|
tests/test_write_simple.py
|
ZELLMECHANIK-DRESDEN/fcswrite
|
3b696a0fd4a34f7d3999d4e28bd7981fe38494d2
|
[
"BSD-3-Clause"
] | 2
|
2018-06-28T19:18:01.000Z
|
2018-11-05T15:20:04.000Z
|
import hashlib
import os
import tempfile
import numpy as np
import fcswrite
def test_write_fcs():
"""test that fcm can read the data files"""
fname = tempfile.mktemp(suffix=".fcs", prefix="write_test")
data = 1.0*np.arange(400).reshape((100, 4))
chn_names = ['cha', 'chb', 'ch3', 'ch4']
# monkey-patch fcswrite version to have reproducible result
oldver = fcswrite.__version__
fcswrite.fcswrite.version = "0.5.0"
fcswrite.write_fcs(filename=fname,
chn_names=chn_names,
data=data
)
# write back correct version
fcswrite.fcswrite.version = oldver
with open(fname, "rb") as fd:
data = fd.read()
data = np.frombuffer(data, dtype=np.uint8)
# remove empty lines
data = data[data != 8224]
data = data.tostring()
hasher = hashlib.md5()
hasher.update(data)
hexval = hasher.hexdigest()
assert hexval == "2b4fdb7012b0693285c31aa91c606216"
os.remove(fname)
if __name__ == "__main__":
# Run all tests
loc = locals()
for key in list(loc.keys()):
if key.startswith("test_") and hasattr(loc[key], "__call__"):
loc[key]()
| 27.906977
| 69
| 0.615833
| 149
| 1,200
| 4.798658
| 0.563758
| 0.083916
| 0.064336
| 0.083916
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.048533
| 0.261667
| 1,200
| 42
| 70
| 28.571429
| 0.758465
| 0.13
| 0
| 0
| 0
| 0
| 0.083092
| 0.030918
| 0
| 0
| 0
| 0
| 0.032258
| 1
| 0.032258
| false
| 0
| 0.16129
| 0
| 0.193548
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0165ca0a608b2f11c5571565ecd2b89540a7f4ec
| 1,810
|
py
|
Python
|
adam_visual_perception/preprocessor.py
|
isi-vista/adam-visual-perception
|
8ad6ed883b184b5407a1bf793617b226c78b3a13
|
[
"MIT"
] | 1
|
2020-07-21T10:52:26.000Z
|
2020-07-21T10:52:26.000Z
|
adam_visual_perception/preprocessor.py
|
isi-vista/adam-visual-perception
|
8ad6ed883b184b5407a1bf793617b226c78b3a13
|
[
"MIT"
] | null | null | null |
adam_visual_perception/preprocessor.py
|
isi-vista/adam-visual-perception
|
8ad6ed883b184b5407a1bf793617b226c78b3a13
|
[
"MIT"
] | 2
|
2020-07-21T15:30:42.000Z
|
2021-01-20T21:54:09.000Z
|
from moviepy.editor import VideoFileClip
from datetime import datetime
import numpy as np
import time
import os
def manage_time(timestamp):
"""
Given the string representation of a the time using the
"minutes:seconds[:miliseconds]" representation, returns the number
of seconds using double precision
"""
time_strip = timestamp.split(":")
seconds = int(time_strip[0]) * 60 + int(time_strip[1])
# Add miliseconds
if len(time_strip) == 3:
seconds += int(time_strip[2]) / 60
return seconds
def preprocess_video(filename, start, end, target_name, audio, codec=None):
"""
Preprocess an input video by cutting it given start time to end time,
optionally removing the audio and changing video encoding
"""
# Load the video file
clip = VideoFileClip(filename)
# Calculate start and end points in seconds
starting_point = manage_time(start)
end_point = manage_time(end)
# Resize the video and save the file
subclip = clip.subclip(starting_point, end_point)
subclip.write_videofile(target_name, audio=audio, codec=codec)
def concatenate_videos(base="", ext="mp4"):
stringa = 'ffmpeg -i "concat:'
elenco_video = glob.glob(base + "*." + ext)
elenco_file_temp = []
for f in elenco_video:
file = "temp" + str(elenco_video.index(f) + 1) + ".ts"
os.system(
"ffmpeg -i " + f + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + file
)
elenco_file_temp.append(file)
print(elenco_file_temp)
for f in elenco_file_temp:
stringa += f
if elenco_file_temp.index(f) != len(elenco_file_temp) - 1:
stringa += "|"
else:
stringa += '" -c copy -bsf:a aac_adtstoasc output.mp4'
print(stringa)
os.system(stringa)
| 29.672131
| 83
| 0.654696
| 242
| 1,810
| 4.756198
| 0.433884
| 0.048653
| 0.07298
| 0.033015
| 0.045178
| 0.045178
| 0.045178
| 0
| 0
| 0
| 0
| 0.011687
| 0.243646
| 1,810
| 60
| 84
| 30.166667
| 0.829072
| 0.21989
| 0
| 0
| 0
| 0
| 0.092972
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.083333
| false
| 0
| 0.138889
| 0
| 0.25
| 0.055556
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0166496ddadc3242ff31aa5f6df7726900b884d0
| 505
|
py
|
Python
|
test/demo-random.py
|
ruth-ann/snap-python
|
fe98de7b5697b3d60eb3497893e24801ae1916f9
|
[
"BSD-3-Clause"
] | 242
|
2015-01-01T08:40:28.000Z
|
2022-03-18T05:22:09.000Z
|
test/demo-random.py
|
ruth-ann/snap-python
|
fe98de7b5697b3d60eb3497893e24801ae1916f9
|
[
"BSD-3-Clause"
] | 99
|
2015-01-24T07:55:27.000Z
|
2021-10-30T18:20:13.000Z
|
test/demo-random.py
|
ruth-ann/snap-python
|
fe98de7b5697b3d60eb3497893e24801ae1916f9
|
[
"BSD-3-Clause"
] | 105
|
2015-03-03T06:45:17.000Z
|
2022-02-24T15:52:40.000Z
|
import snap
G = snap.GenFull(snap.PNEANet, 100)
# get a new random generator, provide the seed value
Rnd = snap.TRnd(42)
# randomize the generator, every execution will produce a different sequence.
# Comment out the line to get the same sequence on every execution.
Rnd.Randomize()
for i in range(0,10):
# provide the random generator as a parameter to the function
NId = G.GetRndNId(Rnd)
print(NId)
# result is not well formed, the following statement fails
#print(NI.GetId())
| 25.25
| 77
| 0.724752
| 79
| 505
| 4.632911
| 0.670886
| 0.081967
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.019753
| 0.19802
| 505
| 19
| 78
| 26.578947
| 0.883951
| 0.645545
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.142857
| 0
| 0.142857
| 0.142857
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0168c916329d1339e42f8c2b7773aa690c463962
| 3,562
|
py
|
Python
|
smdebug/core/logger.py
|
jsspric/sagemaker-debugger
|
d7010869e19ae49c4f371935f27afcb585195f79
|
[
"Apache-2.0"
] | 133
|
2019-12-03T18:56:27.000Z
|
2022-03-18T19:54:49.000Z
|
smdebug/core/logger.py
|
jsspric/sagemaker-debugger
|
d7010869e19ae49c4f371935f27afcb585195f79
|
[
"Apache-2.0"
] | 384
|
2019-12-04T03:04:14.000Z
|
2022-03-31T20:42:48.000Z
|
smdebug/core/logger.py
|
jsspric/sagemaker-debugger
|
d7010869e19ae49c4f371935f27afcb585195f79
|
[
"Apache-2.0"
] | 64
|
2019-12-05T20:39:51.000Z
|
2022-03-25T13:30:54.000Z
|
# Standard Library
import logging
import os
import socket
import sys
from collections import defaultdict
# First Party
from smdebug.core.config_constants import LOG_DUPLICATION_THRESHOLD
_logger_initialized = False
class MaxLevelFilter(logging.Filter):
"""Filters (lets through) all messages with level < LEVEL"""
def __init__(self, level):
super().__init__()
self.level = level
def filter(self, record):
# "<" instead of "<=": since logger.setLevel is inclusive, this should be exclusive
return record.levelno < self.level
class DuplicateLogFilter:
"""Filters duplicate messages to prevent spamming users"""
def __init__(self):
self.msgs = defaultdict(int)
self.repeat_threshold = LOG_DUPLICATION_THRESHOLD
def filter(self, record):
self.msgs[record.msg] += 1
return self.msgs[record.msg] <= self.repeat_threshold
def _get_log_level():
default = "info"
log_level = os.environ.get("SMDEBUG_LOG_LEVEL", default=default)
log_level = log_level.lower()
allowed_levels = ["info", "debug", "warning", "error", "critical", "off"]
if log_level not in allowed_levels:
log_level = default
level = None
if log_level is None or log_level == "off":
level = None
else:
if log_level == "critical":
level = logging.CRITICAL
elif log_level == "error":
level = logging.ERROR
elif log_level == "warning":
level = logging.WARNING
elif log_level == "info":
level = logging.INFO
elif log_level == "debug":
level = logging.DEBUG
return level
def get_logger(name="smdebug"):
global _logger_initialized
if not _logger_initialized:
worker_pid = f"{socket.gethostname()}:{os.getpid()}"
log_context = os.environ.get("SMDEBUG_LOG_CONTEXT", default=worker_pid)
level = _get_log_level()
logger = logging.getLogger(name)
logger.handlers = []
log_formatter = logging.Formatter(
fmt="[%(asctime)s.%(msecs)03d "
+ log_context
+ " %(levelname)s %(filename)s:%(lineno)d] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(log_formatter)
if os.environ.get("SMDEBUG_LOG_ALL_TO_STDOUT", default="TRUE").lower() == "false":
stderr_handler = logging.StreamHandler(sys.stderr)
min_level = logging.DEBUG
# lets through all levels less than ERROR
stdout_handler.addFilter(MaxLevelFilter(logging.ERROR))
stdout_handler.setLevel(min_level)
stderr_handler.setLevel(max(min_level, logging.ERROR))
stderr_handler.setFormatter(log_formatter)
logger.addHandler(stderr_handler)
logger.addHandler(stdout_handler)
logger.addFilter(DuplicateLogFilter())
# SMDEBUG_LOG_PATH is the full path to log file
# by default, log is only written to stdout&stderr
# if this is set, it is written to file
path = os.environ.get("SMDEBUG_LOG_PATH", default=None)
if path is not None:
fh = logging.FileHandler(path)
fh.setFormatter(log_formatter)
logger.addHandler(fh)
if level:
logger.setLevel(level)
else:
logger.disabled = True
logger.propagate = False
_logger_initialized = True
return logging.getLogger(name)
| 31.803571
| 91
| 0.635598
| 412
| 3,562
| 5.300971
| 0.313107
| 0.054945
| 0.021978
| 0.034799
| 0.076923
| 0
| 0
| 0
| 0
| 0
| 0
| 0.001145
| 0.264458
| 3,562
| 111
| 92
| 32.09009
| 0.832443
| 0.110051
| 0
| 0.075
| 0
| 0
| 0.091976
| 0.03457
| 0
| 0
| 0
| 0
| 0
| 1
| 0.075
| false
| 0
| 0.075
| 0.0125
| 0.225
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
016a2008401fbef8b48e430f13646f4e48a823a9
| 1,292
|
py
|
Python
|
datacube_classification/models.py
|
brazil-data-cube/datacube-classification
|
727c045c58c06fd87cb26d408201e34b9e471e9c
|
[
"MIT"
] | 2
|
2021-04-20T03:26:50.000Z
|
2021-04-20T21:20:27.000Z
|
datacube_classification/models.py
|
brazil-data-cube/datacube-classification
|
727c045c58c06fd87cb26d408201e34b9e471e9c
|
[
"MIT"
] | 2
|
2021-04-20T03:14:09.000Z
|
2021-04-20T03:14:53.000Z
|
datacube_classification/models.py
|
brazil-data-cube/datacube-classification
|
727c045c58c06fd87cb26d408201e34b9e471e9c
|
[
"MIT"
] | null | null | null |
#
# This file is part of datacube-classification
# Copyright (C) 2021 INPE.
#
# datacube-classification Library is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""classification models module"""
import pandas as pd
def train_sklearn_model(model, labeled_timeseries: pd.DataFrame, label_col="label"):
"""Train a sklearn model using the time series extracted with the
`datacube_classification.sits.datacube_get_sits` function
This function receives time series with associated labels and performs the model training. To do this, each
of the instances present in the input table (labeled_timeseries) must contain a column (label_col) with the
associated label information
Args:
model (object): scikit-learn classification model
labeled_timeseries (pd.DataFrame): table with time-series extracted from a data cube. Each instance must be have
a label associated
label_col (str): column where labels is in `labeled_timeseries`
Returns:
object: scikit-learn treined model
"""
x = labeled_timeseries[labeled_timeseries.columns.difference([label_col])]
y = labeled_timeseries[label_col].astype(int)
return model.fit(x, y)
| 35.888889
| 120
| 0.745356
| 178
| 1,292
| 5.314607
| 0.522472
| 0.125793
| 0.046512
| 0.05074
| 0.069767
| 0
| 0
| 0
| 0
| 0
| 0
| 0.003813
| 0.188081
| 1,292
| 35
| 121
| 36.914286
| 0.897998
| 0.732972
| 0
| 0
| 0
| 0
| 0.017921
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.2
| false
| 0
| 0.2
| 0
| 0.6
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
016d5efe3c27993b8afc080b9aed799c0438da3c
| 2,304
|
py
|
Python
|
main.py
|
RushanNotOfficial/adminweapons
|
d9738fb0302b64ef7d54b22b14e913d1ff7de79e
|
[
"Apache-2.0"
] | 1
|
2021-09-17T17:13:10.000Z
|
2021-09-17T17:13:10.000Z
|
main.py
|
RushanNotOfficial/adminweapons
|
d9738fb0302b64ef7d54b22b14e913d1ff7de79e
|
[
"Apache-2.0"
] | null | null | null |
main.py
|
RushanNotOfficial/adminweapons
|
d9738fb0302b64ef7d54b22b14e913d1ff7de79e
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2021 RushanNotOfficial#1146. 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.
# ==============================================================================
"""
Run the main bot
"""
from discord_components import DiscordComponents # library for interacting with buttons and components
from discord.ext import commands # library for make a client and registering commands
TOKEN = ""
client = commands.Bot(command_prefix="") # make the bot object
client.remove_command("help") # remove the basic help command as we have a better one
@client.event # register a new event
async def on_ready(): # event name is 'on_ready' which occuurs when the bot reconnects or starts up
DiscordComponents(client) # initialize the client with component support
print(f'Logged in as: {client.user.name}') # print username to console
@client.event # register a new event
async def on_message(ctx): # event name is 'on_message' which occurs when a new message is sent anywhere where the bot exists
await client.process_commands(ctx) # process the commands if it is a command which is registered
cogs = ("cogs.help") # cogs which we want to register. (using a tuple as it takes less space than a array)
for cog in cogs:
client.load_extension(cog) # load the cog/extension
print(f"Loaded {cog} cog") # print the cog name to console
client.run(TOKEN) # now, lets run the bot
| 53.581395
| 150
| 0.601997
| 287
| 2,304
| 4.801394
| 0.494774
| 0.043541
| 0.018868
| 0.023222
| 0.055152
| 0.055152
| 0.055152
| 0.055152
| 0.055152
| 0
| 0
| 0.007524
| 0.307726
| 2,304
| 43
| 151
| 53.581395
| 0.856426
| 0.589844
| 0
| 0.117647
| 0
| 0
| 0.067107
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.117647
| 0
| 0.117647
| 0.117647
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
016d6e7e508bdd3f4bc8579c90a03098e462920c
| 1,076
|
py
|
Python
|
src/classes/widgets/engine_gauge.py
|
bergthor13/VehicleGPS
|
643413b3cb910102689081d692223a4a03fccea4
|
[
"MIT"
] | 3
|
2019-06-21T23:39:22.000Z
|
2020-08-17T03:39:04.000Z
|
src/classes/widgets/engine_gauge.py
|
bergthor13/VehicleGPS
|
643413b3cb910102689081d692223a4a03fccea4
|
[
"MIT"
] | null | null | null |
src/classes/widgets/engine_gauge.py
|
bergthor13/VehicleGPS
|
643413b3cb910102689081d692223a4a03fccea4
|
[
"MIT"
] | 1
|
2020-02-04T16:13:06.000Z
|
2020-02-04T16:13:06.000Z
|
"""File containing a class for the main gauge."""
from tkinter import font, Label, Frame
from classes.widgets.main_gauge import MainGauge
from classes.pub_sub import Subscriber
class EngineGauge(MainGauge, Subscriber):
"""
A gauge that displays the speed, acceleration and average speed.
"""
def __init__(self, app, *args, **kwargs):
MainGauge.__init__(self, *args, **kwargs)
self.app = app
def update(self, message, value):
if message == "OBD-ENGINE_LOAD":
if value is None:
self.update_values(value="--%")
else:
self.update_values(value=str(int(value))+"%")
if message == "OBD-COOLANT_TEMP":
if value is None:
self.update_values(subvalue="--°C")
else:
self.update_values(subvalue=str(int(value))+"°C")
if message == "OBD-RPM":
if value is None:
self.update_values(subvalue2="----")
else:
self.update_values(subvalue2=int(value))
| 32.606061
| 72
| 0.572491
| 125
| 1,076
| 4.8
| 0.424
| 0.1
| 0.16
| 0.065
| 0.145
| 0.145
| 0.145
| 0
| 0
| 0
| 0
| 0.002681
| 0.306691
| 1,076
| 33
| 73
| 32.606061
| 0.798928
| 0.100372
| 0
| 0.26087
| 0
| 0
| 0.055085
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.086957
| false
| 0
| 0.130435
| 0
| 0.26087
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0170b972d86c93a3e3cdb19cde4605229cdb91d4
| 4,358
|
py
|
Python
|
packages/augur-core/tests/gov/test_gov.py
|
jeremyschlatter/augur
|
4dbfe476905c1c032231ac18b5e4e9cb817c90d4
|
[
"MIT"
] | 3
|
2021-05-10T06:44:19.000Z
|
2021-06-16T00:04:27.000Z
|
packages/augur-core/tests/gov/test_gov.py
|
Penny-Admixture/augur
|
374366d15f455a1814cc1d10b1219455a9ac71d0
|
[
"MIT"
] | null | null | null |
packages/augur-core/tests/gov/test_gov.py
|
Penny-Admixture/augur
|
374366d15f455a1814cc1d10b1219455a9ac71d0
|
[
"MIT"
] | 1
|
2021-04-02T12:47:01.000Z
|
2021-04-02T12:47:01.000Z
|
from eth_tester.exceptions import TransactionFailed
from utils import captureFilteredLogs, AssertLog, nullAddress, TokenDelta, PrintGasUsed
from pytest import raises, mark
pytestmark = mark.skip(reason="We might not even need governance and currently dont account for transfering ownership")
def test_gov(contractsFixture, universe, reputationToken, cash):
if not contractsFixture.paraAugur:
return
nexus = contractsFixture.contracts["OINexus"]
deployer = contractsFixture.accounts[0]
bob = contractsFixture.accounts[1]
alice = contractsFixture.accounts[2]
reputationToken.faucet(100, sender=bob)
reputationToken.faucet(100, sender=alice)
feePot = contractsFixture.getFeePot(universe)
cash.faucet(10000)
cash.approve(feePot.address, 10000000000000000)
reputationToken.approve(feePot.address, 10000000000000000, sender=bob)
reputationToken.approve(feePot.address, 10000000000000000, sender=alice)
rewardsToken = contractsFixture.upload('../src/contracts/Cash.sol', "rewardsToken")
lpToken = contractsFixture.upload('../src/contracts/Cash.sol', "lpToken")
# Deploy GOV token
govToken = contractsFixture.upload("../src/contracts/gov/GovToken.sol", constructorArgs=[deployer])
# Deploy Timelock
timelock = contractsFixture.upload("../src/contracts/gov/Timelock.sol", constructorArgs=[deployer])
# Deploy a FeePotStakingContract for S_REP (Fee Pot Tokens)
feePotStakingContract = contractsFixture.upload("../src/contracts/gov/FeePotStakingRewards.sol", constructorArgs=[deployer, deployer, govToken.address, feePot.address])
initialSupply = 11 * 10**6 * 10**18
govToken.setMintAllowance(feePotStakingContract.address, initialSupply)
feePotStakingContract.notifyRewardAmount(initialSupply)
# Deploy Governance
governance = contractsFixture.upload("../src/contracts/gov/Governance.sol", constructorArgs=[timelock.address, govToken.address])
# Cede control of Timelock to Governance
timelock.setAdmin(governance.address)
# Cede control of GOV Token to Governance
govToken.transferOwnership(timelock.address)
# Cede control of OINexus to Governance
nexus.transferOwnership(timelock.address)
# Cede control of FeePotStakingContract to Governance
feePotStakingContract.setRewardsDistribution(timelock.address)
feePotStakingContract.transferOwnership(timelock.address)
# Get S_REP
feePot.stake(1, sender=alice)
# Stake
feePot.approve(feePotStakingContract.address, 100, sender=alice)
feePotStakingContract.stake(1, sender=alice)
# Move time
timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp
contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60))
# Redeem
feePotStakingContract.exit(sender=alice)
totalSupply = govToken.totalSupply()
assert governance.quorumVotes() - (totalSupply / 25) == 0
assert governance.proposalThreshold() - (totalSupply / 1000) == 0
assert govToken.balanceOf(alice) == totalSupply
target = govToken.address
signature = ""
calldata = govToken.mint_encode(bob, 100)
# Delegate votes to self and propose to mint GOV and fail due to time constraint
govToken.delegate(alice, sender=alice)
with raises(TransactionFailed):
governance.propose([target], [0], [signature], [calldata], "Give Bob the Monies", sender=alice)
# Move time forward
timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp
contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 7))
# Propose to mint GOV to Bob
proposalId = governance.propose([target], [0], [signature], [calldata], "Give Bob the Monies", sender=alice)
# Vote it into effect
contractsFixture.eth_tester.backend.chain.mine_block()
governance.castVote(proposalId, True, sender=alice)
# Queue the proposal
timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp
contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 3))
governance.queue(proposalId)
# Execute the proposal
timestamp = contractsFixture.eth_tester.backend.chain.header.timestamp
contractsFixture.eth_tester.time_travel(int(timestamp + 24 * 60 * 60 * 2))
governance.execute(proposalId)
assert govToken.balanceOf(bob) == 100
| 39.981651
| 172
| 0.750344
| 463
| 4,358
| 7.021598
| 0.311015
| 0.027684
| 0.069209
| 0.083667
| 0.334359
| 0.277453
| 0.188865
| 0.188865
| 0.188865
| 0.188865
| 0
| 0.033
| 0.151675
| 4,358
| 108
| 173
| 40.351852
| 0.846362
| 0.113355
| 0
| 0.066667
| 0
| 0
| 0.089987
| 0.050975
| 0
| 0
| 0
| 0
| 0.083333
| 1
| 0.016667
| false
| 0
| 0.05
| 0
| 0.083333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01718641d209b93e71922a83a09841a7c405d585
| 3,153
|
py
|
Python
|
setup.py
|
insolor/pymorphy2
|
92d546f042ff14601376d3646242908d5ab786c1
|
[
"MIT"
] | 859
|
2015-01-05T00:48:23.000Z
|
2022-03-19T07:42:23.000Z
|
setup.py
|
insolor/pymorphy2
|
92d546f042ff14601376d3646242908d5ab786c1
|
[
"MIT"
] | 106
|
2015-01-03T12:21:56.000Z
|
2022-03-30T11:07:46.000Z
|
setup.py
|
insolor/pymorphy2
|
92d546f042ff14601376d3646242908d5ab786c1
|
[
"MIT"
] | 118
|
2015-01-05T21:10:35.000Z
|
2022-03-15T14:29:29.000Z
|
#!/usr/bin/env python
import sys
import platform
from setuptools import setup
# from Cython.Build import cythonize
def get_version():
with open("pymorphy2/version.py", "rt") as f:
return f.readline().split("=")[1].strip(' "\n')
# TODO: use environment markres instead of Python code in order to
# allow building proper wheels. Markers are not enabled right now because
# of setuptools/wheel incompatibilities and the 'pip >= 6.0' requirement.
# extras_require = {
# 'fast:platform_python_implementation==CPython': ["DAWG>=0.7.7"],
# 'fast:platform_python_implementation==CPython and python_version<3.5': [
# "fastcache>=1.0.2"
# ],
# ':python_version<"3.0"': [
# "backports.functools_lru_cache>=1.0.1",
# ],
# }
is_cpython = platform.python_implementation() == 'CPython'
py_version = sys.version_info[:2]
install_requires = [
'dawg-python >= 0.7.1',
'pymorphy2-dicts-ru >=2.4, <3.0',
'docopt >= 0.6',
]
if py_version < (3, 0):
install_requires.append("backports.functools_lru_cache >= 1.0.1")
extras_require = {'fast': []}
if is_cpython:
extras_require['fast'].append("DAWG >= 0.8")
if py_version < (3, 5):
# lru_cache is optimized in Python 3.5
extras_require['fast'].append("fastcache >= 1.0.2")
setup(
name='pymorphy2',
version=get_version(),
author='Mikhail Korobov',
author_email='kmike84@gmail.com',
url='https://github.com/kmike/pymorphy2/',
description='Morphological analyzer (POS tagger + inflection engine) for Russian language.',
long_description=open('README.rst').read(),
license='MIT license',
packages=[
'pymorphy2',
'pymorphy2.units',
'pymorphy2.lang',
'pymorphy2.lang.ru',
'pymorphy2.lang.uk',
'pymorphy2.opencorpora_dict',
],
entry_points={
'console_scripts': ['pymorphy = pymorphy2.cli:main']
},
install_requires=install_requires,
extras_require=extras_require,
zip_safe=False,
# ext_modules=cythonize([
# 'pymorphy2/*.py',
# 'pymorphy2/units/*.py',
# 'pymorphy2/opencorpora_dict/*.py',
# ], annotate=True, profile=True),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: Russian',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Text Processing :: Linguistic',
],
)
| 31.217822
| 96
| 0.625119
| 351
| 3,153
| 5.507123
| 0.450142
| 0.098293
| 0.129333
| 0.067253
| 0.098293
| 0.030005
| 0.030005
| 0
| 0
| 0
| 0
| 0.02814
| 0.222328
| 3,153
| 100
| 97
| 31.53
| 0.760196
| 0.232794
| 0
| 0.03125
| 0
| 0
| 0.503543
| 0.032097
| 0
| 0
| 0
| 0.01
| 0
| 1
| 0.015625
| false
| 0
| 0.046875
| 0
| 0.078125
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01737ac1253524fca8701279c0c0189f76386d90
| 8,031
|
py
|
Python
|
habitat/tasks/rearrange/utils.py
|
elombardi2/habitat-lab
|
02326fffe1c781fda69b23d7d89ac6d11bd37ca2
|
[
"MIT"
] | null | null | null |
habitat/tasks/rearrange/utils.py
|
elombardi2/habitat-lab
|
02326fffe1c781fda69b23d7d89ac6d11bd37ca2
|
[
"MIT"
] | null | null | null |
habitat/tasks/rearrange/utils.py
|
elombardi2/habitat-lab
|
02326fffe1c781fda69b23d7d89ac6d11bd37ca2
|
[
"MIT"
] | 1
|
2021-09-09T08:15:24.000Z
|
2021-09-09T08:15:24.000Z
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import hashlib
import os
import os.path as osp
import pickle
import time
import attr
import gym
import magnum as mn
import numpy as np
import quaternion
import habitat_sim
from habitat_sim.nav import NavMeshSettings
from habitat_sim.physics import MotionType
def make_render_only(obj_idx, sim):
if hasattr(MotionType, "RENDER_ONLY"):
sim.set_object_motion_type(MotionType.RENDER_ONLY, obj_idx)
else:
sim.set_object_motion_type(MotionType.KINEMATIC, obj_idx)
sim.set_object_is_collidable(False, obj_idx)
def get_collision_matches(link, colls, search_key="link"):
matches = []
for coll0, coll1 in colls:
if link in [coll0[search_key], coll1[search_key]]:
matches.append((coll0, coll1))
return matches
def get_other_matches(link, colls):
matches = get_collision_matches(link, colls)
other_surfaces = [b if a["link"] == link else a for a, b in matches]
return other_surfaces
def coll_name(coll, name):
return coll_prop(coll, name, "name")
def coll_prop(coll, val, prop):
return val in [coll[0][prop], coll[1][prop]]
def coll_link(coll, link):
return coll_prop(coll, link, "link")
def swap_axes(x):
x[1], x[2] = x[2], x[1]
return x
@attr.s(auto_attribs=True, kw_only=True)
class CollDetails:
obj_scene_colls: int = 0
robo_obj_colls: int = 0
robo_scene_colls: int = 0
def rearrange_collision(
colls,
snapped_obj_id,
count_obj_colls,
verbose=False,
ignore_names=None,
ignore_base=True,
):
"""
Defines what counts as a collision for the Rearrange environment execution
"""
# Filter out any collisions from the base
if ignore_base:
colls = [
x
for x in colls
if not ("base" in x[0]["link"] or "base" in x[1]["link"])
]
def should_keep(x):
if ignore_names is None:
return True
return any(coll_name(x, ignore_name) for ignore_name in ignore_names)
# Filter out any collisions with the ignore objects
colls = list(filter(should_keep, colls))
# Check for robot collision
robo_obj_colls = 0
robo_scene_colls = 0
robo_scene_matches = get_collision_matches("fetch", colls, "name")
for match in robo_scene_matches:
urdf_on_urdf = (
match[0]["type"] == "URDF" and match[1]["type"] == "URDF"
)
with_stage = coll_prop(match, "Stage", "type")
fetch_on_fetch = (
match[0]["name"] == "fetch" and match[1]["name"] == "fetch"
)
if fetch_on_fetch:
continue
if urdf_on_urdf or with_stage:
robo_scene_colls += 1
else:
robo_obj_colls += 1
# Checking for holding object collision
obj_scene_colls = 0
if count_obj_colls and snapped_obj_id is not None:
matches = get_collision_matches(
"id %i" % snapped_obj_id, colls, "link"
)
for match in matches:
if coll_name(match, "fetch"):
continue
obj_scene_colls += 1
total_colls = robo_obj_colls + robo_scene_colls + obj_scene_colls
return total_colls > 0, CollDetails(
obj_scene_colls=min(obj_scene_colls, 1),
robo_obj_colls=min(robo_obj_colls, 1),
robo_scene_colls=min(robo_scene_colls, 1),
)
def get_nav_mesh_settings(agent_config):
return get_nav_mesh_settings_from_height(agent_config.HEIGHT)
def get_nav_mesh_settings_from_height(height):
navmesh_settings = NavMeshSettings()
navmesh_settings.set_defaults()
navmesh_settings.agent_radius = 0.4
navmesh_settings.agent_height = height
navmesh_settings.agent_max_climb = 0.05
return navmesh_settings
def convert_legacy_cfg(obj_list):
if len(obj_list) == 0:
return obj_list
def convert_fn(obj_dat):
fname = "/".join(obj_dat[0].split("/")[-2:])
if ".urdf" in fname:
obj_dat[0] = osp.join("data/replica_cad/urdf", fname)
else:
obj_dat[0] = obj_dat[0].replace(
"data/objects/", "data/objects/ycb/"
)
if (
len(obj_dat) == 2
and len(obj_dat[1]) == 4
and np.array(obj_dat[1]).shape == (4, 4)
):
# Specifies the full transformation, no object type
return (obj_dat[0], (obj_dat[1], int(MotionType.DYNAMIC)))
elif len(obj_dat) == 2 and len(obj_dat[1]) == 3:
# Specifies XYZ, no object type
trans = mn.Matrix4.translation(mn.Vector3(obj_dat[1]))
return (obj_dat[0], (trans, int(MotionType.DYNAMIC)))
else:
# Specifies the full transformation and the object type
return (obj_dat[0], obj_dat[1])
return list(map(convert_fn, obj_list))
def get_aabb(obj_id, sim, transformed=False):
obj_node = sim.get_object_scene_node(obj_id)
obj_bb = obj_node.cumulative_bb
if transformed:
obj_bb = habitat_sim.geo.get_transformed_bb(
obj_node.cumulative_bb, obj_node.transformation
)
return obj_bb
def euler_to_quat(rpy):
rot = quaternion.from_euler_angles(rpy)
rot = mn.Quaternion(mn.Vector3(rot.vec), rot.w)
return rot
def allowed_region_to_bb(allowed_region):
if len(allowed_region) == 0:
return allowed_region
return mn.Range2D(allowed_region[0], allowed_region[1])
def recover_nav_island_point(v, ref_v, sim):
"""
Snaps a point to the LARGEST island.
"""
nav_vs = sim.pathfinder.build_navmesh_vertices()
ref_r = sim.pathfinder.island_radius(ref_v)
nav_vs_r = {
i: sim.pathfinder.island_radius(nav_v)
for i, nav_v in enumerate(nav_vs)
}
# Get the points closest to "v"
v_dist = np.linalg.norm(v - nav_vs, axis=-1)
ordered_idxs = np.argsort(v_dist)
# Go through the closest points until one has the same island radius.
for i in ordered_idxs:
if nav_vs_r[i] == ref_r:
return nav_vs[i]
print("Could not find point off of island")
return v
CACHE_PATH = "./data/cache"
class CacheHelper:
def __init__(
self, cache_name, lookup_val, def_val=None, verbose=False, rel_dir=""
):
self.use_cache_path = osp.join(CACHE_PATH, rel_dir)
if not osp.exists(self.use_cache_path):
os.makedirs(self.use_cache_path)
sec_hash = hashlib.md5(str(lookup_val).encode("utf-8")).hexdigest()
cache_id = f"{cache_name}_{sec_hash}.pickle"
self.cache_id = osp.join(self.use_cache_path, cache_id)
self.def_val = def_val
self.verbose = verbose
def exists(self):
return osp.exists(self.cache_id)
def load(self, load_depth=0):
if not self.exists():
return self.def_val
try:
with open(self.cache_id, "rb") as f:
if self.verbose:
print("Loading cache @", self.cache_id)
return pickle.load(f)
except EOFError as e:
if load_depth == 32:
raise e
# try again soon
print(
"Cache size is ",
osp.getsize(self.cache_id),
"for ",
self.cache_id,
)
time.sleep(1.0 + np.random.uniform(0.0, 1.0))
return self.load(load_depth + 1)
def save(self, val):
with open(self.cache_id, "wb") as f:
if self.verbose:
print("Saving cache @", self.cache_id)
pickle.dump(val, f)
def reshape_obs_space(obs_space, new_shape):
assert isinstance(obs_space, gym.spaces.Box)
return gym.spaces.Box(
shape=new_shape,
high=obs_space.low.reshape(-1)[0],
low=obs_space.high.reshape(-1)[0],
dtype=obs_space.dtype,
)
| 28.784946
| 78
| 0.625949
| 1,142
| 8,031
| 4.162872
| 0.24606
| 0.020194
| 0.018511
| 0.013462
| 0.092764
| 0.056374
| 0.022297
| 0.022297
| 0.022297
| 0
| 0
| 0.014022
| 0.271822
| 8,031
| 278
| 79
| 28.888489
| 0.798906
| 0.087536
| 0
| 0.054187
| 0
| 0
| 0.041049
| 0.007002
| 0
| 0
| 0
| 0
| 0.004926
| 1
| 0.108374
| false
| 0
| 0.064039
| 0.024631
| 0.330049
| 0.019704
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
0174f6ef49b2600601fc8286f239c0c51ed868ee
| 1,867
|
py
|
Python
|
0382_LinkedListRandomNode/python/solution.py
|
jeffvswanson/LeetCode
|
6bc7d6cad3c2b1bd6ccb2616ec081fb5eb51ccc8
|
[
"MIT"
] | null | null | null |
0382_LinkedListRandomNode/python/solution.py
|
jeffvswanson/LeetCode
|
6bc7d6cad3c2b1bd6ccb2616ec081fb5eb51ccc8
|
[
"MIT"
] | null | null | null |
0382_LinkedListRandomNode/python/solution.py
|
jeffvswanson/LeetCode
|
6bc7d6cad3c2b1bd6ccb2616ec081fb5eb51ccc8
|
[
"MIT"
] | null | null | null |
"""
382. Linked List Random Node
Given a singly linked list, return a random node's value from the linked list. Each node
must have the same probability of being chosen.
Implement the Solution class:
Solution(ListNode head) Initializes the object with the integer array nums.
int getRandom() Chooses a node randomly from the list and returns its value. All the
nodes of the list should be equally likely to be choosen.
Examples
--------
Example 1:
Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]
Explanation
solution = Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have
equal probability of returning.
Constraints
-----------
* The number of nodes in the linked list will be in the range [1, 104].
* -104 <= Node.val <= 104
* At most 104 calls will be made to getRandom.
"""
import random
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""
Your Solution object will be instantiated and called as such:
obj = Solution(head)
param_1 = obj.getRandom()
"""
def __init__(self, head: Optional[ListNode]):
node_vals = []
node = head
while node:
node_vals.append(node.val)
node = node.next
self.list_len = len(node_vals)
self.node_vals = node_vals
def getRandom(self) -> int:
return self.node_vals[random.randint(0, self.list_len - 1)]
| 28.723077
| 88
| 0.644885
| 254
| 1,867
| 4.673228
| 0.374016
| 0.085931
| 0.096883
| 0.060657
| 0.059815
| 0.059815
| 0.059815
| 0
| 0
| 0
| 0
| 0.028169
| 0.239422
| 1,867
| 64
| 89
| 29.171875
| 0.807746
| 0.698982
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.176471
| false
| 0
| 0.117647
| 0.058824
| 0.470588
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01756befa2192d53cb57f12407d058724b5d5f3a
| 3,833
|
py
|
Python
|
tests/app/models/test_broadcast_message.py
|
alphagov/notify-admin-frontend
|
70f2a6a97aefe2432d7a3b54dc1555c030dd3693
|
[
"MIT"
] | 33
|
2016-01-11T20:16:17.000Z
|
2021-11-23T12:50:29.000Z
|
tests/app/models/test_broadcast_message.py
|
alphagov/notify-admin-frontend
|
70f2a6a97aefe2432d7a3b54dc1555c030dd3693
|
[
"MIT"
] | 1,249
|
2015-11-30T16:43:21.000Z
|
2022-03-24T13:04:55.000Z
|
tests/app/models/test_broadcast_message.py
|
alphagov/notify-admin-frontend
|
70f2a6a97aefe2432d7a3b54dc1555c030dd3693
|
[
"MIT"
] | 36
|
2015-12-02T09:49:26.000Z
|
2021-04-10T18:05:41.000Z
|
import pytest
from app.broadcast_areas.models import CustomBroadcastAreas
from app.models.broadcast_message import BroadcastMessage
from tests import broadcast_message_json
@pytest.mark.parametrize('areas, expected_area_ids', [
({'simple_polygons': []}, []),
({'ids': ['123'], 'simple_polygons': []}, ['123'])
])
def test_area_ids(
areas,
expected_area_ids,
):
broadcast_message = BroadcastMessage(broadcast_message_json(
areas=areas
))
assert broadcast_message.area_ids == expected_area_ids
def test_simple_polygons():
broadcast_message = BroadcastMessage(broadcast_message_json(
area_ids=[
# Hackney Central
'wd20-E05009372',
# Hackney Wick
'wd20-E05009374',
],
))
assert [
[
len(polygon)
for polygon in broadcast_message.polygons.as_coordinate_pairs_lat_long
],
[
len(polygon)
for polygon in broadcast_message.simple_polygons.as_coordinate_pairs_lat_long
],
] == [
# One polygon for each area
[27, 31],
# Because the areas are close to each other, the simplification
# and unioning process results in a single polygon with fewer
# total coordinates
[57],
]
def test_content_comes_from_attribute_not_template():
broadcast_message = BroadcastMessage(broadcast_message_json())
assert broadcast_message.content == 'This is a test'
@pytest.mark.parametrize(('areas', 'expected_length'), [
({'ids': []}, 0),
({'ids': ['wd20-E05009372']}, 1),
({'no data': 'just created'}, 0),
({'names': ['somewhere'], 'simple_polygons': [[[3.5, 1.5]]]}, 1)
])
def test_areas(
areas,
expected_length
):
broadcast_message = BroadcastMessage(broadcast_message_json(
areas=areas
))
assert len(list(broadcast_message.areas)) == expected_length
def test_areas_treats_missing_ids_as_custom_broadcast(notify_admin):
broadcast_message = BroadcastMessage(broadcast_message_json(
areas={
'ids': [
'wd20-E05009372',
'something else',
],
# although the IDs may no longer be usable, we can
# expect the broadcast to have names and polygons,
# which is enough to show the user something
'names': [
'wd20 name',
'something else name'
],
'simple_polygons': [[[1, 2]]]
}
))
assert len(list(broadcast_message.areas)) == 2
assert type(broadcast_message.areas) == CustomBroadcastAreas
@pytest.mark.parametrize('area_ids, approx_bounds', (
([
'ctry19-N92000002', # Northern Ireland (UTM zone 29N)
'ctry19-W92000004', # Wales (UTM zone 30N)
], [
-8.2, 51.5, -2.1, 55.1
]),
([
'lad20-E06000031', # Peterborough (UTM zone 30N)
'lad20-E07000146', # Kings Lyn and West Norfolk (UTM zone 31N)
], [
-0.5, 52.5, 0.8, 53.0
]),
([
'wd20-E05009372', # Hackney Central (UTM zone 30N)
'wd20-E05009374', # Hackney Wick (UTM zone 30N)
], [
-0.1, 51.5, -0.0, 51.6
]),
([
'wd20-E05009372', # Hackney Central (UTM zone 30N)
'test-santa-claus-village-rovaniemi-a', # (UTM zone 35N)
], [
-0.1, 51.5, 25.9, 66.6
]),
))
def test_combining_multiple_areas_keeps_same_bounds(area_ids, approx_bounds):
broadcast_message = BroadcastMessage(broadcast_message_json(
areas={'ids': area_ids}
))
assert [
round(coordinate, 1) for coordinate in broadcast_message.polygons.bounds
] == [
round(coordinate, 1) for coordinate in broadcast_message.simple_polygons.bounds
] == (
approx_bounds
)
| 28.604478
| 89
| 0.604226
| 424
| 3,833
| 5.257075
| 0.334906
| 0.165096
| 0.062808
| 0.110363
| 0.366981
| 0.327501
| 0.224316
| 0.157021
| 0.061014
| 0
| 0
| 0.069935
| 0.276285
| 3,833
| 133
| 90
| 28.819549
| 0.733598
| 0.146882
| 0
| 0.45283
| 0
| 0
| 0.134686
| 0.01107
| 0
| 0
| 0
| 0
| 0.066038
| 1
| 0.056604
| false
| 0
| 0.037736
| 0
| 0.09434
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
017a9e7cf566c8e735c6560428aeffefe5652de2
| 9,460
|
py
|
Python
|
nilmtk_contrib/disaggregate/dsc.py
|
PiaDiepman/NILMTK-contrib
|
cd0b4337c9d87d71b3e88ad6581e5377ed8d82aa
|
[
"Apache-2.0"
] | 75
|
2019-07-05T06:43:10.000Z
|
2022-03-30T09:18:51.000Z
|
nilmtk_contrib/disaggregate/dsc.py
|
PiaDiepman/NILMTK-contrib
|
cd0b4337c9d87d71b3e88ad6581e5377ed8d82aa
|
[
"Apache-2.0"
] | 52
|
2019-06-10T14:36:40.000Z
|
2022-03-25T16:28:05.000Z
|
nilmtk_contrib/disaggregate/dsc.py
|
PiaDiepman/NILMTK-contrib
|
cd0b4337c9d87d71b3e88ad6581e5377ed8d82aa
|
[
"Apache-2.0"
] | 50
|
2019-06-14T05:31:28.000Z
|
2022-03-23T17:38:39.000Z
|
from __future__ import print_function, division
from warnings import warn
from nilmtk.disaggregate import Disaggregator
import pandas as pd
import numpy as np
from collections import OrderedDict
import matplotlib.pyplot as plt
from sklearn.decomposition import MiniBatchDictionaryLearning, SparseCoder
from sklearn.metrics import mean_squared_error
import time
import warnings
warnings.filterwarnings("ignore")
class DSC(Disaggregator):
def __init__(self, params):
self.MODEL_NAME = 'DSC' # Add the name for the algorithm
self.chunk_wise_training = False
self.dictionaries = OrderedDict()
self.power = OrderedDict()
self.shape = 60*2
self.learning_rate = 1e-9
self.iterations = 3000
self.sparsity_coef = 20
self.n_components = 10
self.shape = params.get('shape',self.shape)
self.learning_rate = params.get('learning_rate',self.learning_rate)
self.iterations = params.get('iterations',self.iterations)
self.n_epochs = self.iterations
self.n_components = params.get('n_components',self.n_components)
def learn_dictionary(self, appliance_main, app_name):
if appliance_main.size%self.shape!=0:
extra_values = self.shape - (appliance_main.size)%(self.shape)
appliance_main = list(appliance_main.values.flatten()) + [0]*extra_values
appliance_main = np.array(appliance_main).reshape((-1,self.shape)).T
self.power[app_name] = appliance_main
if app_name not in self.dictionaries:
print ("Training First dictionary for ",app_name)
model = MiniBatchDictionaryLearning(n_components=self.n_components,positive_code=True,positive_dict=True,transform_algorithm='lasso_lars',alpha=self.sparsity_coef)
else:
print ("Re-training dictionary for ",app_name)
model = self.dictionaries[app_name]
model.fit(appliance_main.T)
reconstruction = np.matmul(model.components_.T,model.transform(appliance_main.T).T)
print ("RMSE reconstruction for appliance %s is %s"%(app_name,mean_squared_error(reconstruction,appliance_main)**(.5)))
self.dictionaries[app_name] = model
def discriminative_training(self,concatenated_activations,concatenated_bases, verbose = 100):
# Making copies of concatenated bases and activation.
optimal_a = np.copy(concatenated_activations)
predicted_b = np.copy(concatenated_bases)
'''
Next step is to modify bases such that, we get optimal A upon sparse coding
We want to get a_opt on finding activations from b_hat
'''
alpha = self.learning_rate
least_error = 1e10
total_power = self.total_power
v_size = .20
v_index = int(total_power.shape[1] * v_size)
train_power = total_power[:,:-v_index]
v_power = total_power[:,-v_index:]
train_optimal_a = optimal_a[:,:-v_index]
v_optimal_a = optimal_a[:,-v_index:]
print ("If Iteration wise errors are not decreasing, then please decrease the learning rate")
for i in range(self.iterations):
a = time.time()
# Finding activations for the given bases
model = SparseCoder(dictionary=predicted_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef)
train_predicted_a = model.transform(train_power.T).T
model = SparseCoder(dictionary=predicted_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef)
val_predicted_a = model.transform(v_power.T).T
err = np.mean(np.abs(val_predicted_a - v_optimal_a))
if err<least_error:
#print ("Chose the best")
least_error = err
best_b = np.copy(predicted_b)
# Modify the bases b_hat so that they result activations closer to a_opt
T1 = (train_power - predicted_b@train_predicted_a)@train_predicted_a.T
T2 = (train_power - predicted_b@train_optimal_a)@train_optimal_a.T
predicted_b = predicted_b - alpha *( T1 - T2)
predicted_b = np.where(predicted_b>0,predicted_b,0)
# Making sure that columns sum to 1
predicted_b = (predicted_b.T/np.linalg.norm(predicted_b.T,axis=1).reshape((-1,1))).T
#if i%verbose==0:
print ("Iteration ",i," Error ",err)
return best_b
def print_appliance_wise_errors(self, activations, bases):
start_comp = 0
for cnt, i in enumerate(self.power):
X = self.power[i]
n_comps = self.dictionaries[i].n_components
pred = np.matmul(bases[:,start_comp:start_comp+n_comps],activations[start_comp:start_comp+n_comps,:])
start_comp+=n_comps
#plt.plot(pred.T[home_id],label=i)
print ("Error for ",i," is ",mean_squared_error(pred, X)**(.5))
def partial_fit(self, train_main, train_appliances, **load_kwargs):
print("...............DSC partial_fit running...............")
#print (train_main[0])
train_main = pd.concat(train_main,axis=1) #np.array([i.values.reshape((self.sequence_length,1)) for i in train_main])
if train_main.size%self.shape!=0:
extra_values = self.shape - (train_main.size)%(self.shape)
train_main = list(train_main.values.flatten()) + [0]*extra_values
train_main = np.array(train_main).reshape((-1,self.shape)).T
self.total_power = train_main
new_train_appliances = []
for app_name, app_df in train_appliances:
app_df = pd.concat(app_df)
new_train_appliances.append((app_name, app_df))
train_appliances = new_train_appliances
if len(train_main)>10:
for appliance_name, power in train_appliances:
self.learn_dictionary(power, appliance_name)
concatenated_bases = []
concatenated_activations = []
for i in self.dictionaries:
model = self.dictionaries[i]
concatenated_bases.append(model.components_.T)
concatenated_activations.append(model.transform(self.power[i].T).T)
concatenated_bases = np.concatenate(concatenated_bases,axis=1)
concatenated_activations = np.concatenate(concatenated_activations,axis=0)
print ("--"*15)
print ("Optimal Errors")
self.print_appliance_wise_errors(concatenated_activations, concatenated_bases)
print ("--"*15)
model = SparseCoder(dictionary=concatenated_bases.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef)
predicted_activations = model.transform(train_main.T).T
print ('\n\n')
print ("--"*15)
print ("Error in prediction before discriminative sparse coding")
self.print_appliance_wise_errors(predicted_activations, concatenated_bases)
print ("--"*15)
print ('\n\n')
optimal_b = self.discriminative_training(concatenated_activations,concatenated_bases)
model = SparseCoder(dictionary=optimal_b.T,positive_code=True,transform_algorithm='lasso_lars',transform_alpha=self.sparsity_coef)
self.disggregation_model = model
predicted_activations = model.transform(train_main.T).T
print ("--"*15)
print ("Model Errors after Discriminative Training")
self.print_appliance_wise_errors(predicted_activations, concatenated_bases)
print ("--"*15)
self.disaggregation_bases = optimal_b
self.reconstruction_bases = concatenated_bases
else:
print ("This chunk has small number of samples, so skipping the training")
def disaggregate_chunk(self, test_main_list):
test_predictions = []
for test_main in test_main_list:
if test_main.size%self.shape!=0:
extra_values = self.shape - (test_main.size)%(self.shape)
test_main = list(test_main.values.flatten()) + [0]*extra_values
test_main = np.array(test_main).reshape((-1,self.shape)).T
predicted_activations = self.disggregation_model.transform(test_main.T).T
#predicted_usage = self.reconstruction_bases@predicted_activations
disggregation_dict = {}
start_comp = 0
for cnt, app_name in enumerate(self.power):
n_comps = self.dictionaries[app_name].n_components
predicted_usage = np.matmul(self.reconstruction_bases[:,start_comp:start_comp+n_comps],predicted_activations[start_comp:start_comp+n_comps,:])
start_comp+=n_comps
predicted_usage = predicted_usage.T.flatten()
flat_mains = test_main.T.flatten()
predicted_usage = np.where(predicted_usage>flat_mains,flat_mains,predicted_usage)
disggregation_dict[app_name] = pd.Series(predicted_usage)
results = pd.DataFrame(disggregation_dict, dtype='float32')
test_predictions.append(results)
return test_predictions
| 46.146341
| 175
| 0.647992
| 1,142
| 9,460
| 5.110333
| 0.189142
| 0.023132
| 0.01645
| 0.017478
| 0.269191
| 0.186772
| 0.160555
| 0.141707
| 0.141707
| 0.105038
| 0
| 0.009517
| 0.255814
| 9,460
| 204
| 176
| 46.372549
| 0.81946
| 0.048732
| 0
| 0.13245
| 0
| 0
| 0.064257
| 0.002493
| 0
| 0
| 0
| 0
| 0
| 1
| 0.039735
| false
| 0
| 0.072848
| 0
| 0.13245
| 0.15894
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
017df8740dfde25e6ca97dee8d4e923144b40c7c
| 7,033
|
py
|
Python
|
deprecated/demo/tutorial_5/qr_code.py
|
mfkiwl/GAAS
|
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
|
[
"BSD-3-Clause"
] | 2,111
|
2019-01-29T07:01:32.000Z
|
2022-03-29T06:48:14.000Z
|
demo/tutorial_5/qr_code.py
|
Wayne-xixi/GAAS
|
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
|
[
"BSD-3-Clause"
] | 131
|
2019-02-18T10:56:18.000Z
|
2021-09-27T12:07:00.000Z
|
demo/tutorial_5/qr_code.py
|
Wayne-xixi/GAAS
|
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
|
[
"BSD-3-Clause"
] | 421
|
2019-02-12T07:59:18.000Z
|
2022-03-27T05:22:01.000Z
|
from __future__ import print_function
import pyzbar.pyzbar as pyzbar
import numpy as np
import cv2
class QRdetect:
def __init__(self, QRcode_image, k=np.array([[376.0, 0, 376], [0, 376.0, 240.0], [0, 0, 1]])):
if QRcode_image is None:
return
self.query_image = QRcode_image
self.K = k
# points order is:
# A-------D
# | |
# | |
# B-------C
self.query_image_position = self.QRcode_Position(self.query_image)
print("query QRcode position: ", self.query_image_position)
query_image = self.drawPoints(self.query_image.copy(), self.query_image_position)
cv2.imwrite("query_detected.png", query_image)
self.train_qrcode_position = None
self.found_QRcode = False
def decode(self, image):
decodedObjects = pyzbar.decode(image)
if not decodedObjects:
return None
# There could be multiple qr codes in the same image
# each detected qr code has a type and corresponding polygon
for obj in decodedObjects:
print('Type : ', obj.type)
print('Polygon : ', obj.polygon)
if obj.type is not "QRCODE":
return None
return decodedObjects
# Display barcode and QR code location
def display(self, image):
decodedObjects = self.decode(image)
# Loop over all decoded objects
for decodedObject in decodedObjects:
points = decodedObject.polygon
# If the points do not form a quad, find convex hull
if len(points) > 4:
hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
hull = list(map(tuple, np.squeeze(hull)))
else:
hull = points
# Number of points in the convex hull
n = len(hull)
# Draw the convext hull
for j in range(0, n):
cv2.line(image, hull[j], hull[(j + 1) % n], (255, 0, 0), 3)
# Display results
# image = cv2.resize(image, (np.shape(image)[1] / 3, np.shape(image)[0] / 3), interpolation=cv2.INTER_CUBIC)
# cv2.imshow("Results", image)
# cv2.waitKey(5000)
def QRcode_Position(self, image):
qrcode_results = self.decode(image)
if not qrcode_results:
return None
if len(qrcode_results) > 0:
# assume there is only one qr code in the FOV
qrcode_result = qrcode_results[0]
polygon = qrcode_result.polygon
print("polygon: ", polygon)
qrcode_position = np.array([[polygon[0][0], polygon[0][1]],
[polygon[1][0], polygon[1][1]],
[polygon[2][0], polygon[2][1]],
[polygon[3][0], polygon[3][1]]], dtype="float32")
print(qrcode_position)
return qrcode_position
else:
return None
def drawPoints(self, image, target_qrcode_position):
if target_qrcode_position is None:
return
for p in target_qrcode_position:
image = cv2.circle(image, (p[0], p[1]), 10, (0, 255, 0))
image = cv2.putText(image,
str(p[0]) + ", " + str(p[1]),
(p[0], p[1]),
cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 0, 255), 1, cv2.LINE_AA)
return image
def getPerspectiveTransformaAndWarpedImage(self, train_qrcode_image):
train_qrcode_position = self.QRcode_Position(train_qrcode_image)
# print("Incoming train image qr code position: ", train_qrcode_position)
if train_qrcode_position is None:
return None, None
train_image = self.drawPoints(train_qrcode_image.copy(), train_qrcode_position)
# print("train_qrcode_position: \n", train_qrcode_position)
if train_image is not None:
cv2.imwrite("train_detected.png", train_image)
# train_qrcode_position: current incoming image
# query_image_position: pre-set target qrcode image
#H = cv2.getPerspectiveTransform(train_qrcode_position, self.query_image_position)
H = cv2.getPerspectiveTransform(train_qrcode_position, self.query_image_position)
self.train_qrcode_position = train_qrcode_position
(h, w, c) = train_qrcode_image.shape
warped_image = cv2.warpPerspective(train_qrcode_image, H, (w, h))
cv2.imwrite("warped_image.png", warped_image)
return H, warped_image
# from train image to query image
def recoverRTfromHomographyMat(self, H):
_, Rotations, translations, normals = cv2.decomposeHomographyMat(H, self.K)
return Rotations, translations, normals
# def process_image(self, image):
#
# H, warped_image = self.getPerspectiveTransformaAndWarpedImage(image)
#
# if H is None:
# self.found_QRcode = False
# return None, None, None
#
# Rs, ts, ns = self.recoverRTfromHomographyMat(H)
# self.found_QRcode = True
#
# train_image_camera_points = self.pixel2cameraWithoutScale(self.train_qrcode_position)
#
# # return Rs, ts, ns
# new_Rs = []
# new_ts = []
# new_normals = []
# idxs = []
# for index, normal in enumerate(ns):
# for pt in train_image_camera_points:
# result = np.dot(normal.T, np.array(pt))
# if result < 0:
# continue
# else:
# idxs.append(index)
#
# idxs = set(idxs)
# for idx in idxs:
# new_Rs.append(Rs[idx])
# new_ts.append(ts[idx])
# new_normals.append(ns[idx])
#
# return new_Rs, new_ts, new_normals
def process_image(self, image):
H, warped_image = self.getPerspectiveTransformaAndWarpedImage(image)
if H is None:
self.found_QRcode = False
return None, None, None
Rs, ts, ns = self.recoverRTfromHomographyMat(H)
self.found_QRcode = True
return Rs, ts, ns
def pixel2cameraWithoutScale(self, pixel_points):
camera_points = []
camera_point = [0, 0, 0]
for pixel in pixel_points:
# assume depth is 1
depth = 1
camera_point[0] = (pixel[0] - 376.0) / 376.0
camera_point[1] = (pixel[1] - 376.0) / 240.0
camera_point[2] = depth
camera_points.append(camera_point)
return camera_points
if __name__ == '__main__':
train_image = cv2.imread('target.png')
query_image = cv2.imread('target.png')
cv2.imwrite("train_image.png", train_image)
qr = QRdetect(query_image)
R, t = qr.process_image(train_image)
print("R: ", R)
print("t: ", t)
| 30.578261
| 116
| 0.570027
| 825
| 7,033
| 4.682424
| 0.201212
| 0.083355
| 0.06394
| 0.028475
| 0.217706
| 0.15299
| 0.135128
| 0.135128
| 0.135128
| 0.135128
| 0
| 0.027572
| 0.329589
| 7,033
| 229
| 117
| 30.71179
| 0.791729
| 0.253661
| 0
| 0.093458
| 0
| 0
| 0.03181
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.084112
| false
| 0
| 0.037383
| 0
| 0.271028
| 0.074766
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
017f2c1c96c787b6d2e75710df80d07ac95d8ea9
| 881
|
py
|
Python
|
utils/Logger.py
|
Team-Squad-Up/multigraph_transformer
|
180a4dc172695d305ab8a945698cd24401d42e66
|
[
"MIT"
] | 268
|
2019-12-24T05:27:57.000Z
|
2022-03-31T13:59:30.000Z
|
utils/Logger.py
|
Team-Squad-Up/multigraph_transformer
|
180a4dc172695d305ab8a945698cd24401d42e66
|
[
"MIT"
] | 2
|
2020-08-10T02:57:57.000Z
|
2021-01-05T06:19:40.000Z
|
utils/Logger.py
|
PengBoXiangShang/multigraph_transformer
|
04aaf575a5242d44e08910a9583c623f14b61b62
|
[
"MIT"
] | 26
|
2019-12-24T13:24:58.000Z
|
2022-03-21T08:42:20.000Z
|
import logging
import os
class Logger(object):
"""
set logger
"""
def __init__(self, logger_path):
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
self.logfile = logging.FileHandler(logger_path)
#
self.logfile.setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter(
'%(asctime)s -%(filename)s:%(lineno)s - %(levelname)s - %(message)s')
self.logfile.setFormatter(formatter)
self.logdisplay = logging.StreamHandler()
#
self.logdisplay.setLevel(logging.DEBUG)
self.logdisplay.setFormatter(formatter)
self.logger.addHandler(self.logfile)
self.logger.addHandler(self.logdisplay)
def get_logger(self):
return self.logger
| 29.366667
| 95
| 0.631101
| 92
| 881
| 5.967391
| 0.326087
| 0.10929
| 0.10929
| 0.087432
| 0.189435
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.239501
| 881
| 29
| 96
| 30.37931
| 0.819403
| 0.110102
| 0
| 0
| 0
| 0.055556
| 0.086275
| 0.031373
| 0
| 0
| 0
| 0
| 0
| 1
| 0.111111
| false
| 0
| 0.111111
| 0.055556
| 0.333333
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
018015cf927908eea70db9b02fdbb5cdefd59ff5
| 6,224
|
py
|
Python
|
LineNotifyBot/orderManager.py
|
cryptocat-miner/BitMexLineNotifyBot
|
2388d5fbccd3e8b7110484a1c10bd490e4b13859
|
[
"MIT"
] | 1
|
2019-09-23T12:34:18.000Z
|
2019-09-23T12:34:18.000Z
|
LineNotifyBot/orderManager.py
|
cryptocat-miner/BitMexLineNotifyBot
|
2388d5fbccd3e8b7110484a1c10bd490e4b13859
|
[
"MIT"
] | null | null | null |
LineNotifyBot/orderManager.py
|
cryptocat-miner/BitMexLineNotifyBot
|
2388d5fbccd3e8b7110484a1c10bd490e4b13859
|
[
"MIT"
] | null | null | null |
import ccxt
from datetime import datetime
from datetime import timedelta
import calendar
import time
from enum import Enum
import ccxtWrapper
import math
import LineNotify
import orderInfo
class orderManagementEnum(Enum):
NO_POSITION = 0
HAVE_POSITION = 1
class orderManager(ccxtWrapper.ccxtWrapper):
orderManagementState = orderManagementEnum(0)
exchangeInstance = None
orderErrorCounter = 0
isPosition = False
balance = None
orderAmount = 0
positionAmount = 0
size = 0
preSize = 0
btcAmount = 0
averagePrice = 0
liquidationPrice = 0 # 清算価格
maintMargin = 0
realisedPnl = 0 # 実現損益
unrealisedPnl = 0 # 未実現損益
unrealisedRoePcnt = 0 # 未実現損益(ROE%)
satoshiUnit = 0.00000001
totalBlance = 0
diffBalance = 0
def __init__(self, instance: ccxtWrapper.ccxtWrapper):
self.orderManagementState = orderManagementEnum.NO_POSITION
self.exchangeInstance = instance
self.changeToNoPositionState()
self.setPositionDirection()
def setPositionDirection(self):
positions = self.exchangeInstance.privateGetPosition()
if positions != None and len(positions) > 0:
if positions[0]["currentQty"] != None:
self.preSize = self.size
self.size = positions[0]["currentQty"]
if positions[0]["homeNotional"] != None:
self.btcAmount = abs(positions[0]["homeNotional"])
if positions[0]["avgCostPrice"] != None:
self.averagePrice = "{:.2f}".format(positions[0]["avgCostPrice"])
if positions[0]["liquidationPrice"] != None:
self.liquidationPrice = positions[0]["liquidationPrice"]
if positions[0]["maintMargin"] != None:
self.maintMargin = "{:.4f}".format(positions[0]["maintMargin"] * self.satoshiUnit)
if positions[0]["realisedPnl"] != None and positions[0]["rebalancedPnl"] != None:
self.realisedPnl = "{:.4f}".format((positions[0]["realisedPnl"] + positions[0]["rebalancedPnl"]) * self.satoshiUnit)
if positions[0]["unrealisedPnl"] != None:
self.unrealisedPnl = "{:.4f}".format(positions[0]["unrealisedPnl"] * self.satoshiUnit)
if positions[0]["unrealisedRoePcnt"] != None:
self.unrealisedRoePcnt = "{:.2f}".format(positions[0]["unrealisedRoePcnt"] * 100)
balance = self.exchangeInstance.fetchBalance()
if balance != None:
# 起動時の一回目に資産情報を通知
if self.balance == None:
LineNotify.PostMessage("監視botを起動しました\r\n資産は" + "{:.4f}".format(balance["total"]) + "XBTです")
self.balance = balance
if self.balance != None and self.isPosition == False:
self.totalBlance = self.balance["total"] # イン-アウトの損益計算用に記憶
usdPosition = None
if positions != None:
for position in positions:
if position["symbol"] == "XBTUSD":
usdPosition = position
if usdPosition == None or usdPosition["currentQty"] == 0:
self.isPosition = False
self.positionAmount = 0
else:
self.isPosition = True
self.positionAmount = abs(usdPosition["currentQty"])
# else:
# エラーの場合は前回値を残しておいた方が良いかも?
# self.isPosition = False
# self.positionAmount = 0
def switchState(self):
print("現在の発注管理状態:" + str(self.orderManagementState))
self.setPositionDirection()
# 状態毎に処理する関数を分岐
if self.orderManagementState == orderManagementEnum.NO_POSITION:
self.noPositionState()
elif self.orderManagementState == orderManagementEnum.HAVE_POSITION:
self.havePositionState()
else:
print(str(self.orderManagementState) + ":定義されていない状態です")
print("強制的に初期化します")
self.changeToNoPositionState()
def noPositionState(self):
ret = None
if self.isPosition == True:
self.changeToHavePositionState()
self.sendPositionMessage("ポジションを持ちました\r\n")
return ret
def havePositionState(self):
if self.isPosition == False:
balance = self.exchangeInstance.fetchBalance()
if balance != None:
self.diffBalance = balance["total"] - self.totalBlance
self.totalBalance = balance["total"]
LineNotify.PostMessage("ポジションを決済しました\r\n今回の取引結果は" + "{:.4f}".format(self.diffBalance) + "XBTです\r\n現在の合計資産は" + "{:.4f}".format(self.totalBalance) + "XBTです")
self.changeToNoPositionState()
else:
LineNotify.PostMessage("ポジションを決済しました\r\nエラーが発生して資産情報は読めませんでした\r\n再度資産情報を読みます")
else:
if self.size != self.preSize:
self.sendPositionMessage("ポジションが変更されました\r\n")
return None
def sendPositionMessage(self, message: str):
balanceMessage = message
# 資産情報を通知
balanceMessage = balanceMessage + orderInfo.getBalanceText(self.balance) + "\r\n"
balanceMessage = balanceMessage + "サイズ:" + str(self.size) + "\r\n"
balanceMessage = balanceMessage + "値:" + str(self.btcAmount) + " XBT\r\n"
balanceMessage = balanceMessage + "参入価格:" + str(self.averagePrice) + "\r\n"
balanceMessage = balanceMessage + "清算価格:" + str(self.liquidationPrice) + "\r\n"
balanceMessage = balanceMessage + "証拠金:" + str(self.maintMargin) + " XBT\r\n"
balanceMessage = balanceMessage + "未実現損益(ROE%):" + str(self.unrealisedPnl) + " XBT (" + str(self.unrealisedRoePcnt) + "%)\r\n"
balanceMessage = balanceMessage + "実現損益:" + str(self.realisedPnl) + " XBT\r\n"
LineNotify.PostMessage(balanceMessage)
def changeToNoPositionState(self):
self.orderErrorCounter = 0
self.orderManagementState = orderManagementEnum.NO_POSITION
print("発注管理状態変更:" + str(self.orderManagementState))
def changeToHavePositionState(self):
self.orderErrorCounter = 0
self.orderManagementState = orderManagementEnum.HAVE_POSITION
print("発注管理状態変更:" + str(self.orderManagementState))
| 38.9
| 171
| 0.621144
| 545
| 6,224
| 7.073395
| 0.216514
| 0.049287
| 0.024903
| 0.054475
| 0.190921
| 0.136965
| 0.062776
| 0
| 0
| 0
| 0
| 0.013336
| 0.265103
| 6,224
| 159
| 172
| 39.144654
| 0.829471
| 0.026671
| 0
| 0.150794
| 0
| 0
| 0.103226
| 0.012572
| 0
| 0
| 0
| 0
| 0
| 1
| 0.063492
| false
| 0
| 0.079365
| 0
| 0.34127
| 0.039683
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
018153b0720e76bdbfa6aa63e1ed23fa87f47eb2
| 1,917
|
py
|
Python
|
강의 자료/02-알고리즘/autoindex.py
|
rhs0266/FastCampus
|
88b5f4c18ebfb9ebf141ace644e40d2975ff665a
|
[
"MIT"
] | 407
|
2020-11-14T02:25:56.000Z
|
2022-03-31T04:12:17.000Z
|
강의 자료/02-알고리즘/autoindex.py
|
rhs0266/FastCampus
|
88b5f4c18ebfb9ebf141ace644e40d2975ff665a
|
[
"MIT"
] | 48
|
2020-11-16T15:29:10.000Z
|
2022-03-14T06:32:16.000Z
|
강의 자료/02-알고리즘/autoindex.py
|
rhs0266/FastCampus
|
88b5f4c18ebfb9ebf141ace644e40d2975ff665a
|
[
"MIT"
] | 78
|
2020-11-28T08:29:39.000Z
|
2022-03-29T06:54:48.000Z
|
import os
from lxml import html
import requests
def get_dir_list(path):
return [p for p in os.listdir(path) if os.path.isdir(p)]
def get_file_list(path):
return [p for p in os.listdir(path) if os.path.isfile(p)]
def get_number(str):
res = ''.join(list(filter(lambda x: '0'<=x<='9', str)))
if res:
return res
return None
def get_code_dir(path, numberStr):
for p in os.listdir(path):
p = path + '/' + p
if not os.path.isdir(p):
continue
if numberStr not in p:
continue
req = ['solution.cpp', 'solution.java', 'solution.py']
if all(r in os.listdir(p) for r in req):
return p.replace(' ', '%20')
return False
for chapter in get_dir_list('./'):
md_path = os.path.join(chapter, 'README.md')
new_md = []
with open(md_path, "r", encoding="UTF8") as f:
for line in f.readlines():
line = line.strip()
row = line.split('|')
numberStr : str = get_number(row[2])
if numberStr:
res = requests.get('http://boj.kr/' + numberStr)
res.raise_for_status()
res.encoding = 'UTF-8'
tree = html.fromstring(res.text)
title = tree.xpath('//title/text()')[0].split(' ', 1)[1]
row[1] = title
codePath = get_code_dir(chapter+'/문제별 코드', numberStr)
row[2] = f"[링크](http://boj.kr/{numberStr})"
if codePath:
row[3] = f'[링크](https://github.com/rhs0266/FastCampus/tree/main/%EA%B0%95%EC%9D%98%20%EC%9E%90%EB%A3%8C/02-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98/{codePath})'
else:
if len(row[3]) < 10:
row[3] = f'[링크]'
new_md.append('|'.join(row))
with open(md_path, "w", encoding="UTF8") as f:
f.write('\n'.join(new_md))
| 34.854545
| 176
| 0.521127
| 278
| 1,917
| 3.521583
| 0.384892
| 0.024515
| 0.044944
| 0.024515
| 0.105209
| 0.105209
| 0.085802
| 0.085802
| 0.085802
| 0.085802
| 0
| 0.035088
| 0.316119
| 1,917
| 54
| 177
| 35.5
| 0.71167
| 0
| 0
| 0.041667
| 0
| 0.020833
| 0.150235
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.083333
| false
| 0
| 0.0625
| 0.041667
| 0.270833
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
01886934cd30258f1bbd5bc214cc5822c242b7c6
| 504
|
py
|
Python
|
general/kneeOsteoarthritisDataset/KneeDataset_utility.py
|
duennbart/masterthesis_VAE
|
1a161bc5c234acc0a021d84cde8cd69e784174e1
|
[
"BSD-3-Clause"
] | 14
|
2020-06-28T15:38:48.000Z
|
2021-12-05T01:49:50.000Z
|
general/kneeOsteoarthritisDataset/KneeDataset_utility.py
|
duennbart/masterthesis_VAE
|
1a161bc5c234acc0a021d84cde8cd69e784174e1
|
[
"BSD-3-Clause"
] | null | null | null |
general/kneeOsteoarthritisDataset/KneeDataset_utility.py
|
duennbart/masterthesis_VAE
|
1a161bc5c234acc0a021d84cde8cd69e784174e1
|
[
"BSD-3-Clause"
] | 3
|
2020-06-28T15:38:49.000Z
|
2022-02-13T22:04:34.000Z
|
import numpy as np
from kneeOsteoarthritisDataset.KneeOsteoarthritsDataset import KneeOsteoarthritsDataset
data_path = '/home/biomech/Documents/OsteoData/KneeXrayData/ClsKLData/kneeKL299'
kneeosteo = KneeOsteoarthritsDataset(data_path = data_path)
imgs, labels = kneeosteo.load_imgs()
rand_idx = np.random.randint(low=0,high=len(labels))
img = imgs[rand_idx]
label = labels[rand_idx]
kneeosteo.plot_img(img,label)
counter = 0
for item in labels:
if item == 2:
counter += 1
print(counter)
| 26.526316
| 87
| 0.781746
| 65
| 504
| 5.938462
| 0.6
| 0.062176
| 0.165803
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.015801
| 0.121032
| 504
| 19
| 88
| 26.526316
| 0.85553
| 0
| 0
| 0
| 0
| 0
| 0.130693
| 0.130693
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.142857
| 0
| 0.142857
| 0.071429
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
018a6d7e60dff23b8dbdde473c02f7669ed70154
| 1,551
|
py
|
Python
|
src/main.py
|
ubirch/pycom-bootloader
|
6510eb34ec198ef74e15bb757bb67e88aaf15b74
|
[
"Apache-2.0"
] | null | null | null |
src/main.py
|
ubirch/pycom-bootloader
|
6510eb34ec198ef74e15bb757bb67e88aaf15b74
|
[
"Apache-2.0"
] | null | null | null |
src/main.py
|
ubirch/pycom-bootloader
|
6510eb34ec198ef74e15bb757bb67e88aaf15b74
|
[
"Apache-2.0"
] | null | null | null |
print("SD bootloader")
import pycom
import time
import machine
import sys
import uos
#paths for the code/lib/mount locations
SD_MOUNTPOINT = '/sd'
CODE_PATH = '/sd/src'
LIB_PATH = '/sd/src/lib'
#LED colors
#for errors (full brightness)
C_YELLOW = 0xffff00
C_RED = 0xff0000
C_PURPLE = 0xff00ff
C_BLUE = 0x0000ff
#for normal boot (dimmed)
C_WHITE_DIM = 0x030303
C_RED_DIM = 0x060000
### Functions ###
def mount_sd():
try:
sd = machine.SD()
os.mount(sd, SD_MOUNTPOINT)
return True
except OSError:
return False
def endless_blink(color1: int, color2: int):
pycom.heartbeat(False)
while True:
pycom.rgbled(color1)
time.sleep(0.5)
pycom.rgbled(color2)
time.sleep(0.5)
### Main Code ###
pycom.heartbeat(False)
pycom.rgbled(C_RED_DIM)
if mount_sd():
print("booting from SD")
pycom.rgbled(C_WHITE_DIM)
#add code and lib dir on sd to import path
sys.path.append(CODE_PATH)
sys.path.append(LIB_PATH)
#change working dir to code directory
try:
uos.chdir(CODE_PATH)
except Exception:
print("could not change to code folder:")
print(CODE_PATH)
endless_blink(C_PURPLE,C_RED)
print("sys.path:")
print(sys.path)
print("uos.getcwd():")
print(uos.getcwd())
#execute code from SD
try:
execfile('main.py')
except Exception:
print("could not execute main.py")
endless_blink(C_BLUE,C_RED)
#sd was not mounted
print("no SD found")
endless_blink(C_YELLOW,C_RED)
| 20.142857
| 49
| 0.654417
| 226
| 1,551
| 4.349558
| 0.380531
| 0.024415
| 0.039674
| 0.024415
| 0.056968
| 0
| 0
| 0
| 0
| 0
| 0
| 0.03204
| 0.235332
| 1,551
| 76
| 50
| 20.407895
| 0.796796
| 0.152805
| 0
| 0.169811
| 0
| 0
| 0.112828
| 0
| 0
| 0
| 0.037094
| 0
| 0
| 1
| 0.037736
| false
| 0
| 0.09434
| 0
| 0.169811
| 0.188679
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|
018d436c5de06e246b9aa736124eb44597086ab1
| 122,321
|
py
|
Python
|
gui.py
|
michael11892/picoscopeDataLogger
|
f50d26f33b5a42731e52261e52c6fe8574ca2bbc
|
[
"MIT"
] | 3
|
2021-07-02T10:34:16.000Z
|
2021-07-03T10:27:22.000Z
|
gui.py
|
michael11892/picoscopeDataLogger
|
f50d26f33b5a42731e52261e52c6fe8574ca2bbc
|
[
"MIT"
] | null | null | null |
gui.py
|
michael11892/picoscopeDataLogger
|
f50d26f33b5a42731e52261e52c6fe8574ca2bbc
|
[
"MIT"
] | null | null | null |
import os
import sys
import copy
from math import gcd
from driver_config_macros import *
from data_capture_macros import *
from signal_generator_macros import *
from power_operation_macros import *
from capture_config_macros import *
from trig_config_macros import *
from data_processing_macros import *
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
app_ = QtWidgets.QApplication(sys.argv)
w, h = app_.primaryScreen().size().width(), app_.primaryScreen().size().height()
#Screen Ratio Corrections
gcd_ = gcd(w, h)
resRatio = w/h
baseRatio = 16/9
wR = w/(gcd_*16) #Ratio Correction
hR = h/(gcd_*9) #Ratio Correction
widthRatio = 1#1/wR #Full Width Ratio Correction
heightRatio = 1#1/hR #Full Height Ratio Correction
app_.exit()
conditionList = {'conditionTab': [], 'extConditionLabel': [], 'aConditionLabel': [], 'bConditionLabel': [], 'cConditionLabel': [], 'dConditionLabel': [],
'aStateComboBox': [], 'bStateComboBox': [], 'cStateComboBox': [], 'dStateComboBox': [], 'extStateComboBox': [], 'stateLabel': []}
runList = {'runTab': [], 'stackedWidget': [], 'captureTab': []}
class Canvas(FigureCanvasQTAgg):
def __init__(self, parent=None, width=4.61*widthRatio, height=3.61*heightRatio, dpi=100):
fig, self.axes = plt.subplots(figsize=(width, height), dpi=dpi)
super().__init__(fig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(801*widthRatio, 580*heightRatio)
MainWindow.setMinimumSize(QtCore.QSize(801*widthRatio, 580*heightRatio))
MainWindow.setMaximumSize(QtCore.QSize(801*widthRatio, 580*heightRatio))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(".\\icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setEnabled(True)
self.centralwidget.setObjectName("centralwidget")
self.driverLabel = QtWidgets.QLabel(self.centralwidget)
self.driverLabel.setGeometry(QtCore.QRect(20*widthRatio, 10*heightRatio, 51*widthRatio, 21*heightRatio))
self.driverLabel.setObjectName("driverLabel")
self.presetComboBox = QtWidgets.QComboBox(self.centralwidget)
self.presetComboBox.setGeometry(QtCore.QRect(60*widthRatio, 40*heightRatio, 91*widthRatio, 22*heightRatio))
self.presetComboBox.setEditable(False)
self.presetComboBox.setObjectName("presetComboBox")
self.presetComboBox.addItem("")
self.presetLabel = QtWidgets.QLabel(self.centralwidget)
self.presetLabel.setGeometry(QtCore.QRect(20*widthRatio, 40*heightRatio, 41*widthRatio, 21*heightRatio))
self.presetLabel.setObjectName("presetLabel")
self.channelBox = QtWidgets.QGroupBox(self.centralwidget)
self.channelBox.setGeometry(QtCore.QRect(210*widthRatio, 0*heightRatio, 281*widthRatio, 121*heightRatio))
self.channelBox.setObjectName("channelBox")
self.aLabel = QtWidgets.QLabel(self.channelBox)
self.aLabel.setGeometry(QtCore.QRect(10*widthRatio, 30*heightRatio, 21*widthRatio, 16*heightRatio))
self.aLabel.setObjectName("aLabel")
self.bLabel = QtWidgets.QLabel(self.channelBox)
self.bLabel.setGeometry(QtCore.QRect(10*widthRatio, 50*heightRatio, 21*widthRatio, 16*heightRatio))
self.bLabel.setObjectName("bLabel")
self.cLabel = QtWidgets.QLabel(self.channelBox)
self.cLabel.setGeometry(QtCore.QRect(10*widthRatio, 70*heightRatio, 21*widthRatio, 16*heightRatio))
self.cLabel.setObjectName("cLabel")
self.dLabel = QtWidgets.QLabel(self.channelBox)
self.dLabel.setGeometry(QtCore.QRect(10*widthRatio, 90*heightRatio, 21*widthRatio, 16*heightRatio))
self.dLabel.setObjectName("dLabel")
self.aCheck = QtWidgets.QCheckBox(self.channelBox)
self.aCheck.setGeometry(QtCore.QRect(30*widthRatio, 30*heightRatio, 16*widthRatio, 17*heightRatio))
self.aCheck.setText("")
self.aCheck.setObjectName("aCheck")
self.bCheck = QtWidgets.QCheckBox(self.channelBox)
self.bCheck.setGeometry(QtCore.QRect(30*widthRatio, 50*heightRatio, 16*widthRatio, 17*heightRatio))
self.bCheck.setText("")
self.bCheck.setObjectName("bCheck")
self.cCheck = QtWidgets.QCheckBox(self.channelBox)
self.cCheck.setGeometry(QtCore.QRect(30*widthRatio, 70*heightRatio, 16*widthRatio, 17*heightRatio))
self.cCheck.setText("")
self.cCheck.setObjectName("cCheck")
self.dCheck = QtWidgets.QCheckBox(self.channelBox)
self.dCheck.setGeometry(QtCore.QRect(30*widthRatio, 90*heightRatio, 16*widthRatio, 17*heightRatio))
self.dCheck.setText("")
self.dCheck.setObjectName("dCheck")
self.aRangeComboBox = QtWidgets.QComboBox(self.channelBox)
self.aRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 30*heightRatio, 69*widthRatio, 16*heightRatio))
self.aRangeComboBox.setObjectName("aRangeComboBox")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.aRangeComboBox.addItem("")
self.bRangeComboBox = QtWidgets.QComboBox(self.channelBox)
self.bRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 50*heightRatio, 69*widthRatio, 16*heightRatio))
self.bRangeComboBox.setObjectName("bRangeComboBox")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.bRangeComboBox.addItem("")
self.cRangeComboBox = QtWidgets.QComboBox(self.channelBox)
self.cRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 70*heightRatio, 69*widthRatio, 16*heightRatio))
self.cRangeComboBox.setObjectName("cRangeComboBox")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.cRangeComboBox.addItem("")
self.dRangeComboBox = QtWidgets.QComboBox(self.channelBox)
self.dRangeComboBox.setGeometry(QtCore.QRect(60*widthRatio, 90*heightRatio, 69*widthRatio, 16*heightRatio))
self.dRangeComboBox.setObjectName("dRangeComboBox")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.dRangeComboBox.addItem("")
self.aOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox)
self.aOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 30*heightRatio, 62*widthRatio, 16*heightRatio))
self.aOffsetSpinBox.setMaximum(999999.0)
self.aOffsetSpinBox.setObjectName("aOffsetSpinBox")
self.bOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox)
self.bOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 50*heightRatio, 62*widthRatio, 16*heightRatio))
self.bOffsetSpinBox.setMaximum(999999.0)
self.bOffsetSpinBox.setObjectName("bOffsetSpinBox")
self.cOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox)
self.cOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 70*heightRatio, 62*widthRatio, 16*heightRatio))
self.cOffsetSpinBox.setMaximum(999999.0)
self.cOffsetSpinBox.setObjectName("cOffsetSpinBox")
self.dOffsetSpinBox = QtWidgets.QDoubleSpinBox(self.channelBox)
self.dOffsetSpinBox.setGeometry(QtCore.QRect(150*widthRatio, 90*heightRatio, 62*widthRatio, 16*heightRatio))
self.dOffsetSpinBox.setMaximum(999999.0)
self.dOffsetSpinBox.setObjectName("dOffsetSpinBox")
self.rangeLabel = QtWidgets.QLabel(self.channelBox)
self.rangeLabel.setGeometry(QtCore.QRect(80*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio))
self.rangeLabel.setObjectName("rangeLabel")
self.offsetLabel = QtWidgets.QLabel(self.channelBox)
self.offsetLabel.setGeometry(QtCore.QRect(160*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio))
self.offsetLabel.setObjectName("offsetLabel")
self.couplingLabel = QtWidgets.QLabel(self.channelBox)
self.couplingLabel.setGeometry(QtCore.QRect(230*widthRatio, 10*heightRatio, 47*widthRatio, 13*heightRatio))
self.couplingLabel.setObjectName("couplingLabel")
self.aCouplingComboBox = QtWidgets.QComboBox(self.channelBox)
self.aCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 30*heightRatio, 41*widthRatio, 16*heightRatio))
self.aCouplingComboBox.setObjectName("aCouplingComboBox")
self.aCouplingComboBox.addItem("")
self.aCouplingComboBox.addItem("")
self.bCouplingComboBox = QtWidgets.QComboBox(self.channelBox)
self.bCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 50*heightRatio, 41*widthRatio, 16*heightRatio))
self.bCouplingComboBox.setObjectName("bCouplingComboBox")
self.bCouplingComboBox.addItem("")
self.bCouplingComboBox.addItem("")
self.cCouplingComboBox = QtWidgets.QComboBox(self.channelBox)
self.cCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 70*heightRatio, 41*widthRatio, 16*heightRatio))
self.cCouplingComboBox.setObjectName("cCouplingComboBox")
self.cCouplingComboBox.addItem("")
self.cCouplingComboBox.addItem("")
self.dCouplingComboBox = QtWidgets.QComboBox(self.channelBox)
self.dCouplingComboBox.setGeometry(QtCore.QRect(230*widthRatio, 90*heightRatio, 41*widthRatio, 16*heightRatio))
self.dCouplingComboBox.setObjectName("dCouplingComboBox")
self.dCouplingComboBox.addItem("")
self.dCouplingComboBox.addItem("")
self.captureBox = QtWidgets.QGroupBox(self.centralwidget)
self.captureBox.setGeometry(QtCore.QRect(500*widthRatio, 0*heightRatio, 291*widthRatio, 121*heightRatio))
self.captureBox.setObjectName("captureBox")
self.modeComboBox = QtWidgets.QComboBox(self.captureBox)
self.modeComboBox.setGeometry(QtCore.QRect(40*widthRatio, 20*heightRatio, 81*widthRatio, 22*heightRatio))
self.modeComboBox.setObjectName("modeComboBox")
self.modeComboBox.addItem("")
self.modeComboBox.addItem("")
self.modeComboBox.addItem("")
self.modeLabel = QtWidgets.QLabel(self.captureBox)
self.modeLabel.setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 31*widthRatio, 21*heightRatio))
self.modeLabel.setObjectName("modeLabel")
self.preTriggerSamplesLabel = QtWidgets.QLabel(self.captureBox)
self.preTriggerSamplesLabel.setGeometry(QtCore.QRect(130*widthRatio, 50*heightRatio, 101*widthRatio, 16*heightRatio))
self.preTriggerSamplesLabel.setObjectName("preTriggerSamplesLabel")
self.postTriggerSamplesLabel = QtWidgets.QLabel(self.captureBox)
self.postTriggerSamplesLabel.setGeometry(QtCore.QRect(130*widthRatio, 70*heightRatio, 101*widthRatio, 16*heightRatio))
self.postTriggerSamplesLabel.setObjectName("postTriggerSamplesLabel")
self.preTriggerSamplesSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.preTriggerSamplesSpinBox.setEnabled(True)
self.preTriggerSamplesSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 50*heightRatio, 51*widthRatio, 16*heightRatio))
self.preTriggerSamplesSpinBox.setAutoFillBackground(False)
self.preTriggerSamplesSpinBox.setReadOnly(False)
self.preTriggerSamplesSpinBox.setProperty("showGroupSeparator", False)
self.preTriggerSamplesSpinBox.setMaximum(999999)
self.preTriggerSamplesSpinBox.setObjectName("preTriggerSamplesSpinBox")
self.postTriggerSamplesSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.postTriggerSamplesSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 70*heightRatio, 51*widthRatio, 16*heightRatio))
self.postTriggerSamplesSpinBox.setMaximum(999999)
self.postTriggerSamplesSpinBox.setObjectName("postTriggerSamplesSpinBox")
self.timebaseLabel = QtWidgets.QLabel(self.captureBox)
self.timebaseLabel.setGeometry(QtCore.QRect(10*widthRatio, 50*heightRatio, 47*widthRatio, 13*heightRatio))
self.timebaseLabel.setObjectName("timebaseLabel")
self.timebaseSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.timebaseSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 50*heightRatio, 42*widthRatio, 16*heightRatio))
self.timebaseSpinBox.setMaximum(999999)
self.timebaseSpinBox.setObjectName("timebaseSpinBox")
self.segmentsLabel = QtWidgets.QLabel(self.captureBox)
self.segmentsLabel.setGeometry(QtCore.QRect(10*widthRatio, 70*heightRatio, 47*widthRatio, 13*heightRatio))
self.segmentsLabel.setObjectName("segmentsLabel")
self.capturesLabel = QtWidgets.QLabel(self.captureBox)
self.capturesLabel.setGeometry(QtCore.QRect(10*widthRatio, 90*heightRatio, 47*widthRatio, 13*heightRatio))
self.capturesLabel.setObjectName("capturesLabel")
self.segmentsSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.segmentsSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 70*heightRatio, 42*widthRatio, 16*heightRatio))
self.segmentsSpinBox.setMaximum(999999)
self.segmentsSpinBox.setObjectName("segmentsSpinBox")
self.capturesSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.capturesSpinBox.setGeometry(QtCore.QRect(60*widthRatio, 90*heightRatio, 42*widthRatio, 16*heightRatio))
self.capturesSpinBox.setMaximum(999999)
self.capturesSpinBox.setObjectName("capturesSpinBox")
self.timeUnitsLabel = QtWidgets.QLabel(self.captureBox)
self.timeUnitsLabel.setGeometry(QtCore.QRect(130*widthRatio, 30*heightRatio, 71*widthRatio, 16*heightRatio))
self.timeUnitsLabel.setObjectName("timeUnitsLabel")
self.totalRuntimeLabel = QtWidgets.QLabel(self.captureBox)
self.totalRuntimeLabel.setGeometry(QtCore.QRect(130*widthRatio, 10*heightRatio, 81*widthRatio, 16*heightRatio))
self.totalRuntimeLabel.setObjectName("totalRuntimeLabel")
self.totalRuntimeSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.totalRuntimeSpinBox.setGeometry(QtCore.QRect(201*widthRatio, 10*heightRatio, 81*widthRatio, 16*heightRatio))
self.totalRuntimeSpinBox.setMaximum(999999999)
self.totalRuntimeSpinBox.setObjectName("totalRuntimeSpinBox")
self.timeUnitsComboBox = QtWidgets.QComboBox(self.captureBox)
self.timeUnitsComboBox.setGeometry(QtCore.QRect(210*widthRatio, 30*heightRatio, 69*widthRatio, 16*heightRatio))
self.timeUnitsComboBox.setObjectName("timeUnitsComboBox")
self.timeUnitsComboBox.addItem("")
self.timeUnitsComboBox.addItem("")
self.timeUnitsComboBox.addItem("")
self.timeUnitsComboBox.addItem("")
self.timeUnitsComboBox.addItem("")
self.timeUnitsComboBox.addItem("")
self.samplesPerBufferLabel = QtWidgets.QLabel(self.captureBox)
self.samplesPerBufferLabel.setGeometry(QtCore.QRect(130*widthRatio, 90*heightRatio, 101*widthRatio, 16*heightRatio))
self.samplesPerBufferLabel.setObjectName("samplesPerBufferLabel")
self.samplesPerBufferSpinBox = QtWidgets.QSpinBox(self.captureBox)
self.samplesPerBufferSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 90*heightRatio, 51*widthRatio, 16*heightRatio))
self.samplesPerBufferSpinBox.setMaximum(999999)
self.samplesPerBufferSpinBox.setObjectName("samplesPerBufferSpinBox")
self.driverLineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.driverLineEdit.setGeometry(QtCore.QRect(60*widthRatio, 10*heightRatio, 71*widthRatio, 22*heightRatio))
self.driverLineEdit.setReadOnly(True)
self.driverLineEdit.setObjectName("driverLineEdit")
self.outFileCheckBox = QtWidgets.QCheckBox(self.centralwidget)
self.outFileCheckBox.setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 81*widthRatio, 17*heightRatio))
self.outFileCheckBox.setObjectName("outFileCheckBox")
self.outFileNameLineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.outFileNameLineEdit.setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 113*widthRatio, 20*heightRatio))
self.outFileNameLineEdit.setObjectName("outFileNameLineEdit")
self.triggerBox = QtWidgets.QGroupBox(self.centralwidget)
self.triggerBox.setGeometry(QtCore.QRect(500*widthRatio, 130*heightRatio, 291*widthRatio, 391*heightRatio))
self.triggerBox.setObjectName("triggerBox")
self.triggerTypeLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerTypeLabel.setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 47*widthRatio, 16*heightRatio))
self.triggerTypeLabel.setObjectName("triggerTypeLabel")
self.triggerTypeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.triggerTypeComboBox.setGeometry(QtCore.QRect(40*widthRatio, 20*heightRatio, 69*widthRatio, 21*heightRatio))
self.triggerTypeComboBox.setObjectName("triggerTypeComboBox")
self.triggerTypeComboBox.addItem("")
self.triggerTypeComboBox.addItem("")
self.aAutotriggerSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aAutotriggerSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 10*heightRatio, 51*widthRatio, 16*heightRatio))
self.aAutotriggerSpinBox.setMaximum(999999)
self.aAutotriggerSpinBox.setObjectName("aAutotriggerSpinBox")
self.aDelaySpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aDelaySpinBox.setGeometry(QtCore.QRect(231*widthRatio, 30*heightRatio, 51*widthRatio, 16*heightRatio))
self.aDelaySpinBox.setMaximum(999999)
self.aDelaySpinBox.setObjectName("aDelaySpinBox")
self.triggerAutotriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerAutotriggerLabel.setGeometry(QtCore.QRect(160*widthRatio, 10*heightRatio, 71*widthRatio, 21*heightRatio))
self.triggerAutotriggerLabel.setObjectName("triggerAutotriggerLabel")
self.triggerDelayLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerDelayLabel.setGeometry(QtCore.QRect(190*widthRatio, 30*heightRatio, 41*widthRatio, 16*heightRatio))
self.triggerDelayLabel.setObjectName("triggerDelayLabel")
self.cUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.cUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio))
self.cUpperThresholdSpinBox.setMaximum(32512)
self.cUpperThresholdSpinBox.setObjectName("cUpperThresholdSpinBox")
self.dUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.dUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio))
self.dUpperThresholdSpinBox.setMaximum(32512)
self.dUpperThresholdSpinBox.setObjectName("dUpperThresholdSpinBox")
self.aUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio))
self.aUpperThresholdSpinBox.setMaximum(32512)
self.aUpperThresholdSpinBox.setObjectName("aUpperThresholdSpinBox")
self.cTriggerCheck = QtWidgets.QCheckBox(self.triggerBox)
self.cTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 120*heightRatio, 16*widthRatio, 17*heightRatio))
self.cTriggerCheck.setText("")
self.cTriggerCheck.setObjectName("cTriggerCheck")
self.aTriggerCheck = QtWidgets.QCheckBox(self.triggerBox)
self.aTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 16*widthRatio, 17*heightRatio))
self.aTriggerCheck.setText("")
self.aTriggerCheck.setObjectName("aTriggerCheck")
self.bTriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.bTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 100*heightRatio, 16*widthRatio, 16*heightRatio))
self.bTriggerLabel.setObjectName("bTriggerLabel")
self.bUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.bUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio))
self.bUpperThresholdSpinBox.setMaximum(32512)
self.bUpperThresholdSpinBox.setObjectName("bUpperThresholdSpinBox")
self.aTriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.aTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 80*heightRatio, 16*widthRatio, 16*heightRatio))
self.aTriggerLabel.setObjectName("aTriggerLabel")
self.cTriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.cTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 120*heightRatio, 16*widthRatio, 16*heightRatio))
self.cTriggerLabel.setObjectName("cTriggerLabel")
self.dTriggerCheck = QtWidgets.QCheckBox(self.triggerBox)
self.dTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 140*heightRatio, 16*widthRatio, 17*heightRatio))
self.dTriggerCheck.setText("")
self.dTriggerCheck.setObjectName("dTriggerCheck")
self.triggerUpperThresholdLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerUpperThresholdLabel.setGeometry(QtCore.QRect(50*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio))
self.triggerUpperThresholdLabel.setWordWrap(True)
self.triggerUpperThresholdLabel.setObjectName("triggerUpperThresholdLabel")
self.dTriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.dTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 140*heightRatio, 16*widthRatio, 16*heightRatio))
self.dTriggerLabel.setObjectName("dTriggerLabel")
self.bTriggerCheck = QtWidgets.QCheckBox(self.triggerBox)
self.bTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 16*widthRatio, 17*heightRatio))
self.bTriggerCheck.setText("")
self.bTriggerCheck.setObjectName("bTriggerCheck")
self.deleteConditionButton = QtWidgets.QPushButton(self.triggerBox)
self.deleteConditionButton.setGeometry(QtCore.QRect(100*widthRatio, 340*heightRatio, 91*widthRatio, 23*heightRatio))
self.deleteConditionButton.setObjectName("deleteConditionButton")
self.newConditionButton = QtWidgets.QPushButton(self.triggerBox)
self.newConditionButton.setGeometry(QtCore.QRect(10*widthRatio, 340*heightRatio, 81*widthRatio, 21*heightRatio))
self.newConditionButton.setObjectName("newConditionButton")
self.conditionsTabWidget = QtWidgets.QTabWidget(self.triggerBox)
self.conditionsTabWidget.setEnabled(True)
self.conditionsTabWidget.setGeometry(QtCore.QRect(10*widthRatio, 180*heightRatio, 121*widthRatio, 151*heightRatio))
self.conditionsTabWidget.setObjectName("conditionsTabWidget")
self.newCondition()
self.dUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.dUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio))
self.dUpperHysteresisSpinBox.setMaximum(32512)
self.dUpperHysteresisSpinBox.setObjectName("dUpperHysteresisSpinBox")
self.bUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.bUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio))
self.bUpperHysteresisSpinBox.setMaximum(32512)
self.bUpperHysteresisSpinBox.setObjectName("bUpperHysteresisSpinBox")
self.triggerUpperHysteresisLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerUpperHysteresisLabel.setGeometry(QtCore.QRect(110*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio))
self.triggerUpperHysteresisLabel.setWordWrap(True)
self.triggerUpperHysteresisLabel.setObjectName("triggerUpperHysteresisLabel")
self.aUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio))
self.aUpperHysteresisSpinBox.setMaximum(32512)
self.aUpperHysteresisSpinBox.setObjectName("aUpperHysteresisSpinBox")
self.cUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.cUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio))
self.cUpperHysteresisSpinBox.setMaximum(32512)
self.cUpperHysteresisSpinBox.setObjectName("cUpperHysteresisSpinBox")
self.dLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.dLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio))
self.dLowerThresholdSpinBox.setMaximum(32512)
self.dLowerThresholdSpinBox.setObjectName("dLowerThresholdSpinBox")
self.dLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.dLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 140*heightRatio, 51*widthRatio, 16*heightRatio))
self.dLowerHysteresisSpinBox.setMaximum(32512)
self.dLowerHysteresisSpinBox.setObjectName("dLowerHysteresisSpinBox")
self.triggerLowerHysteresisLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerLowerHysteresisLabel.setGeometry(QtCore.QRect(230*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio))
self.triggerLowerHysteresisLabel.setWordWrap(True)
self.triggerLowerHysteresisLabel.setObjectName("triggerLowerHysteresisLabel")
self.aLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio))
self.aLowerHysteresisSpinBox.setMaximum(32512)
self.aLowerHysteresisSpinBox.setObjectName("aLowerHysteresisSpinBox")
self.bLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.bLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio))
self.bLowerThresholdSpinBox.setMaximum(32512)
self.bLowerThresholdSpinBox.setObjectName("bLowerThresholdSpinBox")
self.bLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.bLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 100*heightRatio, 51*widthRatio, 16*heightRatio))
self.bLowerHysteresisSpinBox.setMaximum(32512)
self.bLowerHysteresisSpinBox.setObjectName("bLowerHysteresisSpinBox")
self.cLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.cLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio))
self.cLowerHysteresisSpinBox.setMaximum(32512)
self.cLowerHysteresisSpinBox.setObjectName("cLowerHysteresisSpinBox")
self.triggerLowerThresholdLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerLowerThresholdLabel.setGeometry(QtCore.QRect(170*widthRatio, 50*heightRatio, 51*widthRatio, 31*heightRatio))
self.triggerLowerThresholdLabel.setWordWrap(True)
self.triggerLowerThresholdLabel.setObjectName("triggerLowerThresholdLabel")
self.aLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.aLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 80*heightRatio, 51*widthRatio, 16*heightRatio))
self.aLowerThresholdSpinBox.setMaximum(32512)
self.aLowerThresholdSpinBox.setObjectName("aLowerThresholdSpinBox")
self.cLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.cLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 120*heightRatio, 51*widthRatio, 16*heightRatio))
self.cLowerThresholdSpinBox.setMaximum(32512)
self.cLowerThresholdSpinBox.setObjectName("cLowerThresholdSpinBox")
self.extTriggerLabel = QtWidgets.QLabel(self.triggerBox)
self.extTriggerLabel.setGeometry(QtCore.QRect(10*widthRatio, 160*heightRatio, 16*widthRatio, 16*heightRatio))
self.extTriggerLabel.setObjectName("extTriggerLabel")
self.extTriggerCheck = QtWidgets.QCheckBox(self.triggerBox)
self.extTriggerCheck.setGeometry(QtCore.QRect(30*widthRatio, 160*heightRatio, 16*widthRatio, 17*heightRatio))
self.extTriggerCheck.setText("")
self.extTriggerCheck.setObjectName("extTriggerCheck")
self.extUpperThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.extUpperThresholdSpinBox.setGeometry(QtCore.QRect(51*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio))
self.extUpperThresholdSpinBox.setMaximum(32767)
self.extUpperThresholdSpinBox.setObjectName("extUpperThresholdSpinBox")
self.extUpperHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.extUpperHysteresisSpinBox.setGeometry(QtCore.QRect(111*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio))
self.extUpperHysteresisSpinBox.setMaximum(32767)
self.extUpperHysteresisSpinBox.setObjectName("extUpperHysteresisSpinBox")
self.extLowerThresholdSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.extLowerThresholdSpinBox.setGeometry(QtCore.QRect(171*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio))
self.extLowerThresholdSpinBox.setMaximum(32767)
self.extLowerThresholdSpinBox.setObjectName("extLowerThresholdSpinBox")
self.extLowerHysteresisSpinBox = QtWidgets.QSpinBox(self.triggerBox)
self.extLowerHysteresisSpinBox.setGeometry(QtCore.QRect(231*widthRatio, 160*heightRatio, 51*widthRatio, 16*heightRatio))
self.extLowerHysteresisSpinBox.setMaximum(32767)
self.extLowerHysteresisSpinBox.setObjectName("extLowerHysteresisSpinBox")
self.triggerDirectionLabel = QtWidgets.QLabel(self.triggerBox)
self.triggerDirectionLabel.setGeometry(QtCore.QRect(140*widthRatio, 200*heightRatio, 47*widthRatio, 21*heightRatio))
self.triggerDirectionLabel.setObjectName("triggerDirectionLabel")
self.aThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.aThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 220*heightRatio, 61*widthRatio, 16*heightRatio))
self.aThresholdModeComboBox.setObjectName("aThresholdModeComboBox")
self.aThresholdModeComboBox.addItem("")
self.aThresholdModeComboBox.addItem("")
self.bDirectionComboBox = QtWidgets.QComboBox(self.triggerBox)
self.bDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 240*heightRatio, 71*widthRatio, 16*heightRatio))
self.bDirectionComboBox.setObjectName("bDirectionComboBox")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.bDirectionComboBox.addItem("")
self.extDirectionComboBox = QtWidgets.QComboBox(self.triggerBox)
self.extDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 300*heightRatio, 71*widthRatio, 16*heightRatio))
self.extDirectionComboBox.setObjectName("extDirectionComboBox")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.extDirectionComboBox.addItem("")
self.dDirectionComboBox = QtWidgets.QComboBox(self.triggerBox)
self.dDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 280*heightRatio, 71*widthRatio, 16*heightRatio))
self.dDirectionComboBox.setObjectName("dDirectionComboBox")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.dDirectionComboBox.addItem("")
self.thresholdModeLabel = QtWidgets.QLabel(self.triggerBox)
self.thresholdModeLabel.setGeometry(QtCore.QRect(220*widthRatio, 200*heightRatio, 47*widthRatio, 21*heightRatio))
self.thresholdModeLabel.setObjectName("thresholdModeLabel")
self.cDirectionComboBox = QtWidgets.QComboBox(self.triggerBox)
self.cDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 260*heightRatio, 71*widthRatio, 16*heightRatio))
self.cDirectionComboBox.setObjectName("cDirectionComboBox")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.cDirectionComboBox.addItem("")
self.aDirectionComboBox = QtWidgets.QComboBox(self.triggerBox)
self.aDirectionComboBox.setGeometry(QtCore.QRect(140*widthRatio, 220*heightRatio, 71*widthRatio, 16*heightRatio))
self.aDirectionComboBox.setObjectName("aDirectionComboBox")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.aDirectionComboBox.addItem("")
self.dThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.dThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 280*heightRatio, 61*widthRatio, 16*heightRatio))
self.dThresholdModeComboBox.setObjectName("dThresholdModeComboBox")
self.dThresholdModeComboBox.addItem("")
self.dThresholdModeComboBox.addItem("")
self.bThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.bThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 240*heightRatio, 61*widthRatio, 16*heightRatio))
self.bThresholdModeComboBox.setObjectName("bThresholdModeComboBox")
self.bThresholdModeComboBox.addItem("")
self.bThresholdModeComboBox.addItem("")
self.extThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.extThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 300*heightRatio, 61*widthRatio, 16*heightRatio))
self.extThresholdModeComboBox.setObjectName("extThresholdModeComboBox")
self.extThresholdModeComboBox.addItem("")
self.extThresholdModeComboBox.addItem("")
self.cThresholdModeComboBox = QtWidgets.QComboBox(self.triggerBox)
self.cThresholdModeComboBox.setGeometry(QtCore.QRect(220*widthRatio, 260*heightRatio, 61*widthRatio, 16*heightRatio))
self.cThresholdModeComboBox.setObjectName("cThresholdModeComboBox")
self.cThresholdModeComboBox.addItem("")
self.cThresholdModeComboBox.addItem("")
self.runButton = QtWidgets.QPushButton(self.centralwidget)
self.runButton.setGeometry(QtCore.QRect(720*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio))
self.runButton.setObjectName("runButton")
self.runsLabel = QtWidgets.QLabel(self.centralwidget)
self.runsLabel.setGeometry(QtCore.QRect(120*widthRatio, 70*heightRatio, 47*widthRatio, 16*heightRatio))
self.runsLabel.setObjectName("runsLabel")
self.runsSpinBox = QtWidgets.QSpinBox(self.centralwidget)
self.runsSpinBox.setGeometry(QtCore.QRect(160*widthRatio, 70*heightRatio, 42*widthRatio, 16*heightRatio))
self.runsSpinBox.setObjectName("runsSpinBox")
self.runsSpinBox.setMaximum(999999999)
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(20*widthRatio, 130*heightRatio, 471*widthRatio, 391*heightRatio))
self.tabWidget.setObjectName("tabWidget")
runList['runTab'].append(QtWidgets.QWidget())
runList['runTab'][-1].setObjectName("run_1")
runList['stackedWidget'].append(QtWidgets.QStackedWidget(runList['runTab'][-1]))
runList['stackedWidget'][-1].setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 461*widthRatio, 361*heightRatio))
runList['stackedWidget'][-1].setObjectName("stackedWidget_1")
self.tabWidget.addTab(runList['runTab'][-1], "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 801*widthRatio, 21*heightRatio))
self.menubar.setObjectName("menubar")
self.menuPreset = QtWidgets.QMenu(self.menubar)
self.menuPreset.setObjectName("menuPreset")
MainWindow.setMenuBar(self.menubar)
self.actionLoad_Preset = QtWidgets.QAction(MainWindow)
self.actionLoad_Preset.setObjectName("actionLoad_Preset")
self.actionSave_Preset = QtWidgets.QAction(MainWindow)
self.actionSave_Preset.setObjectName("actionSave_Preset")
self.menuPreset.addAction(self.actionSave_Preset)
self.menuPreset.addAction(self.actionLoad_Preset)
self.menubar.addAction(self.menuPreset.menuAction())
self.nextPushButton = QtWidgets.QPushButton(self.centralwidget)
self.nextPushButton.setGeometry(QtCore.QRect(260*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio))
self.nextPushButton.setObjectName("nextPushButton")
self.pageNumLineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.pageNumLineEdit.setGeometry(QtCore.QRect(232*widthRatio, 531*heightRatio, 21*widthRatio, 20*heightRatio))
self.pageNumLineEdit.setObjectName("pageNumLineEdit")
self.previousPushButton = QtWidgets.QPushButton(self.centralwidget)
self.previousPushButton.setGeometry(QtCore.QRect(150*widthRatio, 530*heightRatio, 75*widthRatio, 23*heightRatio))
self.previousPushButton.setObjectName("previousPushButton")
self.graphCheck = QtWidgets.QCheckBox(self.centralwidget)
self.graphCheck.setGeometry(QtCore.QRect(650*widthRatio, 530*heightRatio, 70*widthRatio, 21*heightRatio))
self.graphCheck.setObjectName("graphCheck")
self.retranslateUi(MainWindow)
self.conditionsTabWidget.setCurrentIndex(0)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Logger"))
self.driverLabel.setText(_translate("MainWindow", "Driver"))
self.presetComboBox.setItemText(0, _translate("MainWindow", "Manual"))
self.presetLabel.setText(_translate("MainWindow", "Preset"))
self.channelBox.setTitle(_translate("MainWindow", "Channels"))
self.aLabel.setText(_translate("MainWindow", "A"))
self.bLabel.setText(_translate("MainWindow", "B"))
self.cLabel.setText(_translate("MainWindow", "C"))
self.dLabel.setText(_translate("MainWindow", "D"))
self.aRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV"))
self.aRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV"))
self.aRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV"))
self.aRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV"))
self.aRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV"))
self.aRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV"))
self.aRangeComboBox.setItemText(6, _translate("MainWindow", "1 V"))
self.aRangeComboBox.setItemText(7, _translate("MainWindow", "2 V"))
self.aRangeComboBox.setItemText(8, _translate("MainWindow", "5 V"))
self.aRangeComboBox.setItemText(9, _translate("MainWindow", "10 V"))
self.aRangeComboBox.setItemText(10, _translate("MainWindow", "20 V"))
self.aRangeComboBox.setItemText(11, _translate("MainWindow", "50 V"))
self.bRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV"))
self.bRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV"))
self.bRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV"))
self.bRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV"))
self.bRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV"))
self.bRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV"))
self.bRangeComboBox.setItemText(6, _translate("MainWindow", "1 V"))
self.bRangeComboBox.setItemText(7, _translate("MainWindow", "2 V"))
self.bRangeComboBox.setItemText(8, _translate("MainWindow", "5 V"))
self.bRangeComboBox.setItemText(9, _translate("MainWindow", "10 V"))
self.bRangeComboBox.setItemText(10, _translate("MainWindow", "20 V"))
self.bRangeComboBox.setItemText(11, _translate("MainWindow", "50 V"))
self.cRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV"))
self.cRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV"))
self.cRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV"))
self.cRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV"))
self.cRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV"))
self.cRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV"))
self.cRangeComboBox.setItemText(6, _translate("MainWindow", "1 V"))
self.cRangeComboBox.setItemText(7, _translate("MainWindow", "2 V"))
self.cRangeComboBox.setItemText(8, _translate("MainWindow", "5 V"))
self.cRangeComboBox.setItemText(9, _translate("MainWindow", "10 V"))
self.cRangeComboBox.setItemText(10, _translate("MainWindow", "20 V"))
self.cRangeComboBox.setItemText(11, _translate("MainWindow", "50 V"))
self.dRangeComboBox.setItemText(0, _translate("MainWindow", "10 mV"))
self.dRangeComboBox.setItemText(1, _translate("MainWindow", "20 mV"))
self.dRangeComboBox.setItemText(2, _translate("MainWindow", "50 mV"))
self.dRangeComboBox.setItemText(3, _translate("MainWindow", "100 mV"))
self.dRangeComboBox.setItemText(4, _translate("MainWindow", "200 mV"))
self.dRangeComboBox.setItemText(5, _translate("MainWindow", "500 mV"))
self.dRangeComboBox.setItemText(6, _translate("MainWindow", "1 V"))
self.dRangeComboBox.setItemText(7, _translate("MainWindow", "2 V"))
self.dRangeComboBox.setItemText(8, _translate("MainWindow", "5 V"))
self.dRangeComboBox.setItemText(9, _translate("MainWindow", "10 V"))
self.dRangeComboBox.setItemText(10, _translate("MainWindow", "20 V"))
self.dRangeComboBox.setItemText(11, _translate("MainWindow", "50 V"))
self.aCouplingComboBox.setItemText(0, _translate("MainWindow", "AC"))
self.aCouplingComboBox.setItemText(1, _translate("MainWindow", "DC"))
self.bCouplingComboBox.setItemText(0, _translate("MainWindow", "AC"))
self.bCouplingComboBox.setItemText(1, _translate("MainWindow", "DC"))
self.cCouplingComboBox.setItemText(0, _translate("MainWindow", "AC"))
self.cCouplingComboBox.setItemText(1, _translate("MainWindow", "DC"))
self.dCouplingComboBox.setItemText(0, _translate("MainWindow", "AC"))
self.dCouplingComboBox.setItemText(1, _translate("MainWindow", "DC"))
self.rangeLabel.setText(_translate("MainWindow", "Range"))
self.offsetLabel.setText(_translate("MainWindow", "Offset"))
self.couplingLabel.setText(_translate("MainWindow", "Coupling"))
self.captureBox.setTitle(_translate("MainWindow", "Capture"))
self.modeComboBox.setItemText(0, _translate("MainWindow", "Block"))
self.modeComboBox.setItemText(1, _translate("MainWindow", "Rapid Block"))
self.modeComboBox.setItemText(2, _translate("MainWindow", "Streaming"))
self.modeLabel.setText(_translate("MainWindow", "Mode"))
self.preTriggerSamplesLabel.setText(_translate("MainWindow", "Pre Trigger Samples"))
self.postTriggerSamplesLabel.setText(_translate("MainWindow", "Post Trigger Samples"))
self.timebaseLabel.setText(_translate("MainWindow", "Timebase"))
self.segmentsLabel.setText(_translate("MainWindow", "Segments"))
self.capturesLabel.setText(_translate("MainWindow", "Captures"))
self.timeUnitsLabel.setText(_translate("MainWindow", "Time Units"))
self.totalRuntimeLabel.setText(_translate("MainWindow", "Total Runtime"))
self.timeUnitsComboBox.setItemText(0, _translate("MainWindow", "fs"))
self.timeUnitsComboBox.setItemText(1, _translate("MainWindow", "ps"))
self.timeUnitsComboBox.setItemText(2, _translate("MainWindow", "ns"))
self.timeUnitsComboBox.setItemText(3, _translate("MainWindow", "μs"))
self.timeUnitsComboBox.setItemText(4, _translate("MainWindow", "ms"))
self.timeUnitsComboBox.setItemText(5, _translate("MainWindow", "s"))
self.samplesPerBufferLabel.setText(_translate("MainWindow", "Samples per Buffer"))
self.outFileCheckBox.setText(_translate("MainWindow", "File Output"))
self.triggerBox.setTitle(_translate("MainWindow", "Trigger"))
self.triggerTypeLabel.setText(_translate("MainWindow", "Type"))
self.triggerTypeComboBox.setItemText(0, _translate("MainWindow", "Simple"))
self.triggerTypeComboBox.setItemText(1, _translate("MainWindow", "Complex"))
self.triggerAutotriggerLabel.setText(_translate("MainWindow", "Auto-Trigger"))
self.triggerDelayLabel.setText(_translate("MainWindow", "Delay"))
self.bTriggerLabel.setText(_translate("MainWindow", "B"))
self.aTriggerLabel.setText(_translate("MainWindow", "A"))
self.cTriggerLabel.setText(_translate("MainWindow", "C"))
self.triggerUpperThresholdLabel.setText(_translate("MainWindow", "Upper Threshold"))
self.dTriggerLabel.setText(_translate("MainWindow", "D"))
self.deleteConditionButton.setText(_translate("MainWindow", "Delete Condition"))
self.newConditionButton.setText(_translate("MainWindow", "New Condition"))
self.triggerUpperHysteresisLabel.setText(_translate("MainWindow", "Upper Hysteresis"))
self.triggerLowerHysteresisLabel.setText(_translate("MainWindow", "Lower Hysteresis"))
self.triggerLowerThresholdLabel.setText(_translate("MainWindow", "Lower Threshold"))
self.extTriggerLabel.setText(_translate("MainWindow", "Ext"))
self.triggerDirectionLabel.setText(_translate("MainWindow", "Direction"))
self.aThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level"))
self.aThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window"))
self.bDirectionComboBox.setItemText(0, _translate("MainWindow", "Above"))
self.bDirectionComboBox.setItemText(1, _translate("MainWindow", "Below"))
self.bDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising"))
self.bDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling"))
self.bDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling"))
self.bDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower"))
self.bDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower"))
self.bDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower"))
self.bDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower"))
self.bDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt"))
self.bDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt"))
self.extDirectionComboBox.setItemText(0, _translate("MainWindow", "Above"))
self.extDirectionComboBox.setItemText(1, _translate("MainWindow", "Below"))
self.extDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising"))
self.extDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling"))
self.extDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling"))
self.extDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower"))
self.extDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower"))
self.extDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower"))
self.extDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower"))
self.extDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt"))
self.extDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt"))
self.dDirectionComboBox.setItemText(0, _translate("MainWindow", "Above"))
self.dDirectionComboBox.setItemText(1, _translate("MainWindow", "Below"))
self.dDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising"))
self.dDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling"))
self.dDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling"))
self.dDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower"))
self.dDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower"))
self.dDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower"))
self.dDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower"))
self.dDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt"))
self.dDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt"))
self.thresholdModeLabel.setText(_translate("MainWindow", "Mode"))
self.cDirectionComboBox.setItemText(0, _translate("MainWindow", "Above"))
self.cDirectionComboBox.setItemText(1, _translate("MainWindow", "Below"))
self.cDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising"))
self.cDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling"))
self.cDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling"))
self.cDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower"))
self.cDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower"))
self.cDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower"))
self.cDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower"))
self.cDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt"))
self.cDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt"))
self.aDirectionComboBox.setItemText(0, _translate("MainWindow", "Above"))
self.aDirectionComboBox.setItemText(1, _translate("MainWindow", "Below"))
self.aDirectionComboBox.setItemText(2, _translate("MainWindow", "Rising"))
self.aDirectionComboBox.setItemText(3, _translate("MainWindow", "Falling"))
self.aDirectionComboBox.setItemText(4, _translate("MainWindow", "Rising or Falling"))
self.aDirectionComboBox.setItemText(5, _translate("MainWindow", "Above Lower"))
self.aDirectionComboBox.setItemText(6, _translate("MainWindow", "Below Lower"))
self.aDirectionComboBox.setItemText(7, _translate("MainWindow", "Rising Lower"))
self.aDirectionComboBox.setItemText(8, _translate("MainWindow", "Falling Lower"))
self.aDirectionComboBox.setItemText(9, _translate("MainWindow", "Positive Runt"))
self.aDirectionComboBox.setItemText(10, _translate("MainWindow", "Negative Runt"))
self.dThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level"))
self.dThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window"))
self.bThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level"))
self.bThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window"))
self.extThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level"))
self.extThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window"))
self.cThresholdModeComboBox.setItemText(0, _translate("MainWindow", "Level"))
self.cThresholdModeComboBox.setItemText(1, _translate("MainWindow", "Window"))
self.runButton.setText(_translate("MainWindow", "Run"))
self.runsLabel.setText(_translate("MainWindow", "Runs"))
self.tabWidget.setTabText(self.tabWidget.indexOf(runList['runTab'][-1]), _translate("MainWindow", "Run 1"))
self.menuPreset.setTitle(_translate("MainWindow", "Presets"))
self.actionLoad_Preset.setText(_translate("MainWindow", "Load Preset"))
self.actionLoad_Preset.setShortcut(_translate("MainWindow", "Ctrl+O"))
self.actionSave_Preset.setText(_translate("MainWindow", "Save Preset"))
self.actionSave_Preset.setShortcut(_translate("MainWindow", "Ctrl+S"))
#Defaults
self.outFileNameLineEdit.setEnabled(False)
self.cCheck.setEnabled(False)
self.dCheck.setEnabled(False)
self.cRangeComboBox.setEnabled(False)
self.dRangeComboBox.setEnabled(False)
self.cOffsetSpinBox.setEnabled(False)
self.dOffsetSpinBox.setEnabled(False)
self.cCouplingComboBox.setEnabled(False)
self.dCouplingComboBox.setEnabled(False)
self.cTriggerCheck.setEnabled(False)
self.dTriggerCheck.setEnabled(False)
self.extTriggerCheck.setEnabled(False)
self.cUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.cUpperHysteresisSpinBox.setEnabled(False)
self.dUpperHysteresisSpinBox.setEnabled(False)
self.extUpperHysteresisSpinBox.setEnabled(False)
self.cLowerThresholdSpinBox.setEnabled(False)
self.dLowerThresholdSpinBox.setEnabled(False)
self.extLowerThresholdSpinBox.setEnabled(False)
self.cLowerHysteresisSpinBox.setEnabled(False)
self.dLowerHysteresisSpinBox.setEnabled(False)
self.extLowerHysteresisSpinBox.setEnabled(False)
conditionList['cStateComboBox'][-1].setEnabled(False)
conditionList['dStateComboBox'][-1].setEnabled(False)
conditionList['extStateComboBox'][-1].setEnabled(False)
self.cDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
self.cThresholdModeComboBox.setEnabled(False)
self.dThresholdModeComboBox.setEnabled(False)
self.extThresholdModeComboBox.setEnabled(False)
self.totalRuntimeSpinBox.setEnabled(False)
self.timeUnitsComboBox.setEnabled(False)
self.segmentsSpinBox.setEnabled(False)
self.capturesSpinBox.setEnabled(False)
self.samplesPerBufferSpinBox.setEnabled(False)
self.aUpperHysteresisSpinBox.setEnabled(False)
self.bUpperHysteresisSpinBox.setEnabled(False)
self.cUpperHysteresisSpinBox.setEnabled(False)
self.dUpperHysteresisSpinBox.setEnabled(False)
self.aLowerThresholdSpinBox.setEnabled(False)
self.bLowerThresholdSpinBox.setEnabled(False)
self.cLowerThresholdSpinBox.setEnabled(False)
self.dLowerThresholdSpinBox.setEnabled(False)
self.aLowerHysteresisSpinBox.setEnabled(False)
self.bLowerHysteresisSpinBox.setEnabled(False)
self.cLowerHysteresisSpinBox.setEnabled(False)
self.dLowerHysteresisSpinBox.setEnabled(False)
self.aThresholdModeComboBox.setEnabled(False)
self.bThresholdModeComboBox.setEnabled(False)
self.cThresholdModeComboBox.setEnabled(False)
self.dThresholdModeComboBox.setEnabled(False)
conditionList['aStateComboBox'][-1].setEnabled(False)
conditionList['bStateComboBox'][-1].setEnabled(False)
self.newConditionButton.setEnabled(False)
self.deleteConditionButton.setEnabled(False)
self.aRangeComboBox.model().item(0).setEnabled(False)
self.aRangeComboBox.model().item(11).setEnabled(False)
self.bRangeComboBox.model().item(0).setEnabled(False)
self.bRangeComboBox.model().item(11).setEnabled(False)
self.aRangeComboBox.setCurrentIndex(1)
self.bRangeComboBox.setCurrentIndex(1)
self.timeUnitsComboBox.setCurrentText('ns')
self.aAutotriggerSpinBox.setValue(0)
self.runsSpinBox.setMinimum(1)
self.timebaseSpinBox.setMinimum(1)
self.segmentsSpinBox.setMinimum(1)
self.capturesSpinBox.setMinimum(1)
self.totalRuntimeSpinBox.setMinimum(1)
self.preTriggerSamplesSpinBox.setMinimum(0)
self.postTriggerSamplesSpinBox.setMinimum(0)
self.samplesPerBufferSpinBox.setMinimum(1)
self.aUpperThresholdSpinBox.setMinimum(-32512)
self.aUpperHysteresisSpinBox.setMinimum(-32512)
self.aLowerThresholdSpinBox.setMinimum(-32512)
self.aLowerHysteresisSpinBox.setMinimum(-32512)
self.bUpperThresholdSpinBox.setMinimum(-32512)
self.bUpperHysteresisSpinBox.setMinimum(-32512)
self.bLowerThresholdSpinBox.setMinimum(-32512)
self.bLowerHysteresisSpinBox.setMinimum(-32512)
self.cUpperThresholdSpinBox.setMinimum(-32512)
self.cUpperHysteresisSpinBox.setMinimum(-32512)
self.cLowerThresholdSpinBox.setMinimum(-32512)
self.cLowerHysteresisSpinBox.setMinimum(-32512)
self.dUpperThresholdSpinBox.setMinimum(-32512)
self.dUpperHysteresisSpinBox.setMinimum(-32512)
self.dLowerThresholdSpinBox.setMinimum(-32512)
self.dLowerHysteresisSpinBox.setMinimum(-32512)
self.extUpperThresholdSpinBox.setMinimum(-32767)
self.extUpperHysteresisSpinBox.setMinimum(-32767)
self.extLowerThresholdSpinBox.setMinimum(-32767)
self.extLowerHysteresisSpinBox.setMinimum(-32767)
self.pageNumLineEdit.setText('1')
self.pageNumLineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.nextPushButton.setText(_translate("MainWindow", "Next"))
self.nextPushButton.setEnabled(False)
self.previousPushButton.setText(_translate("MainWindow", "Previous"))
self.previousPushButton.setEnabled(False)
self.graphCheck.setText(_translate("MainWindow", "Graphing"))
self.graphCheck.setChecked(True)
f = open('driver.log', 'r')
self.driverLineEdit.setText(f.readline().replace('\n', ''))
f.close()
self.driverChannelCheck()
dir = os.path.join('.', 'presets')
if not os.path.exists(dir):
os.mkdir(dir)
presetList = os.listdir('./presets')
for i in range(len(presetList)):
if presetList[i].split('.')[1] =='prst':
f = open('./presets/'+presetList[i], 'r')
driver = f.readline().replace('\n', '')
if self.driverLineEdit.text() != driver:
continue
f.close()
self.presetComboBox.addItem(presetList[i].split('.')[0])
#Actions
self.outFileCheckBox.clicked.connect(self.fileOutCheck)
self.modeComboBox.currentTextChanged.connect(self.captureModeCheck)
self.triggerTypeComboBox.currentTextChanged.connect(self.triggerTypeCheck)
self.newConditionButton.clicked.connect(self.newCondition)
self.deleteConditionButton.clicked.connect(self.deleteCondition)
self.actionSave_Preset.triggered.connect(self.savePreset)
self.actionLoad_Preset.triggered.connect(self.loadPreset)
self.presetComboBox.currentTextChanged.connect(self.loadDetectedPreset)
self.runButton.clicked.connect(self.run)
self.aTriggerCheck.clicked.connect(self.simpleTriggerCheck)
self.bTriggerCheck.clicked.connect(self.simpleTriggerCheck)
self.cTriggerCheck.clicked.connect(self.simpleTriggerCheck)
self.dTriggerCheck.clicked.connect(self.simpleTriggerCheck)
self.extTriggerCheck.clicked.connect(self.simpleTriggerCheck)
self.nextPushButton.clicked.connect(self.nextPage)
self.pageNumLineEdit.textChanged.connect(self.pageChangeCheck)
self.previousPushButton.clicked.connect(self.previousPage)
self.tabWidget.currentChanged.connect(self.runTabChange)
self.graphCheck.clicked.connect(self.graphing)
def graphing(self):
self.tabWidget.setEnabled(int(self.graphCheck.checkState()))
def nextPage(self):
self.pageNumLineEdit.setText(str(int(self.pageNumLineEdit.text())+1))
def previousPage(self):
self.pageNumLineEdit.setText(str(int(self.pageNumLineEdit.text())-1))
def pageChangeCheck(self):
try:
self.pageNumLineEdit.setText(str(int(float(self.pageNumLineEdit.text()))))
if int(float(self.pageNumLineEdit.text())) > len(runList['captureTab'][self.tabWidget.currentIndex()]):
self.pageNumLineEdit.setText(str(len(runList['captureTab'][self.tabWidget.currentIndex()])))
elif int(float(self.pageNumLineEdit.text())) < 1:
self.pageNumLineEdit.setText('1')
if int(float(self.pageNumLineEdit.text())) == len(runList['captureTab'][self.tabWidget.currentIndex()]):
self.nextPushButton.setEnabled(False)
else:
self.nextPushButton.setEnabled(True)
if int(float(self.pageNumLineEdit.text())) == 1:
self.previousPushButton.setEnabled(False)
else:
self.previousPushButton.setEnabled(True)
runList['stackedWidget'][self.tabWidget.currentIndex()].setCurrentIndex(int(float(self.pageNumLineEdit.text()))-1)
except:
pass
def runTabChange(self):
self.pageNumLineEdit.setText(str(runList['stackedWidget'][self.tabWidget.currentIndex()].currentIndex()+1))
def fileOutCheck(self):
if self.outFileCheckBox.isChecked():
self.outFileNameLineEdit.setEnabled(True)
else:
self.outFileNameLineEdit.setText('')
self.outFileNameLineEdit.setEnabled(False)
def driverChannelCheck(self):
driver_replacement(self.driverLineEdit.text())
if str(self.driverLineEdit.text()) == 'ps2000a':
self.cCheck.setEnabled(False)
self.cCheck.setChecked(False)
self.dCheck.setEnabled(False)
self.dCheck.setChecked(False)
self.cRangeComboBox.setEnabled(False)
self.dRangeComboBox.setEnabled(False)
self.cOffsetSpinBox.setEnabled(False)
self.dOffsetSpinBox.setEnabled(False)
self.cCouplingComboBox.setEnabled(False)
self.dCouplingComboBox.setEnabled(False)
self.aTriggerCheck.setEnabled(True)
self.bTriggerCheck.setEnabled(True)
self.cTriggerCheck.setEnabled(False)
self.cTriggerCheck.setChecked(False)
self.dTriggerCheck.setEnabled(False)
self.dTriggerCheck.setChecked(False)
self.extTriggerCheck.setEnabled(False)
self.extTriggerCheck.setChecked(False)
self.aUpperThresholdSpinBox.setEnabled(True)
self.bUpperThresholdSpinBox.setEnabled(True)
self.cUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.cUpperHysteresisSpinBox.setEnabled(False)
self.dUpperHysteresisSpinBox.setEnabled(False)
self.extUpperHysteresisSpinBox.setEnabled(False)
self.cLowerThresholdSpinBox.setEnabled(False)
self.dLowerThresholdSpinBox.setEnabled(False)
self.extLowerThresholdSpinBox.setEnabled(False)
self.cLowerHysteresisSpinBox.setEnabled(False)
self.dLowerHysteresisSpinBox.setEnabled(False)
self.extLowerHysteresisSpinBox.setEnabled(False)
for i in range(len(conditionList['aStateComboBox'])):
conditionList['cStateComboBox'][i].setEnabled(False)
conditionList['dStateComboBox'][i].setEnabled(False)
conditionList['extStateComboBox'][i].setEnabled(False)
self.aDirectionComboBox.setEnabled(True)
self.bDirectionComboBox.setEnabled(True)
self.cDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
self.cThresholdModeComboBox.setEnabled(False)
self.dThresholdModeComboBox.setEnabled(False)
self.extThresholdModeComboBox.setEnabled(False)
self.aRangeComboBox.model().item(0).setEnabled(False)
self.aRangeComboBox.model().item(11).setEnabled(False)
self.bRangeComboBox.model().item(0).setEnabled(False)
self.bRangeComboBox.model().item(11).setEnabled(False)
elif str(self.driverLineEdit.text()) == 'ps3000a':
self.cCheck.setEnabled(True)
self.dCheck.setEnabled(True)
self.cRangeComboBox.setEnabled(True)
self.dRangeComboBox.setEnabled(True)
self.cOffsetSpinBox.setEnabled(True)
self.dOffsetSpinBox.setEnabled(True)
self.cCouplingComboBox.setEnabled(True)
self.dCouplingComboBox.setEnabled(True)
self.aRangeComboBox.model().item(0).setEnabled(True)
self.aRangeComboBox.model().item(11).setEnabled(True)
self.bRangeComboBox.model().item(0).setEnabled(True)
self.bRangeComboBox.model().item(11).setEnabled(True)
if (str(self.triggerTypeComboBox.currentText()) == 'Simple' and not (self.aTriggerCheck.isChecked() or self.bTriggerCheck.isChecked())) or str(self.triggerTypeComboBox.currentText()) == 'Complex':
self.cTriggerCheck.setEnabled(True)
self.dTriggerCheck.setEnabled(True)
self.extTriggerCheck.setEnabled(True)
self.cUpperThresholdSpinBox.setEnabled(True)
self.dUpperThresholdSpinBox.setEnabled(True)
self.extUpperThresholdSpinBox.setEnabled(True)
self.cDirectionComboBox.setEnabled(True)
self.dDirectionComboBox.setEnabled(True)
self.extDirectionComboBox.setEnabled(True)
if str(self.triggerTypeComboBox.currentText()) == 'Complex':
self.cUpperHysteresisSpinBox.setEnabled(True)
self.dUpperHysteresisSpinBox.setEnabled(True)
self.extUpperHysteresisSpinBox.setEnabled(True)
self.cLowerThresholdSpinBox.setEnabled(True)
self.dLowerThresholdSpinBox.setEnabled(True)
self.extLowerThresholdSpinBox.setEnabled(True)
self.cLowerHysteresisSpinBox.setEnabled(True)
self.dLowerHysteresisSpinBox.setEnabled(True)
self.extLowerHysteresisSpinBox.setEnabled(True)
for i in range(len(conditionList['aStateComboBox'])):
conditionList['cStateComboBox'][i].setEnabled(True)
conditionList['dStateComboBox'][i].setEnabled(True)
conditionList['extStateComboBox'][i].setEnabled(True)
self.cThresholdModeComboBox.setEnabled(True)
self.dThresholdModeComboBox.setEnabled(True)
self.extThresholdModeComboBox.setEnabled(True)
def captureModeCheck(self):
if str(self.modeComboBox.currentText()) == 'Block':
self.timebaseSpinBox.setEnabled(True)
self.totalRuntimeSpinBox.setEnabled(False)
self.totalRuntimeSpinBox.setValue(1)
self.timeUnitsComboBox.setEnabled(False)
self.timeUnitsComboBox.setCurrentText('ns')
self.capturesSpinBox.setEnabled(False)
self.capturesSpinBox.setValue(1)
self.samplesPerBufferSpinBox.setEnabled(False)
self.samplesPerBufferSpinBox.setValue(1)
self.segmentsSpinBox.setEnabled(False)
self.segmentsSpinBox.setValue(1)
elif str(self.modeComboBox.currentText()) == 'Rapid Block':
self.timebaseSpinBox.setEnabled(True)
self.totalRuntimeSpinBox.setEnabled(False)
self.totalRuntimeSpinBox.setValue(1)
self.timeUnitsComboBox.setEnabled(False)
self.timeUnitsComboBox.setCurrentText('ns')
self.capturesSpinBox.setEnabled(True)
self.samplesPerBufferSpinBox.setEnabled(False)
self.samplesPerBufferSpinBox.setValue(1)
self.segmentsSpinBox.setEnabled(True)
elif str(self.modeComboBox.currentText()) == 'Streaming':
self.timebaseSpinBox.setEnabled(False)
self.timebaseSpinBox.setValue(1)
self.totalRuntimeSpinBox.setEnabled(True)
self.timeUnitsComboBox.setEnabled(True)
self.capturesSpinBox.setEnabled(False)
self.capturesSpinBox.setValue(1)
self.samplesPerBufferSpinBox.setEnabled(True)
self.segmentsSpinBox.setEnabled(True)
def triggerTypeCheck(self):
if str(self.triggerTypeComboBox.currentText()) == 'Simple':
self.simpleTriggerCheck()
checkCount = 0
if bool(int(self.aTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps2000a':
checkCount += 1
self.aTriggerCheck.setEnabled(True)
self.aUpperThresholdSpinBox.setEnabled(True)
self.aDirectionComboBox.setEnabled(True)
if bool(int(self.bTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps2000a':
checkCount += 1
self.bTriggerCheck.setEnabled(True)
self.bUpperThresholdSpinBox.setEnabled(True)
self.bDirectionComboBox.setEnabled(True)
if bool(int(self.cTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a':
checkCount += 1
self.cTriggerCheck.setEnabled(True)
self.cUpperThresholdSpinBox.setEnabled(True)
self.cDirectionComboBox.setEnabled(True)
if bool(int(self.dTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a':
checkCount += 1
self.dTriggerCheck.setEnabled(True)
self.dUpperThresholdSpinBox.setEnabled(True)
self.dDirectionComboBox.setEnabled(True)
if bool(int(self.extTriggerCheck.checkState())) and str(self.driverLineEdit.text()) == 'ps3000a':
checkCount += 1
self.extTriggerCheck.setEnabled(True)
self.extUpperThresholdSpinBox.setEnabled(True)
self.extDirectionComboBox.setEnabled(True)
if checkCount > 1:
self.aTriggerCheck.setChecked(False)
self.bTriggerCheck.setChecked(False)
self.cTriggerCheck.setChecked(False)
self.dTriggerCheck.setChecked(False)
self.extTriggerCheck.setChecked(False)
self.aUpperHysteresisSpinBox.setEnabled(False)
self.bUpperHysteresisSpinBox.setEnabled(False)
self.cUpperHysteresisSpinBox.setEnabled(False)
self.dUpperHysteresisSpinBox.setEnabled(False)
self.extUpperHysteresisSpinBox.setEnabled(False)
self.aLowerThresholdSpinBox.setEnabled(False)
self.bLowerThresholdSpinBox.setEnabled(False)
self.cLowerThresholdSpinBox.setEnabled(False)
self.dLowerThresholdSpinBox.setEnabled(False)
self.extLowerThresholdSpinBox.setEnabled(False)
self.aLowerHysteresisSpinBox.setEnabled(False)
self.bLowerHysteresisSpinBox.setEnabled(False)
self.cLowerHysteresisSpinBox.setEnabled(False)
self.dLowerHysteresisSpinBox.setEnabled(False)
self.extLowerHysteresisSpinBox.setEnabled(False)
self.aThresholdModeComboBox.setEnabled(False)
self.bThresholdModeComboBox.setEnabled(False)
self.cThresholdModeComboBox.setEnabled(False)
self.dThresholdModeComboBox.setEnabled(False)
self.extThresholdModeComboBox.setEnabled(False)
for i in range(len(conditionList['aStateComboBox'])):
conditionList['aStateComboBox'][i].setEnabled(False)
conditionList['bStateComboBox'][i].setEnabled(False)
conditionList['cStateComboBox'][i].setEnabled(False)
conditionList['dStateComboBox'][i].setEnabled(False)
conditionList['extStateComboBox'][i].setEnabled(False)
self.newConditionButton.setEnabled(False)
self.deleteConditionButton.setEnabled(False)
elif str(self.triggerTypeComboBox.currentText()) == 'Complex':
self.aTriggerCheck.setEnabled(True)
self.bTriggerCheck.setEnabled(True)
self.aUpperThresholdSpinBox.setEnabled(True)
self.bUpperThresholdSpinBox.setEnabled(True)
self.aUpperHysteresisSpinBox.setEnabled(True)
self.bUpperHysteresisSpinBox.setEnabled(True)
self.aLowerThresholdSpinBox.setEnabled(True)
self.bLowerThresholdSpinBox.setEnabled(True)
self.aLowerHysteresisSpinBox.setEnabled(True)
self.bLowerHysteresisSpinBox.setEnabled(True)
self.aThresholdModeComboBox.setEnabled(True)
self.bThresholdModeComboBox.setEnabled(True)
self.aDirectionComboBox.setEnabled(True)
self.bDirectionComboBox.setEnabled(True)
for i in range(len(conditionList['aStateComboBox'])):
conditionList['aStateComboBox'][i].setEnabled(True)
conditionList['bStateComboBox'][i].setEnabled(True)
self.newConditionButton.setEnabled(True)
self.deleteConditionButton.setEnabled(True)
if str(self.driverLineEdit.text()) == 'ps3000a':
self.cTriggerCheck.setEnabled(True)
self.dTriggerCheck.setEnabled(True)
self.extTriggerCheck.setEnabled(True)
self.cUpperThresholdSpinBox.setEnabled(True)
self.dUpperThresholdSpinBox.setEnabled(True)
self.extUpperThresholdSpinBox.setEnabled(True)
self.cUpperHysteresisSpinBox.setEnabled(True)
self.dUpperHysteresisSpinBox.setEnabled(True)
self.extUpperHysteresisSpinBox.setEnabled(True)
self.cLowerThresholdSpinBox.setEnabled(True)
self.dLowerThresholdSpinBox.setEnabled(True)
self.extLowerThresholdSpinBox.setEnabled(True)
self.cLowerHysteresisSpinBox.setEnabled(True)
self.dLowerHysteresisSpinBox.setEnabled(True)
self.extLowerHysteresisSpinBox.setEnabled(True)
self.cThresholdModeComboBox.setEnabled(True)
self.dThresholdModeComboBox.setEnabled(True)
self.extThresholdModeComboBox.setEnabled(True)
self.cDirectionComboBox.setEnabled(True)
self.dDirectionComboBox.setEnabled(True)
self.extDirectionComboBox.setEnabled(True)
for i in range(len(conditionList['aStateComboBox'])):
conditionList['cStateComboBox'][i].setEnabled(True)
conditionList['dStateComboBox'][i].setEnabled(True)
conditionList['extStateComboBox'][i].setEnabled(True)
def newCondition(self):
_translate = QtCore.QCoreApplication.translate
conditionList['conditionTab'].append(QtWidgets.QWidget())
conditionList['conditionTab'][-1].setObjectName("condition"+str(len(conditionList['conditionTab']))+"Tab")
conditionList['extConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['extConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 100*heightRatio, 16*widthRatio, 16*heightRatio))
conditionList['extConditionLabel'][-1].setObjectName("extConditionLabel")
conditionList['aConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['aConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 20*heightRatio, 16*widthRatio, 16*heightRatio))
conditionList['aConditionLabel'][-1].setObjectName("aConditionLabel")
conditionList['bConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['bConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 40*heightRatio, 16*widthRatio, 16*heightRatio))
conditionList['bConditionLabel'][-1].setObjectName("bConditionLabel")
conditionList['cConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['cConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 60*heightRatio, 16*widthRatio, 16*heightRatio))
conditionList['cConditionLabel'][-1].setObjectName("cConditionLabel")
conditionList['dConditionLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['dConditionLabel'][-1].setGeometry(QtCore.QRect(10*widthRatio, 80*heightRatio, 16*widthRatio, 16*heightRatio))
conditionList['dConditionLabel'][-1].setObjectName("dConditionLabel")
conditionList['aStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1]))
conditionList['aStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 20*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['aStateComboBox'][-1].setObjectName("aStateComboBox")
conditionList['aStateComboBox'][-1].addItem("")
conditionList['aStateComboBox'][-1].addItem("")
conditionList['aStateComboBox'][-1].addItem("")
conditionList['bStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1]))
conditionList['bStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 40*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['bStateComboBox'][-1].setObjectName("bStateComboBox")
conditionList['bStateComboBox'][-1].addItem("")
conditionList['bStateComboBox'][-1].addItem("")
conditionList['bStateComboBox'][-1].addItem("")
conditionList['cStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1]))
conditionList['cStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 60*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['cStateComboBox'][-1].setObjectName("cStateComboBox")
conditionList['cStateComboBox'][-1].addItem("")
conditionList['cStateComboBox'][-1].addItem("")
conditionList['cStateComboBox'][-1].addItem("")
conditionList['dStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1]))
conditionList['dStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 80*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['dStateComboBox'][-1].setObjectName("dStateComboBox")
conditionList['dStateComboBox'][-1].addItem("")
conditionList['dStateComboBox'][-1].addItem("")
conditionList['dStateComboBox'][-1].addItem("")
conditionList['extStateComboBox'].append(QtWidgets.QComboBox(conditionList['conditionTab'][-1]))
conditionList['extStateComboBox'][-1].setGeometry(QtCore.QRect(30*widthRatio, 100*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['extStateComboBox'][-1].setObjectName("extStateComboBox")
conditionList['extStateComboBox'][-1].addItem("")
conditionList['extStateComboBox'][-1].addItem("")
conditionList['extStateComboBox'][-1].addItem("")
conditionList['stateLabel'].append(QtWidgets.QLabel(conditionList['conditionTab'][-1]))
conditionList['stateLabel'][-1].setGeometry(QtCore.QRect(30*widthRatio, 0*heightRatio, 81*widthRatio, 16*heightRatio))
conditionList['stateLabel'][-1].setObjectName("stateLabel")
self.conditionsTabWidget.addTab(conditionList['conditionTab'][-1], "")
conditionList['extConditionLabel'][-1].setText(_translate("MainWindow", "Ext"))
conditionList['aConditionLabel'][-1].setText(_translate("MainWindow", "A"))
conditionList['bConditionLabel'][-1].setText(_translate("MainWindow", "B"))
conditionList['cConditionLabel'][-1].setText(_translate("MainWindow", "C"))
conditionList['dConditionLabel'][-1].setText(_translate("MainWindow", "D"))
conditionList['aStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care"))
conditionList['aStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True"))
conditionList['aStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False"))
conditionList['bStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care"))
conditionList['bStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True"))
conditionList['bStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False"))
conditionList['cStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care"))
conditionList['cStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True"))
conditionList['cStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False"))
conditionList['dStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care"))
conditionList['dStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True"))
conditionList['dStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False"))
conditionList['extStateComboBox'][-1].setItemText(0, _translate("MainWindow", "Don\'t Care"))
conditionList['extStateComboBox'][-1].setItemText(1, _translate("MainWindow", "True"))
conditionList['extStateComboBox'][-1].setItemText(2, _translate("MainWindow", "False"))
conditionList['stateLabel'][-1].setText(_translate("MainWindow", "State Condition"))
self.conditionsTabWidget.setTabText(self.conditionsTabWidget.indexOf(conditionList['conditionTab'][-1]), _translate("MainWindow", str(len(conditionList['conditionTab']))))
conditionList['aStateComboBox'][-1].setEnabled(False)
conditionList['bStateComboBox'][-1].setEnabled(False)
conditionList['cStateComboBox'][-1].setEnabled(False)
conditionList['dStateComboBox'][-1].setEnabled(False)
conditionList['extStateComboBox'][-1].setEnabled(False)
self.triggerTypeCheck()
def deleteCondition(self):
_translate = QtCore.QCoreApplication.translate
indx = self.conditionsTabWidget.currentIndex()
self.conditionsTabWidget.removeTab(indx)
if len(conditionList['aStateComboBox']) == 0:
return 0
for name in conditionList:
conditionList[name].pop(indx)
for i in range(indx, len(conditionList['aStateComboBox'])):
self.conditionsTabWidget.setTabText(self.conditionsTabWidget.indexOf(conditionList['conditionTab'][i]), _translate("MainWindow", str(i+1)))
def savePreset(self):
_translate = QtCore.QCoreApplication.translate
if self.presetComboBox.currentText() == 'Manual':
presetFileName, ok = QtWidgets.QInputDialog().getText(MainWindow, 'New Preset', 'New Preset File Name:', QtWidgets.QLineEdit.Normal, QtCore.QDir().home().dirName())
else:
presetFileName = self.presetComboBox.currentText()
if presetFileName == '':
return 0
f = open('presets/'+presetFileName+'.prst', 'w')
f.write(self.driverLineEdit.text()+'\n')
f.write(str(self.outFileCheckBox.checkState())+'\n')
f.write(self.outFileNameLineEdit.text()+'\n')
f.write(self.runsSpinBox.text()+'\n')
f.write(str(self.aCheck.checkState())+'\n')
f.write(str(self.bCheck.checkState())+'\n')
f.write(str(self.cCheck.checkState())+'\n')
f.write(str(self.dCheck.checkState())+'\n')
f.write(self.aRangeComboBox.currentText()+'\n')
f.write(self.bRangeComboBox.currentText()+'\n')
f.write(self.cRangeComboBox.currentText()+'\n')
f.write(self.dRangeComboBox.currentText()+'\n')
f.write(self.aOffsetSpinBox.text()+'\n')
f.write(self.bOffsetSpinBox.text()+'\n')
f.write(self.cOffsetSpinBox.text()+'\n')
f.write(self.dOffsetSpinBox.text()+'\n')
f.write(self.modeComboBox.currentText()+'\n')
f.write(self.timebaseSpinBox.text()+'\n')
f.write(self.segmentsSpinBox.text()+'\n')
f.write(self.capturesSpinBox.text()+'\n')
f.write(self.totalRuntimeSpinBox.text()+'\n')
f.write(self.timeUnitsComboBox.currentText()+'\n')
f.write(self.preTriggerSamplesSpinBox.text()+'\n')
f.write(self.postTriggerSamplesSpinBox.text()+'\n')
f.write(self.samplesPerBufferSpinBox.text()+'\n')
f.write(self.triggerTypeComboBox.currentText()+'\n')
f.write(self.aAutotriggerSpinBox.text()+'\n')
f.write(self.aDelaySpinBox.text()+'\n')
f.write(str(self.aTriggerCheck.checkState())+'\n')
f.write(str(self.bTriggerCheck.checkState())+'\n')
f.write(str(self.cTriggerCheck.checkState())+'\n')
f.write(str(self.dTriggerCheck.checkState())+'\n')
f.write(str(self.extTriggerCheck.checkState())+'\n')
f.write(self.aUpperThresholdSpinBox.text()+'\n')
f.write(self.bUpperThresholdSpinBox.text()+'\n')
f.write(self.cUpperThresholdSpinBox.text()+'\n')
f.write(self.dUpperThresholdSpinBox.text()+'\n')
f.write(self.extUpperThresholdSpinBox.text()+'\n')
f.write(self.aUpperHysteresisSpinBox.text()+'\n')
f.write(self.bUpperHysteresisSpinBox.text()+'\n')
f.write(self.cUpperHysteresisSpinBox.text()+'\n')
f.write(self.dUpperHysteresisSpinBox.text()+'\n')
f.write(self.extUpperHysteresisSpinBox.text()+'\n')
f.write(self.aLowerThresholdSpinBox.text()+'\n')
f.write(self.bLowerThresholdSpinBox.text()+'\n')
f.write(self.cLowerThresholdSpinBox.text()+'\n')
f.write(self.dLowerThresholdSpinBox.text()+'\n')
f.write(self.extLowerThresholdSpinBox.text()+'\n')
f.write(self.aLowerHysteresisSpinBox.text()+'\n')
f.write(self.bLowerHysteresisSpinBox.text()+'\n')
f.write(self.cLowerHysteresisSpinBox.text()+'\n')
f.write(self.dLowerHysteresisSpinBox.text()+'\n')
f.write(self.extLowerHysteresisSpinBox.text()+'\n')
f.write(self.aDirectionComboBox.currentText()+'\n')
f.write(self.bDirectionComboBox.currentText()+'\n')
f.write(self.cDirectionComboBox.currentText()+'\n')
f.write(self.dDirectionComboBox.currentText()+'\n')
f.write(self.extDirectionComboBox.currentText()+'\n')
f.write(self.aThresholdModeComboBox.currentText()+'\n')
f.write(self.bThresholdModeComboBox.currentText()+'\n')
f.write(self.cThresholdModeComboBox.currentText()+'\n')
f.write(self.dThresholdModeComboBox.currentText()+'\n')
f.write(self.extThresholdModeComboBox.currentText()+'\n')
f.write(str(len(conditionList['aStateComboBox']))+'\n')
for name in conditionList:
if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']:
continue
for element in conditionList[name]:
f.write(element.currentText()+'\n')
f.close()
self.presetComboBox.addItem(presetFileName)
self.presetComboBox.setCurrentText(presetFileName)
def loadPreset(self):
presetFilePath = QtWidgets.QFileDialog.getOpenFileName(MainWindow, 'Find Preset File', '.')
if presetFilePath[0] == '':
return 0
f = open(presetFilePath[0], 'r')
driver = f.readline().replace('\n', '')
if self.driverLineEdit.text() != driver:
self.error = QtWidgets.QMessageBox()
self.error.setWindowTitle('Error')
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(".\\icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.error.setWindowIcon(icon)
self.error.setText('Incompatible Driver Preset')
self.error.setIcon(QtWidgets.QMessageBox.Information)
ok = self.error.exec_()
return 0
self.outFileCheckBox.setCheckState(int(f.readline().replace('\n', '')))
self.outFileNameLineEdit.setText(f.readline().replace('\n', ''))
self.runsSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aCheck.setCheckState(int(f.readline().replace('\n', '')))
self.bCheck.setCheckState(int(f.readline().replace('\n', '')))
self.cCheck.setCheckState(int(f.readline().replace('\n', '')))
self.dCheck.setCheckState(int(f.readline().replace('\n', '')))
self.aRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.bOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.cOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.dOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.modeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.timebaseSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.segmentsSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.capturesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.totalRuntimeSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.timeUnitsComboBox.setCurrentText(f.readline().replace('\n', ''))
self.preTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.postTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.samplesPerBufferSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.triggerTypeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aAutotriggerSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aDelaySpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.bTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.cTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.dTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.extTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.aUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.extDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.extThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
for i in range(len(conditionList['aStateComboBox'])):
self.deleteCondition()
conditionNum = int(f.readline().replace('\n', ''))
for i in range(conditionNum):
self.newCondition()
for name in conditionList:
if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']:
continue
for i in range(conditionNum):
conditionList[name][i].setCurrentText(f.readline().replace('\n', ''))
f.close()
self.presetComboBox.setCurrentText(str(os.path.basename(presetFilePath[0])).split('.')[0])
def loadDetectedPreset(self):
if self.presetComboBox.currentText() == 'Manual':
return 0
presetFilePath = ['./presets/'+str(self.presetComboBox.currentText())+'.prst']
f = open(presetFilePath[0], 'r')
self.driverLineEdit.setText(f.readline().replace('\n', ''))
self.outFileCheckBox.setCheckState(int(f.readline().replace('\n', '')))
self.outFileNameLineEdit.setText(f.readline().replace('\n', ''))
self.runsSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aCheck.setCheckState(int(f.readline().replace('\n', '')))
self.bCheck.setCheckState(int(f.readline().replace('\n', '')))
self.cCheck.setCheckState(int(f.readline().replace('\n', '')))
self.dCheck.setCheckState(int(f.readline().replace('\n', '')))
self.aRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dRangeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.bOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.cOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.dOffsetSpinBox.setValue(float(f.readline().replace('\n', '')))
self.modeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.timebaseSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.segmentsSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.capturesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.totalRuntimeSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.timeUnitsComboBox.setCurrentText(f.readline().replace('\n', ''))
self.preTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.postTriggerSamplesSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.samplesPerBufferSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.triggerTypeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aAutotriggerSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aDelaySpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.bTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.cTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.dTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.extTriggerCheck.setCheckState(int(f.readline().replace('\n', '')))
self.aUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extUpperThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extUpperHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extLowerThresholdSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.bLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.cLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.dLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.extLowerHysteresisSpinBox.setValue(int(float(f.readline().replace('\n', ''))))
self.aDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.extDirectionComboBox.setCurrentText(f.readline().replace('\n', ''))
self.aThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.bThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.cThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.dThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
self.extThresholdModeComboBox.setCurrentText(f.readline().replace('\n', ''))
for i in range(len(conditionList['aStateComboBox'])):
self.deleteCondition()
conditionNum = int(f.readline().replace('\n', ''))
for i in range(conditionNum):
self.newCondition()
for name in conditionList:
if name in ['conditionTab', 'extConditionLabel', 'aConditionLabel', 'bConditionLabel', 'cConditionLabel', 'dConditionLabel', 'stateLabel']:
continue
for i in range(conditionNum):
conditionList[name][i].setCurrentText(f.readline().replace('\n', ''))
f.close()
def autodetect(self):
self.driverLineEdit.setText(driver_autodetect())
def simpleTriggerCheck(self):
if self.triggerTypeComboBox.currentText() == 'Simple':
if bool(int(self.aTriggerCheck.checkState())):
self.bTriggerCheck.setEnabled(False)
self.cTriggerCheck.setEnabled(False)
self.dTriggerCheck.setEnabled(False)
self.extTriggerCheck.setEnabled(False)
self.bUpperThresholdSpinBox.setEnabled(False)
self.cUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.bDirectionComboBox.setEnabled(False)
self.cDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
elif bool(int(self.bTriggerCheck.checkState())):
self.aTriggerCheck.setEnabled(False)
self.cTriggerCheck.setEnabled(False)
self.dTriggerCheck.setEnabled(False)
self.extTriggerCheck.setEnabled(False)
self.aUpperThresholdSpinBox.setEnabled(False)
self.cUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.aDirectionComboBox.setEnabled(False)
self.cDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
elif bool(int(self.cTriggerCheck.checkState())):
self.aTriggerCheck.setEnabled(False)
self.bTriggerCheck.setEnabled(False)
self.dTriggerCheck.setEnabled(False)
self.extTriggerCheck.setEnabled(False)
self.aUpperThresholdSpinBox.setEnabled(False)
self.bUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.aDirectionComboBox.setEnabled(False)
self.bDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
elif bool(int(self.dTriggerCheck.checkState())):
self.aTriggerCheck.setEnabled(False)
self.bTriggerCheck.setEnabled(False)
self.cTriggerCheck.setEnabled(False)
self.extTriggerCheck.setEnabled(False)
self.aUpperThresholdSpinBox.setEnabled(False)
self.bUpperThresholdSpinBox.setEnabled(False)
self.cUpperThresholdSpinBox.setEnabled(False)
self.extUpperThresholdSpinBox.setEnabled(False)
self.aDirectionComboBox.setEnabled(False)
self.bDirectionComboBox.setEnabled(False)
self.cDirectionComboBox.setEnabled(False)
self.extDirectionComboBox.setEnabled(False)
elif bool(int(self.extTriggerCheck.checkState())):
self.aTriggerCheck.setEnabled(False)
self.bTriggerCheck.setEnabled(False)
self.cTriggerCheck.setEnabled(False)
self.dTriggerCheck.setEnabled(False)
self.aUpperThresholdSpinBox.setEnabled(False)
self.bUpperThresholdSpinBox.setEnabled(False)
self.cUpperThresholdSpinBox.setEnabled(False)
self.dUpperThresholdSpinBox.setEnabled(False)
self.aDirectionComboBox.setEnabled(False)
self.bDirectionComboBox.setEnabled(False)
self.cDirectionComboBox.setEnabled(False)
self.dDirectionComboBox.setEnabled(False)
else:
if self.driverLineEdit.text() == 'ps2000a':
self.aTriggerCheck.setEnabled(True)
self.bTriggerCheck.setEnabled(True)
self.aUpperThresholdSpinBox.setEnabled(True)
self.bUpperThresholdSpinBox.setEnabled(True)
self.aDirectionComboBox.setEnabled(True)
self.bDirectionComboBox.setEnabled(True)
else:
self.aTriggerCheck.setEnabled(True)
self.bTriggerCheck.setEnabled(True)
self.cTriggerCheck.setEnabled(True)
self.dTriggerCheck.setEnabled(True)
self.extTriggerCheck.setEnabled(True)
self.aUpperThresholdSpinBox.setEnabled(True)
self.bUpperThresholdSpinBox.setEnabled(True)
self.cUpperThresholdSpinBox.setEnabled(True)
self.dUpperThresholdSpinBox.setEnabled(True)
self.extUpperThresholdSpinBox.setEnabled(True)
self.aDirectionComboBox.setEnabled(True)
self.bDirectionComboBox.setEnabled(True)
self.cDirectionComboBox.setEnabled(True)
self.dDirectionComboBox.setEnabled(True)
self.extDirectionComboBox.setEnabled(True)
def run(self):
_translate = QtCore.QCoreApplication.translate
global runList
#Reset
self.tabWidget.clear()
runList = {'runTab': [], 'stackedWidget': [], 'captureTab': []}
chandle = ctypes.c_int16()
status = {}
start_scope([chandle, status])
#Channel Configuration
channels_ = []
couplings_ = []
cranges_ = []
offsets_ = []
if bool(int(self.aCheck.checkState())):
channels_.append(0)
couplings_.append(self.aCouplingComboBox.currentIndex())
cranges_.append(self.aRangeComboBox.currentIndex())
offsets_.append(float(self.aOffsetSpinBox.text()))
if bool(int(self.bCheck.checkState())):
channels_.append(1)
couplings_.append(self.bCouplingComboBox.currentIndex())
cranges_.append(self.bRangeComboBox.currentIndex())
offsets_.append(float(self.bOffsetSpinBox.text()))
if bool(int(self.cCheck.checkState())):
channels_.append(2)
couplings_.append(self.cCouplingComboBox.currentIndex())
cranges_.append(self.cRangeComboBox.currentIndex())
offsets_.append(float(self.cOffsetSpinBox.text()))
if bool(int(self.dCheck.checkState())):
channels_.append(3)
couplings_.append(self.dCouplingComboBox.currentIndex())
cranges_.append(self.dRangeComboBox.currentIndex())
offsets_.append(float(self.dOffsetSpinBox.text()))
channel_config(chandle, status, 1, channels_, couplings_, cranges_, offsets_)
#Trigger Configuration
trigChannel = 0 #Default Value
trigAdcCounts = 0
trigDirection = 0
if self.triggerTypeComboBox.currentText() == 'Simple':
if bool(int(self.aTriggerCheck.checkState())):
trigChannel = 0
trigAdcCounts = int(self.aUpperThresholdSpinBox.text())
trigDirection = int(self.aDirectionComboBox.currentIndex())
elif bool(int(self.bTriggerCheck.checkState())):
trigChannel = 1
trigAdcCounts = int(self.bUpperThresholdSpinBox.text())
trigDirection = int(self.bDirectionComboBox.currentIndex())
elif bool(int(self.cTriggerCheck.checkState())):
trigChannel = 2
trigAdcCounts = int(self.cUpperThresholdSpinBox.text())
trigDirection = int(self.cDirectionComboBox.currentIndex())
elif bool(int(self.dTriggerCheck.checkState())):
trigChannel = 3
trigAdcCounts = int(self.dUpperThresholdSpinBox.text())
trigDirection = int(self.dDirectionComboBox.currentIndex())
elif bool(int(self.extTriggerCheck.checkState())):
trigChannel = 4
trigAdcCounts = int(self.extUpperThresholdSpinBox.text())
trigDirection = int(self.extDirectionComboBox.currentIndex())
trig_simple_config(chandle, status, 1, trigChannel, trigAdcCounts, trigDirection, int(self.aDelaySpinBox.text()), int(self.aAutotriggerSpinBox.text())) #Setup a simple trigger
elif self.triggerTypeComboBox.currentText() == 'Complex':
trigCond_ = []
for i in range(len(conditionList['conditionTab'])):
trigCond_.append([conditionList['aStateComboBox'][i].currentIndex(), conditionList['bStateComboBox'][i].currentIndex(), conditionList['cStateComboBox'][i].currentIndex(), conditionList['dStateComboBox'][i].currentIndex(), conditionList['extStateComboBox'][i].currentIndex(), 0, 0, 0])
trigChannelConf_ = []
if bool(int(self.aTriggerCheck.checkState())):
trigChannelConf_.append([int(self.aUpperThresholdSpinBox.text()), int(self.aUpperHysteresisSpinBox.text()), int(self.aLowerThresholdSpinBox.text()), int(self.aLowerHysteresisSpinBox.text()), 0 ,int(self.aThresholdModeComboBox.currentIndex())])
if bool(int(self.bTriggerCheck.checkState())):
trigChannelConf_.append([int(self.bUpperThresholdSpinBox.text()), int(self.bUpperHysteresisSpinBox.text()), int(self.bLowerThresholdSpinBox.text()), int(self.bLowerHysteresisSpinBox.text()), 1 ,int(self.bThresholdModeComboBox.currentIndex())])
if bool(int(self.cTriggerCheck.checkState())):
trigChannelConf_.append([int(self.cUpperThresholdSpinBox.text()), int(self.cUpperHysteresisSpinBox.text()), int(self.cLowerThresholdSpinBox.text()), int(self.cLowerHysteresisSpinBox.text()), 2 ,int(self.cThresholdModeComboBox.currentIndex())])
if bool(int(self.dTriggerCheck.checkState())):
trigChannelConf_.append([int(self.dUpperThresholdSpinBox.text()), int(self.dUpperHysteresisSpinBox.text()), int(self.dLowerThresholdSpinBox.text()), int(self.dLowerHysteresisSpinBox.text()), 3 ,int(self.dThresholdModeComboBox.currentIndex())])
if bool(int(self.extTriggerCheck.checkState())):
trigChannelConf_.append([int(self.extUpperThresholdSpinBox.text()), int(self.extUpperHysteresisSpinBox.text()), int(self.extLowerThresholdSpinBox.text()), int(self.extLowerHysteresisSpinBox.text()), 4 ,int(self.extThresholdModeComboBox.currentIndex())])
print(chandle, status, trigCond_, [self.aDirectionComboBox.currentIndex(), self.bDirectionComboBox.currentIndex(), self.cDirectionComboBox.currentIndex(), self.dDirectionComboBox.currentIndex(), self.extDirectionComboBox.currentIndex(), self.aDirectionComboBox.currentIndex()], trigChannelConf_, int(self.aAutotriggerSpinBox.text()))
trig_logic_config(chandle, status, trigCond_, [self.aDirectionComboBox.currentIndex(), self.bDirectionComboBox.currentIndex(), self.cDirectionComboBox.currentIndex(), self.dDirectionComboBox.currentIndex(), self.extDirectionComboBox.currentIndex(), self.aDirectionComboBox.currentIndex()], trigChannelConf_, int(self.aAutotriggerSpinBox.text()))
#Capture Configuration
buffFileName = 'buffer_swap.txt'
buff = open(buffFileName, 'w')
buff.close()
if self.modeComboBox.currentText() == 'Block':
preTriggerSamples = int(self.preTriggerSamplesSpinBox.text())
postTriggerSamples = int(self.postTriggerSamplesSpinBox.text())
timebase = int(self.timebaseSpinBox.text())
totalSamples = preTriggerSamples+postTriggerSamples
segments = int(self.segmentsSpinBox.text())
captures = int(self.capturesSpinBox.text())
time_ = timebase_block_config(chandle, status, timebase, totalSamples) #Setup timebase and time axis
buffersMax, buffersMin = buffer_block_config(chandle, status, channels_, totalSamples, segments, 0) #Setup buffer and segments
buff = open(buffFileName, 'a')
if bool(int(self.outFileCheckBox.checkState())):
clear_file(self.outFileNameLineEdit.text())
for i in range(int(self.runsSpinBox.text())):
data_block(chandle, status, preTriggerSamples, postTriggerSamples, timebase, 0, 0) #Get data
for chann in buffersMax:
for segm in chann:
for j in segm:
buff.write(str(j)+',')
buff.write('\n\n')
buff.write('/\n')
buff.write('//\n')
elif self.modeComboBox.currentText() == 'Rapid Block':
preTriggerSamples = int(self.preTriggerSamplesSpinBox.text())
postTriggerSamples = int(self.postTriggerSamplesSpinBox.text())
timebase = int(self.timebaseSpinBox.text())
totalSamples = preTriggerSamples+postTriggerSamples
segments = int(self.segmentsSpinBox.text())
captures = int(self.capturesSpinBox.text())
time_ = timebase_block_config(chandle, status, timebase, totalSamples) #Setup timebase and time axis
segment_capture_config(chandle, status, segments, captures, totalSamples) #Setup memory segmentation & capture configuration
buffersMax, buffersMin = buffer_block_config(chandle, status, channels_, totalSamples, segments, 0) #Setup buffer and segments
buff = open(buffFileName, 'a')
if bool(int(self.outFileCheckBox.checkState())):
clear_file(self.outFileNameLineEdit.text())
for i in range(int(self.runsSpinBox.text())):
data_rapid_block(chandle, status, preTriggerSamples, postTriggerSamples, timebase, segments, captures, 0, 0) #Get data
for chann in buffersMax:
for segm in chann:
for j in segm:
buff.write(str(j)+',')
buff.write('\n\n')
buff.write('/\n')
buff.write('//\n')
elif self.modeComboBox.currentText() == 'Streaming':
preTriggerSamples = int(self.preTriggerSamplesSpinBox.text())
postTriggerSamples = int(self.postTriggerSamplesSpinBox.text())
totalSamples = preTriggerSamples+postTriggerSamples
sizeOfOneBuffer = int(self.samplesPerBufferSpinBox.text())
totalRuntime = int(self.totalRuntimeSpinBox.text())
sampleInterval = int(totalRuntime/totalSamples)
sampleUnits = int(self.timeUnitsComboBox.currentIndex())
segments = int(self.segmentsSpinBox.text())
captures = int(self.capturesSpinBox.text())
time_ = timebase_stream_config(totalSamples, sampleInterval, sampleUnits) #Setup timebase and time axis
buffersComplete, buffersMax, buffersMin = buffer_stream_config(chandle, status, channels_, totalSamples, sizeOfOneBuffer, segments, 0) #Setup buffers
buff = open(buffFileName, 'a')
if bool(int(self.outFileCheckBox.checkState())):
clear_file(self.outFileNameLineEdit.text())
for i in range(int(self.runsSpinBox.text())):
data_streaming(chandle, status, sampleInterval, 0, buffersComplete, buffersMax, sizeOfOneBuffer, sampleUnits, preTriggerSamples, postTriggerSamples, 0, 1) #Get data
for chann in buffersMax:
for segm in chann:
for j in segm:
buff.write(str(j)+',')
buff.write('\n\n')
buff.write('/\n')
buff.write('//\n')
buff.write('F') #EOF character
buff.close()
#Data Processing
tabMax = 7
capturesMax = 7
indx = 0
buff = open(buffFileName, 'r')
temp = buff.readline().replace('\n', '')
while temp != 'F':
indx += 1
run = []
while temp != '//':
chann = []
while temp != '/':
segm = []
while temp != '':
data = ''
for char in temp:
if char == ',':
segm.append(int(data))
data = ''
else:
data += char
temp = buff.readline().replace('\n', '')
chann.append(segm)
temp = buff.readline().replace('\n', '')
run.append(chann)
temp = buff.readline().replace('\n', '')
#print(run)
run = run_to_mV(chandle, status, run, channels_, cranges_, totalSamples, segments)
if bool(int(self.graphCheck.checkState())) and len(runList['runTab']) < tabMax:
runList['runTab'].append(QtWidgets.QWidget())
runList['runTab'][-1].setObjectName("run_"+str(indx))
runList['stackedWidget'].append(QtWidgets.QStackedWidget(runList['runTab'][-1]))
runList['stackedWidget'][-1].setGeometry(QtCore.QRect(0*widthRatio, 0*heightRatio, 461*widthRatio, 361*heightRatio))
runList['stackedWidget'][-1].setObjectName("stackedWidget_"+str(indx))
runList['captureTab'].append([])
self.tabWidget.addTab(runList['runTab'][-1], "")
self.tabWidget.setTabText(self.tabWidget.indexOf(runList['runTab'][-1]), _translate("MainWindow", "Run "+str(indx)))
for i in range(captures):
if i >= capturesMax:
break
runList['captureTab'][-1].append(Canvas(self, width=4.61*widthRatio, height=3.61*heightRatio, dpi=100))
for j in range(len(channels_)):
run_channel_capture = run[j][i]
runList['captureTab'][-1][-1].axes.plot(time_, run_channel_capture)
runList['captureTab'][-1][-1].axes.set(xlabel = 'Time ('+self.timeUnitsComboBox.currentText()+')', ylabel = 'Voltage (mV)', title = 'Capture '+str(i+1))
runList['stackedWidget'][-1].addWidget(runList['captureTab'][-1][i])
self.pageChangeCheck()
else:
plt.close('all')
if bool(int(self.outFileCheckBox.checkState())): #True for file writing
run_to_file(time_, self.timeUnitsComboBox.currentText(), run, channels_, segments, indx, self.outFileNameLineEdit.text())
temp = buff.readline().replace('\n', '')
stop_scope([chandle, status])
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| 65.412299
| 357
| 0.692931
| 10,725
| 122,321
| 7.869464
| 0.055758
| 0.046825
| 0.040071
| 0.026588
| 0.617263
| 0.501386
| 0.4284
| 0.353152
| 0.322192
| 0.310592
| 0
| 0.019782
| 0.178825
| 122,321
| 1,869
| 358
| 65.447298
| 0.820463
| 0.004235
| 0
| 0.414286
| 0
| 0
| 0.075156
| 0.007218
| 0
| 0
| 0
| 0
| 0
| 1
| 0.010989
| false
| 0.000549
| 0.009341
| 0
| 0.024176
| 0.000549
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
1
| 0
|