hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 251 | max_issues_repo_name stringlengths 4 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 251 | max_forks_repo_name stringlengths 4 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
91bccefcfa09a20e9fc27c2975179329c5876dd6 | 2,461 | py | Python | simplejson/ordered_dict.py | BarracudaPff/code-golf-data-pythpn | 42e8858c2ebc6a061012bcadb167d29cebb85c5e | [
"MIT"
] | null | null | null | simplejson/ordered_dict.py | BarracudaPff/code-golf-data-pythpn | 42e8858c2ebc6a061012bcadb167d29cebb85c5e | [
"MIT"
] | null | null | null | simplejson/ordered_dict.py | BarracudaPff/code-golf-data-pythpn | 42e8858c2ebc6a061012bcadb167d29cebb85c5e | [
"MIT"
] | null | null | null | """Drop-in replacement for collections.OrderedDict by Raymond Hettinger
http://code.activestate.com/recipes/576693/
"""
try:
all
except NameError: | 26.180851 | 94 | 0.670053 |
91be6d919cdb079a9a7700432f62e3627d2ca47d | 286 | py | Python | Water.py | KRHS-GameProgramming-2015/Adlez | 8912da1ee4b3c7b105851dbcc00579ff0c3cf33e | [
"BSD-2-Clause"
] | null | null | null | Water.py | KRHS-GameProgramming-2015/Adlez | 8912da1ee4b3c7b105851dbcc00579ff0c3cf33e | [
"BSD-2-Clause"
] | 4 | 2016-04-01T15:12:31.000Z | 2016-04-18T15:05:29.000Z | Water.py | KRHS-GameProgramming-2015/Adlez | 8912da1ee4b3c7b105851dbcc00579ff0c3cf33e | [
"BSD-2-Clause"
] | null | null | null | from HardBlock import *
| 17.875 | 55 | 0.534965 |
91be89ca5480384018cb3e20d95ea9abdcb4c1bb | 4,136 | py | Python | baselines/bc.py | bgalbraith/minerl-haiku-baselines | c33b14699af14c904394d9c4e30dee680a8718d6 | [
"Apache-2.0"
] | 2 | 2020-07-11T07:56:46.000Z | 2020-08-20T07:59:53.000Z | baselines/bc.py | bgalbraith/minerl-haiku-baselines | c33b14699af14c904394d9c4e30dee680a8718d6 | [
"Apache-2.0"
] | null | null | null | baselines/bc.py | bgalbraith/minerl-haiku-baselines | c33b14699af14c904394d9c4e30dee680a8718d6 | [
"Apache-2.0"
] | null | null | null | import dill
import haiku as hk
import jax
from jax.experimental import optix
import jax.numpy as jnp
from dataset import load_data
MINERL_ENV = 'MineRLTreechopVectorObf-v0'
PARAMS_FILENAME = 'bc_params_treechop.pkl'
def behavioral_cloning(batch):
""" The full forward model definition """
x_0 = PovStack(name='pov_stack')(batch[0])
x_1 = VectorStack(name='vector_stack')(batch[1])
x = jnp.concatenate((x_0, x_1), axis=1)
return jnp.tanh(hk.Linear(64)(x))
if __name__ == '__main__':
main()
| 30.411765 | 105 | 0.579787 |
91c15e0720d4970bd1fb3bf3b4458b92fb250bec | 3,236 | py | Python | qiskit/circuit/library/templates/__init__.py | ajavadia/qiskit-sdk-py | a59e8e6be1793197e19998c1f7dcfc45e6f2f3af | [
"Apache-2.0"
] | 15 | 2020-06-29T08:33:39.000Z | 2022-02-12T00:28:51.000Z | qiskit/circuit/library/templates/__init__.py | ajavadia/qiskit-sdk-py | a59e8e6be1793197e19998c1f7dcfc45e6f2f3af | [
"Apache-2.0"
] | 6 | 2021-01-17T17:56:08.000Z | 2021-04-01T12:40:21.000Z | qiskit/circuit/library/templates/__init__.py | ajavadia/qiskit-sdk-py | a59e8e6be1793197e19998c1f7dcfc45e6f2f3af | [
"Apache-2.0"
] | 11 | 2020-06-29T08:40:24.000Z | 2022-02-24T17:39:16.000Z | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
A library of template circuits.
Templates are circuits that compute the identity. They find use
in circuit optimization where matching part of the template allows the compiler
to replace the match with the inverse of the remainder from the template.
"""
from .nct.template_nct_2a_1 import template_nct_2a_1
from .nct.template_nct_2a_2 import template_nct_2a_2
from .nct.template_nct_2a_3 import template_nct_2a_3
from .nct.template_nct_4a_1 import template_nct_4a_1
from .nct.template_nct_4a_2 import template_nct_4a_2
from .nct.template_nct_4a_3 import template_nct_4a_3
from .nct.template_nct_4b_1 import template_nct_4b_1
from .nct.template_nct_4b_2 import template_nct_4b_2
from .nct.template_nct_5a_1 import template_nct_5a_1
from .nct.template_nct_5a_2 import template_nct_5a_2
from .nct.template_nct_5a_3 import template_nct_5a_3
from .nct.template_nct_5a_4 import template_nct_5a_4
from .nct.template_nct_6a_1 import template_nct_6a_1
from .nct.template_nct_6a_2 import template_nct_6a_2
from .nct.template_nct_6a_3 import template_nct_6a_3
from .nct.template_nct_6a_4 import template_nct_6a_4
from .nct.template_nct_6b_1 import template_nct_6b_1
from .nct.template_nct_6b_2 import template_nct_6b_2
from .nct.template_nct_6c_1 import template_nct_6c_1
from .nct.template_nct_7a_1 import template_nct_7a_1
from .nct.template_nct_7b_1 import template_nct_7b_1
from .nct.template_nct_7c_1 import template_nct_7c_1
from .nct.template_nct_7d_1 import template_nct_7d_1
from .nct.template_nct_7e_1 import template_nct_7e_1
from .nct.template_nct_9a_1 import template_nct_9a_1
from .nct.template_nct_9c_1 import template_nct_9c_1
from .nct.template_nct_9c_2 import template_nct_9c_2
from .nct.template_nct_9c_3 import template_nct_9c_3
from .nct.template_nct_9c_4 import template_nct_9c_4
from .nct.template_nct_9c_5 import template_nct_9c_5
from .nct.template_nct_9c_6 import template_nct_9c_6
from .nct.template_nct_9c_7 import template_nct_9c_7
from .nct.template_nct_9c_8 import template_nct_9c_8
from .nct.template_nct_9c_9 import template_nct_9c_9
from .nct.template_nct_9c_10 import template_nct_9c_10
from .nct.template_nct_9c_11 import template_nct_9c_11
from .nct.template_nct_9c_12 import template_nct_9c_12
from .nct.template_nct_9d_1 import template_nct_9d_1
from .nct.template_nct_9d_2 import template_nct_9d_2
from .nct.template_nct_9d_3 import template_nct_9d_3
from .nct.template_nct_9d_4 import template_nct_9d_4
from .nct.template_nct_9d_5 import template_nct_9d_5
from .nct.template_nct_9d_6 import template_nct_9d_6
from .nct.template_nct_9d_7 import template_nct_9d_7
from .nct.template_nct_9d_8 import template_nct_9d_8
from .nct.template_nct_9d_9 import template_nct_9d_9
from .nct.template_nct_9d_10 import template_nct_9d_10
| 48.298507 | 79 | 0.860939 |
91c2124933101c4997c3e85497e979cf423b2846 | 10,418 | py | Python | Tests/test_ironmath.py | btddg28/ironpython | 8006238c19d08db5db9bada39d765143e631059e | [
"Apache-2.0"
] | null | null | null | Tests/test_ironmath.py | btddg28/ironpython | 8006238c19d08db5db9bada39d765143e631059e | [
"Apache-2.0"
] | null | null | null | Tests/test_ironmath.py | btddg28/ironpython | 8006238c19d08db5db9bada39d765143e631059e | [
"Apache-2.0"
] | null | null | null | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################
#
# test Microsoft.Scripting.Math
#
from iptest.assert_util import *
skiptest("win32")
from System import *
import clr
#silverlight already has this
if is_cli:
math_assembly = (1).GetType().Assembly
clr.AddReference(math_assembly)
load_iron_python_test()
import IronPythonTest
if is_net40:
from System.Numerics import BigInteger, Complex
else:
from Microsoft.Scripting.Math import BigInteger
from Microsoft.Scripting.Math import Complex64 as Complex
p = myFormatProvider()
#complex
run_test(__name__)
| 41.015748 | 241 | 0.656748 |
91c2c2561ea4fef57e7b95890c99ab69daf79a23 | 6,939 | py | Python | python/lib/viewer/gener_q_vs_w_for_df.py | timtyree/bgmc | 891e003a9594be9e40c53822879421c2b8c44eed | [
"MIT"
] | null | null | null | python/lib/viewer/gener_q_vs_w_for_df.py | timtyree/bgmc | 891e003a9594be9e40c53822879421c2b8c44eed | [
"MIT"
] | null | null | null | python/lib/viewer/gener_q_vs_w_for_df.py | timtyree/bgmc | 891e003a9594be9e40c53822879421c2b8c44eed | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt, numpy as np, pandas as pd,os
from ..model import recall_powerlaw_fits_to_full_models
from .. import compute_power_rmse
from .bluf import *
from ..measure.powerlaw import *
from .gener_q_vs_w_for_result_folder import *
| 39.651429 | 130 | 0.678484 |
91c49a7dc1b6f619c4919335c93fb67b97477b88 | 7,917 | py | Python | decatt/model.py | achyudh/castor | d7a02ce03f2b71ef1fa490122dd4bbc8214b8b19 | [
"Apache-2.0"
] | 132 | 2017-04-02T12:31:55.000Z | 2019-03-09T07:53:29.000Z | decatt/model.py | sudipta90/castor | fa2f59535c71a0fb4586afbe543b81ba812c8630 | [
"Apache-2.0"
] | 111 | 2017-04-01T23:00:24.000Z | 2019-03-10T08:29:20.000Z | decatt/model.py | sudipta90/castor | fa2f59535c71a0fb4586afbe543b81ba812c8630 | [
"Apache-2.0"
] | 53 | 2017-04-06T01:17:18.000Z | 2019-02-27T03:10:35.000Z | import sys
import math
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
| 46.298246 | 136 | 0.653909 |
91c545eedebfe63072291f5498dba2aca85beda1 | 8,738 | py | Python | basic_code/networks.py | J-asy/Emotion-FAN | 30c1e24a31b2a05c0810a17eb533096a7baaeeef | [
"MIT"
] | 275 | 2019-09-11T10:22:06.000Z | 2022-03-29T07:14:31.000Z | basic_code/networks.py | J-asy/Emotion-FAN | 30c1e24a31b2a05c0810a17eb533096a7baaeeef | [
"MIT"
] | 34 | 2019-09-11T11:32:32.000Z | 2022-03-18T09:32:42.000Z | basic_code/networks.py | J-asy/Emotion-FAN | 30c1e24a31b2a05c0810a17eb533096a7baaeeef | [
"MIT"
] | 69 | 2019-09-18T19:00:17.000Z | 2022-03-08T11:43:49.000Z | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch
import numpy as np
import cv2
import pdb
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
###''' self-attention; relation-attention '''
''' self-attention; relation-attention '''
| 34.674603 | 120 | 0.54509 |
91c59190736d04c98947f42fd90af017204111ac | 505 | py | Python | ndscheduler/server/handlers/index.py | symphonyrm/ndscheduler | e9a56ef345b25916a2b53d1ea3349efb532d63ce | [
"BSD-2-Clause"
] | null | null | null | ndscheduler/server/handlers/index.py | symphonyrm/ndscheduler | e9a56ef345b25916a2b53d1ea3349efb532d63ce | [
"BSD-2-Clause"
] | null | null | null | ndscheduler/server/handlers/index.py | symphonyrm/ndscheduler | e9a56ef345b25916a2b53d1ea3349efb532d63ce | [
"BSD-2-Clause"
] | null | null | null | """Serves the single page app web ui."""
import json
import tornado.gen
from ndscheduler import settings
from ndscheduler import utils
from ndscheduler.server.handlers import base
| 25.25 | 82 | 0.732673 |
91c6b0a778c821558e257de0d52e71c5f953c2bf | 801 | py | Python | Scripts/xbbtools/xbb_io.py | eoc21/biopython | c0f8db8f55a506837c320459957a0ce99b0618b6 | [
"PostgreSQL"
] | 3 | 2017-10-23T21:53:57.000Z | 2019-09-23T05:14:12.000Z | Scripts/xbbtools/xbb_io.py | eoc21/biopython | c0f8db8f55a506837c320459957a0ce99b0618b6 | [
"PostgreSQL"
] | null | null | null | Scripts/xbbtools/xbb_io.py | eoc21/biopython | c0f8db8f55a506837c320459957a0ce99b0618b6 | [
"PostgreSQL"
] | 6 | 2020-02-26T16:34:20.000Z | 2020-03-04T15:34:00.000Z | #!/usr/bin/env python
# Created: Wed Jun 21 13:46:35 2000
# Last changed: Time-stamp: <00/12/02 14:18:23 thomas>
# Thomas.Sicheritz@molbio.uu.se, http://evolution.bmc.uu.se/~thomas
# File: xbb_io.py
import os, sys # os.system, sys.argv
sys.path.insert(0, '.')
sys.path.insert(0, os.path.expanduser('~thomas/cbs/python/biopython'))
from Bio.ParserSupport import *
from Bio import Fasta
| 23.558824 | 81 | 0.604245 |
91c7653e4b544fa3638814ac8e321e91f01ca6d4 | 288 | py | Python | HW6/Andrii_Haponov/cw_4.py | kolyasalubov/Lv-677.PythonCore | c9f9107c734a61e398154a90b8a3e249276c2704 | [
"MIT"
] | null | null | null | HW6/Andrii_Haponov/cw_4.py | kolyasalubov/Lv-677.PythonCore | c9f9107c734a61e398154a90b8a3e249276c2704 | [
"MIT"
] | null | null | null | HW6/Andrii_Haponov/cw_4.py | kolyasalubov/Lv-677.PythonCore | c9f9107c734a61e398154a90b8a3e249276c2704 | [
"MIT"
] | 6 | 2022-02-22T22:30:49.000Z | 2022-03-28T12:51:19.000Z | # Convert a Number to a String!
# We need a function that can transform a number into a string.
# What ways of achieving this do you know?
print(number_to_string(123))
print(type(number_to_string(123))) | 24 | 63 | 0.729167 |
91c7cf66ad6751a13ba5162d5a7e62b526efecd6 | 2,693 | py | Python | project/scripts/clausecat/evaluate_clausecat.py | explosion/healthsea | 4481488ed9fc85b89844ee872d0a8412a33f0b15 | [
"MIT"
] | 60 | 2021-12-15T17:14:37.000Z | 2022-03-26T18:25:15.000Z | project/scripts/clausecat/evaluate_clausecat.py | zhinoos-adibi/healthsea | 4481488ed9fc85b89844ee872d0a8412a33f0b15 | [
"MIT"
] | 3 | 2021-12-16T19:50:15.000Z | 2022-03-28T06:10:48.000Z | project/scripts/clausecat/evaluate_clausecat.py | zhinoos-adibi/healthsea | 4481488ed9fc85b89844ee872d0a8412a33f0b15 | [
"MIT"
] | 9 | 2021-12-15T21:00:05.000Z | 2022-03-17T09:20:51.000Z | import spacy
from spacy.scorer import PRFScore
import typer
from pathlib import Path
from wasabi import Printer, table
import operator
import benepar
import clausecat_component
import clausecat_model
import clausecat_reader
import clause_segmentation
import clause_aggregation
msg = Printer()
def main(model_path: Path, eval_path: Path):
"""This script is used to evaluate the clausecat component"""
nlp = spacy.load(model_path)
reader = clausecat_reader.ClausecatCorpus(eval_path)
examples = reader(nlp)
clausecat = nlp.get_pipe("clausecat")
scorer = {
"POSITIVE": PRFScore(),
"NEGATIVE": PRFScore(),
"NEUTRAL": PRFScore(),
"ANAMNESIS": PRFScore(),
}
for i, example in enumerate(examples):
prediction = example.predicted
reference = example.reference
# Prediction
prediction = clausecat(prediction)
# Iterate through prediction and references
for pred_clause, ref_clause in zip(prediction._.clauses, reference._.clauses):
prediction_cats = pred_clause["cats"]
reference_cats = ref_clause["cats"]
prediction_class = max(prediction_cats.items(), key=operator.itemgetter(1))[
0
]
# Add to matrix
for label in prediction_cats:
if label != prediction_class:
prediction = 0
else:
prediction = 1
if prediction == 0 and reference_cats[label] != 0:
scorer[label].fn += 1
elif prediction == 1 and reference_cats[label] != 1:
scorer[label].fp += 1
elif prediction == 1 and reference_cats[label] == 1:
scorer[label].tp += 1
# Printing
textcat_data = []
avg_fscore = 0
avg_recall = 0
avg_precision = 0
for label in scorer:
textcat_data.append(
(
label,
round(scorer[label].fscore, 2),
round(scorer[label].recall, 2),
round(scorer[label].precision, 2),
)
)
avg_fscore += scorer[label].fscore
avg_recall += scorer[label].recall
avg_precision += scorer[label].precision
textcat_data.append(
(
"AVERAGE",
round(avg_fscore / len(scorer), 2),
round(avg_recall / len(scorer), 2),
round(avg_precision / len(scorer), 2),
)
)
header = ("Label", "F-Score", "Recall", "Precision")
print(table(textcat_data, header=header, divider=True))
if __name__ == "__main__":
typer.run(main)
| 26.93 | 88 | 0.580394 |
91c7ef0594439547e88e45169d2cad470d31a591 | 130 | py | Python | utils/test.py | david-waugh/network-automation | c85ab092cd9b76753c4d35f113126cfb663c1933 | [
"MIT"
] | null | null | null | utils/test.py | david-waugh/network-automation | c85ab092cd9b76753c4d35f113126cfb663c1933 | [
"MIT"
] | null | null | null | utils/test.py | david-waugh/network-automation | c85ab092cd9b76753c4d35f113126cfb663c1933 | [
"MIT"
] | null | null | null | import pathlib
print(pathlib.Path(__file__).parent.resolve())
while True:
next_cmd = input("> ")
print(eval(next_cmd))
| 14.444444 | 46 | 0.684615 |
91c92b40c4f1e26399a0ff522ec30f406f0ff98d | 934 | py | Python | nlp_annotator_api/server/app.py | IBM/deepsearch-nlp-annotator-api-example | 76c2c8fd83c1e6d51c51c7b581a8c3f273b23c40 | [
"Apache-2.0"
] | 3 | 2022-01-04T12:15:22.000Z | 2022-03-25T21:19:20.000Z | nlp_annotator_api/server/app.py | IBM/deepsearch-nlp-annotator-api-example | 76c2c8fd83c1e6d51c51c7b581a8c3f273b23c40 | [
"Apache-2.0"
] | null | null | null | nlp_annotator_api/server/app.py | IBM/deepsearch-nlp-annotator-api-example | 76c2c8fd83c1e6d51c51c7b581a8c3f273b23c40 | [
"Apache-2.0"
] | 5 | 2021-09-27T08:26:09.000Z | 2022-03-10T11:41:35.000Z | import logging
import os
import aiohttp.web
from connexion import AioHttpApp
from nlp_annotator_api.config.config import conf
from nlp_annotator_api.config.logging import setup_logging
from nlp_annotator_api.server.middleware.statsd_middleware import StatsdMiddleware
from nlp_annotator_api.server.signals.statsd_client import statsd_client_factory
setup_logging()
access_log = logging.getLogger("nlp_annotator_api.access")
_file_dir = os.path.dirname(__file__)
app = AioHttpApp(
__name__, specification_dir=os.path.join(_file_dir, "..", "resources", "schemas"),
server_args=dict(
client_max_size=8 * 1024**2
)
)
app.add_api("openapi.yaml", pass_context_arg_name="request")
aiohttp_app: aiohttp.web.Application = app.app
aiohttp_app.cleanup_ctx.append(statsd_client_factory(conf.statsd))
aiohttp_app.middlewares.append(StatsdMiddleware())
if __name__ == "__main__":
app.run(access_log=access_log)
| 26.685714 | 86 | 0.799786 |
91c97df0fae07bca6b5ed203a6e4102faddf3f12 | 4,534 | py | Python | keras_cv_attention_models/resnest/resnest.py | dcleres/keras_cv_attention_models | 264876673e369f23eff49b3b589b72f908a9625b | [
"MIT"
] | 140 | 2021-08-04T06:51:41.000Z | 2022-03-30T08:08:32.000Z | keras_cv_attention_models/resnest/resnest.py | dcleres/keras_cv_attention_models | 264876673e369f23eff49b3b589b72f908a9625b | [
"MIT"
] | 12 | 2021-09-29T00:43:58.000Z | 2022-03-28T07:50:35.000Z | keras_cv_attention_models/resnest/resnest.py | dcleres/keras_cv_attention_models | 264876673e369f23eff49b3b589b72f908a9625b | [
"MIT"
] | 20 | 2021-09-28T20:07:35.000Z | 2022-03-31T14:06:40.000Z | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from keras_cv_attention_models.aotnet import AotNet
from keras_cv_attention_models.download_and_load import reload_model_weights
from keras_cv_attention_models.attention_layers import batchnorm_with_activation, conv2d_no_bias
PRETRAINED_DICT = {
"resnest101": {"imagenet": "63f9ebdcd32529cbc4b4fbbec3d1bb2f"},
"resnest200": {"imagenet": "8e211dcb089b588e18d36ba7cdf92ef0"},
"resnest269": {"imagenet": "4309ed1b0a8ae92f2b1143dc3512c5c7"},
"resnest50": {"imagenet": "eee7b20a229821f730ab205b6afeb369"},
}
| 50.377778 | 155 | 0.696074 |
91c9ae32ffd6100ceb2a8fceee2c2c30ae4e7dc4 | 3,518 | py | Python | dataactcore/migrations/versions/8692ab1298e1_replace_filerequest_with_filegeneration.py | brianherman/data-act-broker-backend | 80eb055b9d245046192f7ad4fd0be7d0e11d2dec | [
"CC0-1.0"
] | 1 | 2019-06-22T21:53:16.000Z | 2019-06-22T21:53:16.000Z | dataactcore/migrations/versions/8692ab1298e1_replace_filerequest_with_filegeneration.py | brianherman/data-act-broker-backend | 80eb055b9d245046192f7ad4fd0be7d0e11d2dec | [
"CC0-1.0"
] | 3 | 2021-08-22T11:47:45.000Z | 2022-03-29T22:06:49.000Z | dataactcore/migrations/versions/8692ab1298e1_replace_filerequest_with_filegeneration.py | brianherman/data-act-broker-backend | 80eb055b9d245046192f7ad4fd0be7d0e11d2dec | [
"CC0-1.0"
] | 1 | 2020-07-17T23:50:56.000Z | 2020-07-17T23:50:56.000Z | """replace FileRequest with FileGeneration
Revision ID: 8692ab1298e1
Revises: 4bbc47f2b48d
Create Date: 2018-10-24 14:54:39.278159
"""
# revision identifiers, used by Alembic.
revision = '8692ab1298e1'
down_revision = '4bbc47f2b48d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
| 45.102564 | 158 | 0.726549 |
91cb094ac7602563246a111f9c1326b917365ed1 | 10,652 | py | Python | cluster.py | Birfy/Endlinking | cc87a5528498e1733111d302437aeb1142b0a47f | [
"MIT"
] | 1 | 2020-02-20T03:46:10.000Z | 2020-02-20T03:46:10.000Z | cluster.py | Birfy/Endlinking | cc87a5528498e1733111d302437aeb1142b0a47f | [
"MIT"
] | null | null | null | cluster.py | Birfy/Endlinking | cc87a5528498e1733111d302437aeb1142b0a47f | [
"MIT"
] | null | null | null | import numpy as np
import random
import sys
chainlength = int(sys.argv[1])
dfname = sys.argv[2]
outfl = 'result.data'
cluster_size = int(sys.argv[3])
# This function will perform statistical analysis to the clustering results
X, Xi = readdata(dfname, chainlength)
size = readsize(dfname)
boxl = np.array([size, size, size])
n = len(X)
k = int(len(X)/cluster_size)
# Set up the database of objects
# X = readdata(dfname, chainlength)
# Choose initial means with K-means
means = initmeans(k)
# Set up initial clusters
distmat = SetDistMat(X, means)
clusters = InitialAssignment(distmat)
## debug code
#keys = sorted(clusters.keys())
#for key in keys:
# print("cluster %i:"%key)
# print(clusters[key])
## end of debug
# Iteration step
for iter in range(100):
active = 0 # indicate the number of transfers in the current iteration
tranlst = (-1)*np.ones(k, dtype='int') # set up transfer list for each cluster
# Compute the cluster means
oldmeans = means.copy()
means = CalcMeans(X, oldmeans, clusters)
# Get statistics about the clustering
#ClusterStat(X, means, clusters)
## debug code
#print("old means:")
#print(oldmeans)
#print("new means:")
#print(means)
## end of debug
# For each object, compute the distances to the cluster means
distmat = SetDistMat(X, means)
# Sort objects based on the delta of the current assignment and the best
# possible alternate assignment
objlst = SortObj(X, clusters, means, distmat)
##debug code
#print(objlst)
##return
#end of debug
# For each element by prioty:
while (len(objlst)):
(i, key, temp) = objlst.pop()
obj2key = GetDist(X[i], means[key])
transferred = False #record if any transfering has occured to i
if (key == distmat[i,0][0]):
##debug
#print("%i is already the opt cluster for obj %i. no transfer"%(clu, i))
##end of debug
continue
# For each other clusters by element gain:
else:
for j in range(k):
clu = distmat[i,j][0] # the key of another cluster
objgain = obj2key - distmat[i,j][1] # gain by transfering i from cluster key to clu
if (clu==key): # already in the cluster
continue
if (len(clusters[clu]) < cluster_size):
active += 1
transferred = True
clusters = Transfer(i, key, clu, clusters)
##debug
#print("cluster %i not full. transfer obj %i from cluster %i to it."%(clu, i, key))
##end of debug
break
elif (tranlst[clu] != -1): # if the tranlst of another cluster is not empty
# distance between the obj in the tranlst and the current cluster
tran2key = GetDist(X[tranlst[clu]], means[key])
tran2clu = GetDist(X[tranlst[clu]], means[clu])
# gain by transfering the obj in tranlst from cluster clu to key
trangain = tran2clu - tran2key
if (objgain + trangain > 0): # transfer if the sum of gains are positive, ie net gain
active += 2
transferred = True
clusters = Transfer(i, key, clu, clusters)
clusters = Transfer(tranlst[clu], clu, key, clusters)
##debug
#print("obj %i is transfered from cluster %i to %i"%(i, key, clu))
#print("obj %i is transfered from cluster %i to %i"%(tranlst[clu], clu, key))
#print("objgain: %f, trangain: %f"%(objgain, trangain))
##end of debug
tranlst[clu] = -1 # reset the tranlst to empty
break
if (not transferred):
tranlst[key] = i
##debug
#print("add obj %i in cluster %i to the transfer list"%(i, key))
##end of debug
# nothing is transferred during this iteration, return the clustering result
if (not active):
break
#debug code
print("number of transfers in iter %i: %i\n"%(iter+1, active))
#end of debug
print("K-means clustering converged in %d iterations!\n"%(iter+1))
# Output the clustering results
WriteResult(outfl, X, means, clusters)
ClusterStat(X, means, clusters)
# print(X)
| 36.986111 | 135 | 0.557548 |
91cb09a3e92988e65a39aed7bb0bc23d1f6a9538 | 20,537 | py | Python | util/hierarchical_primitive/cube_inclusion.py | isunchy/cuboid_abstraction | afda6ca8516c2f5e5e7292b3b22a059a4f6c84ec | [
"MIT"
] | 43 | 2019-09-20T07:45:08.000Z | 2022-03-23T04:07:21.000Z | util/hierarchical_primitive/cube_inclusion.py | SilenKZYoung/cuboid_abstraction | afda6ca8516c2f5e5e7292b3b22a059a4f6c84ec | [
"MIT"
] | 4 | 2019-11-25T00:57:10.000Z | 2021-09-02T10:59:05.000Z | util/hierarchical_primitive/cube_inclusion.py | SilenKZYoung/cuboid_abstraction | afda6ca8516c2f5e5e7292b3b22a059a4f6c84ec | [
"MIT"
] | 10 | 2019-09-10T02:19:47.000Z | 2021-06-16T05:23:43.000Z | import numpy as np
import quaternion
sample_points = np.array([[-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0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0.8,1.0,-1.0,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0,-1.0,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0,-1.0,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0,-1.0,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0]
], dtype=np.float32) # [3, n]
sample_points = np.transpose(sample_points) # [n, 3]
if __name__ == '__main__':
# generate_sample_cube_points()
z1 = np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.1, 0.1, 0.1]])
q1 = np.array([[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]])
t1 = np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.4, 0.4, 0.4]])
cube_param_1 = {'z': z1, 'q': q1, 't': t1}
z2 = np.array([[0.1, 0.1, 0.1], [0.2, 0.2, 0.2]])
q2 = np.array([[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]])
t2 = np.array([[0.2, 0.2, 0.2], [0.3, 0.3, 0.3]])
cube_param_2 = {'z': z2, 'q': q2, 't': t2}
index = cube_inclusion(cube_param_1, cube_param_2)
print(index)
assert((index == np.array([0, 0, 1])).all())
| 315.953846 | 5,958 | 0.466378 |
91cc3e617eabbbaa426a11dc2dc6c376ad5cab95 | 740 | py | Python | ituro/accounts/tests.py | kayduemre/ituro | eb5bb0655c2d85eed212d28c1d154006c57a4f03 | [
"MIT"
] | 9 | 2015-03-18T01:59:24.000Z | 2022-03-09T06:36:21.000Z | ituro/accounts/tests.py | kayduemre/ituro | eb5bb0655c2d85eed212d28c1d154006c57a4f03 | [
"MIT"
] | 29 | 2015-03-18T01:59:49.000Z | 2021-06-10T20:39:03.000Z | ituro/accounts/tests.py | kayduemre/ituro | eb5bb0655c2d85eed212d28c1d154006c57a4f03 | [
"MIT"
] | 10 | 2016-01-31T05:44:46.000Z | 2019-10-15T06:12:27.000Z | from django.test import TestCase
from django.utils import timezone
from accounts.models import CustomUser, CustomUserManager
| 33.636364 | 71 | 0.671622 |
91ce005123b48bec43dd6a96411c6f2b6ba102be | 2,284 | py | Python | continuum/datasets/dtd.py | oleksost/continuum | 682d66540bfbfa171ac73281ed2989f9338e88bf | [
"MIT"
] | 282 | 2020-05-09T21:35:22.000Z | 2022-03-20T11:29:41.000Z | continuum/datasets/dtd.py | oleksost/continuum | 682d66540bfbfa171ac73281ed2989f9338e88bf | [
"MIT"
] | 180 | 2020-05-03T09:31:48.000Z | 2022-03-30T12:12:48.000Z | continuum/datasets/dtd.py | oleksost/continuum | 682d66540bfbfa171ac73281ed2989f9338e88bf | [
"MIT"
] | 34 | 2020-06-13T14:09:29.000Z | 2022-03-14T14:05:07.000Z | import os
from typing import List
import numpy as np
from torchvision import datasets as torchdata
from continuum.datasets import ImageFolderDataset
from continuum import download
from continuum.tasks import TaskType
| 35.6875 | 108 | 0.595009 |
91ce047cf63bd3235780b724cb14faa1d2a5cf51 | 1,732 | py | Python | src/tests/testdata.py | Doometnick/MaxiMin-2048 | f1d795ec07fffe1aa239c105cf522d2c3bc9b011 | [
"MIT"
] | null | null | null | src/tests/testdata.py | Doometnick/MaxiMin-2048 | f1d795ec07fffe1aa239c105cf522d2c3bc9b011 | [
"MIT"
] | null | null | null | src/tests/testdata.py | Doometnick/MaxiMin-2048 | f1d795ec07fffe1aa239c105cf522d2c3bc9b011 | [
"MIT"
] | null | null | null | from board import Direction
# Tuples of input, action, expected output.
moving_tests = [
(
[[0,0,0,0],
[4,0,0,0],
[0,0,0,0],
[4,0,2,0]],
Direction.UP,
[[8,0,2,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
),
(
[[0,0,0,0],
[4,0,0,0],
[0,0,0,0],
[4,0,2,0]],
Direction.DOWN,
[[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[8,0,2,0]]
),
(
[[0,0,0,0],
[4,0,0,0],
[0,0,0,0],
[4,0,2,0]],
Direction.LEFT,
[[0,0,0,0],
[4,0,0,0],
[0,0,0,0],
[4,2,0,0]]
),
(
[[0,0,0,0],
[4,0,0,0],
[0,0,0,0],
[4,0,2,0]],
Direction.RIGHT,
[[0,0,0,0],
[0,0,0,4],
[0,0,0,0],
[0,0,4,2]]
),
(
[[4,4,4,4],
[8,0,8,4],
[32,16,0,16],
[16,8,2,4]],
Direction.RIGHT,
[[0,0,8,8],
[0,0,16,4],
[0,0,32,32],
[16,8,2,4]]
),
(
[[4,4,4,4],
[8,0,8,4],
[32,16,0,16],
[16,8,2,4]],
Direction.LEFT,
[[8,8,0,0],
[16,4,0,0],
[32,32,0,0],
[16,8,2,4]]
),
(
[[4,4,4,4],
[8,0,8,4],
[32,16,0,16],
[16,8,2,4]],
Direction.UP,
[[4,4,4,8],
[8,16,8,16],
[32,8,2,4],
[16,0,0,0]]
),
(
[[4,4,4,4],
[8,0,8,4],
[32,16,0,16],
[16,8,2,4]],
Direction.DOWN,
[[4,0,0,0],
[8,4,4,8],
[32,16,8,16],
[16,8,2,4]]
)
] | 18.623656 | 43 | 0.265012 |
91ce29247f546090ea7272eb8cba1493be43a9a9 | 449 | py | Python | test/utils/test_value.py | HansBug/pji | 449d171cea0c03f4c302da886988f36f70e34ee6 | [
"Apache-2.0"
] | null | null | null | test/utils/test_value.py | HansBug/pji | 449d171cea0c03f4c302da886988f36f70e34ee6 | [
"Apache-2.0"
] | null | null | null | test/utils/test_value.py | HansBug/pji | 449d171cea0c03f4c302da886988f36f70e34ee6 | [
"Apache-2.0"
] | null | null | null | import pytest
from pji.utils import ValueProxy
| 20.409091 | 36 | 0.63029 |
91d00c668e9c3c29e1e078f088b136cfebc103ca | 1,727 | py | Python | intro.py | Ebenazer-2002/library-management | 8c1ededc7167d2221a3947abfeec4773da39dca9 | [
"Apache-2.0"
] | null | null | null | intro.py | Ebenazer-2002/library-management | 8c1ededc7167d2221a3947abfeec4773da39dca9 | [
"Apache-2.0"
] | null | null | null | intro.py | Ebenazer-2002/library-management | 8c1ededc7167d2221a3947abfeec4773da39dca9 | [
"Apache-2.0"
] | 1 | 2021-09-22T22:08:15.000Z | 2021-09-22T22:08:15.000Z | #Intro Page
from tkinter import *
from PIL import Image, ImageTk
import cv2
#----------------------------Start Function--------------------------#
#------------------------Main Window---------------------------------#li
main_window()
| 28.311475 | 72 | 0.466126 |
91d02ed15b88e5d9e5da4c1c6b0a923344ec181d | 16,740 | py | Python | notebooks/week4_help.py | hugh9876/04-multivariate-analysis | 0541962842df8844aa323c368f8a4e44999c2d7f | [
"MIT"
] | null | null | null | notebooks/week4_help.py | hugh9876/04-multivariate-analysis | 0541962842df8844aa323c368f8a4e44999c2d7f | [
"MIT"
] | null | null | null | notebooks/week4_help.py | hugh9876/04-multivariate-analysis | 0541962842df8844aa323c368f8a4e44999c2d7f | [
"MIT"
] | null | null | null | """
This module provides helper functions to support exercises during AM1
with outliers, robust regression and template regression in the CORE
data analytics workshop series, week 4.
"""
import numpy as np
import pandas as pd
import math
from collections import namedtuple
def recovery_sulphur_dataframe_with_outliers(outlier_probability):
"""Return dataframe representing recovery as a function of sulphur.
Parameters:
----------
outlier_probability:
This floating point parameter should range between 0 and 1
and is probability of an observation being an outlier.
Returns:
-------
Pandas dataframe:
A dataframe is returned with two series, the first being observed
recovery, and the second being sulphur %. The data may be sampled
from the true underlying relationship, plus gaussian noise, or
may be an outlier value taken from a non-gaussian distribution.
The proportion of outliers to non-outliers will depend on
the outlier_probability parameter.
"""
# Check that the outlier_probability is an ordinary number.
assert isinstance(outlier_probability, (float, int))
# As it's a probability, ensure that it ranges between 0 and 1.
assert outlier_probability >= 0.0
assert outlier_probability <= 1.0
# If no exceptions have been thrown then we likely have a valid input.
# Get 50 pairs of sulphur features and recovery labels
sulphur_percent = _draw_sulphur_observations(50)
recovery_percent = _observe_recovery(sulphur_percent,
outlier_probability)
return pd.DataFrame({'metal_recovery_percent': recovery_percent,
'feed_sulphur_percent': sulphur_percent})
def _initialise_randomstate(seed):
""" Use RandomState object with seed set."""
return np.random.RandomState(seed)
def _observe_recovery(sulphur_percent, outlier_probability):
"""Returns an array of metal recoveries.
This method returns an array of metal recoveries given both
an array of sulphur percentages and the probability of an
outlier being observed.
"""
recovery_percent = np.zeros_like(sulphur_percent)
is_outlier = _is_outlier(outlier_probability, len(sulphur_percent))
for index in range(0, len(recovery_percent)):
if is_outlier[index]:
recovery_percent [index]= _return_outlier_model_of_recovery(sulphur_percent[index])
else:
recovery_percent [index]=_noise_free_model_of_recovery(sulphur_percent[index])
return recovery_percent
def _noise_free_model_of_recovery(sulphur):
"""This method returns a metal recovery for a given sulphur %."""
return 74.81 - 6.81/sulphur
def _is_outlier(outlier_probability, how_many):
"""Return true/false numpy array
"""
rs = _initialise_randomstate(5)
uniformly_distributed = rs.uniform(0, 1, how_many)
is_outlier = np.zeros_like(uniformly_distributed)
for index in range(0, len(is_outlier)):
is_outlier[index]=uniformly_distributed[index]>(1-outlier_probability)
return is_outlier
def add_gaussian_noise(noise_free_input, mean, sigma):
"""Adds gaussian noise to vector, given mean and sigma
"""
bins = len(noise_free_input)
noise = np.random.normal(mean, sigma, bins)
return noise_free_input + noise
def gaussian_fwhm_pdf(X, height, x_position, fwhm):
"""Returns guassian probability distribution function, given FWHM
This computes a gaussian probability density function (pdf) given a
Full Width at Half Maximum (FWHM) instead of standard deviation, and
scales it by the height parameters. If the height is one, then the
area of the guassian will also be unity, as required for a pdf, and
for preserving area when used as an impulse response function in
convolution operations.
Note, this returns the function, it does not sample from the
distribution.
"""
return gaussian_pdf(X, height, x_position, fwhm / (2 * math.sqrt(2 * math.log(2))))
def gaussian_pdf(X, area, x_position, standard_deviation):
"""Returns gaussian probability distribution function multiplied by area.
This computes a gaussian with unit area and multiplies it
by the area parameter. It is translated to be centered
on x_position and has the width specified by standard_deviation.
Unit area gaussians are used as probability distributions functions,
and are also important in convolutions, as area of the convolution
of two functions is the product of their areas. If it is important
for the convolution to preserve area of a function when convolved
with a gaussian then that gaussian needs to have unit area. Preserving
area also implies conservation of energy in many physical models.
It can be shown that the integral of the gaussian function is unity
when the guassian's height is scaled as a function of standard_deviation
as:
height_scaling = 1/(standard_deviation*sqrt(2*pi))
So this function multiplies the height of the guassian by this factor and
then multiplies this result by the area parameter that is passed in.
If area parameter is 1, then the height of this gaussian with also
be 1 for all standard deviations, otherwise the area will be set by the
area parameter. The relationship between height and area, and the scaling
of height by the second parameter below, will be made clearer by
also studying the guassian function.
"""
return gaussian(X, area / (standard_deviation * math.sqrt(2 * math.pi)), x_position,
standard_deviation)
def gaussian(X, height, x_position, standard_deviation):
"""Return standard gaussian function
This is the unnormalised gaussian function
f(x)=height*exp(-(x-x_position)^2/(2*standard_deviation^2))
Parameters
----------
height:
This is the maximum of the gaussian peak.
This function does not normalise to constant area, the caller
must do this if this is what they want.
x_position:
This is the x position of the centre of the gaussian. If the
guassian is being used to apply the impulse response of an
instrument applied to an XRD reflection, then this will be the
two-theta position of the peak.
standard_deviation:
The standard deviation of the guassian curve.
If this function is being applied in spectroscopy, optics or
electrical engineering, it is common for gaussians to be
defined in terms of Full Width at Half Maximum (FWHM), which
is the width of the peak when the height drops to half
of the peak height, specified by the height parameter. If
the x-axis represents frequency, and the function height
is proportional to energy or power, then this will be the
gaussian's bandwidth, that is, the width between the -3db points.
To convert from FWHM to standard deviation use the relationship:
FWHM = 2*sqrt(2*log(2)) * standard_deviation
Returns
-------
double:
Evaluated gaussian function.
"""
return height * math.e**(-(X - x_position)**2 / 2 / standard_deviation**2)
def _apply_convolution_kernals(x_axis_vector, intensity, two_theta_angle,
instrument_broadening_fwhm,
reflection_broadening_fwhm):
"""Apply gaussian kernel for instrument broadening only."""
fwhm = _add_gaussian_fwhms (instrument_broadening_fwhm,
reflection_broadening_fwhm)
return gaussian_fwhm_pdf(x_axis_vector, intensity, two_theta_angle,
fwhm)
def create_templates_matrix():
"""Create templates for four test pure components.
This creates templates for quartz, dilithium, kryptonite and
unobtainium, in that order. The templates are returned
in an array where the first column is quartz, and the last is
unobtainium. If you plot them, you'll see gently varying
squiggly lines.
"""
# Create a templates matrix containing space for four templates, plus
# a column of ones.
x_axis = MultichannelXAxis(5, 90, 0.2)
template_count = 4
templates_matrix = np.zeros((x_axis.channel_count, template_count+1))
# set 4 two-theta units of instrument broadening
instrument_broadening = 4
# create a tuple for each reflection, and add it to a list. The loop
# then grabs each reflection from the list and then adds it to the
# template. The first value in the tuple is intensity, the second
# two-theta angle and the third is how much broadening to apply.
Reflection = namedtuple('Reflection', ('intensity', 'two_theta', 'broadening'))
quartz_reflections = []
quartz_reflections.append (Reflection(intensity=10.0, two_theta=25.0, broadening=3.0))
quartz_reflections.append (Reflection(13.0, 38.0, 6.0))
quartz_reflections.append (Reflection(10.0, 43.0, 2.0))
quartz_reflections.append (Reflection(25.0, 60, 2.0))
dilithium_reflections = []
dilithium_reflections.append (Reflection(25.0, 80, 1.0))
kryptonite_reflections = []
#kryptonite_reflections.append (Reflection(intensity=12.0, two_theta=25.0, broadening=9.0))
kryptonite_reflections.append (Reflection(17.0, 12.0, 1.0))
kryptonite_reflections.append (Reflection(19.0, 43.0, 12.0))
#kryptonite_reflections.append (Reflection(4.0, 70, 2.0))
#kryptonite_reflections.append (Reflection(32.0, 74, 2.0))
unobtainium_reflections = []
#unobtainium_reflections.append (Reflection(intensity=4.0, two_theta=25.0, broadening=12.0))
unobtainium_reflections.append (Reflection(5.0, 18.0, 6.0))
unobtainium_reflections.append (Reflection(1.0, 23.0, 1.0))
unobtainium_reflections.append (Reflection(5.0, 31.0, 2.0))
unobtainium_reflections.append (Reflection(3.0, 55.0, 6.0))
unobtainium_reflections.append (Reflection(7.0, 58.0, 1.0))
#unobtainium_reflections.append (Reflection(5.0, 80, 2.0))
phases=[]
# create four phases
phases.append(quartz_reflections)
phases.append(dilithium_reflections)
phases.append(kryptonite_reflections)
phases.append(unobtainium_reflections)
for phase_idx in range(0, template_count):
for a_reflection in phases[phase_idx]:
contribution_of_this_reflection = \
_apply_convolution_kernals(
x_axis.as_vector,
a_reflection.intensity,
a_reflection.two_theta,
instrument_broadening,
a_reflection.broadening)
templates_matrix[:, phase_idx] += \
contribution_of_this_reflection
# set the last column to be all ones
templates_matrix[:, template_count] = \
np.ones(x_axis.channel_count)
return templates_matrix
def create_composition_dataframe(observations_count):
"""Create a dataframe of observations of drilling samples
Returns:
Pandas DataFrame with observations_count observations.
The dataframe has four columns representing the amount
of quartz, dilithium, kryptonite and unobtainium present.
These values are drawn from uniform distributions."""
unobtainium = _draw_unobtainium_observations (observations_count)
dilithium = _draw_dilithium_observations(observations_count)
kryptonite = _draw_kryptonite_observations(observations_count)
quartz = _draw_quartz_observations(observations_count)
# Create clusters by imposing a relationship between quartz
# and dilithium.
for observation_idx in range(0, observations_count):
if quartz[observation_idx] > 30:
dilithium[observation_idx] = 5
if dilithium[observation_idx] > 30:
quartz[observation_idx] = 5
return pd.DataFrame({'Quartz': quartz,
'Dilithium': dilithium,
'Kryptonite': kryptonite,
'Unobtainium': unobtainium})
def create_observations(compositions_dataframe, templates):
"""Create a new array containing synthetic observations"""
observations_count = len(compositions_dataframe)
channels_count = len(templates[:,0])
observations_matrix = np.zeros((channels_count, observations_count))
for observation_idx in range (0, observations_count):
observations_matrix[:, observation_idx] = \
templates[:,0]*compositions_dataframe['Quartz'][observation_idx] + \
templates[:,1]*compositions_dataframe['Dilithium'][observation_idx] + \
templates[:,2]*compositions_dataframe['Kryptonite'][observation_idx] + \
templates[:,3]*compositions_dataframe['Unobtainium'][observation_idx]
# add gaussian noise. If you have time, try increasing this and watch
# prediction performance fall over.
observations_matrix[:, observation_idx] = \
add_gaussian_noise(observations_matrix[:, observation_idx], 10, 3)
return observations_matrix
| 41.435644 | 97 | 0.683871 |
91d0d1d94cdf45c4bcbd44fd68f0bba0ecae92c7 | 2,671 | py | Python | tests/actions/test_mutable_token_action.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 32 | 2022-01-12T16:52:28.000Z | 2022-03-24T18:05:47.000Z | tests/actions/test_mutable_token_action.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 3 | 2022-01-12T17:01:55.000Z | 2022-02-12T15:14:16.000Z | tests/actions/test_mutable_token_action.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 1 | 2022-01-21T04:28:07.000Z | 2022-01-21T04:28:07.000Z | from radixlib.actions import CreateTokenDefinition
from typing import Dict, Any
import unittest | 47.696429 | 110 | 0.675028 |
91d124efa1b2bf7e4e72928accf387408c43adc6 | 113 | py | Python | src/tests/testModules/loadCfg_typeCasting/allowsCastFailKeeping/primativeTypes.py | Trimatix/carica | 074be16bdf50541eb3ba92ca42d0ad901cc51bd0 | [
"Apache-2.0"
] | 5 | 2021-09-08T07:29:23.000Z | 2021-11-24T00:18:22.000Z | src/tests/testModules/loadCfg_typeCasting/allowsCastFailKeeping/primativeTypes.py | Trimatix/Carica | 074be16bdf50541eb3ba92ca42d0ad901cc51bd0 | [
"Apache-2.0"
] | 42 | 2021-09-08T07:31:25.000Z | 2022-01-16T17:39:34.000Z | src/tests/testModules/loadCfg_typeCasting/allowsCastFailKeeping/primativeTypes.py | Trimatix/carica | 074be16bdf50541eb3ba92ca42d0ad901cc51bd0 | [
"Apache-2.0"
] | null | null | null | floatVar = 1.0
listVar = [3, "hello"]
dictVar = {
"myField": "value"
}
aotVar = [dictVar, dictVar]
intVar = 1 | 16.142857 | 27 | 0.610619 |
91d348a1fe2260f1d59725d0f07d7baf69518dae | 22 | py | Python | quacc/recipes/xtb/__init__.py | arosen93/HT-ASE | a76542e7a2bc5bf6e7382d8f1387374eb2abc713 | [
"BSD-3-Clause-LBNL"
] | 9 | 2022-02-08T08:31:30.000Z | 2022-03-30T21:37:35.000Z | quacc/recipes/xtb/__init__.py | arosen93/HT-ASE | a76542e7a2bc5bf6e7382d8f1387374eb2abc713 | [
"BSD-3-Clause-LBNL"
] | 5 | 2022-02-02T21:47:59.000Z | 2022-03-18T21:28:52.000Z | quacc/recipes/xtb/__init__.py | arosen93/HT-ASE | a76542e7a2bc5bf6e7382d8f1387374eb2abc713 | [
"BSD-3-Clause-LBNL"
] | 3 | 2022-02-23T12:00:57.000Z | 2022-03-24T23:54:22.000Z | """Recipes for xTB"""
| 11 | 21 | 0.590909 |
91d380ce2b1e14c5b063e9056626bb2c1ea92f55 | 6,869 | py | Python | src/python/pants/backend/native/subsystems/xcode_cli_tools.py | StephanErb/pants | a368267b6b4cf50138ba567f582409ed31bf5db9 | [
"Apache-2.0"
] | null | null | null | src/python/pants/backend/native/subsystems/xcode_cli_tools.py | StephanErb/pants | a368267b6b4cf50138ba567f582409ed31bf5db9 | [
"Apache-2.0"
] | null | null | null | src/python/pants/backend/native/subsystems/xcode_cli_tools.py | StephanErb/pants | a368267b6b4cf50138ba567f582409ed31bf5db9 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pants.backend.native.config.environment import Assembler, CCompiler, CppCompiler, Linker
from pants.engine.rules import rule
from pants.engine.selectors import Select
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil import is_readable_dir
from pants.util.memo import memoized_method, memoized_property
MIN_OSX_SUPPORTED_VERSION = '10.11'
MIN_OSX_VERSION_ARG = '-mmacosx-version-min={}'.format(MIN_OSX_SUPPORTED_VERSION)
def create_xcode_cli_tools_rules():
return [
get_assembler,
get_ld,
get_clang,
get_clang_plusplus,
]
| 34.345 | 105 | 0.7084 |
91d43878e8db19b2ac8a4228dcc70b222e3033cf | 11,998 | py | Python | improver_tests/regrid/test_RegridWithLandSeaMask.py | yzhaobom/improver | 47f9e103c63f890bfbb24d5e08d9d01d041514f7 | [
"BSD-3-Clause"
] | 77 | 2017-04-26T07:47:40.000Z | 2022-03-31T09:40:49.000Z | improver_tests/regrid/test_RegridWithLandSeaMask.py | yzhaobom/improver | 47f9e103c63f890bfbb24d5e08d9d01d041514f7 | [
"BSD-3-Clause"
] | 1,440 | 2017-03-29T10:04:15.000Z | 2022-03-28T10:11:29.000Z | improver_tests/regrid/test_RegridWithLandSeaMask.py | MoseleyS/improver | ca028e3a1c842e3ff00b188c8ea6eaedd0a07149 | [
"BSD-3-Clause"
] | 72 | 2017-03-17T16:53:45.000Z | 2022-02-16T09:41:37.000Z | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for the RegridWithLandSeaMask class"""
# set up a special data set and corresponding land-sea mask info
# set up target grid and its land-sea mask info
# it is designed to cover different scenarios for regridding with land-sea
# the regridding reference results are manually checked for different methods
# not using "set_up_variable_cube" because of different spacing at lat/lon
import numpy as np
from improver.regrid.bilinear import basic_indexes
from improver.regrid.grid import calculate_input_grid_spacing, latlon_from_cube
from improver.regrid.landsea import RegridLandSea
from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube
def modify_cube_coordinate_value(cube, coord_x, coord_y):
"""modify x(longitude) & y(latitude) andcoordinates for a cube"""
cube.coord(axis="x").points = coord_x
cube.coord(axis="x").bounds = None
cube.coord(axis="x").guess_bounds()
cube.coord(axis="y").points = coord_y
cube.coord(axis="y").bounds = None
cube.coord(axis="y").guess_bounds()
return cube
def define_source_target_grid_data():
""" define cube_in, cube_in_mask,cube_out_mask using assumed data """
# source (input) grid
in_lats = np.linspace(0, 15, 4)
in_lons = np.linspace(0, 40, 5)
# target (output) grid
out_lats = np.linspace(0, 14, 8)
out_lons = np.linspace(5, 35, 11)
# assume a set of nwp data
data = np.arange(20).reshape(4, 5).astype(np.float32)
# input grid mask info
in_mask = np.empty((4, 5), dtype=np.int)
in_mask[:, :] = 1
in_mask[0, 2] = 0
in_mask[2, 2:4] = 0
in_mask[3, 2:4] = 0
# output grid mask info
out_mask = np.empty((8, 11), dtype=np.int)
out_mask[:, :] = 1
out_mask[0, 4:7] = 0
out_mask[1, 5] = 0
out_mask[5:9, 4:10] = 0
out_mask[6, 6] = 1
out_mask[7, 6] = 1
out_mask[1, 0] = 0
# create cube with default spacing
cube_in = set_up_variable_cube(data, "air_temperature", "Celsius")
cube_in_mask = set_up_variable_cube(in_mask, "Land_Binary_Mask", "1")
cube_out_mask = set_up_variable_cube(out_mask, "Land_Binary_Mask", "1")
# modify cube coordinates to the designed value
cube_in = modify_cube_coordinate_value(cube_in, in_lons, in_lats)
cube_in_mask = modify_cube_coordinate_value(cube_in_mask, in_lons, in_lats)
cube_out_mask = modify_cube_coordinate_value(cube_out_mask, out_lons, out_lats)
return cube_in, cube_out_mask, cube_in_mask
def define_source_target_grid_data_same_domain():
""" define cube_in, cube_in_mask,cube_out_mask, assume the same domain """
# source (input) grid
in_lats = np.linspace(0, 15, 4)
in_lons = np.linspace(0, 40, 5)
# target (output) grid
out_lats = np.linspace(0, 15, 7)
out_lons = np.linspace(5, 40, 9)
# assume a set of nwp data
data = np.arange(20).reshape(4, 5).astype(np.float32)
# input grid mask info
in_mask = np.empty((4, 5), dtype=np.int)
in_mask[:, :] = 1
in_mask[0, 2] = 0
in_mask[2, 2:4] = 0
in_mask[3, 2:4] = 0
# output grid mask info
out_mask = np.empty((7, 9), dtype=np.int)
out_mask[:, :] = 1
out_mask[0, 3:6] = 0
out_mask[1, 4] = 0
out_mask[4:9, 4:8] = 0
out_mask[6, 6] = 1
out_mask[1, 0] = 0
# create cube with default spacing
cube_in = set_up_variable_cube(data, "air_temperature", "Celsius")
cube_in_mask = set_up_variable_cube(in_mask, "Land_Binary_Mask", "1")
cube_out_mask = set_up_variable_cube(out_mask, "Land_Binary_Mask", "1")
# modify cube coordinates to the designed value
cube_in = modify_cube_coordinate_value(cube_in, in_lons, in_lats)
cube_in_mask = modify_cube_coordinate_value(cube_in_mask, in_lons, in_lats)
cube_out_mask = modify_cube_coordinate_value(cube_out_mask, out_lons, out_lats)
return cube_in, cube_out_mask, cube_in_mask
def test_basic_indexes():
"""Test basic_indexes for identical source and target domain case """
cube_in, cube_out_mask, _ = define_source_target_grid_data_same_domain()
in_latlons = latlon_from_cube(cube_in)
out_latlons = latlon_from_cube(cube_out_mask)
in_lons_size = cube_in.coord(axis="x").shape[0]
lat_spacing, lon_spacing = calculate_input_grid_spacing(cube_in)
indexes = basic_indexes(
out_latlons, in_latlons, in_lons_size, lat_spacing, lon_spacing
)
test_results = indexes[58:63, :]
expected_results = np.array(
[
[12, 17, 18, 13],
[12, 17, 18, 13],
[13, 18, 19, 14],
[13, 18, 19, 14],
[13, 18, 19, 14],
]
)
np.testing.assert_array_equal(test_results, expected_results)
def test_regrid_nearest_2():
"""Test nearest neighbour regridding option 'nearest-2'"""
cube_in, cube_out_mask, _ = define_source_target_grid_data()
regrid_nearest = RegridLandSea(regrid_mode="nearest-2",)(cube_in, cube_out_mask)
expected_results = np.array(
[
[0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3],
[0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3],
[5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8],
[5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8],
[10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13],
[10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13],
[10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13],
[15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 18],
]
)
np.testing.assert_allclose(regrid_nearest.data, expected_results, atol=1e-3)
def test_regrid_bilinear_2():
"""Test bilinear regridding option 'bilinear-2'"""
cube_in, cube_out_mask, _ = define_source_target_grid_data()
regrid_bilinear = RegridLandSea(regrid_mode="bilinear-2",)(cube_in, cube_out_mask)
expected_results = np.array(
[
[0.5, 0.8, 1.1, 1.4, 1.7, 2.0, 2.3, 2.6, 2.9, 3.2, 3.5],
[2.5, 2.8, 3.1, 3.4, 3.7, 4.0, 4.3, 4.6, 4.9, 5.2, 5.5],
[4.5, 4.8, 5.1, 5.4, 5.7, 6.0, 6.3, 6.6, 6.9, 7.2, 7.5],
[6.5, 6.8, 7.1, 7.4, 7.7, 8.0, 8.3, 8.6, 8.9, 9.2, 9.5],
[8.5, 8.8, 9.1, 9.4, 9.7, 10.0, 10.3, 10.6, 10.9, 11.2, 11.5],
[10.5, 10.8, 11.1, 11.4, 11.7, 12.0, 12.3, 12.6, 12.9, 13.2, 13.5],
[12.5, 12.8, 13.1, 13.4, 13.7, 14.0, 14.3, 14.6, 14.9, 15.2, 15.5],
[14.5, 14.8, 15.1, 15.4, 15.7, 16.0, 16.3, 16.6, 16.9, 17.2, 17.5],
]
)
np.testing.assert_allclose(regrid_bilinear.data, expected_results, atol=1e-3)
def test_regrid_nearest_with_mask_2():
"""Test nearest-with-mask-2 regridding"""
cube_in, cube_out_mask, cube_in_mask = define_source_target_grid_data()
regrid_nearest_with_mask = RegridLandSea(
regrid_mode="nearest-with-mask-2",
landmask=cube_in_mask,
landmask_vicinity=250000000,
)(cube_in, cube_out_mask)
expected_results = np.array(
[
[0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3],
[0, 1, 1, 1, 7, 2, 7, 3, 3, 3, 3],
[5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8],
[5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9],
[10, 11, 11, 11, 7, 7, 7, 8, 8, 8, 14],
[10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14],
[10, 11, 11, 11, 12, 12, 7, 13, 13, 13, 14],
[15, 16, 16, 16, 17, 17, 7, 18, 18, 18, 19],
]
)
np.testing.assert_allclose(
regrid_nearest_with_mask.data, expected_results, atol=1e-3
)
# consider constant field
cube_in.data = np.repeat(1.0, 20).reshape(4, 5).astype(np.float32)
regrid_nearest_with_mask = RegridLandSea(
regrid_mode="nearest-with-mask-2",
landmask=cube_in_mask,
landmask_vicinity=250000000,
)(cube_in, cube_out_mask)
expected_results = np.repeat(1.0, 88).reshape(8, 11).astype(np.float32)
np.testing.assert_allclose(
regrid_nearest_with_mask.data, expected_results, atol=1e-3
)
def test_regrid_bilinear_with_mask_2():
"""Test bilinear-with-mask-2 regridding """
cube_in, cube_out_mask, cube_in_mask = define_source_target_grid_data()
regrid_bilinear_with_mask = RegridLandSea(
regrid_mode="bilinear-with-mask-2",
landmask=cube_in_mask,
landmask_vicinity=250000000,
)(cube_in, cube_out_mask)
expected_results = np.array(
[
[0.5, 0.8, 1.40096, 3.2916, 2.0, 2.0, 2.0, 4.94333, 3.25586, 3.2, 3.5],
[2.5, 2.8, 3.1, 3.4, 5.48911, 2.76267, 6.32926, 4.6, 4.9, 5.2, 5.5],
[4.5, 4.8, 5.1, 5.4, 5.7, 7.0154, 6.3, 6.6, 6.9, 7.2, 7.5],
[6.5, 6.8, 7.1, 7.4, 7.7, 7.0, 7.19033, 7.6681, 7.6618, 9.2, 9.5],
[
8.5,
8.8,
9.1,
9.4,
8.10633,
7.0,
7.0,
7.62915,
7.21672,
9.11434,
10.52363,
],
[
10.5,
10.8,
11.00012,
11.01183,
13.15439,
12.0,
12.3,
12.6,
12.9,
13.71286,
15.74504,
],
[
12.5,
12.8,
12.23411,
13.25881,
14.14155,
14.0,
8.07328,
14.6,
14.9,
14.96332,
16.3334,
],
[
14.5,
14.8,
15.0997,
14.22659,
15.50905,
16.0,
9.8733,
16.6,
16.9,
16.91114,
17.03773,
],
]
)
np.testing.assert_allclose(
regrid_bilinear_with_mask.data, expected_results, atol=1e-3
)
# consider constant field
cube_in.data = np.repeat(1.0, 20).reshape(4, 5).astype(np.float32)
regrid_bilinear_with_mask = RegridLandSea(
regrid_mode="bilinear-with-mask-2",
landmask=cube_in_mask,
landmask_vicinity=250000000,
)(cube_in, cube_out_mask)
expected_results = np.repeat(1.0, 88).reshape(8, 11).astype(np.float32)
np.testing.assert_allclose(
regrid_bilinear_with_mask.data, expected_results, atol=1e-3
)
| 35.602374 | 86 | 0.596516 |
91d4aad729e6a3ae80ef7ec7692d7daf662bb479 | 1,127 | py | Python | setup.py | garnaat/details | 07f2fc7f27b29a6ddcda918abf6ae0882450319e | [
"Apache-2.0"
] | 27 | 2015-03-01T10:54:32.000Z | 2021-09-08T14:52:30.000Z | setup.py | garnaat/details | 07f2fc7f27b29a6ddcda918abf6ae0882450319e | [
"Apache-2.0"
] | 3 | 2015-01-29T08:26:13.000Z | 2017-02-14T09:35:06.000Z | setup.py | garnaat/details | 07f2fc7f27b29a6ddcda918abf6ae0882450319e | [
"Apache-2.0"
] | 7 | 2015-03-26T13:53:34.000Z | 2017-05-23T20:58:28.000Z | #!/usr/bin/env python
from setuptools import setup, find_packages
import os
requires = [
]
setup(
name='details',
version=open(os.path.join('details', '_version')).read(),
description='Tools for processing AWS detailed billing reports',
long_description=open('README.md').read(),
author='Mitch Garnaat',
author_email='mitch@scopely.com',
url='https://github.com/scopely-devops/details',
packages=find_packages(exclude=['tests*']),
package_dir={'details': 'details'},
install_requires=requires,
license=open("LICENSE").read(),
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
)
| 30.459459 | 68 | 0.632653 |
91d5346576f73b2550ed5c3a87e027cb58449870 | 4,686 | py | Python | beam_telescope_analysis/testing/test_kalman.py | YannickDieter/beam_telescope_analysis | 0c678ad991a9ef42178b2eeaf58059d387362f2a | [
"MIT"
] | 3 | 2019-03-14T09:28:43.000Z | 2020-02-24T13:04:12.000Z | beam_telescope_analysis/testing/test_kalman.py | YannickDieter/beam_telescope_analysis | 0c678ad991a9ef42178b2eeaf58059d387362f2a | [
"MIT"
] | 14 | 2019-05-09T10:01:06.000Z | 2021-05-20T12:52:46.000Z | beam_telescope_analysis/testing/test_kalman.py | YannickDieter/beam_telescope_analysis | 0c678ad991a9ef42178b2eeaf58059d387362f2a | [
"MIT"
] | 1 | 2019-09-07T12:06:35.000Z | 2019-09-07T12:06:35.000Z | ''' Script to check the correctness of the analysis. The analysis is done on raw data and all results are compared to a recorded analysis.
'''
import os
import unittest
import numpy as np
from beam_telescope_analysis import track_analysis
from beam_telescope_analysis.tools import test_tools
if __name__ == '__main__':
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - [%(levelname)-8s] (%(threadName)-10s) %(message)s")
suite = unittest.TestLoader().loadTestsFromTestCase(TestTrackAnalysis)
unittest.TextTestRunner(verbosity=2).run(suite)
| 62.48 | 153 | 0.588135 |
91d54e85fa9e683a691056ba3de4c8a49958c847 | 3,723 | py | Python | test/test_workflow.py | asnramos/asv | 8a0979b532d06c7c352826e2acf0dd872922260e | [
"BSD-3-Clause"
] | null | null | null | test/test_workflow.py | asnramos/asv | 8a0979b532d06c7c352826e2acf0dd872922260e | [
"BSD-3-Clause"
] | null | null | null | test/test_workflow.py | asnramos/asv | 8a0979b532d06c7c352826e2acf0dd872922260e | [
"BSD-3-Clause"
] | null | null | null | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import glob
import os
import sys
import json
from os.path import join, isfile
import pytest
from asv import util
from . import tools
| 39.189474 | 85 | 0.552243 |
91d673a77f43b00da4523b7edc231f25e64c3f72 | 5,750 | py | Python | trainer.py | Metro1998/P-DQN | 6ab2ac6991d2685f10887c16f854ebba6144b306 | [
"MIT"
] | 5 | 2021-12-13T15:25:07.000Z | 2022-03-29T12:42:37.000Z | trainer.py | Metro1998/P-DQN | 6ab2ac6991d2685f10887c16f854ebba6144b306 | [
"MIT"
] | null | null | null | trainer.py | Metro1998/P-DQN | 6ab2ac6991d2685f10887c16f854ebba6144b306 | [
"MIT"
] | null | null | null | # @author Metro
# @time 2021/11/24
import os.path
import gym
from agents.pdqn import P_DQN
from utilities.memory import ReplayBuffer
from utilities.utilities import *
from utilities.route_generator import generate_routefile
| 42.592593 | 113 | 0.598609 |
91d7cad5b4e7e6fe780b392c22b198941b8e6380 | 10,434 | py | Python | server/splunkdj/views.py | splunk/splunk-webframework | a4179558616f5f4fcbfa2b54e9179f30e6395264 | [
"Apache-2.0"
] | 31 | 2015-01-20T12:49:17.000Z | 2022-02-21T05:21:44.000Z | server/splunkdj/views.py | splunk/splunk-webframework | a4179558616f5f4fcbfa2b54e9179f30e6395264 | [
"Apache-2.0"
] | 2 | 2015-07-08T19:40:41.000Z | 2018-04-26T21:34:35.000Z | server/splunkdj/views.py | splunk/splunk-webframework | a4179558616f5f4fcbfa2b54e9179f30e6395264 | [
"Apache-2.0"
] | 8 | 2015-02-26T13:19:45.000Z | 2022-03-27T08:34:20.000Z | import sys
import pprint
import json
import datetime
import uuid
import urllib
import types
import traceback
from django.core.urlresolvers import reverse, resolve
from django.http import HttpResponseRedirect, Http404, HttpResponseServerError, HttpResponseNotFound
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.views.debug import ExceptionReporter, get_safe_settings
from django.template import TemplateDoesNotExist, Context
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.shortcuts import render
from splunkdj.decorators.render import render_to
from splunkdj.utility import make_splunkweb_url
from urlparse import urlparse
import logging
logger = logging.getLogger('spl.django.service')
error_logger = logging.getLogger('spl.django.request_error')
def format(value):
"""
Format values appropriately for json.dumps:
- Basic types will remain the same
- Unicode will be converted to str
- Everything else will be formatted using pprint
"""
if value is None:
return value
if isinstance(value, (int, long, str, float, list, dict, tuple, bool, unicode)):
return value
return str(pprint.pformat(value))
| 37.804348 | 119 | 0.637531 |
91d867e70ec797fb77cf3fedd501ea6a1aca218d | 8,301 | py | Python | wbia/plottool/interact_keypoints.py | mmulich/wildbook-ia | 81b405e2bfaa3f6c30a546fb6dc6e6488e9b2663 | [
"Apache-2.0"
] | null | null | null | wbia/plottool/interact_keypoints.py | mmulich/wildbook-ia | 81b405e2bfaa3f6c30a546fb6dc6e6488e9b2663 | [
"Apache-2.0"
] | null | null | null | wbia/plottool/interact_keypoints.py | mmulich/wildbook-ia | 81b405e2bfaa3f6c30a546fb6dc6e6488e9b2663 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
import utool as ut
import six
from . import draw_func2 as df2
from wbia.plottool import plot_helpers as ph
from wbia.plottool import interact_helpers as ih
from wbia.plottool.viz_featrow import draw_feat_row
from wbia.plottool.viz_keypoints import show_keypoints
from wbia.plottool import abstract_interaction
(print, rrr, profile) = ut.inject2(__name__)
logger = logging.getLogger('wbia')
def ishow_keypoints(chip, kpts, desc, fnum=0, figtitle=None, nodraw=False, **kwargs):
"""
TODO: Depricate in favor of the class
CommandLine:
python -m wbia.plottool.interact_keypoints --test-ishow_keypoints --show
python -m wbia.plottool.interact_keypoints --test-ishow_keypoints --show --fname zebra.png
Example:
>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_keypoints import * # NOQA
>>> import numpy as np
>>> import wbia.plottool as pt
>>> import utool as ut
>>> import pyhesaff
>>> import vtool as vt
>>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
>>> ut.quit_if_noshow()
>>> #pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4, color='distinct')
>>> pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4)
>>> pt.show_if_requested()
"""
if isinstance(chip, six.string_types):
import vtool as vt
chip = vt.imread(chip)
fig = ih.begin_interaction('keypoint', fnum)
annote_ptr = [1]
self = ut.DynStruct() # MOVE TO A CLASS INTERACTION
self.kpts = kpts
vecs = desc
self.vecs = vecs
# Draw without keypoints the first time
_viz_keypoints(fnum, **kwargs) # MAYBE: remove kwargs
ih.connect_callback(fig, 'button_press_event', _on_keypoints_click)
if not nodraw:
ph.draw()
| 39.15566 | 113 | 0.563787 |
91d921988391847f171d7f816701e122ce388582 | 143 | py | Python | tb/storage/__init__.py | DronMDF/manabot | b412e8cb9b5247f05487bed4cbf4967f7b58327f | [
"MIT"
] | 1 | 2017-11-29T11:51:12.000Z | 2017-11-29T11:51:12.000Z | tb/storage/__init__.py | DronMDF/manabot | b412e8cb9b5247f05487bed4cbf4967f7b58327f | [
"MIT"
] | 109 | 2017-11-28T20:51:59.000Z | 2018-02-02T13:15:29.000Z | tb/storage/__init__.py | DronMDF/manabot | b412e8cb9b5247f05487bed4cbf4967f7b58327f | [
"MIT"
] | null | null | null | from .database import StDatabase
from .telegram import StTelegram
from .tinydb import TinyDataBase, TinySelect
from .utility import StDispatch
| 28.6 | 44 | 0.846154 |
91d9d1d9ae07a637595f6f1be3521d0ea393c068 | 1,468 | py | Python | algorithms/maths/chinese_remainder_theorem.py | hbqdev/algorithms | 65cc8551d86d7e065069d165dd8bf9baf10345a0 | [
"MIT"
] | 22,426 | 2017-01-17T04:01:44.000Z | 2022-03-31T12:06:16.000Z | algorithms/maths/chinese_remainder_theorem.py | Shubhanshu156/algorithms | d8f1428cee7f66376929f72c524b6e0325bf3492 | [
"MIT"
] | 523 | 2017-04-18T12:05:11.000Z | 2022-03-20T11:10:41.000Z | algorithms/maths/chinese_remainder_theorem.py | AmandaStromdahl/algorithms | 1652835c3aef9aa670b67a5459e51dd3a8e6a71c | [
"MIT"
] | 4,900 | 2017-01-19T23:47:05.000Z | 2022-03-31T10:00:47.000Z | from algorithms.maths.gcd import gcd
from typing import List
def solve_chinese_remainder(num : List[int], rem : List[int]):
"""
Computes the smallest x that satisfies the chinese remainder theorem
for a system of equations.
The system of equations has the form:
x % num[0] = rem[0]
x % num[1] = rem[1]
...
x % num[k - 1] = rem[k - 1]
Where k is the number of elements in num and rem, k > 0.
All numbers in num needs to be pariwise coprime otherwise an exception is raised
returns x: the smallest value for x that satisfies the system of equations
"""
if not len(num) == len(rem):
raise Exception("num and rem should have equal length")
if not len(num) > 0:
raise Exception("Lists num and rem need to contain at least one element")
for n in num:
if not n > 1:
raise Exception("All numbers in num needs to be > 1")
if not _check_coprime(num):
raise Exception("All pairs of numbers in num are not coprime")
k = len(num)
x = 1
while True:
i = 0
while i < k:
if x % num[i] != rem[i]:
break
i += 1
if i == k:
return x
else:
x += 1
| 31.234043 | 84 | 0.559264 |
91da549f96f9ccca48e20a796a48546be83febae | 206 | py | Python | exercises/ja/exc_03_16_01.py | Jette16/spacy-course | 32df0c8f6192de6c9daba89740a28c0537e4d6a0 | [
"MIT"
] | 2,085 | 2019-04-17T13:10:40.000Z | 2022-03-30T21:51:46.000Z | exercises/ja/exc_03_16_01.py | Jette16/spacy-course | 32df0c8f6192de6c9daba89740a28c0537e4d6a0 | [
"MIT"
] | 79 | 2019-04-18T14:42:55.000Z | 2022-03-07T08:15:43.000Z | exercises/ja/exc_03_16_01.py | Jette16/spacy-course | 32df0c8f6192de6c9daba89740a28c0537e4d6a0 | [
"MIT"
] | 361 | 2019-04-17T13:34:32.000Z | 2022-03-28T04:42:45.000Z | import spacy
nlp = spacy.load("ja_core_news_sm")
text = (
""
""
)
#
doc = nlp(text)
print([token.text for token in doc])
| 17.166667 | 42 | 0.73301 |
91dad0ab0f33fc6693bf8cc4e9a065c0be985607 | 19,086 | py | Python | apphelper/image.py | caiyueliang/chineseocr | 4495598f938936c6bcb2222fa44f840a7919212c | [
"MIT"
] | null | null | null | apphelper/image.py | caiyueliang/chineseocr | 4495598f938936c6bcb2222fa44f840a7919212c | [
"MIT"
] | null | null | null | apphelper/image.py | caiyueliang/chineseocr | 4495598f938936c6bcb2222fa44f840a7919212c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
##
@author: lywen
"""
import sys
import six
import os
import base64
import requests
import numpy as np
import cv2
from PIL import Image
import traceback
import uuid
from glob import glob
from bs4 import BeautifulSoup
import numpy as np
from scipy.spatial import distance as dist
def _order_points(pts):
# x
"""
---------------------
Tong_T
CSDN
https://blog.csdn.net/Tong_T/article/details/81907132
"""
x_sorted = pts[np.argsort(pts[:, 0]), :]
#
# x
left_most = x_sorted[:2, :]
right_most = x_sorted[2:, :]
# y
left_most = left_most[np.argsort(left_most[:, 1]), :]
(tl, bl) = left_most
# ;
#
distance = dist.cdist(tl[np.newaxis], right_most, "euclidean")[0]
(br, tr) = right_most[np.argsort(distance)[::-1], :]
#
return np.array([tl, tr, br, bl], dtype="float32")
def solve(box):
"""
cx,cy w,h angle
x = cx-w/2
y = cy-h/2
x1-cx = -w/2*cos(angle) +h/2*sin(angle)
y1 -cy= -w/2*sin(angle) -h/2*cos(angle)
h(x1-cx) = -wh/2*cos(angle) +hh/2*sin(angle)
w(y1 -cy)= -ww/2*sin(angle) -hw/2*cos(angle)
(hh+ww)/2sin(angle) = h(x1-cx)-w(y1 -cy)
"""
x1,y1,x2,y2,x3,y3,x4,y4= box[:8]
cx = (x1+x3+x2+x4)/4.0
cy = (y1+y3+y4+y2)/4.0
w = (np.sqrt((x2-x1)**2+(y2-y1)**2)+np.sqrt((x3-x4)**2+(y3-y4)**2))/2
h = (np.sqrt((x2-x3)**2+(y2-y3)**2)+np.sqrt((x1-x4)**2+(y1-y4)**2))/2
#x = cx-w/2
#y = cy-h/2
sinA = (h*(x1-cx)-w*(y1 -cy))*1.0/(h*h+w*w)*2
if abs(sinA)>1:
angle = None
else:
angle = np.arcsin(sinA)
return angle,w,h,cx,cy
def read_singLine_for_yolo(p):
"""
"""
im = Image.open(p).convert('RGB')
w,h = im.size
boxes = [{'cx':w/2,'cy':h/2,'w':w,'h':h,'angle':0.0}]
return im,boxes
def xy_rotate_box(cx,cy,w,h,angle):
"""
cx,cy w,h angle
x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx
y_new = (x-cx)*sin(angle) + (y-cy)*sin(angle)+cy
"""
cx = float(cx)
cy = float(cy)
w = float(w)
h = float(h)
angle = float(angle)
x1,y1 = rotate(cx-w/2,cy-h/2,angle,cx,cy)
x2,y2 = rotate(cx+w/2,cy-h/2,angle,cx,cy)
x3,y3 = rotate(cx+w/2,cy+h/2,angle,cx,cy)
x4,y4 = rotate(cx-w/2,cy+h/2,angle,cx,cy)
return x1,y1,x2,y2,x3,y3,x4,y4
from numpy import cos,sin,pi,tan
def rotate(x,y,angle,cx,cy):
"""
(x,y) (cx,cy)
"""
#angle = angle*pi/180
x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx
y_new = (x-cx)*sin(angle) + (y-cy)*cos(angle)+cy
return x_new,y_new
def get_rorate(boxes,im,degree=0):
"""
boxim
"""
imgW,imgH = im.size
newBoxes = []
for line in boxes:
cx0,cy0 = imgW/2.0,imgH/2.0
x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(**line)
x1,y1 = rotate(x1,y1,-degree/180*np.pi,cx0,cy0)
x2,y2 = rotate(x2,y2,-degree/180*np.pi,cx0,cy0)
x3,y3 = rotate(x3,y3,-degree/180*np.pi,cx0,cy0)
x4,y4 = rotate(x4,y4,-degree/180*np.pi,cx0,cy0)
box = (x1,y1,x2,y2,x3,y3,x4,y4)
degree_,w_,h_,cx_,cy_ = solve(box)
newLine = {'angle':degree_,'w':w_,'h':h_,'cx':cx_,'cy':cy_}
newBoxes.append(newLine)
return im.rotate(degree,center=(imgW/2.0,imgH/2.0 )),newBoxes
def letterbox_image(image, size,fillValue=[128,128,128]):
'''
resize image with unchanged aspect ratio using padding
'''
image_w, image_h = image.size
w, h = size
new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h))
new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h))
resized_image = image.resize((new_w,new_h), Image.BICUBIC)
if fillValue is None:
fillValue = [int(x.mean()) for x in cv2.split(np.array(im))]
boxed_image = Image.new('RGB', size, tuple(fillValue))
boxed_image.paste(resized_image,)
return boxed_image,new_w/image_w
def get_box_spilt(boxes,im,sizeW,SizeH,splitW=8,isRoate=False,rorateDegree=0):
"""
isRoate:box
"""
size = sizeW,SizeH
if isRoate:
##box
im,boxes = get_rorate(boxes,im,degree=rorateDegree)
newIm,f = letterbox_image(im, size)
newBoxes = resize_box(boxes,f)
newBoxes = sum(box_split(newBoxes,splitW),[])
newBoxes = [box+[1] for box in newBoxes]
return newBoxes,newIm
def box_rotate(box,angle=0,imgH=0,imgW=0):
"""
0\90\180\270,
"""
x1,y1,x2,y2,x3,y3,x4,y4 = box[:8]
if angle==90:
x1_,y1_ = y2,imgW-x2
x2_,y2_ = y3,imgW-x3
x3_,y3_ = y4,imgW-x4
x4_,y4_ = y1,imgW-x1
elif angle==180:
x1_,y1_ = imgW-x3,imgH-y3
x2_,y2_ = imgW-x4,imgH-y4
x3_,y3_ = imgW-x1,imgH-y1
x4_,y4_ = imgW-x2,imgH-y2
elif angle==270:
x1_,y1_ = imgH-y4,x4
x2_,y2_ = imgH-y1,x1
x3_,y3_ = imgH-y2,x2
x4_,y4_ = imgH-y3,x3
else:
x1_,y1_,x2_,y2_,x3_,y3_,x4_,y4_ = x1,y1,x2,y2,x3,y3,x4,y4
return (x1_,y1_,x2_,y2_,x3_,y3_,x4_,y4_)
def solve(box):
"""
cx,cy w,h angle
x = cx-w/2
y = cy-h/2
x1-cx = -w/2*cos(angle) +h/2*sin(angle)
y1 -cy= -w/2*sin(angle) -h/2*cos(angle)
h(x1-cx) = -wh/2*cos(angle) +hh/2*sin(angle)
w(y1 -cy)= -ww/2*sin(angle) -hw/2*cos(angle)
(hh+ww)/2sin(angle) = h(x1-cx)-w(y1 -cy)
"""
x1,y1,x2,y2,x3,y3,x4,y4= box[:8]
cx = (x1+x3+x2+x4)/4.0
cy = (y1+y3+y4+y2)/4.0
w = (np.sqrt((x2-x1)**2+(y2-y1)**2)+np.sqrt((x3-x4)**2+(y3-y4)**2))/2
h = (np.sqrt((x2-x3)**2+(y2-y3)**2)+np.sqrt((x1-x4)**2+(y1-y4)**2))/2
sinA = (h*(x1-cx)-w*(y1 -cy))*1.0/(h*h+w*w)*2
angle = np.arcsin(sinA)
return angle,w,h,cx,cy
from numpy import cos,sin,pi
def xy_rotate_box(cx,cy,w,h,angle):
"""
cx,cy w,h angle
x_new = (x-cx)*cos(angle) - (y-cy)*sin(angle)+cx
y_new = (x-cx)*sin(angle) + (y-cy)*sin(angle)+cy
"""
cx = float(cx)
cy = float(cy)
w = float(w)
h = float(h)
angle = float(angle)
x1,y1 = rotate(cx-w/2,cy-h/2,angle,cx,cy)
x2,y2 = rotate(cx+w/2,cy-h/2,angle,cx,cy)
x3,y3 = rotate(cx+w/2,cy+h/2,angle,cx,cy)
x4,y4 = rotate(cx-w/2,cy+h/2,angle,cx,cy)
return x1,y1,x2,y2,x3,y3,x4,y4
# def rotate_cut_img(im, degree, box, w, h, leftAdjust=False, rightAdjust=False, alph=0.2):
# x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
# # print('rotate_cut_img', x1, y1, x2, y2, x3, y3, x4, y4)
#
# x_center, y_center = np.mean([x1, x2, x3, x4]), np.mean([y1, y2, y3, y4])
# right = 0
# left = 0
# if rightAdjust:
# right = 1
# if leftAdjust:
# left = 1
#
# # print(im.shape)
# box = (max(1, x_center - w / 2 - left * alph * (w / 2)), # xmin
# y_center - h / 2, # ymin
# min(x_center + w / 2 + right * alph * (w / 2), im.shape[1] - 1), # xmax
# y_center + h / 2) # ymax
# # print('box', box)
#
# newW = int(box[2] - box[0])
# newH = int(box[3] - box[1])
#
# # =====================================================
# # remap_points = np.array([[0, 0], [164, 0], [164, 48], [0, 48]], dtype=np.float32)
# remap_points = np.array([[0, 0], [newW, 0], [newW, newH], [0, newH]], dtype=np.float32)
# old_points = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]], dtype=np.float32)
# # opencv
# M = cv2.getPerspectiveTransform(old_points, remap_points)
# tmpImg = cv2.warpPerspective(im, M, (newW, newH))
# # cv2.imshow('rotate_cut_img', tmpImg)
# # cv2.waitKey(0)
#
# return tmpImg, newW, newH
def letterbox_image(image, size, fillValue=[128, 128, 128]):
'''resize image with unchanged aspect ratio using padding'''
image_w, image_h = image.size
w, h = size
new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h))
new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h))
resized_image = image.resize((new_w,new_h), Image.BICUBIC)
if fillValue is None:
fillValue = [int(x.mean()) for x in cv2.split(np.array(im))]
boxed_image = Image.new('RGB', size, tuple(fillValue))
boxed_image.paste(resized_image, (0,0))
return boxed_image,new_w/image_w
from scipy.ndimage import filters,interpolation,morphology,measurements,minimum
#from pylab import amin, amax
from numpy import amin, amax
def estimate_skew_angle(raw):
"""
"""
raw = resize_im(raw, scale=600, max_scale=900)
image = raw-amin(raw)
image = image/amax(image)
m = interpolation.zoom(image,0.5)
m = filters.percentile_filter(m,80,size=(20,2))
m = filters.percentile_filter(m,80,size=(2,20))
m = interpolation.zoom(m,1.0/0.5)
w,h = min(image.shape[1],m.shape[1]),min(image.shape[0],m.shape[0])
flat = np.clip(image[:h,:w]-m[:h,:w]+1,0,1)
d0,d1 = flat.shape
o0,o1 = int(0.1*d0),int(0.1*d1)
flat = amax(flat)-flat
flat -= amin(flat)
est = flat[o0:d0-o0,o1:d1-o1]
angles = range(-15,15)
estimates = []
for a in angles:
roest =interpolation.rotate(est,a,order=0,mode='constant')
v = np.mean(roest,axis=1)
v = np.var(v)
estimates.append((v,a))
_,a = max(estimates)
return a
def sort_box(box):
"""
box,
box[index, 0] = x1
box[index, 1] = y1
box[index, 2] = x2
box[index, 3] = y2
box[index, 4] = x3
box[index, 5] = y3
box[index, 6] = x4
box[index, 7] = y4
"""
box = sorted(box,key=lambda x:sum([x[1],x[3],x[5],x[7]]))
return list(box)
def get_boxes( bboxes):
"""
boxes: bounding boxes
"""
text_recs=np.zeros((len(bboxes), 8), np.int)
index = 0
for box in bboxes:
b1 = box[6] - box[7] / 2
b2 = box[6] + box[7] / 2
x1 = box[0]
y1 = box[5] * box[0] + b1
x2 = box[2]
y2 = box[5] * box[2] + b1
x3 = box[0]
y3 = box[5] * box[0] + b2
x4 = box[2]
y4 = box[5] * box[2] + b2
disX = x2 - x1
disY = y2 - y1
width = np.sqrt(disX*disX + disY*disY)
fTmp0 = y3 - y1
fTmp1 = fTmp0 * disY / width
x = np.fabs(fTmp1*disX / width)
y = np.fabs(fTmp1*disY / width)
if box[5] < 0:
x1 -= x
y1 += y
x4 += x
y4 -= y
else:
x2 += x
y2 += y
x3 -= x
y3 -= y
text_recs[index, 0] = x1
text_recs[index, 1] = y1
text_recs[index, 2] = x2
text_recs[index, 3] = y2
text_recs[index, 4] = x3
text_recs[index, 5] = y3
text_recs[index, 6] = x4
text_recs[index, 7] = y4
index = index + 1
return text_recs
def union_rbox(result,alpha=0.1):
"""
box
"""
def diff(box1,box2):
"""
box1,box2
"""
cy1 = box1['cy']
cy2 = box2['cy']
h1 = box1['h']
h2 = box2['h']
return abs(cy1-cy2)/max(0.01,min(h1/2,h2/2))
def sort_group_box(boxes):
"""
box, box
"""
N = len(boxes)
boxes = sorted(boxes,key=lambda x:x['cx'])
text = ' '.join([bx['text'] for bx in boxes])
box4 = np.zeros((N,8))
for i in range(N):
cx =boxes[i]['cx']
cy = boxes[i]['cy']
degree =boxes[i]['degree']
w = boxes[i]['w']
h = boxes[i]['h']
x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(cx, cy, w, h, degree/180*np.pi)
box4[i] = [x1,y1,x2,y2,x3,y3,x4,y4]
x1 = box4[:,0].min()
y1 = box4[:,1].min()
x2 = box4[:,2].max()
y2 = box4[:,3].min()
x3 = box4[:,4].max()
y3 = box4[:,5].max()
x4 = box4[:,6].min()
y4 = box4[:,7].max()
angle,w,h,cx,cy = solve([x1,y1,x2,y2,x3,y3,x4,y4])
return {'text':text,'cx':cx,'cy':cy,'w':w,'h':h,'degree':angle/np.pi*180}
newBox = []
for line in result:
if len(newBox)==0:
newBox.append([line])
else:
check=False
for box in newBox[-1]:
if diff(line,box)>alpha:
check = True
if not check:
newBox[-1].append(line)
else:
newBox.append([line])
newBox = [sort_group_box(bx) for bx in newBox]
return newBox
def adjust_box_to_origin(img,angle, result):
"""
box
"""
h,w = img.shape[:2]
if angle in [90,270]:
imgW,imgH = img.shape[:2]
else:
imgH,imgW= img.shape[:2]
newresult = []
for line in result:
cx =line['box']['cx']
cy = line['box']['cy']
degree =line['box']['angle']
w = line['box']['w']
h = line['box']['h']
x1,y1,x2,y2,x3,y3,x4,y4 = xy_rotate_box(cx, cy, w, h, degree/180*np.pi)
x1,y1,x2,y2,x3,y3,x4,y4 = box_rotate([x1,y1,x2,y2,x3,y3,x4,y4],angle=(360-angle)%360,imgH=imgH,imgW=imgW)
box = x1,y1,x2,y2,x3,y3,x4,y4
newresult.append({'name':line['name'],'text':line['text'],'box':box})
return newresult | 29.40832 | 113 | 0.515561 |
91db99963a9d2cafd0fa8e863ed2ec3e7df55f3e | 1,320 | py | Python | opendatatools/common/ui_util.py | harveywwu/OpenData | cf421465dd9b11fdbb2fbf4d00512e3aaf09d070 | [
"Apache-2.0"
] | null | null | null | opendatatools/common/ui_util.py | harveywwu/OpenData | cf421465dd9b11fdbb2fbf4d00512e3aaf09d070 | [
"Apache-2.0"
] | null | null | null | opendatatools/common/ui_util.py | harveywwu/OpenData | cf421465dd9b11fdbb2fbf4d00512e3aaf09d070 | [
"Apache-2.0"
] | 1 | 2020-05-29T00:26:59.000Z | 2020-05-29T00:26:59.000Z | # -*- coding: UTF-8 -*-
import sys, time
if __name__=='__main__':
max_steps = 100
process_bar = ShowProcess(max_steps, 'OK')
for i in range(max_steps):
process_bar.show_process()
time.sleep(0.1) | 26.938776 | 77 | 0.526515 |
91dbd76ebb4a6ee074d9e41d9b7337c54be487ec | 1,748 | py | Python | data_structure/stack_and_queue/494. Target Sum_ Medium.py | JunzhongLin/leetcode_practice | 47b2f5cc3c87de004ae21a94024e751b40b8f559 | [
"MIT"
] | null | null | null | data_structure/stack_and_queue/494. Target Sum_ Medium.py | JunzhongLin/leetcode_practice | 47b2f5cc3c87de004ae21a94024e751b40b8f559 | [
"MIT"
] | null | null | null | data_structure/stack_and_queue/494. Target Sum_ Medium.py | JunzhongLin/leetcode_practice | 47b2f5cc3c87de004ae21a94024e751b40b8f559 | [
"MIT"
] | null | null | null | '''
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
'''
from collections import defaultdict
input_val, target = [1,1,1,1,1], 3
res = Solution().findTargetSumWays(input_val, target) | 34.96 | 151 | 0.529748 |
91dd1a3b5de5801e9e8baf1d02a035b6853b1ad3 | 3,733 | py | Python | fixtrack/frontend/pickable_markers.py | os-gabe/fixtrack | a0af4dfa9342acc0ba05c0249a32806c825b74b2 | [
"MIT"
] | null | null | null | fixtrack/frontend/pickable_markers.py | os-gabe/fixtrack | a0af4dfa9342acc0ba05c0249a32806c825b74b2 | [
"MIT"
] | null | null | null | fixtrack/frontend/pickable_markers.py | os-gabe/fixtrack | a0af4dfa9342acc0ba05c0249a32806c825b74b2 | [
"MIT"
] | 1 | 2022-03-25T04:26:36.000Z | 2022-03-25T04:26:36.000Z | import numpy as np
from fixtrack.frontend.pickable_base import PickableBase
from vispy import scene
| 33.936364 | 94 | 0.587731 |
91dedad5ac38b05af586adadc029baeb5dbdb36c | 2,242 | py | Python | examples/blocking_subscribe.py | FFY00/jeepney | 293241a54fbb73581755e97191720ed1603aed34 | [
"MIT"
] | null | null | null | examples/blocking_subscribe.py | FFY00/jeepney | 293241a54fbb73581755e97191720ed1603aed34 | [
"MIT"
] | null | null | null | examples/blocking_subscribe.py | FFY00/jeepney | 293241a54fbb73581755e97191720ed1603aed34 | [
"MIT"
] | null | null | null | """
Example of subscribing to a D-Bus signal using blocking I/O.
This subscribes to the signal for a desktop notification being closed.
To try it, start this script, then trigger a desktop notification, and close it
somehow to trigger the signal. Use Ctrl-C to stop the script.
This example relies on the ``org.freedesktop.Notifications.NotificationClosed``
signal; some desktops may not support it. See the notification spec for more
details:
https://people.gnome.org/~mccann/docs/notification-spec/notification-spec-latest.html
Match rules are defined in the D-Bus specification:
https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules
"""
from jeepney.bus_messages import MatchRule, message_bus
from jeepney.integrate.blocking import connect_and_authenticate, Proxy
from jeepney.wrappers import DBusAddress
noti = DBusAddress('/org/freedesktop/Notifications',
bus_name='org.freedesktop.Notifications',
interface='org.freedesktop.Notifications')
connection = connect_and_authenticate(bus="SESSION")
match_rule = MatchRule(
type="signal",
sender=noti.bus_name,
interface=noti.interface,
member="NotificationClosed",
path=noti.object_path,
)
# This defines messages for talking to the D-Bus bus daemon itself:
session_bus = Proxy(message_bus, connection)
# Tell the session bus to pass us matching signal messages:
print("Match added?", session_bus.AddMatch(match_rule) == ())
reasons = {1: 'expiry', 2: 'dismissal', 3: 'dbus', '4': 'undefined'}
def notification_closed(data):
"""Callback for when we receive a notification closed signal"""
nid, reason_no = data
reason = reasons.get(reason_no, 'unknown')
print('Notification {} closed by: {}'.format(nid, reason))
# Connect the callback to the relevant signal
connection.router.subscribe_signal(
callback=notification_closed,
path=noti.object_path,
interface=noti.interface,
member="NotificationClosed"
)
# Using dbus-send or d-feet or blocking_notify.py, send a notification and
# manually close it or call ``.CloseNotification`` after a beat.
try:
while True:
connection.recv_messages()
except KeyboardInterrupt:
pass
connection.close()
| 34.492308 | 88 | 0.752007 |
91dfcb96d3cfa72fba7a82aeea1a69a09b3627d9 | 126 | py | Python | test.py | league3236/shholiday | 54d0fcfd393d09183cd77cab697f5bc60864b314 | [
"MIT"
] | null | null | null | test.py | league3236/shholiday | 54d0fcfd393d09183cd77cab697f5bc60864b314 | [
"MIT"
] | null | null | null | test.py | league3236/shholiday | 54d0fcfd393d09183cd77cab697f5bc60864b314 | [
"MIT"
] | null | null | null | from shholiday import holiday2020 as hd
daytuple = (1,1)
nowholiday = hd.holiday2020()
print(nowholiday.is_holiday(daytuple)) | 25.2 | 39 | 0.793651 |
91e036fe4dd0d56410bf8828136484d3650838c6 | 740 | py | Python | setup.py | dalejung/pandas-composition | e73e5295b2d2f44f09805dcf06db12108c555197 | [
"MIT"
] | 5 | 2015-04-08T20:58:25.000Z | 2018-04-22T00:10:44.000Z | setup.py | dalejung/pandas-composition | e73e5295b2d2f44f09805dcf06db12108c555197 | [
"MIT"
] | null | null | null | setup.py | dalejung/pandas-composition | e73e5295b2d2f44f09805dcf06db12108c555197 | [
"MIT"
] | null | null | null | from distutils.core import setup
DISTNAME='pandas_composition'
FULLVERSION='0.1'
setup(name=DISTNAME,
version=FULLVERSION,
packages=['pandas_composition',
]
)
| 67.272727 | 94 | 0.172973 |
91e12d660ef7f4298457f9dc8c2b1a07e4f99285 | 404 | py | Python | blog/migrations/0005_title_null.py | encukou/Zpetnovazebnik | 0d058fd67049a3d42814b04486bde93bc406fa3b | [
"MIT"
] | 1 | 2019-12-04T10:10:53.000Z | 2019-12-04T10:10:53.000Z | blog/migrations/0005_title_null.py | encukou/Zpetnovazebnik | 0d058fd67049a3d42814b04486bde93bc406fa3b | [
"MIT"
] | 14 | 2019-04-07T07:46:07.000Z | 2022-03-11T23:44:31.000Z | blog/migrations/0005_title_null.py | encukou/Zpetnovazebnik | 0d058fd67049a3d42814b04486bde93bc406fa3b | [
"MIT"
] | 1 | 2019-02-16T09:25:51.000Z | 2019-02-16T09:25:51.000Z | # Generated by Django 2.1.7 on 2019-02-27 14:23
from django.db import migrations, models
| 21.263158 | 74 | 0.601485 |
91e1834b8771a7ae37346ead4e29d9b3101da09b | 917 | py | Python | setup.py | Kuba77/Xian-DB | 2f15ef1b9b7a96c21bd46e9fb8481de6feb713b7 | [
"MIT"
] | 1 | 2016-10-22T21:04:09.000Z | 2016-10-22T21:04:09.000Z | setup.py | Kuba77/Xian-DB | 2f15ef1b9b7a96c21bd46e9fb8481de6feb713b7 | [
"MIT"
] | null | null | null | setup.py | Kuba77/Xian-DB | 2f15ef1b9b7a96c21bd46e9fb8481de6feb713b7 | [
"MIT"
] | null | null | null | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='xiandb',
version='0.2.0',
description='A database model for Xian',
long_description=long_description,
url='https://github.com/Kuba77/Xian-DB',
author='Jakub Chronowski',
author_email='jakub@chronow.ski',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: XIAN Collaborators',
'Topic :: Software Development :: Database',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7'
],
keywords='xian database db',
packages=['xiandb', 'xiandb.models'],
install_requires=['mongokat', 'pyyaml', 'bcrypt'],
extras_require={}
)
| 21.325581 | 64 | 0.641221 |
91e197a6aad024d05c47c68f4923bef335ff491f | 4,993 | py | Python | yolo3/focal_loss.py | ashishpatel26/tf2-yolo3 | 38814178643eb8e1f8b5e4fe8d448faed44ad574 | [
"Apache-2.0"
] | 43 | 2019-12-08T15:05:53.000Z | 2022-03-20T13:38:07.000Z | yolo3/focal_loss.py | 1911590204/tf2-yolo3 | 38814178643eb8e1f8b5e4fe8d448faed44ad574 | [
"Apache-2.0"
] | 3 | 2020-05-18T11:20:15.000Z | 2021-02-26T01:11:04.000Z | yolo3/focal_loss.py | 1911590204/tf2-yolo3 | 38814178643eb8e1f8b5e4fe8d448faed44ad574 | [
"Apache-2.0"
] | 15 | 2019-12-25T01:44:29.000Z | 2022-01-18T08:45:49.000Z | from functools import partial
import tensorflow as tf
_EPSILON = tf.keras.backend.epsilon()
# Helper functions below
def _process_labels(labels, label_smoothing, dtype):
labels = tf.dtypes.cast(labels, dtype=dtype)
if label_smoothing is not None:
labels = (1 - label_smoothing) * labels + label_smoothing * 0.5
return labels
def _binary_focal_loss_from_logits(labels, logits, gamma, pos_weight, label_smoothing):
labels = _process_labels(labels=labels, label_smoothing=label_smoothing, dtype=logits.dtype)
# Compute probabilities for the positive class
p = tf.math.sigmoid(logits)
if label_smoothing is None:
labels_shape = labels.shape
logits_shape = logits.shape
if not labels_shape.is_fully_defined() or labels_shape != logits_shape:
labels_shape = tf.shape(labels)
logits_shape = tf.shape(logits)
shape = tf.broadcast_dynamic_shape(labels_shape, logits_shape)
labels = tf.broadcast_to(labels, shape)
logits = tf.broadcast_to(logits, shape)
if pos_weight is None:
loss_func = tf.nn.sigmoid_cross_entropy_with_logits
else:
loss_func = partial(tf.nn.weighted_cross_entropy_with_logits, pos_weight=pos_weight)
loss = loss_func(labels=labels, logits=logits)
modulation_pos = (1 - p)**gamma
modulation_neg = p**gamma
mask = tf.dtypes.cast(labels, dtype=tf.bool)
modulation = tf.where(mask, modulation_pos, modulation_neg)
return modulation * loss
# Terms for the positive and negative class components of the loss
pos_term = labels * ((1 - p)**gamma)
neg_term = (1 - labels) * (p**gamma)
# Term involving the log and ReLU
log_weight = pos_term
if pos_weight is not None:
log_weight *= pos_weight
log_weight += neg_term
log_term = tf.math.log1p(tf.math.exp(-tf.math.abs(logits)))
log_term += tf.nn.relu(-logits)
log_term *= log_weight
# Combine all the terms into the loss
loss = neg_term * logits + log_term
return loss
def _binary_focal_loss_from_probs(labels, p, gamma, pos_weight, label_smoothing):
q = 1 - p
# For numerical stability (so we don't inadvertently take the log of 0)
p = tf.math.maximum(p, _EPSILON)
q = tf.math.maximum(q, _EPSILON)
# Loss for the positive examples
pos_loss = -(q**gamma) * tf.math.log(p)
if pos_weight is not None:
pos_loss *= pos_weight
# Loss for the negative examples
neg_loss = -(p**gamma) * tf.math.log(q)
# Combine loss terms
if label_smoothing is None:
labels = tf.dtypes.cast(labels, dtype=tf.bool)
loss = tf.where(labels, pos_loss, neg_loss)
else:
labels = _process_labels(labels=labels, label_smoothing=label_smoothing, dtype=p.dtype)
loss = labels * pos_loss + (1 - labels) * neg_loss
return loss | 36.985185 | 106 | 0.616263 |
91e197bc72174a007b45ebf73223d69beb79eca0 | 13,808 | py | Python | characters/models/characters.py | Sult/evetool | 155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f | [
"MIT"
] | null | null | null | characters/models/characters.py | Sult/evetool | 155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f | [
"MIT"
] | null | null | null | characters/models/characters.py | Sult/evetool | 155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f | [
"MIT"
] | null | null | null | import time
from collections import OrderedDict
from datetime import datetime, timedelta
from django.db import models
from django.conf import settings
from django.utils.timezone import utc
from .skills import Skill, SkillGroup
from metrics.models import Corporation
from tasks.models import EveApiCache, Task
from evetool.storage import OverwriteStorage
import utils
#characters trained skills
def trained_skills(self):
cache_key = "trained_skills_%d" % self.pk
result = utils.connection.get_cache(cache_key)
if not result:
cache_timer = 60 * 5
sheet = utils.connection.api_request("CharacterSheet", obj=self)
groups = SkillGroup.objects.exclude(
groupname="Fake Skills"
).order_by("groupname")
skills = Skill.objects.order_by("typename")
all_skills = OrderedDict()
skillpoints = {}
for group in groups:
all_skills[group.groupname] = list()
skillpoints[group.groupname] = 0
for skill in skills:
trained = sheet.skills.Get(skill.typeid, False)
if trained:
all_skills[skill.skillgroup.groupname].append(
{
"skill": skill,
"level": int(trained.level)
}
)
skillpoints[skill.skillgroup.groupname] += \
trained.skillpoints
result = {
"all_skills": all_skills,
"skillpoints": skillpoints,
}
utils.connection.set_cache(cache_key, result, cache_timer)
return result
#get skillqueue
#get total skillpoints for skills in queue
#walletjournal
def wallet_journal(self):
cache_key = "walletjournal_character_%d" % self.pk
result = utils.connection.get_cache(cache_key)
if not result:
self.update_journal()
cache_timer = 60 * 10
utils.connection.set_cache(cache_key, True, cache_timer)
return CharacterJournal.objects.filter(characterapi=self)
#updates journal to current moment
class CharacterApiIcon(models.Model):
""" images related to characters """
relation = models.ForeignKey("characters.CharacterApi")
size = models.IntegerField(choices=settings.IMAGE_SIZES)
typeid = models.IntegerField()
icon = models.ImageField(
upload_to="images/characters/",
storage=OverwriteStorage(),
blank=True,
null=True
)
# def save(self, *args, **kwargs):
# try:
# temp = CharacterApiIcon.objects.get(pk=self.pk)
# if temp.icon != self.icon:
# temp.icon.delete()
# except ObjectDoesNotExist:
# pass
# super(CharacterApiIcon, self).save(*args, **kwargs)
#get list of wanted character icon sizes
| 33.596107 | 79 | 0.571915 |
91e3f480fdcbf40fb3a62c946e3ea8b2a208638d | 92 | py | Python | webex_assistant_sdk/templates/mindmeld_template/{{cookiecutter.skill_name}}/{{cookiecutter.skill_name}}/__init__.py | sachanacar/webex-assistant-sdk | bb0f1ad16973cfa5784d7d887381229fab01effa | [
"Apache-2.0"
] | null | null | null | webex_assistant_sdk/templates/mindmeld_template/{{cookiecutter.skill_name}}/{{cookiecutter.skill_name}}/__init__.py | sachanacar/webex-assistant-sdk | bb0f1ad16973cfa5784d7d887381229fab01effa | [
"Apache-2.0"
] | null | null | null | webex_assistant_sdk/templates/mindmeld_template/{{cookiecutter.skill_name}}/{{cookiecutter.skill_name}}/__init__.py | sachanacar/webex-assistant-sdk | bb0f1ad16973cfa5784d7d887381229fab01effa | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from {{cookiecutter.skill_name}}.root import app
__all__ = ['app']
| 18.4 | 48 | 0.641304 |
91e4401665d568cd4d6102a4a69c6d2f7668744f | 602 | py | Python | backend/api/v1/dialogs/urls.py | donicrazy/ChatApp | ab129a9c0706bbb972cbce43283ba6e06d144635 | [
"MIT"
] | null | null | null | backend/api/v1/dialogs/urls.py | donicrazy/ChatApp | ab129a9c0706bbb972cbce43283ba6e06d144635 | [
"MIT"
] | 7 | 2021-03-19T04:47:13.000Z | 2022-01-13T02:02:46.000Z | backend/api/v1/dialogs/urls.py | donicrazy/ChatApp | ab129a9c0706bbb972cbce43283ba6e06d144635 | [
"MIT"
] | null | null | null | from django.urls import path
from backend.api.v1.dialogs.views import (
DialogListCreateView,
DialogRetrieveUpdateDestroyAPIView,
DialogMembershipListCreateView,
DialogMessageListCreateView,
DialogMessageRetrieveUpdateDestroyAPIView,
)
urlpatterns = [
path('', DialogListCreateView.as_view()),
path('<int:pk>', DialogRetrieveUpdateDestroyAPIView.as_view()),
path('membership/', DialogMembershipListCreateView.as_view()),
path('messages/', DialogMessageListCreateView.as_view()),
path('messages/<int:pk>', DialogMessageRetrieveUpdateDestroyAPIView.as_view()),
]
| 35.411765 | 83 | 0.770764 |
91e4a887944adf9f3a04214dd378ac72dc05e86a | 2,100 | py | Python | biomaj2galaxy/commands/init.py | genouest/biomaj2galaxy | 8c76f3cc96902d9401a03e7b1a6cd8f4a7ba17bd | [
"MIT"
] | 1 | 2015-05-11T00:08:24.000Z | 2015-05-11T00:08:24.000Z | biomaj2galaxy/commands/init.py | genouest/biomaj2galaxy | 8c76f3cc96902d9401a03e7b1a6cd8f4a7ba17bd | [
"MIT"
] | 5 | 2019-04-15T16:09:50.000Z | 2020-11-24T10:35:21.000Z | biomaj2galaxy/commands/init.py | genouest/biomaj2galaxy | 8c76f3cc96902d9401a03e7b1a6cd8f4a7ba17bd | [
"MIT"
] | 3 | 2015-06-14T08:33:49.000Z | 2020-10-16T09:07:21.000Z | # coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from bioblend import galaxy
from biomaj2galaxy import config, pass_context
from biomaj2galaxy.io import info, warn
import click
CONFIG_TEMPLATE = """## BioMAJ2Galaxy: Global Configuration File.
# Each stanza should contain a single Galaxy server to interact with.
#
# You can set the key __default to the name of a default instance
__default: local
local:
url: "%(url)s"
apikey: "%(apikey)s"
"""
SUCCESS_MESSAGE = (
"Ready to go! Type `biomaj2galaxy` to get a list of commands you can execute."
)
| 29.166667 | 121 | 0.65381 |
91e4f118680c4b4128c740a76beaad48599ab626 | 848 | py | Python | datamart/tests/test_Dimension.py | josemrsantos/zoopla_datamart | f3a3af8071199deeb712d1814aecb6cc3cd88d57 | [
"MIT"
] | 1 | 2016-02-01T20:27:25.000Z | 2016-02-01T20:27:25.000Z | datamart/tests/test_Dimension.py | josemrsantos/zoopla_datamart | f3a3af8071199deeb712d1814aecb6cc3cd88d57 | [
"MIT"
] | null | null | null | datamart/tests/test_Dimension.py | josemrsantos/zoopla_datamart | f3a3af8071199deeb712d1814aecb6cc3cd88d57 | [
"MIT"
] | null | null | null | from ..datamart import *
def test_create_dimension_insert_2_identical_lines():
''' with 2 identical lines, only one gets stored
'''
dimension = Dimension("test_dimension")
dimension.addDimensionLine('test')
dimension.addDimensionLine('test')
assert dimension.id_value == 1
assert len(list(dimension.values)) == 1
def test_create_dimension_insert_2_identical_lines_and_1_different():
''' with 2 identical lines and one different, only 2 get stored
'''
dimension = Dimension("test_dimension")
dimension.addDimensionLine('test')
dimension.addDimensionLine('test2')
dimension.addDimensionLine('test')
assert dimension.id_value == 2
assert len(list(dimension.values)) == 2
| 33.92 | 69 | 0.732311 |
91e5db16db7c305afa819a65e2ba7480fc9d4276 | 4,700 | py | Python | preprocessing/convert_formats/msmarco_doc_create_train_input.py | PranjaliJain/matchmaker | b7e22eb8b70cccabf0729076df7cbab3f4ba4a1f | [
"Apache-2.0"
] | 97 | 2021-07-11T14:34:40.000Z | 2022-03-31T14:17:25.000Z | preprocessing/convert_formats/msmarco_doc_create_train_input.py | PranjaliJain/matchmaker | b7e22eb8b70cccabf0729076df7cbab3f4ba4a1f | [
"Apache-2.0"
] | 12 | 2021-07-11T13:03:23.000Z | 2022-03-02T16:07:11.000Z | preprocessing/convert_formats/msmarco_doc_create_train_input.py | PranjaliJain/matchmaker | b7e22eb8b70cccabf0729076df7cbab3f4ba4a1f | [
"Apache-2.0"
] | 16 | 2019-12-23T01:22:35.000Z | 2021-06-23T12:54:36.000Z | #
# msmarco doc: create the train.tsv triples
# -------------------------------
import random
random.seed(42)
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.getcwd())
from matchmaker.evaluation.msmarco_eval import *
from collections import defaultdict
from matchmaker.dataloaders.bling_fire_tokenizer import BlingFireTokenizer
#
# config
#
parser = argparse.ArgumentParser()
parser.add_argument('--out-file', action='store', dest='out_file',
help='training output text file location', required=True)
parser.add_argument('--out-file-ids', action='store', dest='out_file_ids',
help='training output ids file location', required=True)
parser.add_argument('--candidate-file', action='store', dest='candidate_file',
help='trec ranking file location (lucene output)', required=True)
parser.add_argument('--collection-file', action='store', dest='collection_file',
help='collection.tsv location', required=True)
parser.add_argument('--query-file', action='store', dest='query_file',
help='query.tsv location', required=True)
parser.add_argument('--qrel', action='store', dest='qrel_file',
help='qrel location', required=True)
args = parser.parse_args()
max_triples = 10_000_000
max_doc_char_length = 150_000
max_doc_token_length = 10000
#
# load data
# -------------------------------
#
collection = {}
#collection_length = {}
tokenizer = BlingFireTokenizer()
with open(args.collection_file,"r",encoding="utf8") as collection_file:
for line in tqdm(collection_file):
ls = line.split("\t") # id<\t>text ....
_id = ls[0]
max_char_doc = ls[1].rstrip()[:max_doc_char_length]
collection[_id] = max_char_doc
#collection_length[_id] = len(tokenizer.tokenize(max_char_doc))
queries = {}
with open(args.query_file,"r",encoding="utf8") as query_file:
for line in tqdm(query_file):
ls = line.split("\t") # id<\t>text ....
_id = ls[0]
queries[_id] = ls[1].rstrip()
qrels = load_reference(args.qrel_file)
#
# produce output
# -------------------------------
#
triples = []
stats = defaultdict(int)
with open(args.candidate_file,"r",encoding="utf8") as candidate_file:
for line in tqdm(candidate_file):
#if random.random() <= 0.5: continue #skip some entries for faster processing
[topicid, _ , unjudged_docid, rank, _ , _ ] = line.split()
#if int(rank) <= 100:
# #if random.random() < 0.7: continue # skip 70% of candidates to speed up things...
# #else:
# stats['< 100 sampling count'] += 1
#else:
# if random.random() <= 0.9: continue # skip 90% of candidates assumong top1k -> same number of samples from 0-100 as 101 - 1000
# else:
# stats['> 100 sampling count'] += 1
if topicid not in queries or topicid not in qrels: # added: because we carved out the validation qrels from the train -> so there are some missing
stats['skipped'] += 1
continue
#assert topicid in qrels
assert unjudged_docid in collection
# Use topicid to get our positive_docid
positive_docid = random.choice(qrels[topicid])
assert positive_docid in collection
if unjudged_docid in qrels[topicid]:
stats['docid_collision'] += 1
continue
stats['kept'] += 1
#if collection_length[positive_docid] > max_doc_token_length and collection_length[unjudged_docid] > max_doc_token_length:
# stats['both_to_long'] += 1
# continue
#if collection_length[positive_docid] > max_doc_token_length:
# stats['pos_to_long'] += 1
# continue
#if collection_length[unjudged_docid] > max_doc_token_length:
# stats['unjuged_to_long'] += 1
# continue
triples.append((topicid,positive_docid,unjudged_docid))
# important: shuffle the train data
random.shuffle(triples)
with open(args.out_file,"w",encoding="utf8") as out_file_text ,\
open(args.out_file_ids,"w",encoding="utf8") as out_file_ids:
for i,(topicid, positive_docid, unjudged_docid) in tqdm(enumerate(triples)):
if i == max_triples:
break
if collection[positive_docid].strip() != "" and collection[unjudged_docid].strip() != "":
out_file_ids.write(str(topicid)+"\t"+positive_docid+"\t"+unjudged_docid+"\n")
out_file_text.write(queries[topicid]+"\t"+collection[positive_docid]+"\t"+collection[unjudged_docid]+"\n")
for key, val in stats.items():
print(f"{key}\t{val}") | 33.098592 | 154 | 0.636809 |
91e6679035e0b02c68e5fa8e7ebbce0f267caee0 | 13,748 | py | Python | tests/communities/test_reply.py | powerblossom/workcloud | fd943220366ebeadfa90c59fc395f84a734b5686 | [
"MIT"
] | 1 | 2019-10-18T05:57:13.000Z | 2019-10-18T05:57:13.000Z | tests/communities/test_reply.py | powerblossom/workcloud | fd943220366ebeadfa90c59fc395f84a734b5686 | [
"MIT"
] | 11 | 2019-12-02T13:59:22.000Z | 2021-04-24T08:52:19.000Z | tests/communities/test_reply.py | powerblossom/workcloud | fd943220366ebeadfa90c59fc395f84a734b5686 | [
"MIT"
] | null | null | null | from core.response import Response
from communities.tests import TestCase
| 28.404959 | 71 | 0.485598 |
91e82476dc55d0591c20d0a5e9975a53641bca72 | 6,711 | py | Python | examples/Word2Vec_AverageVectorsTuto.py | noiseux1523/Deep-Belief-Network | 6eb364a85fb128a33c539e5e414ef451f24e499d | [
"MIT"
] | 1 | 2019-08-20T12:13:34.000Z | 2019-08-20T12:13:34.000Z | examples/Word2Vec_AverageVectorsTuto.py | noiseux1523/Deep-Belief-Network | 6eb364a85fb128a33c539e5e414ef451f24e499d | [
"MIT"
] | null | null | null | examples/Word2Vec_AverageVectorsTuto.py | noiseux1523/Deep-Belief-Network | 6eb364a85fb128a33c539e5e414ef451f24e499d | [
"MIT"
] | null | null | null | # Author: Angela Chapman
# Date: 8/6/2014
#
# This file contains code to accompany the Kaggle tutorial
# "Deep learning goes to the movies". The code in this file
# is for Parts 2 and 3 of the tutorial, which cover how to
# train a model using Word2Vec.
#
# *************************************** #
# ****** Read the two training sets and the test set
#
import pandas as pd
import os
from nltk.corpus import stopwords
import nltk.data
import logging
import numpy as np # Make sure that numpy is imported
from gensim.models import Word2Vec
from sklearn.ensemble import RandomForestClassifier
from KaggleWord2VecUtility import KaggleWord2VecUtility
# ****** Define functions to create average word vectors
#
if __name__ == '__main__':
# Read data from files
train = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', 'labeledTrainData.tsv'), header=0,
delimiter="\t", quoting=3)
test = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', 'testData.tsv'), header=0, delimiter="\t",
quoting=3)
unlabeled_train = pd.read_csv(os.path.join(os.path.dirname(__file__), 'data', "unlabeledTrainData.tsv"), header=0,
delimiter="\t", quoting=3)
# Verify the number of reviews that were read (100,000 in total)
print "Read %d labeled train reviews, %d labeled test reviews, " \
"and %d unlabeled reviews\n" % (train["review"].size,
test["review"].size, unlabeled_train["review"].size)
# Load the punkt tokenizer
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
# ****** Split the labeled and unlabeled training sets into clean sentences
#
sentences = [] # Initialize an empty list of sentences
print "Parsing sentences from training set"
for review in train["review"]:
sentences += KaggleWord2VecUtility.review_to_sentences(review, tokenizer)
print "Parsing sentences from unlabeled set"
for review in unlabeled_train["review"]:
sentences += KaggleWord2VecUtility.review_to_sentences(review, tokenizer)
# ****** Set parameters and train the word2vec model
#
# Import the built-in logging module and configure it so that Word2Vec
# creates nice output messages
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', \
level=logging.INFO)
# Set values for various parameters
num_features = 300 # Word vector dimensionality
min_word_count = 40 # Minimum word count
num_workers = 4 # Number of threads to run in parallel
context = 10 # Context window size
downsampling = 1e-3 # Downsample setting for frequent words
# Initialize and train the model (this will take some time)
print "Training Word2Vec model..."
model = Word2Vec(sentences, workers=num_workers, \
size=num_features, min_count=min_word_count, \
window=context, sample=downsampling, seed=1)
# If you don't plan to train the model any further, calling
# init_sims will make the model much more memory-efficient.
model.init_sims(replace=True)
# It can be helpful to create a meaningful model name and
# save the model for later use. You can load it later using Word2Vec.load()
model_name = "300features_40minwords_10context"
model.save(model_name)
model.doesnt_match("man woman child kitchen".split())
model.doesnt_match("france england germany berlin".split())
model.doesnt_match("paris berlin london austria".split())
model.most_similar("man")
model.most_similar("queen")
model.most_similar("awful")
# ****** Create average vectors for the training and test sets
#
print "Creating average feature vecs for training reviews"
trainDataVecs = getAvgFeatureVecs(getCleanReviews(train), model, num_features)
print "Creating average feature vecs for test reviews"
testDataVecs = getAvgFeatureVecs(getCleanReviews(test), model, num_features)
# ****** Fit a random forest to the training set, then make predictions
#
# Fit a random forest to the training data, using 100 trees
forest = RandomForestClassifier(n_estimators=100)
print "Fitting a random forest to labeled training data..."
forest = forest.fit(trainDataVecs, train["sentiment"])
# Test & extract results
result = forest.predict(testDataVecs)
# Write the test results
output = pd.DataFrame(data={"id": test["id"], "sentiment": result})
output.to_csv("Word2Vec_AverageVectors.csv", index=False, quoting=3)
print "Wrote Word2Vec_AverageVectors.csv" | 37.915254 | 118 | 0.670094 |
91e8cdd7e37d12c63565c41b5269a325281584b2 | 36 | py | Python | src/phl_budget_data/etl/qcmr/positions/__init__.py | PhiladelphiaController/phl-budget-data | 438999017b8659de5bfb223a038f49fe6fd4a83a | [
"MIT"
] | null | null | null | src/phl_budget_data/etl/qcmr/positions/__init__.py | PhiladelphiaController/phl-budget-data | 438999017b8659de5bfb223a038f49fe6fd4a83a | [
"MIT"
] | null | null | null | src/phl_budget_data/etl/qcmr/positions/__init__.py | PhiladelphiaController/phl-budget-data | 438999017b8659de5bfb223a038f49fe6fd4a83a | [
"MIT"
] | null | null | null | from .core import FullTimePositions
| 18 | 35 | 0.861111 |
91e914734fc05c34e408967e2c372a75de766234 | 1,207 | py | Python | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/models/search_get_schema_response.py | tzhanl/azure-sdk-for-python | 18cd03f4ab8fd76cc0498f03e80fbc99f217c96e | [
"MIT"
] | 1 | 2021-09-07T18:36:04.000Z | 2021-09-07T18:36:04.000Z | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/models/search_get_schema_response.py | tzhanl/azure-sdk-for-python | 18cd03f4ab8fd76cc0498f03e80fbc99f217c96e | [
"MIT"
] | 2 | 2019-10-02T23:37:38.000Z | 2020-10-02T01:17:31.000Z | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/models/search_get_schema_response.py | tzhanl/azure-sdk-for-python | 18cd03f4ab8fd76cc0498f03e80fbc99f217c96e | [
"MIT"
] | 1 | 2019-06-17T22:18:23.000Z | 2019-06-17T22:18:23.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
| 36.575758 | 76 | 0.610605 |
91ebeac4c8302d86c1514c58ecbae0f104ee5904 | 1,332 | py | Python | python/ds/spiralprint.py | unhingedporter/DataStructureMustKnow | 3c5b3225afa2775d37a2ff90121f73208717640a | [
"MIT"
] | 3 | 2019-11-23T08:43:58.000Z | 2019-11-23T08:52:53.000Z | python/ds/spiralprint.py | unhingedpotter/DSMustKnow | 64958cbbbb3f4cdb1104c2255e555233554503f9 | [
"MIT"
] | null | null | null | python/ds/spiralprint.py | unhingedpotter/DSMustKnow | 64958cbbbb3f4cdb1104c2255e555233554503f9 | [
"MIT"
] | null | null | null | # Python3 program to print
# given matrix in spiral form
# Driver Code
a = [[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]]
R = 3
C = 6
spiralPrint(R, C, a)
| 22.965517 | 61 | 0.534535 |
91ed3db43e489e433ff783f8e76e26a52b78a6d5 | 568 | py | Python | rest-api/routers/authorization.py | marintrace/backend | ad34bd50bd5e3f90be1ac16a74d39a0a9342fa33 | [
"MIT"
] | 2 | 2021-12-14T03:14:41.000Z | 2022-01-17T18:36:31.000Z | rest-api/routers/authorization.py | marintrace/backend | ad34bd50bd5e3f90be1ac16a74d39a0a9342fa33 | [
"MIT"
] | 1 | 2021-03-29T08:06:42.000Z | 2021-03-29T08:06:42.000Z | rest-api/routers/authorization.py | tracing-app/backend | ad34bd50bd5e3f90be1ac16a74d39a0a9342fa33 | [
"MIT"
] | null | null | null | """
Authorization Utilities
"""
from shared.models.user_entities import User
from shared.service.jwt_auth_wrapper import JWTAuthManager
manager = JWTAuthManager(oidc_vault_secret="oidc/rest",
object_creator=lambda claims, assumed_role, user_roles: User(
first_name=claims["given_name"],
last_name=claims["family_name"],
school=assumed_role,
email=claims['email']
))
AUTH_USER = manager.auth_header()
| 35.5 | 86 | 0.572183 |
91ee06a1881d10f22e7c8d7c219f9ef37412d52d | 1,365 | py | Python | photonpy/tests/psf_g2d_sigma.py | qnano/photonpy | 9c03a1c9f4c2177c9c6fb3f2f16dfec2306006d4 | [
"MIT"
] | 5 | 2021-04-29T21:06:05.000Z | 2022-03-23T03:45:25.000Z | photonpy/tests/psf_g2d_sigma.py | qnano/photonpy | 9c03a1c9f4c2177c9c6fb3f2f16dfec2306006d4 | [
"MIT"
] | null | null | null | photonpy/tests/psf_g2d_sigma.py | qnano/photonpy | 9c03a1c9f4c2177c9c6fb3f2f16dfec2306006d4 | [
"MIT"
] | 1 | 2021-06-18T12:39:28.000Z | 2021-06-18T12:39:28.000Z | import matplotlib.pyplot as plt
import numpy as np
from photonpy.cpp.context import Context
import photonpy.cpp.gaussian as gaussian
from photonpy.smlm.util import imshow_hstack
from photonpy.cpp.estimator import Estimator
with Context() as ctx:
g = gaussian.Gaussian(ctx)
for cuda in [False]:
print(f"CUDA = {cuda}")
sigma=2
roisize=12
psf = g.CreatePSF_XYIBg(roisize, sigma, cuda)
theta = [[4, 4, 1000, 3]]
img = psf.ExpectedValue(theta)
plt.figure()
plt.set_cmap('inferno')
smp = np.random.poisson(img)
plt.imshow(smp[0])
psf_sigma = g.CreatePSF_XYIBgSigma(roisize, sigma, cuda)
theta_s = [[4,4,1000,3,sigma]]
img2 = psf_sigma.ExpectedValue(theta_s)
CheckDeriv(psf, theta)
# CheckDeriv(psf_sigma)
print(f"PSF Sigma crlb: {psf_sigma.CRLB(theta_s)}")
theta = psf_sigma.Estimate(smp)[0]
print(theta)
| 26.764706 | 106 | 0.606593 |
91ee64a13c556aefe5259d2a930de14c6c79472f | 2,018 | py | Python | tests/tools_tests/helpers_tests.py | Gautierhyp/tespy | d44ae41874baeff77619e560faea59dd0cb84c7c | [
"MIT"
] | null | null | null | tests/tools_tests/helpers_tests.py | Gautierhyp/tespy | d44ae41874baeff77619e560faea59dd0cb84c7c | [
"MIT"
] | null | null | null | tests/tools_tests/helpers_tests.py | Gautierhyp/tespy | d44ae41874baeff77619e560faea59dd0cb84c7c | [
"MIT"
] | null | null | null | # -*- coding: utf-8
"""Module for testing helper functions.
This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted
by the contributors recorded in the version control history of the file,
available from its original location
tests/tools_tests/helpers_tests.py
SPDX-License-Identifier: MIT
"""
from nose.tools import eq_
from tespy.tools.helpers import newton
def test_newton_bounds():
"""
Test newton algorithm value limit handling.
Try to calculate a zero crossing of a quadratic function in three
tries.
- zero crossing within limits, starting value near 4
- zero crossing within limits, starting value near -5
- zero crossing below minimum
- zero crossing above maximum
The function is x^2 + x - 20, there crossings are -5 and 4.
"""
result = newton(func, deriv, [], 0, valmin=-10, valmax=10, val0=0)
msg = ('The newton algorithm should find the zero crossing at 4.0. ' +
str(round(result, 1)) + ' was found instead.')
eq_(4.0, result, msg)
result = newton(func, deriv, [], 0, valmin=-10, valmax=10, val0=-10)
msg = ('The newton algorithm should find the zero crossing at -5.0. ' +
str(round(result, 1)) + ' was found instead.')
eq_(-5.0, result, msg)
result = newton(func, deriv, [], 0, valmin=-4, valmax=-2, val0=-3)
msg = ('The newton algorithm should not be able to find a zero crossing. '
'The value ' + str(round(result, 1)) + ' was found, but the '
'algorithm should have found the lower boundary of -4.0.')
eq_(-4.0, result, msg)
result = newton(func, deriv, [], 0, valmin=-20, valmax=-10, val0=-10)
msg = ('The newton algorithm should not be able to find a zero crossing. '
'The value ' + str(round(result, 1)) + ' was found, but the '
'algorithm should have found the upper boundary of -10.0.')
eq_(-10.0, result, msg)
| 32.548387 | 78 | 0.646184 |
91eebd9cfe8ecc166ed16501e2c6d724f724535d | 4,110 | py | Python | theory/model/form.py | ralfonso/theory | 41684969313cfc545d74b306e409fd5bf21387b3 | [
"MIT"
] | 4 | 2015-07-03T19:53:59.000Z | 2016-04-25T03:03:56.000Z | theory/model/form.py | ralfonso/theory | 41684969313cfc545d74b306e409fd5bf21387b3 | [
"MIT"
] | null | null | null | theory/model/form.py | ralfonso/theory | 41684969313cfc545d74b306e409fd5bf21387b3 | [
"MIT"
] | 2 | 2020-03-29T22:02:29.000Z | 2021-07-13T07:17:19.000Z | import formencode
import pylons
from pylons import app_globals as g
def validate_custom(schema, **state_kwargs):
"""Validate a formencode schema.
Works similar to the @validate decorator. On success return a dictionary
of parameters from request.params. On failure throws a formencode.Invalid
exception."""
# Create a state object if requested
if state_kwargs:
state = State(**state_kwargs)
else:
state = None
# In case of validation errors an exception is thrown. This needs to
# be caught elsewhere.
if state_kwargs.get('variable_decode', False):
params = formencode.variabledecode.variable_decode(pylons.request.params)
print pylons.request.params
print params
else:
params = pylons.request.params
return schema.to_python(params, state)
def htmlfill(html, exception_error=None):
"""Add formencode error messages to an HTML string.
'html' contains the HTML page with the form (e.g. created with render()).
'exception_error' is the formencode.Invalid-Exception from formencode."""
return formencode.htmlfill.render(
form=html,
defaults=pylons.request.params,
errors=(exception_error and exception_error.unpack_errors()),
encoding=pylons.response.determine_charset()
)
| 42.8125 | 139 | 0.682968 |
91eed42dd8cd7828f31d4494c0f4f389955bf685 | 8,960 | py | Python | utils/dynamo.py | OnRails-IN/backend | 5f5c9703fcda282ed54f2e6315680fb30fd91a6f | [
"MIT"
] | null | null | null | utils/dynamo.py | OnRails-IN/backend | 5f5c9703fcda282ed54f2e6315680fb30fd91a6f | [
"MIT"
] | null | null | null | utils/dynamo.py | OnRails-IN/backend | 5f5c9703fcda282ed54f2e6315680fb30fd91a6f | [
"MIT"
] | null | null | null | """
Dynamo Utils
============
All utility functions for interactions with DynamoDB
Functions
- ensure_json
- create_user_table
- create_or_update_record
- list_tables
- list_records
- get_record
- delete_table
- delete_record
- check_active
"""
import boto3
from decimal import Decimal
from constants import AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, DYNAMO_URL
ddb = boto3.resource(
'dynamodb',
aws_access_key_id = AWS_ACCESS_KEY,
aws_secret_access_key = AWS_SECRET_KEY,
endpoint_url = DYNAMO_URL,
region_name = AWS_REGION
)
client = boto3.client(
'dynamodb',
aws_access_key_id = AWS_ACCESS_KEY,
aws_secret_access_key = AWS_SECRET_KEY,
endpoint_url = DYNAMO_URL,
region_name = AWS_REGION
)
def ensure_json(obj):
"""
Function to ensure that a python object is JSON serializable
Params:
obj::dict|[dict]
Object to be JSON serializable
Returns:
obj::dict|[dict]
Returns the JSON serializable object
"""
if isinstance(obj, list):
for i in range(len(obj)):
obj[i] = ensure_json(obj[i])
return obj
elif isinstance(obj, dict):
for k in obj.keys():
obj[k] = ensure_json(obj[k])
return obj
elif isinstance(obj, Decimal):
if obj % 1 == 0:
return int(obj)
else:
return float(obj)
else:
return obj
def create_user_table():
"""
Function to create the "users" table in DynamoDB
Returns:
bool
If the table was created or not
"""
try:
table = ddb.create_table(
TableName = "users",
KeySchema = [
{
"AttributeName": "username",
"KeyType": "HASH" # Partition key
},
{
"AttributeName": "index",
"KeyType": "RANGE" # Sort key
}
],
AttributeDefinitions = [
{
"AttributeName": "username",
"AttributeType": "S"
},
{
"AttributeName": "index",
"AttributeType": "S"
}
],
ProvisionedThroughput = {
"ReadCapacityUnits": 10,
"WriteCapacityUnits": 10
}
)
return True
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ create_user_table\n{}".format(e))
return None
def create_train_table():
"""
Function to create the "trains" table in DynamoDB
Returns:
bool
If the table was created or not
"""
try:
table = ddb.create_table(
TableName = "trains",
KeySchema = [
{
"AttributeName": "train_name",
"KeyType": "HASH" # Partition key
},
{
"AttributeName": "train_type",
"KeyType": "RANGE" # Sort key
}
],
AttributeDefinitions = [
{
"AttributeName": "train_name",
"AttributeType": "N"
},
{
"AttributeName": "train_type",
"AttributeType": "S"
}
],
ProvisionedThroughput = {
"ReadCapacityUnits": 10,
"WriteCapacityUnits": 10
}
)
return True
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ create_user_table\n{}".format(e))
return None
def create_or_update_record(tableName, record):
"""
Function to create or update a record in DynamoDB
Params:
tableName::str
The table name to get the record
record::dict
The object to store
Returns:
bool
If the record was inserted or not
"""
if not tableName or not record:
return False
if not {'username', 'index'}.issubset(record):
return False
try:
res = ddb.Table(tableName).get_item(
Key = {
"username": record['username'],
"index": record['index']
}
)
record = { **res['Item'], **record } if 'Item' in res else record
ddb.Table(tableName).put_item(
Item = record
)
return True
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ create_or_update_record\n{}".format(e))
return None
def list_tables():
"""
Function to list all tables in DynamoDB
Returns:
tables::[str]
The list of tables
"""
try:
return client.list_tables()['TableNames']
except client.exceptions.ResourceNotFoundException:
print("Tables do not exist")
return False
except Exception as e:
print("Exception @ list_tables\n{}".format(e))
return None
def list_records(tableName):
"""
Function to list all records from a DynamoDB table
Params:
tableName::str
The table name to get the records
Returns:
records::[dict]
The list of records stored in the table
"""
if not tableName:
return False
try:
table = ddb.Table(tableName)
res = table.scan()
docs = ensure_json(res['Items'])
while 'LastEvaluatedKey' in res:
res = table.scan(ExclusiveStartKey = res['LastEvaluatedKey'])
docs.extend(ensure_json(res['Items']))
return docs
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ list_records\n{}".format(e))
return None
def get_record(tableName, query):
"""
Function to retrieve one record from DynamoDB table
Params:
tableName::str
The table name to get the record
query::dict
The query to fetch the record
Returns:
doc::dict
The record retrieved from the table
"""
if not tableName or not query or not isinstance(query, dict):
return False
try:
res = ddb.Table(tableName).get_item(
Key = query
)
doc = ensure_json(res['Item']) if 'Item' in res else None
return doc
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ get_record\n{}".format(e))
return None
def delete_table(tableName):
"""
Function to delete a DynamoDB table
Params:
tableName::str
The table name to delete
Returns:
bool
If the table was deleted or not
"""
if not tableName:
return False
try:
ddb.Table(tableName).delete()
return True
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ delete_table\n{}".format(e))
return None
def delete_record(tableName, query):
"""
Function to delete a DynamoDB table
Params:
tableName::str
The table name to get the record
query::dict
The query to fetch the record
Returns:
bool
If the record was deleted or not
"""
if not tableName or not key or not val:
return False
try:
res = ddb.Table(tableName).delete_item(
Key = query
)
print(res)
return True
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ delete_record\n{}".format(e))
return None
def check_active(tableName):
"""
Function to check if a table is ACTIVE
Params:
tableName::str
The table name to check
Returns:
bool
If the table is active or not
"""
if not tableName:
return False
try:
if ddb.Table(tableName).table_status == "ACTIVE":
return True
return False
except client.exceptions.ResourceNotFoundException:
print("Table does not exist")
return False
except Exception as e:
print("Exception @ check_status\n{}".format(e))
return None | 24.888889 | 76 | 0.547098 |
91eee874c4335dfd997cd3ef3e9c2d23c76e47b1 | 26 | py | Python | cloudcms/branch/__init__.py | gitana/cloudcms-python-driver | 8685c634880c1a6af6f359f1a25de42dcf49f319 | [
"Apache-2.0"
] | null | null | null | cloudcms/branch/__init__.py | gitana/cloudcms-python-driver | 8685c634880c1a6af6f359f1a25de42dcf49f319 | [
"Apache-2.0"
] | null | null | null | cloudcms/branch/__init__.py | gitana/cloudcms-python-driver | 8685c634880c1a6af6f359f1a25de42dcf49f319 | [
"Apache-2.0"
] | null | null | null | from .branch import Branch | 26 | 26 | 0.846154 |
91ef6e454e8d3a02bbbb8495426f9e53729bb9c8 | 30 | py | Python | test2/test2.py | kubatom/my_nemtiko_repo | 842a303ae120d871623c267ea76c2353d70b2fce | [
"Apache-2.0"
] | null | null | null | test2/test2.py | kubatom/my_nemtiko_repo | 842a303ae120d871623c267ea76c2353d70b2fce | [
"Apache-2.0"
] | null | null | null | test2/test2.py | kubatom/my_nemtiko_repo | 842a303ae120d871623c267ea76c2353d70b2fce | [
"Apache-2.0"
] | null | null | null | print('this is a test2 file')
| 15 | 29 | 0.7 |
37cd4b6be89839faecee7dd52588398ff12411ba | 247 | py | Python | src/compas_blender/forms/__init__.py | yijiangh/compas | a9e86edf6b602f47ca051fccedcaa88a5e5d3600 | [
"MIT"
] | 1 | 2019-03-27T22:32:56.000Z | 2019-03-27T22:32:56.000Z | src/compas_blender/forms/__init__.py | yijiangh/compas | a9e86edf6b602f47ca051fccedcaa88a5e5d3600 | [
"MIT"
] | null | null | null | src/compas_blender/forms/__init__.py | yijiangh/compas | a9e86edf6b602f47ca051fccedcaa88a5e5d3600 | [
"MIT"
] | null | null | null | """
********************************************************************************
compas_blender.forms
********************************************************************************
.. currentmodule:: compas_blender.forms
"""
__all__ = []
| 22.454545 | 80 | 0.234818 |
37cd97b1c214ca81d9e46e1e2c07bc9bb82f06f0 | 340 | py | Python | Source/Git/Experiments/git_annotate.py | cadappl/scm-workbench | 302cdb8e36bb755f4977062e8977c37e7f4491f9 | [
"Apache-2.0"
] | 24 | 2017-03-23T06:24:02.000Z | 2022-03-19T13:35:44.000Z | Source/Git/Experiments/git_annotate.py | cadappl/scm-workbench | 302cdb8e36bb755f4977062e8977c37e7f4491f9 | [
"Apache-2.0"
] | 14 | 2016-06-21T10:06:27.000Z | 2020-07-25T11:56:23.000Z | Source/Git/Experiments/git_annotate.py | barry-scott/git-workbench | 9f352875ab097ce5e45f85bf255b1fa02a196807 | [
"Apache-2.0"
] | 11 | 2016-12-25T12:36:16.000Z | 2022-03-23T14:25:25.000Z | #!/usr/bin/python3
import sys
import git
r = git.Repo( sys.argv[1] )
num = 0
for info in r.blame( 'HEAD', sys.argv[2] ):
num += 1
commit = info[0]
all_lines = info[1]
print( '%s %6d:%s' % (commit, num, all_lines[0]) )
for line in all_lines[1:]:
num += 1
print( '%*s %6d:%s' % (40, '', num, line) )
| 17 | 54 | 0.517647 |
37cf805b2f12051ac4eca05f7ae1c89c1a8dc059 | 544 | py | Python | configs/global_configs.py | HansikaPH/time-series-forecasting | 23be319a190489bc1464653a3d672edd70ab110b | [
"MIT"
] | 67 | 2019-09-09T14:53:35.000Z | 2022-02-21T08:51:15.000Z | configs/global_configs.py | HansikaPH/time-series-forecasting | 23be319a190489bc1464653a3d672edd70ab110b | [
"MIT"
] | 6 | 2019-09-09T06:11:51.000Z | 2019-12-16T04:31:11.000Z | configs/global_configs.py | HansikaPH/time-series-forecasting | 23be319a190489bc1464653a3d672edd70ab110b | [
"MIT"
] | 18 | 2019-09-12T02:49:58.000Z | 2022-02-16T11:15:57.000Z | # configs for the model training
# configs for the model testing
# configs for hyperparameter tuning(SMAC3)
| 30.222222 | 75 | 0.799632 |
37cf939b241a87e359fb447071196040b0ef99e6 | 26,714 | py | Python | openprocurement/blade/tests/auctions.py | imaginal/openprocurement.blade | 4ef512e3d0c1287af1faca9caa9e5349a3c5b0fb | [
"Apache-2.0"
] | null | null | null | openprocurement/blade/tests/auctions.py | imaginal/openprocurement.blade | 4ef512e3d0c1287af1faca9caa9e5349a3c5b0fb | [
"Apache-2.0"
] | null | null | null | openprocurement/blade/tests/auctions.py | imaginal/openprocurement.blade | 4ef512e3d0c1287af1faca9caa9e5349a3c5b0fb | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import unittest
from uuid import uuid4
from copy import deepcopy
from openprocurement.api.models import get_now
from openprocurement.edge.tests.base import AuctionBaseWebTest, test_award, test_auction_data, test_document, ROUTE_PREFIX
try:
import openprocurement.auctions.core as auctions_core
except ImportError:
auctions_core = None
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(AuctionResourceTest))
suite.addTest(unittest.makeSuite(AuctionAwardResourceTest))
suite.addTest(unittest.makeSuite(AuctionAwardDocumentResourceTest))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| 47.960503 | 145 | 0.63521 |
37cfc9903bdf3148211aecc7d83461d403271fff | 3,967 | py | Python | webium/controls/select.py | kejkz/webium | ccb09876a201e75f5c5810392d4db7a8708b90cb | [
"Apache-2.0"
] | 152 | 2015-01-16T11:26:56.000Z | 2022-01-22T12:11:28.000Z | webium/controls/select.py | goblinintree/webium | ccb09876a201e75f5c5810392d4db7a8708b90cb | [
"Apache-2.0"
] | 13 | 2015-03-05T14:36:44.000Z | 2018-08-08T09:43:39.000Z | webium/controls/select.py | goblinintree/webium | ccb09876a201e75f5c5810392d4db7a8708b90cb | [
"Apache-2.0"
] | 57 | 2015-01-27T12:53:49.000Z | 2022-03-26T23:02:36.000Z | from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.remote.webelement import WebElement
| 33.058333 | 118 | 0.57575 |
37d1196ce920fb2354298f73f3de4a4a984c7332 | 12,564 | py | Python | mc/cookies/CookieManager.py | zy-sunshine/falkon-pyqt5 | bc2b60aa21c9b136439bd57a11f391d68c736f99 | [
"MIT"
] | 1 | 2021-04-29T05:36:44.000Z | 2021-04-29T05:36:44.000Z | mc/cookies/CookieManager.py | zy-sunshine/falkon-pyqt5 | bc2b60aa21c9b136439bd57a11f391d68c736f99 | [
"MIT"
] | 1 | 2020-03-28T17:43:18.000Z | 2020-03-28T17:43:18.000Z | mc/cookies/CookieManager.py | zy-sunshine/falkon-pyqt5 | bc2b60aa21c9b136439bd57a11f391d68c736f99 | [
"MIT"
] | 1 | 2021-01-15T20:09:24.000Z | 2021-01-15T20:09:24.000Z | from PyQt5.QtWidgets import QDialog
from PyQt5 import uic
from PyQt5.Qt import Qt
from PyQt5.Qt import QShortcut
from PyQt5.Qt import QKeySequence
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QInputDialog
from PyQt5.Qt import QDateTime
from PyQt5.Qt import QStyle
from PyQt5.Qt import QNetworkCookie
from PyQt5.QtWidgets import QTreeWidgetItem
from mc.common.globalvars import gVar
from mc.app.Settings import Settings
from mc.common import const
from mc.tools.TreeWidget import TreeWidget
from mc.tools.IconProvider import IconProvider
| 35.897143 | 103 | 0.630372 |
37d161d2ab9998ed2955dcc68be64d87474fc1ce | 1,803 | py | Python | .circleci/process_submitted_data.py | dongbohu/cimr-d | 7d8f7f7319cff0092946a28d1416d38c06e085d7 | [
"CC-BY-4.0"
] | null | null | null | .circleci/process_submitted_data.py | dongbohu/cimr-d | 7d8f7f7319cff0092946a28d1416d38c06e085d7 | [
"CC-BY-4.0"
] | null | null | null | .circleci/process_submitted_data.py | dongbohu/cimr-d | 7d8f7f7319cff0092946a28d1416d38c06e085d7 | [
"CC-BY-4.0"
] | 2 | 2019-05-22T16:05:54.000Z | 2019-05-23T14:29:10.000Z | #!/usr/bin/env python3
import os
import sys
import logging
import subprocess
logging.basicConfig(level=logging.INFO)
root_dir = 'submitted_data'
submitted_file_split = set()
for dir_, _, files in os.walk(root_dir):
for file_name in files:
rel_dir = os.path.relpath(dir_, root_dir)
rel_file = os.path.join(root_dir, rel_dir, file_name)
submitted_file_split.add(rel_file)
for submitted_file in submitted_file_split:
if submitted_file.startswith('submitted_data'):
dir_name, data_type, file_name = submitted_file.split('/')
out_dir_name = 'processed_data'
if not os.path.isdir(out_dir_name):
os.makedirs(out_dir_name, exist_ok=True)
if not os.path.isdir(out_dir_name + '/' + data_type):
os.makedirs(out_dir_name + '/' + data_type, exist_ok=True)
outfile = submitted_file.replace(dir_name, out_dir_name)
if not os.path.isfile(outfile):
if not data_type == 'tad':
from cimr.processor.utils import Infiler
infile = Infiler(
data_type,
submitted_file,
genome_build='b38',
update_rsid=False,
outfile=str(outfile),
chunksize=700000
)
infile.read_file()
if data_type == 'eqtl':
from cimr.processor.query import Querier
genes = list(infile.list_genes())
queried = Querier(genes)
queried.form_query()
else:
logging.info(f' processed file already exists for {submitted_file}')
logging.info(f' if reprocessing, delete {outfile} and file a new pull request')
| 31.086207 | 95 | 0.585136 |
37d19d97641fbdfe4cfca519ffd963eb1a649c60 | 469 | py | Python | common/enums.py | resourceidea/resourceideaapi | 4cc7db98f981d8f2011c1995e23e8a8655e31f75 | [
"MIT"
] | 1 | 2020-05-30T22:27:59.000Z | 2020-05-30T22:27:59.000Z | common/enums.py | resourceidea/resourceideaapi | 4cc7db98f981d8f2011c1995e23e8a8655e31f75 | [
"MIT"
] | 15 | 2020-02-11T21:53:08.000Z | 2021-11-02T21:20:03.000Z | common/enums.py | resourceidea/resourceideaapi | 4cc7db98f981d8f2011c1995e23e8a8655e31f75 | [
"MIT"
] | 1 | 2020-08-27T10:57:47.000Z | 2020-08-27T10:57:47.000Z | import enum
| 21.318182 | 50 | 0.616205 |
37d29492156d47c44672b00f04cedb7fbbdcf78e | 5,880 | py | Python | networks/mobilenet.py | softsys4ai/FlexiBO | 1406d67e5bd14d6b7210e724e6b239889f210db6 | [
"MIT"
] | 8 | 2020-06-23T07:05:18.000Z | 2021-10-24T02:38:14.000Z | networks/mobilenet.py | softsys4ai/FlexiBO | 1406d67e5bd14d6b7210e724e6b239889f210db6 | [
"MIT"
] | null | null | null | networks/mobilenet.py | softsys4ai/FlexiBO | 1406d67e5bd14d6b7210e724e6b239889f210db6 | [
"MIT"
] | 3 | 2020-01-06T10:49:12.000Z | 2020-04-20T03:26:33.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# MobileNet 224 (2017)
# Paper: https://arxiv.org/pdf/1704.04861.pdf
import os
import tensorflow as tf
from tensorflow.keras import layers, Input, Model
def stem(inputs, alpha, n_filters,
filter_size):
""" Construct the stem group
inputs : input tensor
alpha : width multiplier
"""
# Convolutional block
x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)))(inputs)
x = layers.Conv2D(n_filters, (filter_size, filter_size), strides=(2, 2), padding='valid')(x)
x = layers.BatchNormalization()(x)
x = layers.ReLU()(x)
# Depthwise Separable Convolution Block
x = depthwise_block(x, 64, alpha, (1, 1))
return x
def classifier(x, alpha, dropout, n_classes):
""" Construct the classifier group
x : input to the classifier
alpha : width multiplier
dropout : dropout percentage
n_classes : number of output classes
"""
# Flatten the feature maps into 1D feature maps (?, N)
x = layers.GlobalAveragePooling2D()(x)
# Reshape the feature maps to (?, 1, 1, 1024)
shape = (1, 1, int(1024 * alpha))
x = layers.Reshape(shape)(x)
# Perform dropout for preventing overfitting
x = layers.Dropout(dropout)(x)
# Use convolution for classifying (emulates a fully connected layer)
x = layers.Conv2D(n_classes, (1, 1), padding='same')(x)
x = layers.Activation('softmax')(x)
# Reshape the resulting output to 1D vector of number of classes
x = layers.Reshape((n_classes, ))(x)
return x
def depthwise_block(x, n_filters, alpha, strides):
""" Construct a Depthwise Separable Convolution block
x : input to the block
n_filters : number of filters
alpha : width multiplier
strides : strides
"""
# Apply the width filter to the number of feature maps
filters = int(n_filters * alpha)
# Strided convolution to match number of filters
if strides == (2, 2):
x = layers.ZeroPadding2D(padding=((0, 1), (0, 1)))(x)
padding = 'valid'
else:
padding = 'same'
# Depthwise Convolution
x = layers.DepthwiseConv2D((3, 3), strides, padding=padding)(x)
x = layers.BatchNormalization()(x)
x = layers.ReLU()(x)
# Pointwise Convolution
x = layers.Conv2D(filters, (1, 1), strides=(1, 1), padding='same')(x)
x = layers.BatchNormalization()(x)
x = layers.ReLU()(x)
return x
def get_configurable_hyperparams():
"""This function is used to ge the configurable hyperparameters
"""
import yaml
with open("cur_config.yaml") as fp:
cur_cfg=yaml.load(fp)
return (cur_cfg["cur_conf"][0], cur_cfg["cur_conf"][1], cur_cfg["cur_conf"][2],
cur_cfg["cur_conf"][3], cur_cfg["cur_conf"][4])
def get_data():
"""This function is used to get train and test data
"""
from tensorflow.keras.datasets import cifar10
import numpy as np
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = (x_train / 255.0).astype(np.float32)
x_test = (x_test / 255.0).astype(np.float32)
return x_train, y_train, x_test, y_test
if __name__=="__main__":
# get configurable hyperparams
(stem_n_filters,
stem_filter_size
depthwise_block1_n_filters,
depthwise_block2_n_filters,
depthwise_block3_n_filters,
depthwise_block4_n_filters,)=get_configurable_hyperparams()
alpha = 1 # width multiplier
dropout = 0.5 # dropout percentage
n_classes = 1000 # number of classes
inputs = Input(shape=(224, 224, 3))
# Create the stem group
x = stem(inputs, alpha, stem_n_filters,
stem_filter_size)
# First Depth wise Separable Convolution Group
# Strided convolution - feature map size reduction
x = depthwise_block(x, depthwise_block1_n_filters, alpha, strides=(2, 2))
x = depthwise_block(x, depthwise_block1_n_filters, alpha, strides=(1, 1))
# Second Depthwise Separable Convolution Group
# Strided convolution - feature map size reduction
x = depthwise_block(x, depthwise_block2_n_filters, alpha, strides=(2, 2))
x = depthwise_block(x, depthwise_block2_n_filters, alpha, strides=(1, 1))
# Third Depthwise Separable Convolution Group
# Strided convolution - feature map size reduction
x = depthwise_block(x, depthwise_block3_n_filters, alpha, strides=(2, 2))
for _ in range(5):
x = depthwise_block(x, depthwise_block3_n_filters, alpha, strides=(1, 1))
# Fourth Depthwise Separable Convolution Group
# Strided convolution - feature map size reduction
x = depthwise_block(x, depthwise_block4_n_filters, alpha, strides=(2, 2))
x = depthwise_block(x, depthwise_block4_n_filters, alpha, strides=(1, 1))
# Create the classifier
outputs = classifier(x, alpha, dropout, n_classes)
# Instantiate the Model
model = Model(inputs, outputs)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])
model.summary()
xtrain, ytrain, x_test, y_test=get_data()
# train model
model.fit(x_train, y_train, epochs=10,
batch_size=32, validation_split=0.1, verbose=1)
# save model
fmodel=os.path.join(os.getcwd(),"model.h5")
model.save(fmodel)
| 35.209581 | 96 | 0.671769 |
37d2de39d6a42eafed34788e36c34749e153b301 | 500 | py | Python | info.py | altfool/mri_face_detection | 3117f7f00c98efe2260936146ce6b5454b059672 | [
"MIT"
] | 1 | 2021-11-13T02:42:49.000Z | 2021-11-13T02:42:49.000Z | info.py | altfool/mri_face_detection | 3117f7f00c98efe2260936146ce6b5454b059672 | [
"MIT"
] | null | null | null | info.py | altfool/mri_face_detection | 3117f7f00c98efe2260936146ce6b5454b059672 | [
"MIT"
] | null | null | null | import numpy as np
img_dtype = np.float32
imgX, imgY, imgZ = (256, 256, 150)
imgs_path_withfaces = '../dataset/withfaces'
imgs_path_nofaces = '../dataset/nofaces'
imgX_dwt1, imgY_dwt1, imgZ_dwt1 = (128, 128, 75)
imgs_path_withfaces_dwt = './dataset/withfaces'
imgs_path_nofaces_dwt = './dataset/nofaces'
dwt_flag = (True, False)[0]
if dwt_flag:
imgX, imgY, imgZ = imgX_dwt1, imgY_dwt1, imgZ_dwt1
imgs_path_withfaces = imgs_path_withfaces_dwt
imgs_path_nofaces = imgs_path_nofaces_dwt
| 27.777778 | 54 | 0.752 |
37d34e7f40c00147044227bceb687730996c355b | 10,288 | py | Python | biggan/paddorch/paddorch/vision/functional.py | zzz2010/Contrib | d351d83da718145cef9f6c98598f7fedc027efe5 | [
"Apache-2.0"
] | 20 | 2020-03-13T13:40:32.000Z | 2022-03-10T07:31:48.000Z | biggan/paddorch/paddorch/vision/functional.py | zzz2010/Contrib | d351d83da718145cef9f6c98598f7fedc027efe5 | [
"Apache-2.0"
] | 34 | 2020-02-20T11:04:58.000Z | 2022-03-12T00:54:26.000Z | biggan/paddorch/paddorch/vision/functional.py | zzz2010/Contrib | d351d83da718145cef9f6c98598f7fedc027efe5 | [
"Apache-2.0"
] | 41 | 2020-02-14T09:34:39.000Z | 2022-03-10T07:31:42.000Z | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import collections
import random
import math
import cv2
import numbers
import numpy as np
if sys.version_info < (3, 3):
Sequence = collections.Sequence
Iterable = collections.Iterable
else:
Sequence = collections.abc.Sequence
Iterable = collections.abc.Iterable
__all__ = ['flip', 'resize', 'pad', 'rotate', 'to_grayscale']
def flip(image, code):
"""
Accordding to the code (the type of flip), flip the input image
Args:
image: Input image, with (H, W, C) shape
code: Code that indicates the type of flip.
-1 : Flip horizontally and vertically
0 : Flip vertically
1 : Flip horizontally
Examples:
.. code-block:: python
import numpy as np
from paddle.incubate.hapi.vision.transforms import functional as F
fake_img = np.random.rand(224, 224, 3)
# flip horizontally and vertically
F.flip(fake_img, -1)
# flip vertically
F.flip(fake_img, 0)
# flip horizontally
F.flip(fake_img, 1)
"""
return cv2.flip(image, flipCode=code)
def resize(img, size, interpolation=cv2.INTER_LINEAR):
"""
resize the input data to given size
Args:
input: Input data, could be image or masks, with (H, W, C) shape
size: Target size of input data, with (height, width) shape.
interpolation: Interpolation method.
Examples:
.. code-block:: python
import numpy as np
from paddle.incubate.hapi.vision.transforms import functional as F
fake_img = np.random.rand(256, 256, 3)
F.resize(fake_img, 224)
F.resize(fake_img, (200, 150))
"""
if isinstance(interpolation, Sequence):
interpolation = random.choice(interpolation)
if isinstance(size, int):
h, w = img.shape[:2]
if (w <= h and w == size) or (h <= w and h == size):
return img
if w < h:
ow = size
oh = int(size * h / w)
return cv2.resize(img, (ow, oh), interpolation=interpolation)
else:
oh = size
ow = int(size * w / h)
return cv2.resize(img, (ow, oh), interpolation=interpolation)
else:
return cv2.resize(img, tuple(size[::-1]), interpolation=interpolation)
def pad(img, padding, fill=(0, 0, 0), padding_mode='constant'):
"""Pads the given CV Image on all sides with speficified padding mode and fill value.
Args:
img (np.ndarray): Image to be padded.
padding (int|tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a tuple of length 4 is provided
this is the padding for the left, top, right and bottom borders
respectively.
fill (int|tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant
padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
``constant`` means padding with a constant value, this value is specified with fill.
``edge`` means padding with the last value at the edge of the image.
``reflect`` means padding with reflection of image (without repeating the last value on the edge)
padding ``[1, 2, 3, 4]`` with 2 elements on both sides in reflect mode
will result in ``[3, 2, 1, 2, 3, 4, 3, 2]``.
``symmetric`` menas pads with reflection of image (repeating the last value on the edge)
padding ``[1, 2, 3, 4]`` with 2 elements on both sides in symmetric mode
will result in ``[2, 1, 1, 2, 3, 4, 4, 3]``.
Returns:
numpy ndarray: Padded image.
Examples:
.. code-block:: python
import numpy as np
from paddle.incubate.hapi.vision.transforms.functional import pad
fake_img = np.random.rand(500, 500, 3).astype('float32')
fake_img = pad(fake_img, 2)
print(fake_img.shape)
"""
if not isinstance(padding, (numbers.Number, list, tuple)):
raise TypeError('Got inappropriate padding arg')
if not isinstance(fill, (numbers.Number, str, list, tuple)):
raise TypeError('Got inappropriate fill arg')
if not isinstance(padding_mode, str):
raise TypeError('Got inappropriate padding_mode arg')
if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:
raise ValueError(
"Padding must be an int or a 2, or 4 element tuple, not a " +
"{} element tuple".format(len(padding)))
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
'Expected padding mode be either constant, edge, reflect or symmetric, but got {}'.format(padding_mode)
PAD_MOD = {
'constant': cv2.BORDER_CONSTANT,
'edge': cv2.BORDER_REPLICATE,
'reflect': cv2.BORDER_DEFAULT,
'symmetric': cv2.BORDER_REFLECT
}
if isinstance(padding, int):
pad_left = pad_right = pad_top = pad_bottom = padding
if isinstance(padding, collections.Sequence) and len(padding) == 2:
pad_left = pad_right = padding[0]
pad_top = pad_bottom = padding[1]
if isinstance(padding, collections.Sequence) and len(padding) == 4:
pad_left, pad_top, pad_right, pad_bottom = padding
if isinstance(fill, numbers.Number):
fill = (fill,) * (2 * len(img.shape) - 3)
if padding_mode == 'constant':
assert (len(fill) == 3 and len(img.shape) == 3) or (len(fill) == 1 and len(img.shape) == 2), \
'channel of image is {} but length of fill is {}'.format(img.shape[-1], len(fill))
img = cv2.copyMakeBorder(
src=img,
top=pad_top,
bottom=pad_bottom,
left=pad_left,
right=pad_right,
borderType=PAD_MOD[padding_mode],
value=fill)
return img
def rotate(img,
angle,
interpolation=cv2.INTER_LINEAR,
expand=False,
center=None):
"""Rotates the image by angle.
Args:
img (numpy.ndarray): Image to be rotated.
angle (float|int): In degrees clockwise order.
interpolation (int, optional):
interpolation: Interpolation method.
expand (bool|optional): Optional expansion flag.
If true, expands the output image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the input image.
Note that the expand flag assumes rotation around the center and no translation.
center (2-tuple|optional): Optional center of rotation.
Origin is the upper left corner.
Default is the center of the image.
Returns:
numpy ndarray: Rotated image.
Examples:
.. code-block:: python
import numpy as np
from paddle.incubate.hapi.vision.transforms.functional import rotate
fake_img = np.random.rand(500, 500, 3).astype('float32')
fake_img = rotate(fake_img, 10)
print(fake_img.shape)
"""
dtype = img.dtype
h, w, _ = img.shape
point = center or (w / 2, h / 2)
M = cv2.getRotationMatrix2D(point, angle=-angle, scale=1)
if expand:
if center is None:
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - point[0]
M[1, 2] += (nH / 2) - point[1]
dst = cv2.warpAffine(img, M, (nW, nH))
else:
xx = []
yy = []
for point in (np.array([0, 0, 1]), np.array([w - 1, 0, 1]),
np.array([w - 1, h - 1, 1]), np.array([0, h - 1, 1])):
target = np.dot(M, point)
xx.append(target[0])
yy.append(target[1])
nh = int(math.ceil(max(yy)) - math.floor(min(yy)))
nw = int(math.ceil(max(xx)) - math.floor(min(xx)))
M[0, 2] += (nw - w) / 2
M[1, 2] += (nh - h) / 2
dst = cv2.warpAffine(img, M, (nw, nh), flags=interpolation)
else:
dst = cv2.warpAffine(img, M, (w, h), flags=interpolation)
return dst.astype(dtype)
def to_grayscale(img, num_output_channels=1):
"""Converts image to grayscale version of image.
Args:
img (numpy.ndarray): Image to be converted to grayscale.
Returns:
numpy.ndarray: Grayscale version of the image.
if num_output_channels == 1, returned image is single channel
if num_output_channels == 3, returned image is 3 channel with r == g == b
Examples:
.. code-block:: python
import numpy as np
from paddle.incubate.hapi.vision.transforms.functional import to_grayscale
fake_img = np.random.rand(500, 500, 3).astype('float32')
fake_img = to_grayscale(fake_img)
print(fake_img.shape)
"""
if num_output_channels == 1:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
elif num_output_channels == 3:
img = cv2.cvtColor(
cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB)
else:
raise ValueError('num_output_channels should be either 1 or 3')
return img | 38.38806 | 111 | 0.602061 |
37d5209ef3010122c779cf4e6e97b119c2f9a504 | 14,267 | py | Python | ground_battle.py | ashhansen6/minigames | 5b2e0db14b3567c9b6220206105ed448fb303551 | [
"MIT"
] | null | null | null | ground_battle.py | ashhansen6/minigames | 5b2e0db14b3567c9b6220206105ed448fb303551 | [
"MIT"
] | 3 | 2021-03-25T02:39:44.000Z | 2021-06-16T17:53:36.000Z | ground_battle.py | ashhansen6/minigames | 5b2e0db14b3567c9b6220206105ed448fb303551 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 13:38:35 2021
GROUND INVASION! The Game
@author: Ashton Hansen (ashhansen6@outlook.com)
"""
# Packages used:
import numpy as np
import pandas as pd
import random as rng
from termcolor import colored
# Defining starting forces
## Defenders:
def_force = 1250
def_reserves = 400
defenders = def_force + def_reserves
def_strength = def_force
def_guard = def_force
## Attackers:
att_force = 900
att_reserves = 1000
attackers = att_force + att_reserves
att_strength = att_force
att_guard = att_force
# Defining strategies:
## Defenders:
def_strat = ["draft", "turtle"]
### Draft
### Turtle
## Attackers:
att_strat = ["blitz", "guerilla"]
### Blitz
### Guerilla
# Ground Battle Event (Player == Attacker)
wave = 0
player = input("Attacker or Defender? [A/D]:")
while (attackers > 0) and (defenders > 0):
# Wave Information
wave = wave + 1
if wave == 1:
print("############################################################")
print("PREPARE FOR BATTLE! THE FIRST WAVE OF THE BATTLE BEGINS NOW.")
print("############################################################")
else:
print("########## WAVE:", wave, "##########")
print("#############################")
print("Defending force strength:", def_force)
print("Defending forces in reserve:", def_reserves)
print("Attacking force strength:", att_force)
print("Attacking forces in reserve:", att_reserves)
if player =="A":
# Active Player (Attacker)
att_strat_chosen = input(colored("How should we proceed, commander? [blitz/guerilla]:", "yellow"))
elif player == "D":
# CPU Attacker
att_strat_chosen = rng.choice(att_strat)
# Defender Setup
if player == "A":
# CPU Defender
if def_reserves > 0:
def_strat = ["none",
"draft", "draft", "draft", "draft", "draft", "draft",
"turtle", "turtle", "turtle"]
def_strat_chosen = rng.choice(def_strat)
else:
def_strat = ["none", "none",
"turtle", "turtle", "turtle" ,"turtle", "turtle", "turtle", "turtle", "turtle"]
def_strat_chosen = rng.choice(def_strat)
elif player == "D":
# Active Player (defender)
def_strat_chosen = input(colored("How should we proceed, commander? [draft/turtle]:", "yellow"))
if def_strat_chosen == "draft":
draft_results = draft(def_force, def_reserves)
def_force = draft_results[0]
def_reserves = draft_results[1]
def_strength = draft_results[2]
def_guard = draft_results[3]
elif def_strat_chosen == "turtle":
turtle_results = turtle(def_force, def_reserves)
def_force = turtle_results[0]
def_reserves = turtle_results[1]
def_strength = turtle_results[2]
def_guard = turtle_results[3]
elif def_strat_chosen == "none":
print(colored("########## INTELLIGENCE REPORT ##########", on_color = "on_cyan"))
print("It appears that the enemy will employ standard tactics...")
def_force = def_force
def_reserves = def_reserves
def_strength = def_force
def_guard = def_force
print("Defending force strength:", def_force)
print("Forces kept in reserve:", def_reserves)
# Attacker Setup
if att_strat_chosen == "blitz":
blitz_results = blitz(att_force, att_reserves)
att_force = blitz_results[0]
att_reserves = blitz_results[1]
att_strength = blitz_results[2]
att_guard = blitz_results[3]
elif att_strat_chosen == "guerilla":
guerilla_results = guerilla(att_force, att_reserves)
att_force = guerilla_results[0]
att_reserves = guerilla_results[1]
att_strength = guerilla_results[2]
att_guard = guerilla_results[3]
# Combat
# Attacker damage
def_guard = np.random.normal(def_guard, def_guard/10) * 0.50
att_strength = att_strength - def_guard
if att_strength < 0:
att_strength = 0
def_force = def_force - np.random.normal(att_strength, att_strength/10)//2 - (0.1*att_strength)//1
if def_force < 0:
def_force = 0
# Defender damage
att_guard = np.random.normal(att_guard, att_guard/10) * 0.50 - 0.1
def_strength = def_strength - att_guard
if def_strength < 0:
def_strength = 0
att_force = att_force - np.random.normal(def_strength, def_strength/10)//2 - (0.1*def_strength)//1
if att_force < 0:
att_force = 0
# Post-wave results:
print(colored("########## POST-WAVE RESULTS ##########", on_color = "on_cyan"))
print(colored("Defenders:", on_color = "on_blue"))
print("Surviving defensive forces:", def_force)
print("Defenseive forces kept in reserve:", def_reserves)
print("Defender strength estimate:", def_strength)
print("Defender guard estimate:", def_guard)
print(colored("Attackers:", on_color = "on_red"))
print("Surviving attacker forces:", att_force)
print("Attacker forces kept in reserve:", att_reserves)
print("Attacker strength estimate:", att_strength)
print("Attacker guard estimate:", att_guard)
# Reset allocations
# Defender reallocations:
def_reserves = def_reserves + def_force
def_force = 0
if def_reserves >= 1250:
def_reserves = def_reserves - 1250
def_force = 1250
def_guard = def_force
else:
def_force = def_reserves
def_reserves = 0
def_guard = def_force
# Attacker reallocations:
att_reserves = att_reserves + att_force
att_force = 0
if att_reserves >= 900:
att_reserves = att_reserves - 900
att_force = 900
att_guard = att_force
else:
att_force = att_reserves
att_reserves = 0
att_guard = att_force
defenders = def_force + def_reserves
attackers = att_force + att_reserves
# End of wave conditionals
if (attackers > 0) and (defenders > 0) and (player == "A"):
fightflight = input(colored("Continue or retreat?: [continue/retreat]:", "yellow"))
if fightflight == "retreat":
print(colored("########## WITHDRAWAL ##########", on_color = "on_blue"))
print("You choose to withdraw your troops...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", attackers)
print("Total losses:", (1900 - attackers))
print("Survival rate:", (attackers)/1900)
print("Total assault waves:", wave)
break
else:
print("The battle will continue next turn...")
elif attackers <= 0 and player == "A":
print(colored("########## FAILURE! ##########", on_color = "on_red"))
print("Your assault has been repelled!")
print("You return home, wondering what punishment for your failure awaits...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", attackers)
print("Total losses:", (1900 - attackers))
print("Survival rate:", (attackers)/1900)
print("Total assault waves:", wave)
elif defenders <= 0 and player == "A":
print(colored("########## SUCCESS! ##########", on_color = "on_green"))
print("The defenders have been routed!")
print("You may now decide the fate of the defending population...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", attackers)
print("Total losses:", (1900 - attackers))
print("Survival rate:", (attackers)/1900)
print("Total assault waves:", wave)
elif (attackers > 0) and (defenders > 0) and (player == "D"):
fightflight = input(colored("Defend or retreat?: [defend/retreat]:", "yellow"))
if fightflight == "retreat":
print(colored("########## WITHDRAWAL ##########", on_color = "on_blue"))
print("You choose to withdraw your troops from the region...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", defenders)
print("Total losses:", (1900 - defenders))
print("Survival rate:", (defenders)/1900)
print("Total assault waves:", wave)
break
else:
print("The battle will continue next turn...")
elif defenders <= 0 and player == "D":
print(colored("########## FAILURE! ##########", on_color = "on_red"))
print("Your defense has been broken!")
print("Enemy troops now occupy your lands and have claimed dominion...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", defenders)
print("Total losses:", (1650 - defenders))
print("Survival rate:", (defenders)/1650)
print("Total assault waves:", wave)
elif attackers <= 0 and player == "D":
print(colored("########## SUCCESS! ##########", on_color = "on_green"))
print("The attackers have been repelled!")
print("The storm has passed, and your people live another day...")
print(colored("######### INVASION STATISTICS ##########", on_color = "on_cyan"))
print("Troops remaining:", defenders)
print("Total losses:", (1650 - defenders))
print("Survival rate:", (defenders)/1650)
print("Total assault waves:", wave)
print("#############################")
| 41.961765 | 107 | 0.604892 |
37d53dc9e4eafc3370db20f7342e6ffdb10aeb9f | 24,609 | py | Python | src/pretalx/orga/urls.py | martinheidegger/pretalx | d812e665c1c5ce29df3eafc1985af08e4d986fef | [
"Apache-2.0"
] | null | null | null | src/pretalx/orga/urls.py | martinheidegger/pretalx | d812e665c1c5ce29df3eafc1985af08e4d986fef | [
"Apache-2.0"
] | null | null | null | src/pretalx/orga/urls.py | martinheidegger/pretalx | d812e665c1c5ce29df3eafc1985af08e4d986fef | [
"Apache-2.0"
] | null | null | null | from django.conf.urls import include, url
from django.views.generic.base import RedirectView
from pretalx.event.models.event import SLUG_CHARS
from pretalx.orga.views import cards
from .views import (
admin,
auth,
cfp,
dashboard,
event,
mails,
organiser,
person,
plugins,
review,
schedule,
speaker,
submission,
)
app_name = "orga"
urlpatterns = [
url("^login/$", auth.LoginView.as_view(), name="login"),
url("^logout/$", auth.logout_view, name="logout"),
url("^reset/$", auth.ResetView.as_view(), name="auth.reset"),
url(r"^reset/(?P<token>\w+)$", auth.RecoverView.as_view(), name="auth.recover"),
url("^$", RedirectView.as_view(url="event", permanent=False)),
url("^admin/$", admin.AdminDashboard.as_view(), name="admin.dashboard"),
url("^admin/update/$", admin.UpdateCheckView.as_view(), name="admin.update"),
url("^me$", event.UserSettings.as_view(), name="user.view"),
url("^me/subuser$", person.SubuserView.as_view(), name="user.subuser"),
url(
r"^invitation/(?P<code>\w+)$",
event.InvitationView.as_view(),
name="invitation.view",
),
url(
"^organiser/$",
dashboard.DashboardOrganiserListView.as_view(),
name="organiser.list",
),
url(
"^organiser/new$", organiser.OrganiserDetail.as_view(), name="organiser.create"
),
url(
f"^organiser/(?P<organiser>[{SLUG_CHARS}]+)/",
include(
[
url("^$", organiser.OrganiserDetail.as_view(), name="organiser.view"),
url(
"^delete$",
organiser.OrganiserDelete.as_view(),
name="organiser.delete",
),
url("^teams/$", organiser.TeamDetail.as_view(), name="organiser.teams"),
url(
"^teams/new$",
organiser.TeamDetail.as_view(),
name="organiser.teams.create",
),
url(
"^teams/(?P<pk>[0-9]+)/$",
organiser.TeamDetail.as_view(),
name="organiser.teams.view",
),
url(
"^teams/(?P<pk>[0-9]+)/delete$",
organiser.TeamDelete.as_view(),
name="organiser.teams.delete",
),
url(
"^teams/(?P<pk>[0-9]+)/tracks$",
organiser.TeamTracks.as_view(),
name="organiser.teams.tracks",
),
url(
"^teams/(?P<pk>[0-9]+)/delete/(?P<user_pk>[0-9]+)$",
organiser.TeamDelete.as_view(),
name="organiser.teams.delete_member",
),
url(
"^teams/(?P<pk>[0-9]+)/reset/(?P<user_pk>[0-9]+)$",
organiser.TeamResetPassword.as_view(),
name="organiser.team.password_reset",
),
url(
"^teams/(?P<pk>[0-9]+)/uninvite$",
organiser.TeamUninvite.as_view(),
name="organiser.teams.uninvite",
),
url(
"^teams/(?P<pk>[0-9]+)/resend$",
organiser.TeamResend.as_view(),
name="organiser.teams.resend",
),
]
),
),
url("^event/new/$", event.EventWizard.as_view(), name="event.create"),
url("^event/typeahead/$", event.event_list, name="event.typeahead"),
url("^event/$", dashboard.DashboardEventListView.as_view(), name="event.list"),
url(
f"^event/(?P<event>[{SLUG_CHARS}]+)/",
include(
[
url(
"^$", dashboard.EventDashboardView.as_view(), name="event.dashboard"
),
url("^login/$", auth.LoginView.as_view(), name="event.login"),
url("^reset/$", auth.ResetView.as_view(), name="event.auth.reset"),
url(
r"^reset/(?P<token>\w+)$",
auth.RecoverView.as_view(),
name="event.auth.recover",
),
url("^delete$", event.EventDelete.as_view(), name="event.delete"),
url("^live$", event.EventLive.as_view(), name="event.live"),
url("^api/users$", person.UserList.as_view(), name="event.user_list"),
url(
"^cfp/$",
RedirectView.as_view(pattern_name="orga:cfp.text.view"),
name="cfp",
),
url("^cfp/flow/$", cfp.CfPFlowEditor.as_view(), name="cfp.flow"),
url(
"^cfp/questions/$",
cfp.CfPQuestionList.as_view(),
name="cfp.questions.view",
),
url(
"^cfp/questions/new$",
cfp.CfPQuestionDetail.as_view(),
name="cfp.questions.create",
),
url(
"^cfp/questions/remind$",
cfp.CfPQuestionRemind.as_view(),
name="cfp.questions.remind",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/$",
cfp.CfPQuestionDetail.as_view(),
name="cfp.question.view",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/up$",
cfp.question_move_up,
name="cfp.questions.up",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/down$",
cfp.question_move_down,
name="cfp.questions.down",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/delete$",
cfp.CfPQuestionDelete.as_view(),
name="cfp.question.delete",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/edit$",
cfp.CfPQuestionDetail.as_view(),
name="cfp.question.edit",
),
url(
"^cfp/questions/(?P<pk>[0-9]+)/toggle$",
cfp.CfPQuestionToggle.as_view(),
name="cfp.question.toggle",
),
url("^cfp/text$", cfp.CfPTextDetail.as_view(), name="cfp.text.view"),
url(
"^cfp/types/$",
cfp.SubmissionTypeList.as_view(),
name="cfp.types.view",
),
url(
"^cfp/types/new$",
cfp.SubmissionTypeDetail.as_view(),
name="cfp.types.create",
),
url(
"^cfp/types/(?P<pk>[0-9]+)/$",
cfp.SubmissionTypeDetail.as_view(),
name="cfp.type.view",
),
url(
"^cfp/types/(?P<pk>[0-9]+)/delete$",
cfp.SubmissionTypeDelete.as_view(),
name="cfp.type.delete",
),
url(
"^cfp/types/(?P<pk>[0-9]+)/default$",
cfp.SubmissionTypeDefault.as_view(),
name="cfp.type.default",
),
url("^cfp/tracks/$", cfp.TrackList.as_view(), name="cfp.tracks.view"),
url(
"^cfp/tracks/new$",
cfp.TrackDetail.as_view(),
name="cfp.track.create",
),
url(
"^cfp/tracks/(?P<pk>[0-9]+)/$",
cfp.TrackDetail.as_view(),
name="cfp.track.view",
),
url(
"^cfp/tracks/(?P<pk>[0-9]+)/delete$",
cfp.TrackDelete.as_view(),
name="cfp.track.delete",
),
url(
"^cfp/access-codes/$",
cfp.AccessCodeList.as_view(),
name="cfp.access_code.view",
),
url(
"^cfp/access-codes/new$",
cfp.AccessCodeDetail.as_view(),
name="cfp.access_code.create",
),
url(
"^cfp/access-codes/(?P<code>[A-z0-9]+)/$",
cfp.AccessCodeDetail.as_view(),
name="cfp.access_code.view",
),
url(
"^cfp/access-codes/(?P<code>[A-z0-9]+)/send$",
cfp.AccessCodeSend.as_view(),
name="cfp.access_code.send",
),
url(
"^cfp/access-codes/(?P<code>[A-z0-9]+)/delete$",
cfp.AccessCodeDelete.as_view(),
name="cfp.access_code.delete",
),
url(
"^mails/",
include(
[
url(
"^(?P<pk>[0-9]+)/$",
mails.MailDetail.as_view(),
name="mails.outbox.mail.view",
),
url(
"^(?P<pk>[0-9]+)/copy$",
mails.MailCopy.as_view(),
name="mails.outbox.mail.copy",
),
url(
"^(?P<pk>[0-9]+)/delete$",
mails.OutboxPurge.as_view(),
name="mails.outbox.mail.delete",
),
url(
"^(?P<pk>[0-9]+)/send$",
mails.OutboxSend.as_view(),
name="mails.outbox.mail.send",
),
url(
"^templates/$",
mails.TemplateList.as_view(),
name="mails.templates.list",
),
url(
"^templates/new$",
mails.TemplateDetail.as_view(),
name="mails.templates.create",
),
url(
"^templates/(?P<pk>[0-9]+)/$",
mails.TemplateDetail.as_view(),
name="mails.templates.view",
),
url(
"^templates/(?P<pk>[0-9]+)/delete$",
mails.TemplateDelete.as_view(),
name="mails.templates.delete",
),
url(
"^compose$",
mails.ComposeMail.as_view(),
name="mails.compose",
),
url("^sent$", mails.SentMail.as_view(), name="mails.sent"),
url(
"^outbox/$",
mails.OutboxList.as_view(),
name="mails.outbox.list",
),
url(
"^outbox/send$",
mails.OutboxSend.as_view(),
name="mails.outbox.send",
),
url(
"^outbox/purge$",
mails.OutboxPurge.as_view(),
name="mails.outbox.purge",
),
]
),
),
url(
"^submissions/$",
submission.SubmissionList.as_view(),
name="submissions.list",
),
url(
"^submissions/new$",
submission.SubmissionContent.as_view(),
name="submissions.create",
),
url(
"^submissions/cards/$",
cards.SubmissionCards.as_view(),
name="submissions.cards",
),
url(
"^submissions/feed/$",
submission.SubmissionFeed(),
name="submissions.feed",
),
url(
"^submissions/statistics/$",
submission.SubmissionStats.as_view(),
name="submissions.statistics",
),
url(
"^submissions/feedback/$",
submission.AllFeedbacksList.as_view(),
name="submissions.feedback",
),
url(
r"^submissions/(?P<code>[\w-]+)/",
include(
[
url(
"^$",
submission.SubmissionContent.as_view(),
name="submissions.content.view",
),
url(
"^submit$",
submission.SubmissionStateChange.as_view(),
name="submissions.submit",
),
url(
"^accept$",
submission.SubmissionStateChange.as_view(),
name="submissions.accept",
),
url(
"^reject$",
submission.SubmissionStateChange.as_view(),
name="submissions.reject",
),
url(
"^confirm",
submission.SubmissionStateChange.as_view(),
name="submissions.confirm",
),
url(
"^withdraw$",
submission.SubmissionStateChange.as_view(),
name="submissions.withdraw",
),
url(
"^delete",
submission.SubmissionStateChange.as_view(),
name="submissions.delete",
),
url(
"^cancel",
submission.SubmissionStateChange.as_view(),
name="submissions.cancel",
),
url(
"^speakers/$",
submission.SubmissionSpeakers.as_view(),
name="submissions.speakers.view",
),
url(
"^speakers/add$",
submission.SubmissionSpeakersAdd.as_view(),
name="submissions.speakers.add",
),
url(
"^speakers/delete$",
submission.SubmissionSpeakersDelete.as_view(),
name="submissions.speakers.delete",
),
url(
"^reviews/$",
review.ReviewSubmission.as_view(),
name="submissions.reviews",
),
url(
"^reviews/delete$",
review.ReviewSubmissionDelete.as_view(),
name="submissions.reviews.submission.delete",
),
url(
"^feedback/$",
submission.FeedbackList.as_view(),
name="submissions.feedback.list",
),
url(
"^toggle_featured$",
submission.ToggleFeatured.as_view(),
name="submissions.toggle_featured",
),
url(
"^anonymise/$",
submission.Anonymise.as_view(),
name="submissions.anonymise",
),
]
),
),
url("^speakers/$", speaker.SpeakerList.as_view(), name="speakers.list"),
url(
"^speakers/(?P<pk>[0-9]+)/$",
speaker.SpeakerDetail.as_view(),
name="speakers.view",
),
url(
"^speakers/(?P<pk>[0-9]+)/reset$",
speaker.SpeakerPasswordReset.as_view(),
name="speakers.reset",
),
url(
"^speakers/(?P<pk>[0-9]+)/toggle-arrived$",
speaker.SpeakerToggleArrived.as_view(),
name="speakers.arrived",
),
url(
"^info/$",
speaker.InformationList.as_view(),
name="speakers.information.list",
),
url(
"^info/new$",
speaker.InformationDetail.as_view(),
name="speakers.information.create",
),
url(
"^info/(?P<pk>[0-9]+)/$",
speaker.InformationDetail.as_view(),
name="speakers.information.view",
),
url(
"^info/(?P<pk>[0-9]+)/delete$",
speaker.InformationDelete.as_view(),
name="speakers.information.delete",
),
url(
"^reviews/$",
review.ReviewDashboard.as_view(),
name="reviews.dashboard",
),
url(
"^reviews/regenerate/$",
review.RegenerateDecisionMails.as_view(),
name="reviews.regenerate",
),
url(
"^settings/$",
event.EventDetail.as_view(),
name="settings.event.view",
),
url(
"^settings/mail$",
event.EventMailSettings.as_view(),
name="settings.mail.view",
),
url(
"^settings/plugins$",
plugins.EventPluginsView.as_view(),
name="settings.plugins.select",
),
url(
"^settings/widget$",
event.WidgetSettings.as_view(),
name="settings.widget",
),
url(
"^settings/review/$",
event.EventReviewSettings.as_view(),
name="settings.review",
),
url(
"^settings/review/phase/(?P<pk>[0-9]+)/up$",
event.phase_move_up,
name="settings.review.phase.up",
),
url(
"^settings/review/phase/(?P<pk>[0-9]+)/down$",
event.phase_move_down,
name="settings.review.phase.down",
),
url(
"^settings/review/phase/(?P<pk>[0-9]+)/delete$",
event.PhaseDelete.as_view(),
name="settings.review.phasedelete",
),
url(
"^settings/review/phase/(?P<pk>[0-9]+)/activate$",
event.PhaseActivate.as_view(),
name="settings.review.phasedelete",
),
url(
"^schedule/$", schedule.ScheduleView.as_view(), name="schedule.main"
),
url(
"^schedule/export/$",
schedule.ScheduleExportView.as_view(),
name="schedule.export",
),
url(
"^schedule/export/trigger$",
schedule.ScheduleExportTriggerView.as_view(),
name="schedule.export.trigger",
),
url(
"^schedule/export/download$",
schedule.ScheduleExportDownloadView.as_view(),
name="schedule.export.download",
),
url(
"^schedule/release$",
schedule.ScheduleReleaseView.as_view(),
name="schedule.release",
),
url(
r"^schedule/quick/(?P<code>\w+)/$",
schedule.QuickScheduleView.as_view(),
name="schedule.quick",
),
url(
"^schedule/reset$",
schedule.ScheduleResetView.as_view(),
name="schedule.reset",
),
url(
"^schedule/toggle$",
schedule.ScheduleToggleView.as_view(),
name="schedule.toggle",
),
url(
"^schedule/resend_mails$",
schedule.ScheduleResendMailsView.as_view(),
name="schedule.resend_mails",
),
url(
"^schedule/rooms/$",
schedule.RoomList.as_view(),
name="schedule.rooms.list",
),
url(
"^schedule/rooms/new$",
schedule.RoomDetail.as_view(),
name="schedule.rooms.create",
),
url(
"^schedule/rooms/(?P<pk>[0-9]+)/$",
schedule.RoomDetail.as_view(),
name="schedule.rooms.view",
),
url(
"^schedule/rooms/(?P<pk>[0-9]+)/delete$",
schedule.RoomDelete.as_view(),
name="schedule.rooms.delete",
),
url(
"^schedule/rooms/(?P<pk>[0-9]+)/up$",
schedule.room_move_up,
name="schedule.rooms.up",
),
url(
"^schedule/rooms/(?P<pk>[0-9]+)/down$",
schedule.room_move_down,
name="schedule.rooms.down",
),
url(
"^schedule/api/talks/$",
schedule.TalkList.as_view(),
name="schedule.api.talks",
),
url(
"^schedule/api/talks/(?P<pk>[0-9]+)/$",
schedule.TalkUpdate.as_view(),
name="schedule.api.update",
),
url(
"^schedule/api/availabilities/(?P<talkid>[0-9]+)/(?P<roomid>[0-9]+)/$",
schedule.RoomTalkAvailabilities.as_view(),
name="schedule.api.availabilities",
),
]
),
),
]
| 40.54201 | 91 | 0.358771 |
37d57b222d4daa1969049535271df3dff47b0edb | 1,925 | py | Python | ws2122-lspm/Lib/site-packages/pm4py/statistics/overlap/utils/compute.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2022-01-19T04:02:46.000Z | 2022-01-19T04:02:46.000Z | ws2122-lspm/Lib/site-packages/pm4py/statistics/overlap/utils/compute.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2021-11-19T07:21:48.000Z | 2021-11-19T07:21:48.000Z | ws2122-lspm/Lib/site-packages/pm4py/statistics/overlap/utils/compute.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2022-01-14T17:15:38.000Z | 2022-01-14T17:15:38.000Z | '''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PM4Py is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PM4Py. If not, see <https://www.gnu.org/licenses/>.
'''
from enum import Enum
from typing import Optional, Dict, Any, Tuple, List, Union
from intervaltree import Interval, IntervalTree
from pm4py.util import exec_utils
def apply(points: List[Tuple[float, float]], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> List[int]:
"""
Computes the overlap statistic given a list of points, expressed as (min_timestamp, max_timestamp)
Parameters
-----------------
points
List of points with the aforementioned features
parameters
Parameters of the method, including:
- Parameters.EPSILON
Returns
-----------------
overlap
List associating to each point the number of intersecting points
"""
if parameters is None:
parameters = {}
epsilon = exec_utils.get_param_value(Parameters.EPSILON, parameters, 10 ** (-5))
points = [(x[0] - epsilon, x[1] + epsilon) for x in points]
sorted_points = sorted(points)
tree = IntervalTree()
for p in sorted_points:
tree.add(Interval(p[0], p[1]))
overlap = []
for p in points:
overlap.append(len(tree[p[0]:p[1]]))
return overlap
| 31.048387 | 122 | 0.676883 |
37d597714762fd1b5295ccfa14750529f2501042 | 1,775 | py | Python | webapp/apps/Base Quiz/baseui_gen.py | sk-Prime/webapp | c21d7d49de4e4442f9af29ba9f08f37b5abbd20d | [
"MIT"
] | 4 | 2021-12-11T16:01:10.000Z | 2021-12-22T19:47:51.000Z | webapp/apps/Base Quiz/baseui_gen.py | sk-Prime/webapp | c21d7d49de4e4442f9af29ba9f08f37b5abbd20d | [
"MIT"
] | null | null | null | webapp/apps/Base Quiz/baseui_gen.py | sk-Prime/webapp | c21d7d49de4e4442f9af29ba9f08f37b5abbd20d | [
"MIT"
] | null | null | null | from htmlman import HTMLMan
from styleman import Template
page=HTMLMan()
page.make_responsive()
page.add_title("Base Quiz")
style=Template('antartica')
page.add_body_class(style['page'])
page.add_js("baseui.js")
page.create_section('main',append=True)
page['main'].add_style_class(style['main'])
title=page.create_section('title')
title.add_style_class(style['title'])
title.add_content("Base Quiz")
widget=page.create_section("widget")
widget.add_style_class(style['widget'])
label = page.create_section('label',ID='label')
#label.add_style_class(style['center'])
label.add_style(name='label',mode="class")
label.style_to_cssman(style)
label.style(
"font-size","20pt",
"font-family","monospace",
"height","50px",
"border-bottom","1px solid #ccd",
)
label.add_content("0x0")
answer_l=page.create_section("answer_l1",ID="label_t")
answer_l.add_style_class(style["label"])
answer_l2=page.create_section("answer_l2",ID="label_b")
answer_l2.add_style_class(style["label"])
controls = page.create_section("control")
controls.add_style(name="control",mode="class",cssman_obj=style)
controls.style(
"display","grid",
"grid-template-columns","1fr 1fr",
"gap","10px",
"padding","10px"
)
rand_b=page.create_section('random',tag="button",inner_html="Random")
rand_b.config_attr("type","button","onclick","randomize()")
answer_b=page.create_section('answer_b',tag="button",inner_html="Answer")
answer_b.config_attr("type","button","onclick","answer()")
controls.add_content(rand_b)
controls.add_content(answer_b)
widget.add_content(label)
widget.add_content(answer_l)
widget.add_content(answer_l2)
widget.add_content(controls)
page['main'].add_content(title)
page['main'].add_content(widget)
page.render(style,html_path="baseui.html") | 26.102941 | 73 | 0.750423 |
37d5b6f804f5b3c1c18198672cc73bf3cc33a2a6 | 514 | py | Python | cluster_config/cluster.py | srcc-msu/job_statistics | 74680a4e4c105ebcff94f089e07fcb44dbcc12d9 | [
"MIT"
] | null | null | null | cluster_config/cluster.py | srcc-msu/job_statistics | 74680a4e4c105ebcff94f089e07fcb44dbcc12d9 | [
"MIT"
] | null | null | null | cluster_config/cluster.py | srcc-msu/job_statistics | 74680a4e4c105ebcff94f089e07fcb44dbcc12d9 | [
"MIT"
] | null | null | null | name = "cluster"
num_cores = 1000
GENERAL_PARTITIONS = ["regular"]
GPU_PARTITIONS = ["gpu"]
PARTITIONS = GENERAL_PARTITIONS + GPU_PARTITIONS
ACTIVE_JOB_STATES = ["RUNNING", "COMPLETING"]
FINISHED_JOB_STATES = ["COMPLETED", "NODE_FAIL", "TIMEOUT", "FAILED", "CANCELLED"]
JOB_STATES = ACTIVE_JOB_STATES + FINISHED_JOB_STATES
def node2int(node):
"""custom function to convert nodename to int
this one removes all chars from names like node1-001-01"""
return int(''.join(filter(lambda x: x.isdigit(), node)))
| 27.052632 | 82 | 0.741245 |
37d62e06868fc1146c429cff23d726ebbfa8afd8 | 7,146 | py | Python | room_assistance/indico_room_assistance/plugin.py | OmeGak/indico-plugins-cern | 6e32bc158877080085ceffd021ab1d2247192f75 | [
"MIT"
] | 4 | 2019-02-12T05:08:56.000Z | 2022-03-09T23:43:18.000Z | room_assistance/indico_room_assistance/plugin.py | OmeGak/indico-plugins-cern | 6e32bc158877080085ceffd021ab1d2247192f75 | [
"MIT"
] | 40 | 2017-11-08T15:08:50.000Z | 2022-03-28T15:09:51.000Z | room_assistance/indico_room_assistance/plugin.py | OmeGak/indico-plugins-cern | 6e32bc158877080085ceffd021ab1d2247192f75 | [
"MIT"
] | 15 | 2017-11-08T12:35:59.000Z | 2022-01-13T15:16:42.000Z | # This file is part of the CERN Indico plugins.
# Copyright (C) 2014 - 2021 CERN
#
# The CERN Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License; see
# the LICENSE file for more details.
import dateutil.parser
import pytz
from flask import flash, request, session
from flask_pluginengine import render_plugin_template, url_for_plugin
from indico.core import signals
from indico.core.config import config
from indico.core.plugins import IndicoPlugin
from indico.core.settings.converters import ModelListConverter
from indico.modules.events.requests.models.requests import Request, RequestState
from indico.modules.events.requests.views import WPRequestsEventManagement
from indico.modules.rb.models.rooms import Room
from indico.modules.users import User
from indico.util.string import natural_sort_key
from indico.web.forms.base import IndicoForm
from indico.web.forms.fields import EmailListField, IndicoQuerySelectMultipleField, PrincipalListField
from indico.web.menu import TopMenuItem
from indico_room_assistance import _
from indico_room_assistance.blueprint import blueprint
from indico_room_assistance.definition import RoomAssistanceRequest
from indico_room_assistance.util import (can_request_assistance_for_event, event_has_room_with_support_attached,
is_room_assistance_support)
| 52.160584 | 120 | 0.645116 |
37d69c9affc9004808d91089e961fe9861840f56 | 6,808 | py | Python | datamart/materializers/wikidata_spo_materializer.py | liangmuxin/datamart | 495a21588db39c9ad239409208bec701dca07f30 | [
"MIT"
] | 7 | 2018-10-02T01:32:23.000Z | 2020-10-08T00:42:35.000Z | datamart/materializers/wikidata_spo_materializer.py | liangmuxin/datamart | 495a21588db39c9ad239409208bec701dca07f30 | [
"MIT"
] | 47 | 2018-10-02T05:41:13.000Z | 2021-02-02T21:50:31.000Z | datamart/materializers/wikidata_spo_materializer.py | liangmuxin/datamart | 495a21588db39c9ad239409208bec701dca07f30 | [
"MIT"
] | 19 | 2018-10-01T22:27:20.000Z | 2019-02-28T18:59:53.000Z | from datamart.materializers.materializer_base import MaterializerBase
import os
import urllib.request
import sys
import csv
import copy
import json
from typing import List
from pprint import pprint
import re
import typing
from pandas import DataFrame
import traceback
| 38.03352 | 126 | 0.552732 |
37d6ae677936f62a1cad64182feb228714d24c7d | 1,402 | py | Python | axelrod/load_data_.py | danilobellini/Axelrod | 2c9212553e06095c24adcb82a5979279cbdf45fb | [
"MIT"
] | null | null | null | axelrod/load_data_.py | danilobellini/Axelrod | 2c9212553e06095c24adcb82a5979279cbdf45fb | [
"MIT"
] | 1 | 2019-01-22T09:59:52.000Z | 2019-01-22T09:59:52.000Z | axelrod/load_data_.py | danilobellini/Axelrod | 2c9212553e06095c24adcb82a5979279cbdf45fb | [
"MIT"
] | null | null | null | from typing import Dict, List, Tuple
import pkg_resources
def load_file(filename: str, directory: str) -> List[List[str]]:
"""Loads a data file stored in the Axelrod library's data subdirectory,
likely for parameters for a strategy."""
path = "/".join((directory, filename))
data_bytes = pkg_resources.resource_string(__name__, path)
data = data_bytes.decode("UTF-8", "replace")
rows = []
for line in data.split("\n"):
if line.startswith("#") or len(line) == 0:
continue
s = line.split(", ")
rows.append(s)
return rows
def load_weights(
filename: str = "ann_weights.csv", directory: str = "data"
) -> Dict[str, Tuple[int, int, List[float]]]:
"""Load Neural Network Weights."""
rows = load_file(filename, directory)
d = dict()
for row in rows:
name = str(row[0])
num_features = int(row[1])
num_hidden = int(row[2])
weights = list(map(float, row[3:]))
d[name] = (num_features, num_hidden, weights)
return d
def load_pso_tables(filename="pso_gambler.csv", directory="data"):
"""Load lookup tables."""
rows = load_file(filename, directory)
d = dict()
for row in rows:
name, a, b, c, = str(row[0]), int(row[1]), int(row[2]), int(row[3])
values = list(map(float, row[4:]))
d[(name, int(a), int(b), int(c))] = values
return d
| 31.155556 | 75 | 0.601284 |
37d85e09c27d6497523862946e45ed0db97f77b6 | 5,248 | py | Python | prescryptchain/api/views.py | genobank-io/CryptoVault | 7c2f6c4c55df7d9e172058aad334a26786ea839f | [
"Apache-2.0"
] | 3 | 2018-05-03T18:40:48.000Z | 2019-06-09T19:04:44.000Z | prescryptchain/api/views.py | genobank-io/CryptoVault | 7c2f6c4c55df7d9e172058aad334a26786ea839f | [
"Apache-2.0"
] | 6 | 2018-06-27T00:14:46.000Z | 2018-10-29T20:51:45.000Z | prescryptchain/api/views.py | genobank-io/CryptoVault | 7c2f6c4c55df7d9e172058aad334a26786ea839f | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# REST
from rest_framework.viewsets import ViewSetMixin
from rest_framework import routers, serializers, viewsets
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated, BasePermission
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.views import APIView
from rest_framework import mixins, generics
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
# our models
from blockchain.models import Block, Prescription, Transaction, Address
from blockchain.utils import pubkey_string_to_rsa, savify_key, pubkey_base64_to_rsa, pubkey_base64_from_uri
from .exceptions import NonValidPubKey
# Define router
router = routers.DefaultRouter()
# add patient filter by email, after could modify with other
router.register(r'rx-endpoint', PrescriptionViewSet, 'prescription-endpoint')
# add patient filter by email, after could modify with other
router.register(r'block', BlockViewSet, 'block-endpoint')
# add patient filter by email, after could modify with other
router.register(r'address', AddressViewSet, 'address_endpoint')
| 33.858065 | 129 | 0.664444 |
37d92a06667232ad4a4f6ca14ad0257dd6a2e56a | 2,484 | py | Python | client/commands/incremental.py | stvreumi/pyre-check | 94d13c8df37b53843ae92544b81042347b64315d | [
"MIT"
] | null | null | null | client/commands/incremental.py | stvreumi/pyre-check | 94d13c8df37b53843ae92544b81042347b64315d | [
"MIT"
] | null | null | null | client/commands/incremental.py | stvreumi/pyre-check | 94d13c8df37b53843ae92544b81042347b64315d | [
"MIT"
] | null | null | null | # Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import atexit
import logging
import os
import subprocess
import sys
from typing import List
from .command import ClientException, ExitCode, State
from .reporting import Reporting
from .start import Start
LOG = logging.getLogger(__name__)
| 31.846154 | 88 | 0.625201 |
37da81bd71be1d388df7554cdc71e1b8d0bef4e9 | 26,540 | py | Python | main_random_policy.py | rish-raghu/Object-Goal-Navigation | d2c882f3a97396c691fc75b46bd94bb7077f7d0f | [
"MIT"
] | null | null | null | main_random_policy.py | rish-raghu/Object-Goal-Navigation | d2c882f3a97396c691fc75b46bd94bb7077f7d0f | [
"MIT"
] | null | null | null | main_random_policy.py | rish-raghu/Object-Goal-Navigation | d2c882f3a97396c691fc75b46bd94bb7077f7d0f | [
"MIT"
] | null | null | null | from collections import deque, defaultdict
import os
import sys
import logging
import time
import json
import gym
import torch.nn as nn
import torch
import numpy as np
import matplotlib.pyplot as plt
from model import RL_Policy, Semantic_Mapping
from utils.storage import GlobalRolloutStorage
from envs import make_vec_envs
from arguments import get_args
import algo
os.environ["OMP_NUM_THREADS"] = "1"
if __name__ == "__main__":
main()
| 41.020093 | 132 | 0.511492 |
37db93135f06b7cc7a06b9ea9f0839b0af335d54 | 6,889 | py | Python | src/ITN/srmg/core/RiemannianRight.py | Yulv-git/Awesome-Ultrasound-Standard-Plane-Detection | 2e35afaa891badf5a235b5d995102e4dc8a4cf0d | [
"MIT"
] | 1 | 2022-03-24T06:54:36.000Z | 2022-03-24T06:54:36.000Z | src/ITN/srmg/core/RiemannianRight.py | Yulv-git/Awesome-Ultrasound-Standard-Plane-Detection | 2e35afaa891badf5a235b5d995102e4dc8a4cf0d | [
"MIT"
] | null | null | null | src/ITN/srmg/core/RiemannianRight.py | Yulv-git/Awesome-Ultrasound-Standard-Plane-Detection | 2e35afaa891badf5a235b5d995102e4dc8a4cf0d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding=utf-8
'''
Author: Shuangchi He / Yulv
Email: yulvchi@qq.com
Date: 2022-03-19 10:33:38
Motto: Entities should not be multiplied unnecessarily.
LastEditors: Shuangchi He
LastEditTime: 2022-03-23 00:52:55
FilePath: /Awesome-Ultrasound-Standard-Plane-Detection/src/ITN/srmg/core/RiemannianRight.py
Description: Modify here please
Init from https://github.com/yuanwei1989/plane-detection Author: Yuanwei Li (3 Oct 2018)
# Copyright (c) 2006-2017, Nina Milone, Bishesh Kanal, Benjamin Hou
# Copyright (c) 2006-2017, Imperial College of Science, Technology and Medicine
# Produced at Biomedical Image Analysis Group
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
Statistics on Riemannian Manifolds and Groups
---------------------------------------------
This is a set of codes to compare the computing of the different types of means on Lie groups.
These codes can be used to reproduce the experiments illustrated in the video developed for the
MICCAI Educational challenge 2014, available at: url of the video.
:Authors:
`Nina Miolane <website>`
`Bishesh Khanal <website>`
:Organization:
Asclepios Team, INRIA Sophia Antipolis.
:Version:
2017.07.05
Requirements
------------
* `Numpy 1.11 <http://www.numpy.org>`_
Notes
-----
----------
(1) Defining a mean on Lie group.
Nina Miolane. Medical Imaging. 2013. <hal-00938320>
'''
import numpy
import math
from srmg.common.group import *
from srmg.common.util import *
EPS = 1e-5
def riemExpR(a,f0,v):
"""
start: TODO
What the function does
clearer function name ?
Inputs description:
Outputs description:
end: TODO
Riemannian exponential and logarithm from any point f0 (for left- and right-invariant metric)
"""
f = grpCompose((riemExpIdR(a, numpy.linalg.lstsq(jR(f0),v)[0])), f0)
return f
def riemExpIdR(a,v):
"""
start: TODO
What the function does
clearer function name ?
Inputs description:
Outputs description:
end: TODO
Riemannian exponential and logarithm from Id (for left- and right-invariant metric)
"""
v=grpReg(-v);
f = numpy.zeros(6)
f[0:3] = v[0:3]
f[3:6] = a * v[3:6]
f = grpInv(f)
return f
def sigma2R(a,m,tabf,tabw):
"""
start: TODO
What the function does
clearer function name ?
Inputs description:
Outputs description:
end: TODO
"""
siz = tabf.shape[0]
if siz < 2:
print('Error: Calculating variance requires at least 2 points')
return 0
s = 0
for i in range(0,siz):
s = s + tabw[i] * normA2R(a,m,riemLogR(a,m,tabf[i,:]));
return s
def riemLogR(a,f0,f):
"""
DESCRIPTION
Attributes:
a: ?????
f0: ????
f: ????
Return:
v: ?????
"""
v=numpy.dot(jR(f0),riemLogIdR(a,grpCompose(f,grpInv(f0))))
return v
def riemLogIdR(a,f):
"""
DESCRIPTION
Attributes:
a: ?????
f: ????
Return:
v: ?????
"""
v = numpy.zeros(6)
v[0:3] = f[0:3]
v[3:6] = numpy.dot(rotMat(-f[0:3]),f[3:6]);
return v
def qR(a,f):
"""
Left- and right- invariant inner product in the principal chart (propagation of Frobenius inner product)
Attributes:
a: ?????
f: ????
Return:
g: ?????
"""
f = grpReg(f)
g0 = numpy.zeros([6,6])
g0[0:3,0:3] = numpy.eye(3)
g0[3:6,3:6] = a * numpy.eye(3)
g = numpy.dot(numpy.dot(numpy.linalg.inv(jR(f).T) , g0) , numpy.linalg.inv(jR(f)))
return g
def jR(f):
"""
Differentials of the left and right translations for SO(3) in the principal chart
Attributes:
r: ?????
Return:
Jl: ?????
"""
#f = makeColVector(f,6); # unnecessary if 1D
f = grpReg(f);
Jr = numpy.zeros([6,6])
Jr[0:3,0:3] = jRotR(f[0:3]);
Jr[3:6,0:3] = -skew(f[3:6]);
Jr[3:6,3:6] = numpy.eye(3);
return Jr
def normA2R(a,f,v):
"""
This function calculates the normalised left
Attributes:
a: ?????
f: ?????
v: ?????
Return:
n: normalised vector
"""
v=grpReg(v);
n=numpy.dot(numpy.dot(v.T,qR(a,f)),v);
return n
def frechetR(a,tabf,tabw):
"""
This function computes the frechet-L mean
Attributes:
img: The fixed image that will be transformed (simpleitk type)
a: ?????
tabf: SE3 data points (Nx6 vector)
tabw: data point weights (Nx1 vector)
Return:
m: The mean
"""
siz = tabf.shape[0]
if siz < 2:
print('Error: Calculating mean requires at least 2 points')
m = tabf[0,:]
# Iteration 0
mbis=m;
print('mbisR=' + str(mbis))
aux=numpy.zeros(6);
for i in range (0,siz):
aux=aux+tabw[i]*riemLogR(a,mbis,tabf[i,:]);
m=riemExpR(a,mbis,aux);
# Iteration 1 until converges
while (normA2R(a,mbis,riemLogR(a,mbis,m))>EPS*sigma2R(a,mbis,tabf,tabw)):
mbis=m;
print('mbisR=' + str(mbis))
aux=numpy.zeros(6);
for i in range (0,siz):
aux=aux+tabw[i]*riemLogR(a,mbis,tabf[i,:]);
m=riemExpR(a,mbis,aux);
return m
| 27.556 | 108 | 0.609958 |
37dc25007d47db4fa96ca0730b82167ce6738233 | 4,658 | py | Python | v0449gRpc_pb2.py | StormDev87/VPH_bot_python | ae83a0b61e234912c0136ef0f176e7a88603ff28 | [
"MIT"
] | 1 | 2022-02-28T16:20:33.000Z | 2022-02-28T16:20:33.000Z | v0449gRpc_pb2.py | StormDev87/VPH_bot_python | ae83a0b61e234912c0136ef0f176e7a88603ff28 | [
"MIT"
] | null | null | null | v0449gRpc_pb2.py | StormDev87/VPH_bot_python | ae83a0b61e234912c0136ef0f176e7a88603ff28 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: v0449gRpc.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0fv0449gRpc.proto\x12\tv0449gRpc\"\x1b\n\x0b\x64\x61taRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1a\n\x08\x64\x61ta2Plc\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1f\n\x0cslaveReq2Plc\x12\x0f\n\x07request\x18\x01 \x01(\x05\"\x1a\n\x08\x64\x61ta2Hmi\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1b\n\ndata2PlcJs\x12\r\n\x05jsSer\x18\x01 \x01(\t\"\x1b\n\ndata2HmiJs\x12\r\n\x05jsSer\x18\x01 \x01(\t\"\x1c\n\ndata2PlcPb\x12\x0e\n\x06xmlSer\x18\x01 \x01(\t\"\x1d\n\ndataAnswer\x12\x0f\n\x07message\x18\x01 \x01(\t2\x93\x01\n\x0cv0449gRpcSvc\x12=\n\x0bxchRtDataJs\x12\x15.v0449gRpc.data2PlcJs\x1a\x15.v0449gRpc.data2HmiJs\"\x00\x12\x44\n\x10xchRtDataJsSlave\x12\x17.v0449gRpc.slaveReq2Plc\x1a\x15.v0449gRpc.data2HmiJs\"\x00\x62\x06proto3')
_DATAREQUEST = DESCRIPTOR.message_types_by_name['dataRequest']
_DATA2PLC = DESCRIPTOR.message_types_by_name['data2Plc']
_SLAVEREQ2PLC = DESCRIPTOR.message_types_by_name['slaveReq2Plc']
_DATA2HMI = DESCRIPTOR.message_types_by_name['data2Hmi']
_DATA2PLCJS = DESCRIPTOR.message_types_by_name['data2PlcJs']
_DATA2HMIJS = DESCRIPTOR.message_types_by_name['data2HmiJs']
_DATA2PLCPB = DESCRIPTOR.message_types_by_name['data2PlcPb']
_DATAANSWER = DESCRIPTOR.message_types_by_name['dataAnswer']
dataRequest = _reflection.GeneratedProtocolMessageType('dataRequest', (_message.Message,), {
'DESCRIPTOR' : _DATAREQUEST,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.dataRequest)
})
_sym_db.RegisterMessage(dataRequest)
data2Plc = _reflection.GeneratedProtocolMessageType('data2Plc', (_message.Message,), {
'DESCRIPTOR' : _DATA2PLC,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.data2Plc)
})
_sym_db.RegisterMessage(data2Plc)
slaveReq2Plc = _reflection.GeneratedProtocolMessageType('slaveReq2Plc', (_message.Message,), {
'DESCRIPTOR' : _SLAVEREQ2PLC,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.slaveReq2Plc)
})
_sym_db.RegisterMessage(slaveReq2Plc)
data2Hmi = _reflection.GeneratedProtocolMessageType('data2Hmi', (_message.Message,), {
'DESCRIPTOR' : _DATA2HMI,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.data2Hmi)
})
_sym_db.RegisterMessage(data2Hmi)
data2PlcJs = _reflection.GeneratedProtocolMessageType('data2PlcJs', (_message.Message,), {
'DESCRIPTOR' : _DATA2PLCJS,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.data2PlcJs)
})
_sym_db.RegisterMessage(data2PlcJs)
data2HmiJs = _reflection.GeneratedProtocolMessageType('data2HmiJs', (_message.Message,), {
'DESCRIPTOR' : _DATA2HMIJS,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.data2HmiJs)
})
_sym_db.RegisterMessage(data2HmiJs)
data2PlcPb = _reflection.GeneratedProtocolMessageType('data2PlcPb', (_message.Message,), {
'DESCRIPTOR' : _DATA2PLCPB,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.data2PlcPb)
})
_sym_db.RegisterMessage(data2PlcPb)
dataAnswer = _reflection.GeneratedProtocolMessageType('dataAnswer', (_message.Message,), {
'DESCRIPTOR' : _DATAANSWER,
'__module__' : 'v0449gRpc_pb2'
# @@protoc_insertion_point(class_scope:v0449gRpc.dataAnswer)
})
_sym_db.RegisterMessage(dataAnswer)
_V0449GRPCSVC = DESCRIPTOR.services_by_name['v0449gRpcSvc']
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_DATAREQUEST._serialized_start=30
_DATAREQUEST._serialized_end=57
_DATA2PLC._serialized_start=59
_DATA2PLC._serialized_end=85
_SLAVEREQ2PLC._serialized_start=87
_SLAVEREQ2PLC._serialized_end=118
_DATA2HMI._serialized_start=120
_DATA2HMI._serialized_end=146
_DATA2PLCJS._serialized_start=148
_DATA2PLCJS._serialized_end=175
_DATA2HMIJS._serialized_start=177
_DATA2HMIJS._serialized_end=204
_DATA2PLCPB._serialized_start=206
_DATA2PLCPB._serialized_end=234
_DATAANSWER._serialized_start=236
_DATAANSWER._serialized_end=265
_V0449GRPCSVC._serialized_start=268
_V0449GRPCSVC._serialized_end=415
# @@protoc_insertion_point(module_scope)
| 43.12963 | 790 | 0.800129 |
37dd454cd95fe5c19347e66dba4d2c8da8d4857f | 14,423 | py | Python | api/resources_portal/test/views/test_search_endpoint.py | AlexsLemonade/resources-portal | d91c6c8d6135461faccbc78ef2b0be3f9b358f21 | [
"BSD-3-Clause"
] | null | null | null | api/resources_portal/test/views/test_search_endpoint.py | AlexsLemonade/resources-portal | d91c6c8d6135461faccbc78ef2b0be3f9b358f21 | [
"BSD-3-Clause"
] | 536 | 2019-11-13T15:49:03.000Z | 2022-03-28T20:17:24.000Z | api/resources_portal/test/views/test_search_endpoint.py | AlexsLemonade/resources-portal | d91c6c8d6135461faccbc78ef2b0be3f9b358f21 | [
"BSD-3-Clause"
] | 1 | 2020-04-03T02:07:29.000Z | 2020-04-03T02:07:29.000Z | import datetime
from django.core.management import call_command
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from resources_portal.management.commands.populate_dev_database import populate_dev_database
from resources_portal.models import Material, Organization, User
class SearchUsersEndpointTestCase(APITestCase):
"""
Tests /search/users operations.
"""
def test_search_for_name_returns_given_user(self):
self.client.force_authenticate(user=self.primary_prof)
search_url = (
reverse("search-users-list")
+ "?search="
+ self.primary_prof.first_name
+ " "
+ self.primary_prof.last_name
)
response = self.client.get(search_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
first_result_id = response.json()["results"][0]["id"]
self.assertEqual(first_result_id, str(self.primary_prof.id))
def test_order_by_published_name_succeeds(self):
self.client.force_authenticate(user=self.primary_prof)
search_url = reverse("search-users-list") + "?ordering=published_name"
response = self.client.get(search_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user_published_names = []
for user in response.json()["results"]:
if user["published_name"]:
user_published_names.append(user["published_name"])
self.assertEqual(user_published_names, sorted(user_published_names))
def test_empty_search_returns_no_results(self):
self.client.force_authenticate(user=self.primary_prof)
search_url = reverse("search-users-list") + "?search="
response = self.client.get(search_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user_count = int(response.json()["count"])
self.assertEqual(user_count, 0)
class SearchOrganizationsEndpointTestCase(APITestCase):
"""
Tests /search/organizations operations.
"""
def test_search_for_organization_name_returns_given_organization(self):
self.client.force_authenticate(user=self.primary_prof)
search_url = reverse("search-organizations-list") + "?search=" + self.primary_lab.name
response = self.client.get(search_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
first_result_id = int(response.json()["results"][0]["id"])
self.assertEqual(first_result_id, self.primary_lab.id)
def test_search_for_owner_attribute_returns_related_organizations(self):
self.client.force_authenticate(user=self.primary_prof)
search_url = reverse("search-organizations-list") + "?search=" + self.primary_prof.email
response = self.client.get(search_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
organization_count = int(response.json()["count"])
organization_names = []
for org in response.json()["results"]:
organization_names.append(org["name"])
self.assertEqual(
organization_count, len(Organization.objects.filter(owner=self.primary_prof))
)
for name in organization_names:
self.assertTrue(
Organization.objects.filter(name=name, owner=self.primary_prof).exists()
)
| 35.264059 | 99 | 0.662969 |
37ddb9f83521ff471c035e9cd6a4902772e590bf | 5,107 | py | Python | mindarmour/utils/logger.py | hboshnak/mindarmour | 0609a4eaea875a84667bed279add9305752880cc | [
"Apache-2.0"
] | 139 | 2020-03-28T02:37:07.000Z | 2022-03-24T15:35:39.000Z | mindarmour/utils/logger.py | hboshnak/mindarmour | 0609a4eaea875a84667bed279add9305752880cc | [
"Apache-2.0"
] | 2 | 2020-04-02T09:50:21.000Z | 2020-05-09T06:52:57.000Z | mindarmour/utils/logger.py | hboshnak/mindarmour | 0609a4eaea875a84667bed279add9305752880cc | [
"Apache-2.0"
] | 12 | 2020-03-28T02:52:42.000Z | 2021-07-15T08:05:06.000Z | # Copyright 2019 Huawei Technologies Co., Ltd
#
# 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.
""" Util for log module. """
import logging
_LOGGER = logging.getLogger('MA')
def _find_caller():
"""
Bind findCaller() method, which is used to find the stack frame of the
caller so that we can note the source file name, line number and
function name.
"""
return _LOGGER.findCaller()
def add_handler(self, handler):
"""
Add other handler supported by logging module.
Args:
handler (logging.Handler): Other handler supported by logging module.
Raises:
ValueError: If handler is not an instance of logging.Handler.
"""
if isinstance(handler, logging.Handler):
self._logger.addHandler(handler)
else:
raise ValueError('handler must be an instance of logging.Handler,'
' but got {}'.format(type(handler)))
def debug(self, tag, msg, *args):
"""
Log '[tag] msg % args' with severity 'DEBUG'.
Args:
tag (str): Logger tag.
msg (str): Logger message.
args (Any): Auxiliary value.
"""
caller_info = _find_caller()
file_info = ':'.join([caller_info[0], str(caller_info[1])])
self._logger.debug(self._extra_fmt + msg, file_info, tag, *args)
def info(self, tag, msg, *args):
"""
Log '[tag] msg % args' with severity 'INFO'.
Args:
tag (str): Logger tag.
msg (str): Logger message.
args (Any): Auxiliary value.
"""
caller_info = _find_caller()
file_info = ':'.join([caller_info[0], str(caller_info[1])])
self._logger.info(self._extra_fmt + msg, file_info, tag, *args)
def warn(self, tag, msg, *args):
"""
Log '[tag] msg % args' with severity 'WARNING'.
Args:
tag (str): Logger tag.
msg (str): Logger message.
args (Any): Auxiliary value.
"""
caller_info = _find_caller()
file_info = ':'.join([caller_info[0], str(caller_info[1])])
self._logger.warning(self._extra_fmt + msg, file_info, tag, *args)
def error(self, tag, msg, *args):
"""
Log '[tag] msg % args' with severity 'ERROR'.
Args:
tag (str): Logger tag.
msg (str): Logger message.
args (Any): Auxiliary value.
"""
caller_info = _find_caller()
file_info = ':'.join([caller_info[0], str(caller_info[1])])
self._logger.error(self._extra_fmt + msg, file_info, tag, *args)
| 32.119497 | 91 | 0.595457 |
37de891f427c0291be7aba179849ea2f6a86e5c6 | 281 | py | Python | Python/Programming Basics/Simple Calculations/17. Daily Earnings.py | teodoramilcheva/softuni-software-engineering | 98dc9faa66f42570f6538fd7ef186d2bd1d39bff | [
"MIT"
] | null | null | null | Python/Programming Basics/Simple Calculations/17. Daily Earnings.py | teodoramilcheva/softuni-software-engineering | 98dc9faa66f42570f6538fd7ef186d2bd1d39bff | [
"MIT"
] | null | null | null | Python/Programming Basics/Simple Calculations/17. Daily Earnings.py | teodoramilcheva/softuni-software-engineering | 98dc9faa66f42570f6538fd7ef186d2bd1d39bff | [
"MIT"
] | null | null | null | workdays = float(input())
daily_tips = float(input())
exchange_rate = float(input())
salary = workdays * daily_tips
annual_income = salary * 12 + salary * 2.5
net_income = annual_income - annual_income * 25 / 100
result = net_income / 365 * exchange_rate
print('%.2f' % result)
| 23.416667 | 53 | 0.711744 |
37e09e1c599fd41f037cb54000938dba1d33127b | 7,483 | py | Python | bert_rerannker_eval.py | satya77/transformer_rankers | 0d2c20bd26041d887fb65102020a0b609ec967fc | [
"MIT"
] | null | null | null | bert_rerannker_eval.py | satya77/transformer_rankers | 0d2c20bd26041d887fb65102020a0b609ec967fc | [
"MIT"
] | null | null | null | bert_rerannker_eval.py | satya77/transformer_rankers | 0d2c20bd26041d887fb65102020a0b609ec967fc | [
"MIT"
] | null | null | null | from transformer_rankers.trainers import transformer_trainer
from transformer_rankers.datasets import dataset, preprocess_scisumm_ranked
from transformer_rankers.eval import results_analyses_tools
from transformers import BertTokenizer, BertForSequenceClassification
from sacred.observers import FileStorageObserver
from sacred import Experiment
import numpy as np
import torch
import pandas as pd
import argparse
import logging
import sys
ex = Experiment('BERT-ranker experiment')
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(sys.stdout)
]
)
if __name__ == "__main__":
main() | 47.967949 | 116 | 0.526928 |
37e0cdbd73052a4cfa66dd46c357ae89f7505242 | 424 | py | Python | python/p21.py | tonyfg/project_euler | 3a9e6352a98faaa506056b42160c91bffe93838c | [
"WTFPL"
] | null | null | null | python/p21.py | tonyfg/project_euler | 3a9e6352a98faaa506056b42160c91bffe93838c | [
"WTFPL"
] | null | null | null | python/p21.py | tonyfg/project_euler | 3a9e6352a98faaa506056b42160c91bffe93838c | [
"WTFPL"
] | null | null | null | #Q: Evaluate the sum of all the amicable numbers under 10000.
#A: 31626
print sum_amicable(1,10000)
| 26.5 | 61 | 0.610849 |
37e13b4fd890037fc4d7192b2e7467ef9a1cb201 | 4,033 | py | Python | check.py | Dysoncat/student-services-slas-chat-bot | 5d9c7105cef640c34018d260249b6a05b959e73f | [
"MIT"
] | null | null | null | check.py | Dysoncat/student-services-slas-chat-bot | 5d9c7105cef640c34018d260249b6a05b959e73f | [
"MIT"
] | null | null | null | check.py | Dysoncat/student-services-slas-chat-bot | 5d9c7105cef640c34018d260249b6a05b959e73f | [
"MIT"
] | null | null | null | import long_responses as long
# Returns the probability of a message matching the responses that we have
# Checks all the responses using the probability of the messages
| 40.33 | 154 | 0.623109 |
37e16ab061f36f12398b74b8a1440f3cc6768529 | 1,446 | py | Python | image_predictor/utils.py | jdalzatec/streamlit-manizales-tech-talks | 619af5edc79a22ed4cc9f50dd2d0379399357549 | [
"MIT"
] | 2 | 2022-02-05T15:48:55.000Z | 2022-02-05T15:57:40.000Z | image_predictor/utils.py | jdalzatec/streamlit-manizales-tech-talks | 619af5edc79a22ed4cc9f50dd2d0379399357549 | [
"MIT"
] | null | null | null | image_predictor/utils.py | jdalzatec/streamlit-manizales-tech-talks | 619af5edc79a22ed4cc9f50dd2d0379399357549 | [
"MIT"
] | 4 | 2022-02-05T15:49:02.000Z | 2022-02-05T15:58:14.000Z | from io import StringIO
import numpy as np
from h5py import File
from keras.models import load_model as keras_load_model
from PIL import Image, ImageOps
| 32.133333 | 81 | 0.697095 |
37e2c12beb329286ae2d567a8dedde433414f28a | 417 | py | Python | client/setup.py | emilywoods/docker-workshop | 46fef25ed06ab33f653bebffdd837ee4cc31c373 | [
"MIT"
] | 1 | 2022-03-21T07:32:36.000Z | 2022-03-21T07:32:36.000Z | client/setup.py | emilywoods/docker-workshop | 46fef25ed06ab33f653bebffdd837ee4cc31c373 | [
"MIT"
] | null | null | null | client/setup.py | emilywoods/docker-workshop | 46fef25ed06ab33f653bebffdd837ee4cc31c373 | [
"MIT"
] | null | null | null | from setuptools import setup
setup(
name="workshop-client",
install_requires=["flask==1.1.1", "requests==2.22.0"],
python_requires=">=3.7",
classifiers=[
"Development Status :: 1 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
)
| 27.8 | 58 | 0.580336 |
37e304a5ab34e95d070c76d96d91559914adff14 | 561 | py | Python | tests/facebook/models/test_photo.py | Socian-Ltd/python-facebook-1 | e9a4f626b37541103c9534a29342ef6033c09c06 | [
"Apache-2.0"
] | 2 | 2021-03-16T02:58:10.000Z | 2021-03-16T16:53:23.000Z | tests/facebook/models/test_photo.py | nedsons/python-facebook | bf2b4a70ef0e0a67a142f5856586ea318f9807ea | [
"Apache-2.0"
] | null | null | null | tests/facebook/models/test_photo.py | nedsons/python-facebook | bf2b4a70ef0e0a67a142f5856586ea318f9807ea | [
"Apache-2.0"
] | 1 | 2021-06-02T07:15:35.000Z | 2021-06-02T07:15:35.000Z | import json
import unittest
import pyfacebook.models as models
| 28.05 | 60 | 0.686275 |
37e4a1783cf1d5a9318a74c7d860d1f54e64ee4e | 5,837 | py | Python | airbyte-integrations/connectors/source-scaffold-source-python/source_scaffold_source_python/source.py | curanaj/airbyte-dbt-demo | f6b8ccd8f8e57b7ea84caf814b14d836338e8007 | [
"MIT"
] | null | null | null | airbyte-integrations/connectors/source-scaffold-source-python/source_scaffold_source_python/source.py | curanaj/airbyte-dbt-demo | f6b8ccd8f8e57b7ea84caf814b14d836338e8007 | [
"MIT"
] | null | null | null | airbyte-integrations/connectors/source-scaffold-source-python/source_scaffold_source_python/source.py | curanaj/airbyte-dbt-demo | f6b8ccd8f8e57b7ea84caf814b14d836338e8007 | [
"MIT"
] | null | null | null | # MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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.
import json
from datetime import datetime
from typing import Dict, Generator
from airbyte_cdk.logger import AirbyteLogger
from airbyte_cdk.models import (
AirbyteCatalog,
AirbyteConnectionStatus,
AirbyteMessage,
AirbyteRecordMessage,
AirbyteStream,
ConfiguredAirbyteCatalog,
Status,
Type,
)
from airbyte_cdk.sources import Source
| 47.072581 | 122 | 0.704471 |